Пример #1
0
//-----------------------------------------------------------------------------
// Serialization
//-----------------------------------------------------------------------------
bool CVTFTexture::Serialize( CUtlBuffer &buf )
{
	if (!m_pImageData)
	{
		Warning("*** Unable to serialize... have no image data!\n");
		return false;
	}

	VTFFileHeader_t header;
	Q_strncpy( header.fileTypeString, "VTF", 4 );
	header.version[0] = VTF_MAJOR_VERSION;
	header.version[1] = VTF_MINOR_VERSION;
	header.headerSize = sizeof(VTFFileHeader_t);

	header.width = m_nWidth;
	header.height = m_nHeight;
	header.flags = m_nFlags;
	header.numFrames = m_nFrameCount;
	header.numMipLevels = m_nMipCount;
	header.imageFormat = m_Format;
	VectorCopy( m_vecReflectivity, header.reflectivity );
	header.bumpScale = m_flBumpScale;

	// FIXME: Why is this needed?
	header.startFrame = m_iStartFrame;

	header.lowResImageWidth = m_nLowResImageWidth;
	header.lowResImageHeight = m_nLowResImageHeight;
	header.lowResImageFormat = m_LowResImageFormat;

	buf.Put( &header, sizeof(VTFFileHeader_t) );
	if (!buf.IsValid())
		return false;

	// Write the low-res image
	if (m_pLowResImageData)
	{
		int iLowResImageSize = ImageLoader::GetMemRequired( m_nLowResImageWidth, 
			m_nLowResImageHeight, m_LowResImageFormat, false );
		buf.Put( m_pLowResImageData, iLowResImageSize );
		if (!buf.IsValid())
			return false;
	}
	else
	{
		// If we have a non-zero image size, we better have bits!
		Assert((m_nLowResImageWidth == 0) || (m_nLowResImageHeight == 0));
	}
	
	// Write out the image
	WriteImageData( buf );
	return buf.IsValid();
}
bool ImageDataFloat2ndStageBinaryCombined::setConfiguration(ConfigReader &cfg)
{
    double scaleFactor = cfg.rescaleFactor;
    vector<string>::iterator it, end;
    unsigned int iImg, iFeature;
    cv::Mat imgInput;
    cv::Mat imgSegmap1stStage, imgLabel;
    CImageCacheElement *pImgElem;
    char strPostfix[100];
    string strInputLabelPath;

    // iNbMaxImagesLoaded = 10;
    // bUseIntegralImages = true;

    pData1stStage = new ImageDataFloat();
    pData1stStage->bGenerateFeatures = false;

    pData1stStage->setConfiguration(cfg);

    it = cfg.imageFilenames.begin();
    end = cfg.imageFilenames.end();

    vectImageData.resize(end-it);

#ifndef SHUT_UP
    if (bGenerateFeatures==true)
        cout << "Set paths and generate HOT1 features for " << end-it << " images: "<<endl;
    else
        cout << "Just set paths for " << end-it << " images: "<<endl;
#endif

    iNbLabels = cfg.numLabels;
    iNbFeatures = pData1stStage->getNbFeatures() + iNbLabels;

    iWidth = pData1stStage->getWidth();
    iHeight = pData1stStage->getHeight();

    // load image data
    for(iImg = 0; it != end; ++it, ++iImg)
    {
        pImgElem = &(vectImageData[iImg]);

        sprintf(strPostfix, "%04d", iImg);

        pImgElem->strInputImage = cfg.imageFolder + "/" + *it;
        pImgElem->strFeatureImagesPath = cfg.feature2ndStageFolder + "/features" + strPostfix;
        pImgElem->strFeatureImagesIntegralPath = cfg.feature2ndStageFolder + "/features_integral" + strPostfix;
        pImgElem->strLabelImagePath = cfg.outputFolder + "/segmap_1st_stage" + strPostfix + ".png";

        if (bGenerateFeatures==true)
        {
            cout<<"Generating 2nd-stage HOT1 features for image "<<iImg<<endl;

            imgSegmap1stStage = cv::imread(pImgElem->strLabelImagePath, cv::IMREAD_GRAYSCALE);
            if (imgSegmap1stStage.data==NULL)
            {
                cout<<"Failed to read 1st-stage segmentation map "<<iImg<<": "<<pImgElem->strLabelImagePath<<endl;
                return false;
            }

            // Check if segmentation map and ground truth image have the same size
            strInputLabelPath = cfg.groundTruthFolder + "/label_rearranged" + strPostfix + ".png";
            imgLabel = cv::imread(strInputLabelPath, cv::IMREAD_GRAYSCALE);
            if (imgLabel.data==NULL)
            {
                cout<<"Failed to read ground truth image "<<iImg<<": "<<pImgElem->strLabelImagePath<<endl;
                return false;
            }

            if (imgSegmap1stStage.size()!=imgLabel.size())
            {
                cv::resize(imgSegmap1stStage, imgSegmap1stStage, imgLabel.size(), 0, 0, cv::INTER_NEAREST);
                cout<<"Segmentation map "<<iImg<<" resized"<<endl;
            }

            computeFeatures(imgSegmap1stStage, pImgElem->vectFeatures);

            if (bUseIntegralImages==true)
            {
                pImgElem->vectFeaturesIntegral.resize(pImgElem->vectFeatures.size());
                for (iFeature=0; iFeature<pImgElem->vectFeatures.size(); iFeature++)
                {
                    cv::integral(pImgElem->vectFeatures[iFeature], pImgElem->vectFeaturesIntegral[iFeature], CV_32F);
                    /*
                    if (pImgElem->vectFeaturesIntegral[iFeature].rows!=pImgElem->vectFeatures[iFeature].rows+1
                        || pImgElem->vectFeaturesIntegral[iFeature].cols!=pImgElem->vectFeatures[iFeature].cols+1)
                    {
                        cout<<"Size differ"<<endl;
                    }*/
                }
            }

            pImgElem->bLoaded = true;
            if (WriteImageData(iImg)==false)
                return false;

            CloseImageData(iImg);
        }
        else {
            pImgElem->bLoaded = false;
        }
    }

    cout<<"2nd-stage image data initialized"<<endl;

    return true;
}
int main(int argc, char* argv[]){
	char OutFileName[255];
	system("cls");
	printf("請輸入輸出bmp檔名:");
	scanf("%s",OutFileName);

// Step1:declare a bmp header by using BmpHead

	BmpHead *pBmpHeader;			//bmp檔案包含三部份,此一其中的檔頭,BmpHead為structure
	pBmpHeader = new BmpHead;	
	

// Step2:assigment the information of the bmp header

	
	(*pBmpHeader).bfType=19778;
	(*pBmpHeader).bfSize=54 + 1024+ 512*512 ; // raw data size = 512*512 = 262144 bytes, modify when necessary
	(*pBmpHeader).bfReserved=0;
	(*pBmpHeader).bfOffBits=1078;
	(*pBmpHeader).biSize=40;
	(*pBmpHeader).biWidth= 512;		//number of columns of the image
	(*pBmpHeader).biHeight= 512;		//number of rows of the image
	(*pBmpHeader).biPlanes=1;
	(*pBmpHeader).biBitCount=8;
	(*pBmpHeader).biCompression=0;
	(*pBmpHeader).biSizeImage= 512*512;	//raw data size = 512*512 = 26144 bytes, modify when necessary, e.g., a 256x256 image: raw data size = 256*256
	(*pBmpHeader).biXPelsPerMeter=2834;
	(*pBmpHeader).biYpelsPerMeter=2834;
	(*pBmpHeader).biClrUsed=0;
	(*pBmpHeader).biClrImportant=0;

//Step3:reading the colormap (from colormap.bin)

	FILE* pic;
	char *pcColorMap;				//此為colormap
	pcColorMap = new char[1024];
	if((pic=fopen("colormap.bin","rb")) == NULL){
		printf("colormap.bin檔案不存在\n");
		exit(0);
	}
	fread(pcColorMap,sizeof(char),(*pBmpHeader).bfOffBits - 54,pic);
    fclose(pic);
//Step4:reading the raw data from "lena.bin"
    char inputfile[255]="lena.bin";
    unsigned char* pucImageData;
    
    pucImageData = ReadImage(inputfile, (*pBmpHeader).biSizeImage, 0);
// ************** your work ******************



//Step5:processing the data, 
// ************** your work ******************

	
//Step6:write Header	
	WriteHeader(OutFileName,pBmpHeader); // file: output filename, assigned by yourself

//Step7:write colormap
	WriteColorMap(OutFileName,pcColorMap,1024);

// Step8: write processed data
WriteImageData(OutFileName,pucImageData,(*pBmpHeader).biSizeImage);//write rawdata
printf("Done!!");
// ***************** your work *********************
// (1) !!! move the file pointer to the "end of the opened output file" (or say, to the end of the colormap) (by fseek(): Moves the file pointer to a specified location), 
// and then start to write your data into it
// Or (2)That is, Opens for writing at the end of the file (by the mode specifier of fopen())
 
system("pause");
	return 0;
}
bool ImageDataFloat2ndStageCombined::setConfiguration(ConfigReader &cfg)
{
    double scaleFactor = cfg.rescaleFactor;
    vector<string>::iterator it, end;
    unsigned int iImg, iFeature;
    cv::Mat imgInput;
    cv::Mat imgSegmap1stStage, imgLabel;
    CImageCacheElement *pImgElem;
    char strPostfix[100];
    string strInputLabelPath;
    CLabelFeature labelFeature;

    // iNbMaxImagesLoaded = 10;
    // bUseIntegralImages = true;

    pData1stStage = new ImageDataFloat();
    pData1stStage->bGenerateFeatures = false;

    pData1stStage->setConfiguration(cfg);

    it = cfg.imageFilenames.begin();
    end = cfg.imageFilenames.end();

    vectImageData.resize(end-it);

    if (bGenerateFeatures==true)
        cout << "Set paths and generate label features for " << end-it << " images: "<<endl;
    else
        cout << "Just set paths for " << end-it << " images: "<<endl;

    iNbLabels = cfg.numLabels;
    iNbScales = NO_REGION_SCALES;
    iNbFeatures = pData1stStage->getNbFeatures() + regFeatures;

    iWidth = pData1stStage->getWidth();
    iHeight = pData1stStage->getHeight();

    // load image data
    for(iImg = 0; it != end; ++it, ++iImg)
    {
        pImgElem = &(vectImageData[iImg]);

        sprintf(strPostfix, "%04d", iImg);

        pImgElem->strInputImage = cfg.imageFolder + "/" + *it;
        pImgElem->strFeatureImagesPath = cfg.feature2ndStageFolder + "/features" + strPostfix;
        pImgElem->strFeatureImagesIntegralPath = cfg.feature2ndStageFolder + "/label_integral" + strPostfix;
        pImgElem->strLabelImagePath = cfg.outputFolder + "/segmap_1st_stage" + strPostfix + ".png";

        if (bGenerateFeatures==true)
        {
            cout<<"Generating 2nd-stage features for image "<<iImg<<endl;

            imgSegmap1stStage = cv::imread(pImgElem->strLabelImagePath, cv::IMREAD_GRAYSCALE);
            if (imgSegmap1stStage.data==NULL)
            {
                cout<<"Failed to read 1st-stage segmentation map "<<iImg<<": "<<pImgElem->strLabelImagePath<<endl;
                return false;
            }

            // Check if segmentation map and ground truth image have the same size
            strInputLabelPath = cfg.groundTruthFolder + "/label_rearranged" + strPostfix + ".png";
            imgLabel = cv::imread(strInputLabelPath, cv::IMREAD_GRAYSCALE);
            if (imgLabel.data==NULL)
            {
                cout<<"Failed to read ground truth image "<<iImg<<": "<<pImgElem->strLabelImagePath<<endl;
                return false;
            }

            if (imgSegmap1stStage.size()!=imgLabel.size())
            {
                cv::resize(imgSegmap1stStage, imgSegmap1stStage, imgLabel.size(), 0, 0, cv::INTER_NEAREST);
                cout<<"Segmentation map "<<iImg<<" resized"<<endl;
            }

            labelFeature.SetImage(imgSegmap1stStage);
            pImgElem->vectFeaturesIntegral.resize(6*NO_LABELS);

            unsigned int iLabel;

            for (iLabel=0; iLabel<NO_LABELS; iLabel++)
            {
                pImgElem->vectFeaturesIntegral[iLabel*6 + 0] = labelFeature.arrayIntegralImages[iLabel].one;
                pImgElem->vectFeaturesIntegral[iLabel*6 + 1] = labelFeature.arrayIntegralImages[iLabel].x;
                pImgElem->vectFeaturesIntegral[iLabel*6 + 2] = labelFeature.arrayIntegralImages[iLabel].y;
                pImgElem->vectFeaturesIntegral[iLabel*6 + 3] = labelFeature.arrayIntegralImages[iLabel].xx;
                pImgElem->vectFeaturesIntegral[iLabel*6 + 4] = labelFeature.arrayIntegralImages[iLabel].yy;
                pImgElem->vectFeaturesIntegral[iLabel*6 + 5] = labelFeature.arrayIntegralImages[iLabel].xy;
            }

            pImgElem->bLoaded = true;
            if (WriteImageData(iImg)==false)
                return false;

            CloseImageData(iImg);
        }
        else {
            pImgElem->bLoaded = false;
        }
    }

    cout<<"2nd-stage image data initialized"<<endl;

    return true;
}
Пример #5
0
//test letter block from correction table and draw result
string GMainEditor::letterBlockCorrelation(unsigned int in){
   
	cout_<<"letterBlockCorrelation"<<endl;
	int print=1;
	
	int indexLetter=indexById(correctionTable,in);
	//if(pechaDataLoaded)pechaImg->destroy();
    //pechaImg=	
	vector<stringOCR>strArray;
	string str;
    GBitmap *letterImg=loadFromTiffString(correctionTable[indexLetter].img->TIFF_string,1);
	
	GBitset *setBit=GBitset::createResize(letterImg,1,1,1);
	cout_<<"@4_2";
	setBit->pageStringDetector(strArray,1); // Подпрограмма выделения строк и букв ПЕЧА ( РЕЛЬСЫ  )
	cout_<<"@4_3";
	if(strArray.size()>1)strArray[0].wordArray.resize(0);
	
	cout_<<" setBit->border_size()="<<setBit->border_size()<<endl;
	
	
	GBitsetOCR *setOCR=GBitsetOCR::createResize(letterImg,1,1);
	setOCR->setData(
					aliKali,
					strArray,
					correctionTable,
					logicProcessor,
					0,
					0,
					setBit->border_size(),
					ALL_LETTER);
	
	mainString=setOCR->mainString;
	cout_<<mainString<<"strArray="<<strArray[0].wordArray.size();
	
str="/__1draw.jpg";
#ifdef DEBUGLVL_DRAW						
	if(setOCR->setMatrix!=NULL)WriteImageData(setOCR->setMatrix->drawDataRGB,str,0);
#endif
#ifdef DEBUGLVL_GREY1
	if(setOCR->setMatrix!=NULL)WriteImageData(setOCR->setMatrix->drawData,str,0);
#endif
	
	
	ostringstream c_out1;
    int x0,y0,x1,y1,gY,index=0;
	
	// заполнение массива координат прямоугольника
	for (int strInd=(int)strArray.size()-1; strInd >=0; strInd-- ){
		x0=strArray[strInd].x0;   x1=strArray[strInd].x1;
		y0=strArray[strInd].y0;   y1=strArray[strInd].y1;
		c_out1<<"<div class=\"sT\" id=\"s"<<strInd<<"\" style=\"left:";
		c_out1<<x0<<"px; top:"<<y0<<"px; width:"<<x1-x0<<"px; height:";
		c_out1<<y1-y0<<"px;\" ";
		c_out1<<"LimY0=\""<<strArray[strInd].LimY0<<"\" ";
		c_out1<<"LimY1=\""<<strArray[strInd].LimY0<<"\" ";
		c_out1<<"y0=\""<<strArray[strInd].y0<<"\" ";
		c_out1<<"y1=\""<<strArray[strInd].y1<<"\" ";
		c_out1<<"x1=\""<<strArray[strInd].x1<<"\" ></div>\n";
		
		for (int m=0; m < strArray[strInd].wordArray.size(); m++ ){
			wordOCR *wP=&strArray[strInd].wordArray[m];
			if(wP->correlation<0)continue;  //word marked as text frame etc.
			x0=wP->x0;   x1=wP->x1;   y0=wP->y0;   y1=wP->y1;
			//gY=strArray[strInd].y1-y0+10;
			gY=0;
			//DM("y0="<<y0<<" y1="<<y1<<" x0="<<x0<<" x1="<<x1<<" LimY0="<<strArray[strInd].LimY0<<" LimY1="<<strArray[strInd].LimY1<<END);
			if(x1-x0>0){
				c_out1<<"<div class=\"dE\" id=\"g"<<index<<"\" c=\""<<wP->correlation;
				c_out1<<"\" style=\"left:"<<x0<<"px; top:"<<y0<<"px; width:"<<x1-x0<<"px; height:";
				c_out1<<y1-y0<<"px; ";
				if(wP->correlation<70){c_out1<<" border-color:#ff0000; border-width:3px;";}
				if(wP->correlation>70&&wP->correlation<80){c_out1<<" border-color:#cc0033; border-width:2px;";}
				
				c_out1<<"\">\n<div class=\"dM\" style=\"width: "<<x1-x0<<"px; height:3px;\"></div>\n";
				//c_out1<<wP->OCRIndex;
				c_out1<<"<div class=\"nG\" id=\""<<index<<"\" style=\" top:"<<gY<<"px\" onClick=\"edit(";
				c_out1<<index<<")\" onBlur=\"setText("<<index<<")\">"<<wP->name<<"</div></div>";
				index++;
			}
			DT("n="<<wP->name.c_str()<<" c="<<wP->correlation<<END);
			
		} // m
		
	} // strInd
	
	str=c_out1.str();
	
	
	string destStr=drawEditLetterBlock(str,in);
	return destStr;

}
Пример #6
0
///диспетчер выполнения процесса распознавания страницы.
void GMainEditor::startOCR(GBitmap *pechaImg_){

    cout<<"Start#1 "<<inputData.data["inputFile"]<<endl;
    if(!pechaImg_){cout_<<"no open file"<<inputData.data["inputFile"]<<endl; return;}
    pechaImg=pechaImg_;
    int border=0;
    string str;
    float param[11];
    param[0]=1;
    /*
    if(inputData.data["ocrData"]=="batchOCR"||inputData.data["ocrData"]=="lineOCR"){
        //imageEditor->setImageByOCR(pechaImg,param,1);
        aliKali->letterSet.resize(0);
        //param[0]=1;
        if(param[0]!=-1){
            imageEditor->adaptiveFiltration1(pechaImg,param,1);
            if(strArray.size()){
                setBit->destroy();
                setOCR->destroy();
                strArray.resize(0);
            }
        }else{
            //если на странице не определен масштаб, то скорее всего это изображение
            //такие страницы могут занять большой объем в памяти прираспознавании.
            //перед распознаванием таких страниц их необходимо проверить детектором на наличие текста.
            cout<<"no detectabel text on page "<<inputData.data["inputFile"]<<endl;
            mainString="";
            drawOCRPage(strArray);
            pechaImg_->destroy();
            DR_("doneStartOCR_1"<<endl);
            pechaDataLoaded=0;
            return;
        }

    }
    */
    
    //((GImageEditor*)inputData.imageEditor)->WriteImageData(pechaImg,"/_Image2OCR/_1Draw_.jpg",0); exit(0);

   
    if(!strArray.size()){
        setBit=GBitset::createResize(pechaImg_,1,1,1);
        setBit->pageStringDetector(strArray,1); // Подпрограмма выделения строк и букв ПЕЧА ( РЕЛЬСЫ  )
        border=setBit->border_size();
        setBit->destroy();
        setOCR=GBitsetOCR::createResize(pechaImg_,1,1);
        //if(NewLetterOnlyBtn->Checked==true) {mode=NEWLETTERINBOOK;}else{mode=ALL_LETTER;}
        str=fileName(inputData.data["inputFile"]); DT("@@@ file="<<str);
        
    }
    
        setOCR->setData(
                    aliKali,
                    strArray,
                    correctionTable,
                    logicProcessor,
                    iLeft,
                    iTop,
                    border,
                    ALL_LETTER);

	
    mainString=setOCR->mainString;
    //string xmlString=setOCR->xmlString;
	
    
    //cout_<<"time="<<time<<" mainString"<<mainString<<endl;

    //DM("//______timeALL______="<<time1<<END);tm_start1=clock();

    if(setOCR!=NULL){
        
    str="/__1draw.jpg";
#ifdef DEBUGLVL_DRAW						
            //if(setOCR->setMatrix!=NULL)WriteImageData(setOCR->setMatrix->drawDataRGB,str,0);
#endif
#ifdef DEBUGLVL_GREY1
            if(setOCR->setMatrix!=NULL)WriteImageData(setOCR->setMatrix->drawData,str,0);
#endif

        DT("start release setOCR  inputData.data[ocrData]="<< inputData.data["ocrData"]<<endl);
        setOCR->destroy();
        
        DT("draw0");
        
        int max=0; int maxIndex=-1;
        for(int n=0;n<strArray.size();n++){
            if(strArray[n].line.size()>max){
                max=(int)strArray[n].line.size();
                maxIndex=n;
            }
        }
        
        if(inputData.data["ocrData"]=="batchOCR"||
           inputData.data["ocrData"]=="letterBlock"||
           inputData.data["ocrData"]=="OCRTrainingOne"||
           inputData.data["ocrData"]=="OCRTrainingOneFile"
           ){
            //logicProcessor->drawGrapeLine(strArray[maxIndex].line);
            drawOCRPage(strArray);
            //drawStrArrayDebug(strArray,border);
            //cout<<"#";
            
        }

        if(inputData.data["ocrData"]=="testOCRLine"||
           inputData.data["ocrData"]=="OCRTraining"){
            //drawStrArrayDebug(strArray,border);
            cout<<" maxIndex="<<maxIndex<<endl;
            if(maxIndex!=-1)logicProcessor->drawGrapeLine(strArray[maxIndex].line);
        }
        DT("draw1");
        //if(inputData.data["ocrData"]=="ocrBatch")drawLettersInCorrectionPage(LETTER_ADD);	
        DT("draw2");
    }
    //strArray.resize(0);
    pechaImg_->destroy();

    
    DR_("doneStartOCR"<<endl);

    pechaDataLoaded=0;
    //cout<<"done "<<inputData.data["inputFile"]<<endl;
    
}//________________________________________________________________________________________________________________
int main(int argc, char* argv[]){
	char file[255],OutFileName[255];
	system("cls");
	printf("請輸入bmp檔名:");
	scanf("%s",file);
	printf("請輸入輸出bmp檔名:");
	scanf("%s",OutFileName);

// Step1:declare a bmp header by using BmpHead

	BmpHead *pBmpHeader;			//bmp檔案包含三部份,此一其中的檔頭,BmpHead為structure
	pBmpHeader = new BmpHead;
		

// Step2: read the information of the bmp header

	pBmpHeader=ReadBmpHeader(file);
	printf("raw data size: %d\n", (*pBmpHeader).biSizeImage);
    printf("Image Width: %d\n", (*pBmpHeader).biWidth);
    printf("Image Height %d\n", (*pBmpHeader).biHeight);
	printf("Header occupies 54 bytes\n");
    printf("Color map occupies 1024 bytes\n");	

//Step3:reading the colormap from the bmp file
	char *pcColorMap;				//此為colormap
	pcColorMap=ReadColorMap(file,1024);
	
    
	
//Step4:reading the raw data (lena.bmp)
// ************** your work ******************範例是用1D-view  
    unsigned char* pucImageData;
    pucImageData = ReadImage(file, (*pBmpHeader).biSizeImage, (*pBmpHeader).bfOffBits);

// image data is stored behind “header” and “colormap”.
// move your file pointer to the end of colormap, e.g., move to 54 + 1024 (by fseek())





//Step5:processing the data, 
// ************** your work ******************


//Step6:write Header
	
	WriteHeader(OutFileName,pBmpHeader); // file: output filename, assigned by yourself


//Step7:write colormap
	WriteColorMap(OutFileName,pcColorMap,1024);

// Step8: write processed data
WriteImageData(OutFileName,pucImageData,(*pBmpHeader).biSizeImage);//write rawdata
printf("Done!!");
// ***************** your work *********************
// (1) !!! move the file pointer to the "end of the opened output file" (or say, to the end of the colormap) (by fseek(): Moves the file pointer to a specified location), 
// and then start to write your data into it
// Or (2)That is, Opens for writing at the end of the file (by the mode specifier of fopen())
 system("pause");
	return 0;
}
Пример #8
0
void GImageEditor::imageProcess(){
    
    cout<<"START image";
    
	string strHeaderHTML,srcLine,str;
	string  path=inputData.data["tablePath"]+"/header.xml";
	replace(path.begin(),path.end(),'\\','/');
    
	if(!inputData.fileList.size()){
		readDirectoryToArray(inputData.fileList,inputData.data["inputFolder"],"img");
	}
    
    //cout<<"inputData.fileList.size()="<<inputData.fileList.size();
    
#ifdef FORK11
    int maxFork=inputData.num_cores*2;  //обработка изображений легче чем OCR
    pidID *pidIDArray;
    
    
    MemoryFile *pidData_mf;  //main file for conection with child process
    pidData_mf=MemoryFile::create(inputData.data["statPath"].c_str(), MemoryFile::if_exists_keep_if_dont_exists_create);
    pidData_mf->resize(sizeof(pidID)*maxFork);
    pidIDArray=(pidID*)pidData_mf->data(); //array which can be share between processes.
    
    for(int index=0;index<maxFork;index++)pidIDArray[index].status=0;
    //for(int index=0;index<maxFork;index++)cout_<<pidIDArray[index].status;
    
    
    int ID=0;
    unsigned int i=0;
    DIR *dir;
    int countFork=0;
    int status;
    while(i<inputData.fileList.size()){
        
        if( ( dir=opendir(inputData.fileList[i].c_str()))!=NULL){
            cout_<<"NEW DIR#1 "<<inputData.fileList[i]<<endl;
            readDirectoryToArray(inputData.fileList, inputData.fileList[i],"img");
            i++; continue;
        }
        //cout_<<"NEW START"<<endl;
        
        inputData.data["inputFile"]=inputData.fileList[i];
        int statusFork=forkImageProcess(pidIDArray,maxFork,ID);
        if(statusFork==0){
            wait(&status);sleep(1);  //пробуем подождать
            cout<<"fork error. Try to continue;"<<endl;
            continue;
        }
        if(statusFork==3)i++;  //пропускаем битую картинку
        countFork++;
        i++;
        if(i==inputData.fileList.size())break;
        
        cout_<<" pidIDArray[0].status= "<<pidIDArray[0].status<<" >> ";
        for(int index=0;index<maxFork;index++)cout_<<pidIDArray[index].status<<" ";
        cout_<<endl;
        
        ID=100;
        while(ID==100){
            if(countFork<maxFork-1)break;             //есть свободные слоты для новых процессов
            int forkStatusCount=0;
            for(int index=0;index<maxFork;index++){   //подсчитываем количество активных процессов
                if(pidIDArray[index].status==1)forkStatusCount++;
            }
            if(forkStatusCount==countFork){sleep(1);continue;}     //нет завершенных процессов
            wait(&status);                           //регистрируем с системе завершенный процесс
            countFork--;
            for(int index=0;index<maxFork;index++){  //маркируем слот как свободный
                //cout_<<"pidIDArray["<<index<<"].status="<<pidIDArray[index].status<<endl;
                if(pidIDArray[index].status==0){
                    
                    ID=index;
                    pidIDArray[index].status=1;
                    break;
                }
            }
            
        }
    }
    
	
#else
    DIR *dir;
    int printIndex=0;
    string path0="";
    string path1="";

    string mode="tif";
    GBitmap *printPage0;
    GBitmap *printPage1;

	for(int i=0;i<inputData.fileList.size();i++){
        cout<<"inputData.fileList["<<i<<"]="<<inputData.fileList[i]<<END;
        if( ( dir=opendir(inputData.fileList[i].c_str()))!=NULL){
            cout_<<"NEW DIR#1 "<<inputData.fileList[i]<<endl;
            readDirectoryToArray(inputData.fileList, inputData.fileList[i],"img");
            continue;
        }
        cout<<"NEW START"<<endl;
        inputData.data["inputFile"]=inputData.fileList[i];
        pechaImg=LoadImageData(inputData.data["inputFile"],0);
        proccessImage(pechaImg);
        if(inputData.data["fileSave"]=="print3_Pages"){
            //if(pechaImg->rows()<1200||pechaImg->rows()>1300)pechaImg->scaleFast((float)1216/pechaImg->rows());
            cout<<"printIndex="<<printIndex<<" pechaImg->rows()="<<pechaImg->rows()<<endl;

            
            if(printIndex==0){
                path=str_replace(".jpg", ".tif", inputData.data["inputFile"]);
                path=str_replace(".JPG", ".tif", path);
                path=str_replace(".jpg", ".tif", path);
                if(path.find(".tif")==-1)path=path+".tif";
                path0=str_replace(".tif", "_print0.tif", path);
                path1=str_replace(".tif", "_print1.tif", path);
                printPage0=GBitmap::create(pechaImg->columns(),pechaImg->rows()*3);
                printPage1=GBitmap::create(pechaImg->columns(),pechaImg->rows()*3);

                printPage0->drawImg(pechaImg,0, 0);
            }
            if(printIndex==1){
                cout<<" pechaImg->rows()*2="<<pechaImg->rows()*2<<endl;
                printPage1->drawImg(pechaImg,0, pechaImg->rows()*2);
            }
            
            if(printIndex==2){
                printPage0->drawImg(pechaImg,0, pechaImg->rows());
            }
            if(printIndex==3){
                printPage1->drawImg(pechaImg,0, pechaImg->rows());
            }
            if(printIndex==4){
                printPage0->drawImg(pechaImg,0, pechaImg->rows()*2);
            }
            if(printIndex==5){
                printPage1->drawImg(pechaImg,0, 0);
            }
            if(printIndex==5||i==inputData.fileList.size()-1){            //cout_<<" path="<<path<<endl;
                WriteImageData(printPage0,path0,0,mode);
                WriteImageData(printPage1,path1,0,mode);
                printPage0->destroy();
                printPage1->destroy();
                printIndex=-1;
            }
            printIndex++;
        }
        if(inputData.data["fileSave"]=="print3Pages"){
            //if(pechaImg->rows()<1200||pechaImg->rows()>1300)pechaImg->scaleFast((float)1216/pechaImg->rows());
            cout<<"printIndex="<<printIndex<<" pechaImg->rows()="<<pechaImg->rows()<<endl;
            int dY=21;
            int dX=21;
            
            if(printIndex==0){
                path=str_replace(".jpg", ".tif", inputData.data["inputFile"]);
                path=str_replace(".JPG", ".tif", path);
                path=str_replace(".jpg", ".tif", path);
                if(path.find(".tif")==-1)path=path+".tif";
                path0=str_replace(".tif", "_print0.tif", path);
                path1=str_replace(".tif", "_print1.tif", path);
                printPage0=GBitmap::create(pechaImg->columns(),pechaImg->rows()*2);
                printPage1=GBitmap::create(pechaImg->columns(),pechaImg->rows()*2);
                
                printPage0->drawImg(pechaImg,-dX, -dY);
            }
            if(printIndex==1){
                cout<<" pechaImg->rows()="<<pechaImg->rows()<<endl;
                printPage1->drawImg(pechaImg,-dX, pechaImg->rows()+dY);
            }
            
            if(printIndex==2){
                printPage0->drawImg(pechaImg,-dX, pechaImg->rows()+dY);
            }
            if(printIndex==3){
                printPage1->drawImg(pechaImg,-dX, -dY);
            }
           
            if(printIndex==3||i==inputData.fileList.size()-1){            //cout_<<" path="<<path<<endl;
                WriteImageData(printPage0,path0,0,mode);
                WriteImageData(printPage1,path1,0,mode);
                printPage0->destroy();
                printPage1->destroy();
                printIndex=-1;
            }
            printIndex++;
        }
        pechaImg->destroy();
    }
	
#endif
    //inputData.c_out.close();
    
    
	
}//______________________________________________
Пример #9
0
void GImageEditor::proccessImage(GBitmap *pechaImg_){
    
    if(inputData.data["action"]=="splitPages")inputData.data["SplitPage"]="splitPage";
	
	vector<stringOCR>strArray;
    if(inputData.data["SplitPage"]=="splitPage"){
		cout<<"SplitPage"<<endl;
		strArray.resize(0);
        int x=pechaImg_->columns()/6;
        int y=0;
        int w=(pechaImg_->columns()*4)/6;
        int h=pechaImg_->rows();
		GBitmap *pechaImgResize=GBitmap::createRegion(pechaImg_, x, y, w, h);
        GBitmap *pechaImgRotate=GBitmap::createRotate(pechaImgResize,-90);
        pechaImgResize->destroy();
        float angle=pechaImgRotate->detectPageAngle(8);
        pechaImgRotate->destroy();
        pechaImgRotate=GBitmap::createRotate(pechaImg,-angle);
        
		setBit=GBitset::createResize(pechaImgRotate,1,1,1);
		setBit->SplitPagesBtn=1;
		setBit->pageStringDetector(strArray,2);
        cout<<"TurnXL="<<setBit->TurnX<<" border="<<setBit->border_size()<<" w="<<setBit->columns()<<endl;
		//WriteImageData(setBit->drawData,"/_Image2OCR/1.jpg", 1); //exit(0);
		string st=inputData.data["inputFile"];
		string name=st.erase(0,st.rfind('/'));
		string ext=name;
		ext=ext.erase(0,ext.rfind('.'));
		name=name.erase(name.size()-ext.size(),ext.size());
		string folderName=inputData.data["inputFile"];
        folderName=folderName.erase(folderName.rfind('/'),folderName.size()); //cout_<<" st@@@"<<folderName<<END;
		st=folderName; st+="/"; st+=name; st+="_0"; st+=ext;
		WriteSpreadData(pechaImgRotate,setBit,-1, st); // , strArray
		st=folderName;
		st+="/"; st+=name; st+="_1"; st+=ext;  // cout_<<" st"<<st<<END;
		WriteSpreadData(pechaImgRotate,setBit,-2, st); // , strArray
		pechaImgRotate->destroy();
		setBit->destroy();
        return;
		
	}
	if(inputData.data["SplitPage"]=="splitColumns"){
        /*Для определения середины страницы вырезаем ценральную область страницы 2/3 ширины)
         затем поворачиваем на 90 градучов и исправляем наклон, определяя его по центральной области страницы
         всю страницу поворачиваем на нужный угол. В получившейся ровной странице ищем разделение на колонки.
         Лучшие результаты при наличии разделительной линии между колонками.
         */
		cout<<"splitColumns"<<END;
		strArray.resize(0);
        int x=pechaImg_->columns()/6;
        int y=0;
        int w=(pechaImg_->columns()*4)/6;
        int h=pechaImg_->rows();
		GBitmap *pechaImgResize=GBitmap::createRegion(pechaImg_, x, y, w, h);
        GBitmap *pechaImgRotate=GBitmap::createRotate(pechaImgResize,-90);
        pechaImgResize->destroy();
        float angle=pechaImgRotate->detectPageAngle(8);
        pechaImgRotate->destroy();
        pechaImgRotate=GBitmap::createRotate(pechaImg,-angle);
        //WriteImageData(pechaImgRotate,"/test.jpg", 1);
        
        setBit=GBitset::createResize(pechaImgRotate,1,1,1);
		setBit->SplitPagesBtn=1;
		setBit->pageStringDetector(strArray,1);
#ifdef DEBUGLVL_GREY
        WriteImageData(setBit->drawData,"/1.jpg", 0);
#endif
#ifdef DEBUGLVL_DRAW
        WriteImageData(setBit->drawDataRGB,"/1.jpg", 0);
#endif
        
        //  ДЛЯ ПОКАЗА КАРТИНКИ
		//if(CheckBoxTIFF->Checked==true){ext=".tif";}
		//if(AutoRemoveBorderBtn->Checked==true){
		string st=inputData.data["inputFile"];
		string name=st.erase(0,st.rfind('/'));
		string ext=name;
		ext=ext.erase(0,ext.rfind('.'));
		name=name.erase(name.size()-ext.size(),ext.size());
        st=inputData.data["inputFile"];
        st.erase(st.rfind('/'),st.size());
		st+="/";
        inputData.data["outputFolder"]=st;
        st+=name; st+="_0"; st+=ext;   cout<<" st"<<st<<END;
		WriteSpreadData(pechaImgRotate,setBit,-1, st); // , strArray
        st=inputData.data["outputFolder"];
        st+=name; st+="_1"; st+=ext;   cout<<" st"<<st<<END;
		WriteSpreadData(pechaImgRotate,setBit,-2, st); // , strArray
		setBit->destroy();
        pechaImgRotate->destroy();
        cout<<"done split";
        exit(0);
		
	}
    

    if(inputData.data["SplitPage"]=="eraseBorder"){
        int pageBorderX=atoi(inputData.data["BorderX"].c_str());
		int pageBorderY=atoi(inputData.data["BorderY"].c_str());

		cout<<"pageBorderX="<<pageBorderX<<"pageBorderY="<<pageBorderY<<END;
		pechaImg_->eraseBorder(pageBorderX,pageBorderY); // , strArray
	}

	//cout_<<"inputData.data[\"rotationBox\"]"<<inputData.data["rotationBox"]<<END;
    
    float scale=atoi(inputData.data["scale"].c_str());
    scale/=100;
    
	
	if(inputData.data["action"]=="baseNormalisation"){
        adaptiveFiltration1(pechaImg_,scale,1);
	}
    
    if(inputData.data["action"]=="adaptiveFiltration"){
        adaptiveFiltration1(pechaImg_,scale,2);
	}

    if(inputData.data["action"]=="alignContent"||inputData.data["action"]=="crop"){
        /*Для выравнивания страницы:
         0. Стираем мусор по краю страницы
         1. Уменьшаем страницу в 3 раза для оптимизации выделения строк.
         2. Определяем верхнюю и нижнюю строки
         3. Поворачиваем страницу на 90 градусов
         4. Определяем левую и правую границу текста 
         5. Рисуем центральную область по центру пустой страницы*/
		cout<<"alignContent"<<END;
		strArray.resize(0);
        pechaImg_->eraseBorder(25,25); // , strArray
        
        
		GBitmap *pechaImgResize=GBitmap::createScale(pechaImg_,0.5);
        pechaImgResize->gaussian(5);
        GBitmap *pechaImgRotate=GBitmap::createRotate(pechaImgResize,-90);
        
        setBit=GBitset::createResize(pechaImgResize,1,1,1);
        setBit->pageStringDetector(strArray,1);// Подпрограмма управления последовательностью выполнения всех подпрограмм (их 7 штук).
        //WriteImageData(pechaImgResize,"/_Image2OCR/1.jpg", 0); exit(0);
        
        if(!strArray.size())return;
        int pageY0=strArray[strArray.size()-1].y0-140;   pageY0*=2;  if(pageY0<0)pageY0=0;
        int pageY1=strArray[0].y1+140;                   pageY1*=2;  if(pageY1>pechaImg_->rows())pageY1=pechaImg_->rows();
        
#ifdef DEBUGLVL_GREY
        WriteImageData(setBit->drawData,"/_Image2OCR/1.jpg", 0);
#endif
#ifdef DEBUGLVL_DRAW
        WriteImageData(setBit->drawDataRGB,"/_Image2OCR/1.jpg", 0);
#endif
                
        
        int pageH=pageY1-pageY0;
        strArray.resize(0);
        setBit->destroy();
        setBit=GBitset::createResize(pechaImgRotate,1,1,0);
        setBit->pageStringDetector(strArray,1);  // это  надо мерить длинну строки при 90 гр повороте и короткие не учитывать  у нас гдето считактся длинна строки
        // что имеется в виду? количество квадратиков? можно и так несколько квадратиков в строке и она не учитывается.
        // но как тогда будет рамка распознаватся? в ней вообще квадратиков нет В ообше надо не спешить а подумать алгоритмы любят когда их думают
        // да и прыгает она не многое.
        //Можно выравнять по правому краю, там нет букв,  только номер     видел справа целое слово
        // для данной книги можно  по правому краю и подумать дальше. ок.
        //
        if(!strArray.size())return;
        int pageX0=strArray[strArray.size()-1].y0-50;   pageX0*=2; if(pageX0<0)pageX0=0;
        int pageX1=strArray[0].y1+50;                   pageX1*=2; if(pageX1>pechaImg_->columns())pageX0=pechaImg_->columns();
        int pageW=pechaImg_->columns();
        GBitmap *pageContent=GBitmap::createRegion(pechaImg_, 0, pageY0, pageW, pageH);
        pechaImg_->fill(255);
        if(inputData.data["action"]=="alignContent"){
            pechaImg_->drawImg(pageContent, 0, (pechaImg_->rows()-pageH)/2);
            pageContent->destroy();
        }
        if(inputData.data["action"]=="crop"){
            pechaImg_=pageContent;
        }
        
		setBit->destroy();
        pechaImgRotate->destroy();
        pechaImgResize->destroy();
	}

    
    if(inputData.data["fileSave"]=="saveTif"){    
        string mode="tif";
        string path=str_replace(".jpg", ".tif", inputData.data["inputFile"]);
        path=str_replace(".JPG", ".tif", path);
        path=str_replace(".jpg", ".tif", path);
        if(path.find(".tif")==-1)path=path+".tif";
        //cout_<<" path="<<path<<endl;
        WriteImageData(pechaImg_,path,0,mode);
    }
    if(inputData.data["fileSave"]=="saveOriginal"){
        WriteImageData(pechaImg_,inputData.data["inputFile"],0);
    }

}