#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ccnn.h"

/***************************************************************/
void ProcessSeg(const char *cnfXMLName, char *inBuff, int bufLen)
{
    const float PAB_GATE = 0.25F;
    int outBoxNum;

    ReadPixCnfClassify tmpReadPixCnfClassify;
       
    //利用XML配置，构建深度神经网络
    struct CcnnContext *tmpCtx = LcfNet::CreateNetFromXML(cnfXMLName, 1, 1);

    //读取网络输入图像长宽大小   
    int imgHW = LcfNet::ReadInputHeightWidth(tmpCtx);
    float *imgP = ImgHandle::LoadSquareImg((unsigned char *)inBuff, bufLen, 1, NULL, NULL, NULL, imgHW);
        
    //进行分割推理
    int h, w;
    unsigned char *hotMap;
    float *hotMapPab;
    LcfNet::NetPredictSeg(tmpCtx, imgP, &hotMap, &hotMapPab, &h, &w);
    
    //读取RGB对应类别
    ReadPixCnfClassify mReadPixCnfClassify;
    mReadPixCnfClassify.GetClassifyFromCnfFile(cnfXMLName);
    
    //类别热图转换成RGB，并保存
    //hotMap是二维热图
    mReadPixCnfClassify.SaveHotImgFile((char *)"result.jpg", hotMap, h, w);
    
    delete []imgP;
    delete []hotMap;
    delete []hotMapPab;
    
    //释放网络结构及内存等
    LcfNet::RealeaseCcnnStructMemory(tmpCtx);
}

/************************************/
char *ReadImg(char *fileImg, int *len)
{
    FILE *file;
    file = fopen(fileImg, "rb");
    if (file == NULL) {
        return NULL;
    }

    int allocSize = 10240000;
    char *data = new char[allocSize];
    int readNum = (int)fread(data, sizeof(char), allocSize, file);
    fclose(file);

    *len = readNum;
    return data;
}

/******************************/
int main(int argc, char *argv[])
{
    int bufLen;
    char *imgBuff = ReadImg(argv[1], &bufLen);
    if (NULL == imgBuff) {
        printf("Read Img error\n");
        return 0;     
    }

    ProcessSeg("lcfNetfigDeepLab3.xml", imgBuff, bufLen);
    return 1;
}
