void closing(char A[MAX_MN][MAX_MN+1], char B[MAX_B][MAX_B+1], char C[MAX_MN][MAX_MN+1]) { char temp[MAX_MN][MAX_MN+1]; dilation(A, B, temp); erosion(temp, B, C); }
static void bothat( const std::vector<ValueT> & input, std::vector<ValueT> & output, const UInt struc_elem_length ) { const Int size = Int(input.size()); std::vector<ValueT> closing; dilation(input,output,struc_elem_length); erosion(output,closing,struc_elem_length); for ( Int index = 0; index < size; ++ index ) { output[index] = input[index] - closing[index]; } return; }
Mat IITkgp_functions::Morphology::boundaryextraction(Mat image) { int i,j; Mat erodedimage; Mat extractedimage; image.copyTo(erodedimage); image.copyTo(extractedimage); int row,col; row = image.rows; col = image.cols; for(i=0;i<row;i++) { for(j=0;j<col;j++) { erodedimage.data[i*col+j] = 255; extractedimage.data[i*col+j] = 255; } } erodedimage=erosion(image); for(i=0;i<row;i++) { for(j=0;j<col;j++) { if(image.data[i*col+j]==erodedimage.data[i*col+j]) extractedimage.data[i*col+j]=255; else extractedimage.data[i*col+j]=0; } } return(extractedimage); }
Imlib_Image opening(Imlib_Image *source_image,double thresh,luminance_t lt,int n) { int i; Imlib_Image temp_image1, temp_image2; /* erosion n times */ imlib_context_set_image(*source_image); temp_image1 = temp_image2 = imlib_clone_image(); for(i=0; i<n; i++) { temp_image2 = erosion(&temp_image1, thresh, lt); imlib_context_set_image(temp_image1); imlib_free_image(); temp_image1 = temp_image2; } /* dilation n times */ for(i=0; i<n; i++) { temp_image2 = dilation(&temp_image1, thresh, lt); imlib_context_set_image(temp_image1); imlib_free_image(); temp_image1 = temp_image2; } return temp_image2; }
void ProcessFrame(uint8 *pInputImg) { uint8_t thres = (uint8_t)data.ipc.state.nThreshold; /* if the threshold is 0, the otsu algorithm is used */ if(thres == 0) { thres = otsu(IMAGE(GRAYSCALE)); } data.ipc.state.thres_calc = thres; /* make the threshold image */ thresh(IMAGE(THRESHOLD), IMAGE(GRAYSCALE), thres); /* dilation */ dilation(IMAGE(DILATION), IMAGE(THRESHOLD)); /* erosion */ erosion(IMAGE(EROSION), IMAGE(DILATION)); /* do the region labeling stuff */ region_labeling(IMAGE(LABELIMG)); }
//TODO: //TODO: Use libnoise http://libnoise.sourceforge.net/tutorials/index.html !!! //TODO: void generate() { //set crop height and width if (crop_height < 1) crop_height = tmap_size; if (crop_width < 1) crop_width = tmap_size; //if a crop value is set //set tmap_size to fit the cropped values int max_size = std::max(crop_height, crop_width); int max_size_tmp = max_size - 1; if ((max_size_tmp & (max_size_tmp - 1)) == 0) { //leave set size as highest crop value tmap_size = max_size; } else { //find smallest value such that (value is power of 2) + 1 and value > max_size int t = ceil(log2(max_size)) + 1; tmap_size = (1 << t) + 1; } double finish = 0; //display info if (verbose) { std::cout << "Using " << config_file << std::endl; std::cout << "Staring square diamond" << std::endl; std::cout << "Size: " << crop_width << " x " << crop_height << " original size " << tmap_size << std::endl; std::cout << "Starting seed value " << seed << std::endl; std::cout << "Starting random offset " << random_offset << std::endl; std::cout << "Random offset decrease ratio " << offset_dr << std::endl; } //init map array tmap = new int*[tmap_size]; for (int i = 0; i < tmap_size; ++i) { tmap[i] = new int[tmap_size]; for (int j = 0; j < tmap_size; j++) tmap[i][j] = 0; } // initialize random seed: // use for generating a random map every time // srand ( time(NULL) ); //harcoded for now as produces a nice map for testing srand(12); //fill the array with values square_diamond(); //interpolate voronoi diagram //TODO: add noise to voronoi if (verbose) { std::cout << "Voronoi points " << voronoi_size << std::endl; /* for (int i = 0; i < voronoi_size; ++i) { std::cout << "\t" << voronoi_points[i][0] << "," << voronoi_points[i][1] << std::endl; } */ } voronoi(); erosion(); if (!neg) clear_neg(); // finish = clock() - start; if (verbose) std::cout << "Finished square diamond " << (finish / 1000000) << std::endl; double sqadia = (finish / 1000000); if (normalise) { if (verbose) std::cout << "Normalising with value range " << normalise_min << "-" << normalise_max << std::endl; normalise_map(); } if (output_format == STANDRARD_HEIGHTS) { print_map(fopen(output_file.c_str(), "w")); } else if (output_format == STANDARD_XML) { print_map_xml(fopen(output_file.c_str(), "w")); } if (scale > 0 && crop_height > 256 && crop_width > 256) { // start = clock(); if (verbose) std::cout << "Generating rivers" << std::endl; rivers(); // finish = clock() - start; if (verbose) std::cout << "Done " << (finish / 1000000) << std::endl; double rivers_time = (finish / 1000000); print_rivers(0); // start = clock(); if (verbose) std::cout << "Generating vegetation" << std::endl; vegetation(verbose); // finish = clock() - start; if (verbose) std::cout << "Done " << (finish / 1000000) << std::endl; double veg_time = (finish / 1000000); print_vegetation(0); if (verbose) std::cout << "Generating settlements" << std::endl; settlements(); // finish = clock() - start; if (verbose) std::cout << "Done " << (finish / 1000000) << std::endl; double settlement_time = (finish / 1000000); print_settlements(0); std::cout << crop_height << "\t" << (sqadia + rivers_time + veg_time + settlement_time) << "\t" << sqadia << "\t " << rivers_time << "\t" << veg_time << "\t" << settlement_time << std::endl; } std::cout << "Drawing contours" << std::endl; contour_map(32, 32, verbose); print_contour(0); print_kf(0); }
main () { int i,j,k; for (i=0; i < PICTURE_VERTICAL_SIZE; i++) { for (j=PICTURE_HORIZONTAL_OFFSET; j < PICTURE_HORIZONTAL_SIZE+PICTURE_HORIZONTAL_OFFSET; j++) { image_original[i][j-PICTURE_HORIZONTAL_OFFSET] = Y_test[i][j]; } } for (i=0; i < PICTURE_VERTICAL_SIZE; i++) { for (j=PICTURE_HORIZONTAL_OFFSET; j < PICTURE_HORIZONTAL_SIZE+PICTURE_HORIZONTAL_OFFSET; j++) { image_test[i][j-PICTURE_HORIZONTAL_OFFSET] = Y_test[i][j]; } } for (i=0; i < PICTURE_VERTICAL_SIZE; i++) { for (j=PICTURE_HORIZONTAL_OFFSET; j < PICTURE_HORIZONTAL_SIZE+PICTURE_HORIZONTAL_OFFSET; j++) { image_back[i][j-PICTURE_HORIZONTAL_OFFSET] = Y_back[i][j]; } } printf("Starting Motion Detection Application: \n\n"); printf("__attribute__((section(\".heapl2ram\"))) pixel Y_back[%d][%d] = \n{\n",PICTURE_VERTICAL_SIZE,PICTURE_HORIZONTAL_SIZE); print_image_vect((pixel*)image_back); printf("};\n"); printf("__attribute__((section(\".heapl2ram\"))) pixel Y_test[%d][%d] = \n{\n",PICTURE_VERTICAL_SIZE,PICTURE_HORIZONTAL_SIZE); print_image_vect((pixel*)image_test); printf("};\n"); printf("Subtraction and binarization treshold \n\n"); sub_image((pixel*)image_test, (pixel*)image_back); print_image((pixel*)image_test); max_pixel= max_image((pixel*)image_test); printf("Max pixel = %d \n\n",max_pixel); printf("Binarization \n\n"); binarisation((pixel*)image_test, (int)max_pixel*3/10,1,0); print_image((pixel*)image_test); printf("Erosion \n\n"); erosion((pixel*)image_test,KERNEL_SIZE,(pixel*)image_back); print_image((pixel*)image_back); printf("Dilatation \n\n"); dilatation((pixel*)image_back,KERNEL_SIZE ,(pixel*)image_test_out); print_image((pixel*)image_test_out); printf("Sobel Horizontal \n\n"); convolution_rect((pixel*)image_test_out, KERNEL_SIZE, sobel1,(pixel*)image_test); val_abs((pixel*)image_test); print_image((pixel*)image_test); printf("Sobel Vertical \n\n"); convolution_rect( (pixel*)image_test_out, KERNEL_SIZE, sobel2,(pixel*)image_back); val_abs((pixel*)image_back); print_image((pixel*)image_back); printf("Final Sum \n\n"); sum_image((pixel*)image_test, (pixel*)image_back); binarisation((pixel*)image_test, 1,0,1); print_image((pixel*)image_test); printf("Final Multiplication \n\n"); multiply((pixel*)image_test, (pixel*)image_original); printf("__attribute__((section(\".heapl2ram\"))) pixel Y_golden[%d][%d] = \n{\n",PICTURE_VERTICAL_SIZE,PICTURE_HORIZONTAL_SIZE); print_image_vect((pixel*)image_test); printf("};\n\n"); printf("Motion Detection Application Completed\n"); }
closing(unsigned char **image_pixel,int height,int width) { dilation(image_pixel,height,width); erosion(image_pixel,height,width); }
int main(int argc, char* argv[]) { // check if the argument number is valid if (argc < 4) { std::cerr << "Usage: " << argv[0] << " input-file output-file [operations] [parameters]" << std::endl; return 1; } // check if the input file is valid std::ifstream input(argv[1]); if (!input) { std::cerr << "Can not open the grades in file " << argv[1] << std::endl; return 1; } // read in the image std::vector<std::string> image; read_in_image(input, image); if (image.size() == 0) { std::cout << "Cannot import the image " << argv[1] << ". Try again please. " << std::endl; return 1; } std::ofstream output(argv[2]); // the output file std::string op = argv[3]; // the operation name if (op.compare("replace") == 0 && argc == 6) { // replace char before = argv[4][0]; char after = argv[5][0]; replace(image, before, after); } else if (op.compare("dilation") == 0 && (argc == 5 || argc == 6)) { // dilation operation char color = argv[4][0]; if (argc == 5) { // When plus-signed structing element dilation(image, color, false); } else if (argc == 6 && std::string(argv[5]).compare("square") == 0) { // when square-signed structing element dilation(image, color, true); } else { std::cerr << "Usage: " << argv[0] << " input-file output-file dilation color [square]" << std::endl; return 1; } } else if (op.compare("erosion") == 0 && (argc == 6 || argc == 7)) { // erosion operation char color = argv[4][0]; char pixel = argv[5][0]; if (argc == 6) { // When plus-signed structing element erosion(image, color, pixel, false); } else if (argc == 7 && std::string(argv[6]).compare("square") == 0) { // when square-signed structing element erosion(image, color, pixel, true); } else { std::cerr << "Usage: " << argv[0] << " input-file output-file erosion pixel [square]" << std::endl; return 1; } } else if (op.compare("floodfill") == 0 && argc == 7) { // floodfill operation int row = atoi(argv[4]); int col = atoi(argv[5]); if (!isValid(image, row, col)) { std::cerr << "Error: invalid arguments " << row << " and " << col << std::endl; return 1; } char filler = argv[6][0]; flood_fill(image, row, col, filler); } else { // invalid input command std::cerr << "Invalid command." << std::endl; std::cerr << "Usage: " << argv[0] << " input-file output-file [operations] [parameters]" << std::endl; return 1; } // write the modified image to a file if (output.is_open()) { output_image(image, output); output.close(); } else { std::cerr << "Cannot output to " << argv[3] << std::endl; return 1; } return 0; }
main( int argc, char **argv ) { int silent_mode, // Option for silent mode (no time output to stdout) optDetachLim, // Option for detachment-limited erosion only optMeander, // Option for stream meandering optFloodplainDep, // Option for floodplain (overbank) deposition optLoessDep, // Option for eolian deposition optDiffuseDepo; // Option for deposition / no deposition by diff'n tStreamMeander *meander; // -> meander object tFloodplain *floodplain; // -> floodplain object tEolian *loess; // -> eolian deposition object ofstream oefile; /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments if( argc<2 ) { cerr << "Usage: " << argv[0] << " <input file>" << endl; ReportFatalError( "You need to give the name of an input file." ); } // Check whether we're in silent mode silent_mode = ( argc>2 && argv[2][1]=='s' ); // Say hello cout << "\nThis is CHILD, version " << VERSION << endl << "Geoarchaeology special version 1.0" << endl << endl; // Open main input file tInputFile inputFile( argv[1] ); // Create and initialize objects: cout << "Creating mesh...\n"; tMesh<tLNode> mesh( inputFile ); cout << "Creating output files...\n"; tLOutput<tLNode> output( &mesh, inputFile ); tStorm storm( inputFile ); cout << "Creating stream network...\n"; tStreamNet strmNet( mesh, storm, inputFile ); tErosion erosion( &mesh, inputFile ); tUplift uplift( inputFile ); cout << "Writing data for time zero...\n"; tRunTimer time( inputFile, !silent_mode ); output.WriteOutput( 0 ); cout << "Initialization done.\n"; // Get various options optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" ); optMeander = inputFile.ReadItem( optMeander, "OPTMNDR" ); optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" ); optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" ); optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" ); // If applicable, create stream meander object if( optMeander ) meander = new tStreamMeander( strmNet, mesh, inputFile ); // If applicable, create floodplain object if( optFloodplainDep ) floodplain = new tFloodplain( inputFile, &mesh ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // For Geoarchaeology special application double kr = inputFile.ReadItem( kr, "KR" ); double drop = inputFile.ReadItem( drop, "GA_VALDROP" ); double inletElev = inputFile.ReadItem( inletElev, "GA_INLETELEV" ); double meanInletElev = inletElev; double period = inputFile.ReadItem( period, "GA_PERIOD" ); int optwave = inputFile.ReadItem( optwave, "GA_OPTWAVE" ); double amplitude = inputFile.ReadItem( amplitude, "GA_AMPLITUDE" ); double tpeak, mr, mf, ttime, oldar1, noise0, noise1; int numpts; //number of points in the floodplain curve int fpindex=0;//where are you in the floodplain data double fpslope;//slope of floodplain curve double chanslp;//slope of channel, read in if optwave==2 vector<double> fpht; vector<double> fptime; if( optwave==0 ) period = 2.0 * PI / period; else if( optwave==1 ) { tpeak = inputFile.ReadItem( tpeak, "GA_TPEAK" ); if( tpeak<=0.0 || tpeak>=1.0 ) ReportFatalError("GA_TPEAK must be between 0 and 1 (not inclusive"); tpeak = tpeak*period; mr = amplitude/tpeak; mf = amplitude/(period-tpeak); oldar1=0; noise0=0; noise1=0; oefile.open("Geoarch/outletelev"); } else if( optwave==2){ numpts=inputFile.ReadItem( numpts, "NUMFLDPLNPTS" ); fpht.assign( numpts,0 ); fptime.assign( numpts,0 ); int i=0; char add='1'; char add2='0'; char name[30]; double help; double inittime; chanslp=inputFile.ReadItem(chanslp, "CHANSLOPE" ); cout<<"channel slope is "<<chanslp<<endl; inittime=inputFile.ReadItem(inittime, "INPUTTIME" ); while (i<numpts){ if(i<9){ strcpy(name, "FLDPLNTIME" ); strcat(name, &add ); help=inputFile.ReadItem(help,name); fptime[i]=help+inittime; cout<<"index "<<i<<" fldplntime "<<fptime[i]; strcpy(name, "FLDPLNHT" ); strcat(name, &add ); help=inputFile.ReadItem(help,name); fpht[i]=help; cout<<" fldplnht "<<fpht[i]<<endl; i++; add++; } if(i>=9){ add='1'; strcpy(name, "FLDPLNTIME" ); strcat(name, &add ); strcat(name, &add2 ); help=inputFile.ReadItem(help,name); fptime[i]=help; cout<<"index "<<i<<" fldplntime "<<fptime[i]; strcpy(name, "FLDPLNHT" ); strcat(name, &add ); strcat(name, &add2 ); help=inputFile.ReadItem(help,name); fpht[i]=help; cout<<" fldplnht "<<fpht[i]<<endl; i++; add2++; } } fpslope=(fpht[fpindex+1]-fpht[fpindex])/(fptime[fpindex+1]-fptime[fpindex]); oefile.open("Terraces/outletelev"); } int numg = inputFile.ReadItem( numg, "NUMGRNSIZE" ); //if( numg<2 ) ReportFatalError("Must use at least 2 sizes with GA." ); vector<double> deparr; deparr.assign( numg,0 ); int i; for( i=0; i<numg; i++ ) deparr[i] = 0.0; assert( strmNet.getInletNodePtr() != 0 ); /**************** MAIN LOOP ******************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Meandering (if applicable) ** Floodplain deposition (if applicable) ** Do interstorm... ** Hillslope transport ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ while( !time.IsFinished() ) { time.ReportTimeStatus(); // Do storm... storm.GenerateStorm( time.getCurrentTime(), strmNet.getInfilt(), strmNet.getSoilStore() ); //cout << storm.getRainrate() << " " << storm.getStormDuration() << " " // << storm.interstormDur() << endl; //cin >> dbg; strmNet.UpdateNet( time.getCurrentTime(), storm ); // Addition for Geoarchaeology model: set erodibility of main // stream to zero and set its profile elevations as a boundary // condition tMeshListIter<tLNode> nodeIter( mesh.getNodeList() ); tLNode *cn; double elev, totlen; // Start by resetting erodibility for all nodes; will be overridden // to zero for main channel nodes for( cn=nodeIter.FirstP(); nodeIter.IsActive(); cn=nodeIter.NextP() ) cn->setLayerErody( 0, kr ); // Set the new drop elevation if( optwave==0 ) { inletElev = drop + amplitude * sin( period*time.getCurrentTime() ); //cout << "Inlet " << inletElev << " at " << time.getCurrentTime() << endl; } else if( optwave==1 ) { noise1=(0.99*noise0+drand48()-0.5)*0.9; ttime = fmod( time.getCurrentTime(), period ); if( ttime<=tpeak ) inletElev = drop + mr*ttime + noise1; else inletElev = drop + amplitude - mf*(ttime-tpeak) + noise1; noise0=noise1; oefile<<noise1<<endl; } else if( optwave==2 ) { if(time.getCurrentTime()>=fptime[fpindex] && time.getCurrentTime()<fptime[fpindex+1]){ //slope and index don't need to be changed, just calculate elev inletElev = fpht[fpindex] + fpslope*(time.getCurrentTime()-fptime[fpindex]); } else{ //calculate new slope and update index fpindex++; fpslope=(fpht[fpindex+1]-fpht[fpindex])/(fptime[fpindex+1]-fptime[fpindex]); inletElev = fpht[fpindex] + fpslope*(time.getCurrentTime()-fptime[fpindex]); } cout<<"fhpt = "<<fpht[fpindex]<<" fpslope "<<fpslope<<" current time "<<time.getCurrentTime()<<" fptime "<<fptime[fpindex]<<endl; oefile<<inletElev<<endl; } // Find the total length of the main channel and compute slope if( optwave<2){ cn = strmNet.getInletNodePtr(); totlen = 0.0; do { cn->setLayerErody( 0, 0.0 ); // Main channel elev is a B.C., thus unerodible totlen += cn->getFlowEdg()->getLength(); cn = cn->getDownstrmNbr(); } while( cn->getBoundaryFlag()==kNonBoundary ); chanslp = drop/totlen; } // Now set elevations along main channel elev = inletElev; // starting at elevation at inlet cn = strmNet.getInletNodePtr(); // begin at inlet cn->setZ( inletElev ); // set inlet's elev do // work downstream along main channel, setting elevations { double delz; elev = elev - chanslp * cn->getFlowEdg()->getLength(); cn = cn->getDownstrmNbr(); delz = elev - cn->getZ(); while( delz < -0.1 ) { // Test: erode one active layer thick at a tm deparr[0] = -0.1; cn->EroDep( 0, deparr, time.getCurrentTime() ); delz += 0.1; } deparr[0] = delz; cn->EroDep( 0, deparr, time.getCurrentTime() ); } while( cn->getBoundaryFlag()==kNonBoundary ); //cout << "eroding...\n"; if( optDetachLim ) erosion.ErodeDetachLim( storm.getStormDuration() ); else erosion.DetachErode( storm.getStormDuration(), &strmNet, time.getCurrentTime() ); //cout << "meandering...\n"; if( optMeander ) meander->Migrate( time.getCurrentTime() ); //cout << "overbanking...\n"; if( optFloodplainDep ) floodplain->DepositOverbank( storm.getRainrate(), storm.getStormDuration(), time.getCurrentTime() ); // Do interstorm... //cout << "Doing diffusion\n"; erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(), optDiffuseDepo ); //cout << "exposure time...\n"; erosion.UpdateExposureTime( storm.getStormDuration() + storm.interstormDur() ); if( optLoessDep ) loess->DepositLoess( &mesh, storm.getStormDuration()+storm.interstormDur(), time.getCurrentTime() ); //cout << "Uplift\n"; if( time.getCurrentTime() < uplift.getDuration() ) uplift.DoUplift( &mesh, storm.getStormDuration() + storm.interstormDur() ); time.Advance( storm.getStormDuration() + storm.interstormDur() ); //cout << "Output\n"; if( time.CheckOutputTime() ) output.WriteOutput( time.getCurrentTime() ); } }
int main(int argc, char* argv[]) { //error messagea if (argc != 5 and argc != 6 and argc != 7) { std::cerr << "arguments can not be fit in" << argv[0] ; return 1; } std::string row; std::ifstream myFile(argv[1]); if (!myFile.good()) { std::cerr << "The file is not correct!" << argv[1] << "\n"; } //std::string row; //input each row to a string std::vector<std::string> inputs; //Input vectors to hold all the points while (std::getline(myFile, row)) { inputs.push_back(row); } std::cout << "The input:"<<std::endl; //print out the input for (unsigned int i = 0 ; i < inputs.size() ; ++i ) { std::cout << inputs[i] << std::endl; } ///////////starts to do the replace, dialation, erosion and floodfill std::vector<std::string> results; // create a vector called results for later print out // dilation if (argc == 5) { results = dilation(inputs, argv[4][0]); for (unsigned int i = 0 ; i < results.size() ; ++i ) { std::cout << results[i] << std::endl; } } //replace+erosion if (argc == 6) { std::string a = "replace"; std::string b = "erosion"; if (!a.compare(argv[3])) { results = replace(inputs, argv[4][0], argv[5][0]); } if (!b.compare(argv[3])) { results = erosion(inputs, argv[4][0], argv[5][0]); } } //floodfill if (argc ==7) { //convert the string in arguments to integers int r = atoi(argv[4]); int c = atoi(argv[5]); char temp = argv[6][0]; floodfill(inputs, r, c, temp); results = inputs; } std::cout << "The output:"<<std::endl; //print out the output for (unsigned int i = 0 ; i < results.size() ; ++i ) { std::cout << results[i] << std::endl; } //output to a file std::ofstream outputs; outputs.open(argv[2]); for (unsigned int i = 0 ; i < results.size() ; ++i) { outputs << results[i] <<"\n" ; } outputs.close(); return 0; }
void EndogenousSalienceThread::run(){ /* * Identify the modal hue and saturation values in the logpolar image, * segment the cartesian image accordingly, * identify the largest blob, extract the coordinates of the centroid, * package everything with the encoder values & the focal length values in a bottle, * and send it out (typically to the egosphere module) * send out the segmented image out for viewing */ unsigned char pixel_value; if (debug) { printf("endogenousSalienceThread: parameters are %d %d %d %d\n\n", *hueTolerance, *saturationTolerance, *hueBins, *saturationBins); } /* create the histogram */ if (hsHistogram == NULL) { hsHistogram = new DVhs_histogram(*hueBins, *saturationBins); } while (isStopping() != true) { // the thread continues to run until isStopping() returns true /* * Step 1: grab cartesian and logpolar images and copy images to local format * ========================================================================== */ if (debug) cout << "endogenousSalienceThread: grabbing images " << endl; do { cartesianImage = cartesianImagePortIn->read(true); } while ((cartesianImage == NULL) && (isStopping() != true)); if (isStopping()) break; // abort this loop to avoid make sure we don't continue and possibly use NULL images do { logpolarImage = logpolarImagePortIn->read(true); } while ((logpolarImage == NULL)&& (isStopping() != true)); if (isStopping()) break; // abort this loop to avoid make sure we don't continue and possibly use NULL images width = cartesianImage->width(); height = cartesianImage->height(); depth = 3; if (debug) printf("endogenousSalienceThread: width = %d, height = %d, depth = %d\n",width, height, depth); if (cartesianInput == NULL) { cartesianInput = new DVimage(width, height, depth); } if (segmentedOutput == NULL) { segmentedOutput = new DVimage(width, height, depth); } if (tempImageA == NULL) { tempImageA = new DVimage(width, height, depth); } if (tempImageB == NULL) { tempImageB = new DVimage(width, height, depth); } width = logpolarImage->width(); height = logpolarImage->height(); depth = 3; if (debug) printf("endogenousSalienceThread: width = %d, height = %d, depth = %d\n",width, height, depth); if (logpolarInput == NULL) { logpolarInput = new DVimage(width, height, depth); } width = cartesianImage->width(); height = cartesianImage->height(); for (x=0; x<width; x++) { for (y=0; y<height; y++) { rgbPixel = cartesianImage->safePixel(x,y); cartesianInput->put_pixel(x, y, rgbPixel.r, 0); cartesianInput->put_pixel(x, y, rgbPixel.g, 1); cartesianInput->put_pixel(x, y, rgbPixel.b, 2); } } width = logpolarImage->width(); height = logpolarImage->height(); for (x=0; x<width; x++) { for (y=0; y<height/2; y++) { // ***************************** only use the top half, i.e. the fovea rgbPixel = logpolarImage->safePixel(x,y); logpolarInput->put_pixel(x, y, rgbPixel.r, 0); logpolarInput->put_pixel(x, y, rgbPixel.g, 1); logpolarInput->put_pixel(x, y, rgbPixel.b, 2); } } /* * Step 2: Identify the modal hue and saturation values in the logpolar image * ========================================================================== * */ if (debug) cout << "endogenousSalienceThread: generating histogram " << endl; colour_histogram(logpolarInput, hsHistogram); if (true && debug) cout << "endogenousSalienceThread: identifying histogram mode " << endl; hsHistogram->hsMode(&hueMode, &saturationMode); /* * Step 3: segment the cartesian image * ===================================== */ if (debug) cout << "endogenousSalienceThread: performing segmentation " << endl; hueRange = (*hueTolerance * (float) 360) / (float) (100); // convert percentage to real values saturationRange = (*saturationTolerance) / (float) (100); colour_segmentation(cartesianInput, hueMode, saturationMode, hueRange, saturationRange, segmentedOutput); // Step 4: filter the colour_segmentation by performing an morphological opening // ============================================================================= if (debug) cout << "endogenousSalienceThread: post-segmentation filtering - morphological opening " << endl; if (*filterRadius > 0) { erosion (segmentedOutput, *filterRadius, tempImageA); dilation(tempImageA, *filterRadius, tempImageB); } // Step 5: filter the colour segmentation by performing a medial distance transform // ============================================================================= if (debug) cout << "endogenousSalienceThread: post-segmentation filtering - medial distance transform" << endl; distance_from_background_transform(tempImageB, segmentedOutput); segmentedOutput->contrast_stretch(); /* * Step 6: copy the segmented image to the salience image in YARP format and write it out * ====================================================================================== */ if (debug) cout << "endogenousSalienceThread: sending images " << endl; width = cartesianImage->width(); height = cartesianImage->height(); ImageOf<PixelRgb> &salienceImage = salienceImagePortOut->prepare(); salienceImage.resize(width,height); for (x=0; x < width; x++) { for (y=0; y < height; y++) { segmentedOutput->get_pixel(x, y, &pixel_value, 0); rgbPixel.r=pixel_value; segmentedOutput->get_pixel(x, y, &pixel_value, 1); rgbPixel.g=pixel_value; segmentedOutput->get_pixel(x, y, &pixel_value, 2); rgbPixel.b=pixel_value; salienceImage(x,y) = rgbPixel; } } if (isStopping()) break; // abort this loop to avoid make sure we don't continue and possibly use NULL images salienceImagePortOut->write(); } }
void test_run() { laplacian_filter(x, y, Nq); dilation(x, z, Nq); erosion(z, w, Nq); }
int main (int argc, char** argv) { double f; double vd; double r; int iter; double h; // argiment parsing if (pcl::console::parse_argument (argc, argv, "-r", r) >= 0) { MIN_DISTANCE = r; cout << "adjust the registration threshold to " << r << endl; } if (pcl::console::parse_argument (argc, argv, "-giter", iter) >= 0) { GITER = iter; cout << "adjust global alignment iterations to " << iter <<" iterations"<< endl; } if (pcl::console::parse_argument (argc, argv, "-hessian", h) >= 0) { HESSIAN=h; cout << "adjust SIFT matching threshold to " << h << endl; } if (pcl::console::find_argument (argc, argv, "-h") >= 0 || argc == 1) { printUsage (argv[0]); return 0; } if (pcl::console::find_argument (argc, argv, "-g") >= 0) { GLOBAL_FLAG = 1; cout << "Global Reistration is ON" << endl; } if (pcl::console::find_argument (argc, argv, "-lcoff") >= 0) { LOOP_CLOSURE = 0; cout << "Loop CLosure Detection is OFF" << endl; } if (pcl::console::find_argument (argc, argv, "-m") >= 0) { MLS = 1; cout << "Moving least square smoothing is ON" << endl; } if (pcl::console::find_argument (argc, argv, "-dn") >= 0) { DENOISING= 1; cout << "De-noising (statistic) is ON" << endl; } if (pcl::console::parse_argument (argc, argv, "-vd", vd) >= 0) { DEPTH_AVG = 1; cout << "Down-sampling is ON" << endl; if (vd>0.00001) { DOWN_SAMPLE = vd; cout<<"Down sample threshold is changed to "<<DOWN_SAMPLE<<endl; } } vector<PointCloud, Eigen::aligned_allocator<PointCloud> > data; vector<PointCloud, Eigen::aligned_allocator<PointCloud> > key3data; vector<vector<KeyPoint> > key2data; vector<pcl::CorrespondencesPtr> correspondencesdata; Mat previousrgb; vector<KeyPoint> previouskey2d; // read the rgb-d data one by one ifstream index; string root_dir = argv[1]; index.open (string(root_dir + "/input.txt").c_str()); int i = 0; while (!index.eof ()) { string file; index >> file; if (file.empty ()) break; file = root_dir + "/" + file; Mat rgbimg; Mat depimg; Mat mask; // read data readImg (file, "_rgb.png", rgbimg); readImg (file, "_depth.png", depimg); readImg (file, "_mask.png", mask); if (rgbimg.empty () || depimg.empty () || mask.empty ()) { printf ( "Error: The RGB-D file does not exit. Please note that the right format should be: \n"); printf ( "X_rgb.png, X_depth.png, X_mask.png with the same size. ('X' is your input) \n"); return (0); } if (rgbimg.size () != depimg.size () || rgbimg.size () != mask.size ()) { printf ( "Error: The RGB-D files are not consistent. The rgb, depth and mask images should have the same size. \n"); return (0); } cout << "loading: " << file << endl; // check the image size and the offest coordinate int x1, y1; if (rgbimg.rows == 480 && rgbimg.cols == 640) { // if the image is full size (480*640), no offset coordinate x1 = 0; y1 = 0; } else { // if not, read the offset file ifstream loc; string location1 = file + "_loc.txt"; loc.open (location1.c_str ()); if (!loc.is_open ()) { if (TOP_LEFT1!=0 && TOP_LEFT2!=0) { x1=TOP_LEFT2; y1=TOP_LEFT1; } else { cout << "Error! There is no associated off-set location file." << endl; return 0; } } else { char comma; loc >> x1 >> comma >> y1; } loc.close(); } // perform erosion to remove the noises around the boundary erosion (mask, 4); vector<KeyPoint> key2d; PointCloud pointcloud; PointCloud keypoints; // read data and perform surf feature matching read (rgbimg, depimg, mask, pointcloud, keypoints, key2d, x1, y1, HESSIAN); filter (pointcloud, 0.001, pointcloud); data.push_back (pointcloud); key3data.push_back (keypoints); key2data.push_back (key2d); // find the pairwise correspondecnes based on surf feature if (i >= 1) { pcl::CorrespondencesPtr correspondences (new pcl::Correspondences ()); //may have bugs?? vector<DMatch> good_matches; match (rgbimg, previousrgb, key2d, previouskey2d, good_matches, correspondences); correspondencesdata.push_back (correspondences); correspondences.reset (new pcl::Correspondences); } previousrgb = rgbimg; previouskey2d = key2d; i++; } index.close(); printf ("Loaded %d datasets.\n", (int) data.size ()); PointCloudPtr final (new PointCloud); vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > matrix_buffer; // registration: initial+fine+global //initialize the PCL viewer p = new pcl::visualization::PCLVisualizer (argc, argv, "3D Moeling example"); p->setSize (480, 640); p->setPosition (480, 200); // registration int first = 0; int last = 0; if (!LOOP_CLOSURE) { last=(int) data.size ()-1; } // need to change back double threshold = MIN_DISTANCE; for (int z = 0; z < GITER; z++) { vector<PointCloud, Eigen::aligned_allocator<PointCloud> > out; PointCloudPtr output (new PointCloud); PointCloudPtr final_temp (new PointCloud); if (GLOBAL_FLAG) { vector<PointCloud, Eigen::aligned_allocator<PointCloud> > out_global; if (z == 0) pairwiseAlign (data, correspondencesdata, key3data, *output, out, matrix_buffer, 1, threshold); else { pairwiseAlign (data, correspondencesdata, key3data, *output, out, matrix_buffer, 0, threshold); } // global optimization cout << endl << "Global optimization begins ... at iteration " <<z+1<< endl; globalAlign (out, final_temp, matrix_buffer, out_global, first, last); data = out_global; } else { pairwiseAlign (data, correspondencesdata, key3data, *output, out, matrix_buffer, 1, threshold); final = output; break; } threshold = threshold * 0.9; final = final_temp;
void main( int argc, char *argv[]) { int gdriver = DETECT, gmode, errorcode; UL pos,m; int x,y,couleur,i; if (argc != 2) { printf("Finger Recognition Module Version 1.01\n"); printf("Usage is : FingRun <file.bmp>\n"); exit(1); } // recopie des paramŠtres xwin = 3; ywin = 3; // initialise le mode graphique initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); if (errorcode != grOk) // erreur d‚tect‚e { Erreur = ErreurGraphique; printf("Erreur Graphique Code Nø %d \n",Erreur); exit(1); } if ((out = fopen("resu.dat", "wt"))== NULL) { fprintf(stderr, "Erreur … l'ouverture de Resu.dat\n"); exit(-1); } MaxX = getmaxx(); MaxY = getmaxy(); // Lecture du fichier image f_lectureFichier (argv[1],&Image); // Allocation de m‚moire pour les images ImageOut = (int huge*) farcalloc(Image.ligne*Image.colonne,(UL)sizeof(int)); if (ImageOut == NULL) { printf("Not enough memory for Image buffer allocation\n"); exit(-4); } Image2 = (int huge*) farcalloc(Image.ligne*Image.colonne,(UL)sizeof(int)); if (Image2 == NULL) { printf("Not enough memory for Image buffer allocation\n"); exit(-4); } // Initialisation de ImageOut, Image2 … z‚ro InitImage(ImageOut); InitImage(Image2); // Affiche ImageOut ViewZoom(ImageInit); // ImageOut=ImageInit CopyImage(ImageOut,ImageInit); // Erosion de ImageInit : r‚sultat = ImageOut erosion(ImageInit,ImageOut); free(ImageInit); // Image2 = ImageOut CopyImage(Image2,ImageOut); // D‚termine contour de ImageOut : r‚sultat dans Image2 contour(ImageOut,Image2); // Groupe pixel 45ø 135ø CopyImage(ImageOut,Image2); groupe(Image2,ImageOut); CopyImage(Image2,ImageOut); // Erosion du contour sur Image2 erosion2(4,Image2); // Init de ImageOut InitImage(ImageOut); // D‚finir le orientations de l'empreinte : r‚sultat dans ImageOut CopyImage(ImageOut,Image2); New_directions2(Image2,ImageOut); // Copie ImageOut dans Image2 CopyImage(Image2,ImageOut); // Erosion de ImageOut : r‚sultat dans Image2 erosion3(ImageOut,Image2); free(ImageOut); free(Image2); lin=Image.ligne; col=Image.colonne; // ZONE GLOBALE nbpix=0; v=0.0; matrix_co4d(Image2,0, 0, lin, col, mat5); for (x=yellow; x<=blue; x++) { for (y=yellow; y<=blue; y++) { if (nbpix) v= (float)mat5[y][x] / (float)nbpix; fprintf(out,"%2.5f ",v); } } // ZONE 1 nbpix=0; v=0.0; matrix_co4d(Image2, 0, 0, lin/2, col/2,mat); for (x=yellow; x<=blue; x++) { for (y=yellow; y<=blue; y++) { if (nbpix) v = (float)mat[y][x] / (float)nbpix; fprintf(out,"%2.5f ",v); } } // ZONE 2 nbpix=0; v=0.0; matrix_co4d(Image2, 0, 1+col/2, lin/2 ,col, mat2); for (x=yellow; x<=blue; x++) { for (y=yellow; y<=blue; y++) { if (nbpix) v= (float)mat2[y][x] / (float)nbpix; fprintf(out,"%2.5f ",v); } } // ZONE 3 nbpix=0; v=0.0; matrix_co4d(Image2,1+lin/2, 0, lin, col/2, mat3); for (x=yellow; x<=blue; x++) { for (y=yellow; y<=blue; y++) { if (nbpix) v= (float)mat3[y][x] / (float)nbpix; fprintf(out,"%2.5f ",v); } } // ZONE 4 nbpix=0; v=0.0; matrix_co4d(Image2,1+lin/2, 1+col/2, lin, col, mat4); for (x=yellow; x<=blue; x++) { for (y=yellow; y<=blue; y++) { if (nbpix) v= (float)mat4[y][x] / (float)nbpix; fprintf(out,"%2.5f ",v); } } message("Tapez une touche"); fprintf(out,"%s\n",argv[1]); fclose(out); closegraph(); system("neuro2 test.con"); system("show.exe"); system("del test.out"); }