void binarize(const symbol_type& label, Iterator first, Iterator last, tree_type& target) { target.label_ = label; target.antecedent_.resize(2); if (std::distance(first, last) == 2) { binarize(*first, target.antecedent_.front()); binarize(*(first + 1), target.antecedent_.back()); } else { binarize(label, first, last - 1, target.antecedent_.front()); binarize(*(last - 1), target.antecedent_.back()); } }
void binarize_basic(t_img_desc* img) { if (img->comp != 1) return; binarize(img->data, img->x * img->y, 127); }
Pix* pixPrepareLayoutAnalysis(Pix* pixOrg, ProgressCallback* callback) { FUNCNAME("pixPrepareLayoutAnalysis"); auto binarizeWithCallback = [&](Pix* p){ return binarize(p, callback); }; return run(pixOrg, {convertTo8, findResolution, savGol, binarizeWithCallback}, callback); }
Pix* pixPrepareForOcr(Pix* pixOrg, ProgressCallback* callback) { auto binarizeWithCallback = [&](Pix* p){ return binarize(p, callback); }; Pix* result = run(pixOrg, {convertTo8, findResolution, savGol, binarizeWithCallback , ensure150dpi, dewarpOrDeskew}); FUNCNAME("pixPrepareForOcr"); return result; }
int main(int argc, char *argv[]) { char* input_filename = argv[1]; char* output_filename = argv[2]; int thread_count = atoi(argv[3]); binarize(input_filename, output_filename, thread_count); return 0; }
void binarize_otsu(t_img_desc* img) { if (img->comp != 1) return; uint *h = histogram_fast(img); int th = thresold(h, img->x * img->y); free(h); binarize(img->data, img->x * img->y, th); }
void binarize(const tree_type& source, tree_type& target) { if (source.antecedent_.empty()) target = source; else if (source.antecedent_.size() <= 2) { target.label_ = source.label_; target.antecedent_.resize(source.antecedent_.size()); for (size_t i = 0; i != source.antecedent_.size(); ++ i) binarize(source.antecedent_[i], target.antecedent_[i]); } else { target.label_ = source.label_; target.antecedent_.resize(2); // left-heavy binarization binarize("[" + source.label_.strip() + "^]", source.antecedent_.begin(), source.antecedent_.end() - 1, target.antecedent_.front()); binarize(source.antecedent_.back(), target.antecedent_.back()); } }
void MainWindow::openfile() { while (true) { QString filename = QFileDialog::getOpenFileName(this, "Select an image file", "/home/dmitry/percent/"); if (filename.isEmpty()) { if (_isFileOpen) return; else exit(EXIT_FAILURE); } try { /// Load an image _src = cv::imread(filename.toStdString()); _isFileOpen = true; resizeImageToFit(); /// Convert the image to Gray cv::cvtColor(_src, _src_gray, CV_BGR2GRAY); fixLightness(); } catch (cv::Exception&) { QMessageBox::critical(this, "Error", "File is not an image."); continue; } break; } setCSlider(); binarize(); }
/************************************************************************* #cat: lfs_detect_minutiae - Takes a grayscale fingerprint image (of arbitrary #cat: size), and returns a map of directional ridge flow in the image #cat: (2 versions), a binarized image designating ridges from valleys, #cat: and a list of minutiae (including position, type, direction, #cat: neighbors, and ridge counts to neighbors). Input: idata - input 8-bit grayscale fingerprint image data iw - width (in pixels) of the image ih - height (in pixels) of the image lfsparms - parameters and thresholds for controlling LFS Output: ominutiae - resulting list of minutiae oimap - resulting IMAP {invalid (-1) or valid ridge directions} onmap - resulting NMAP {invalid (-1), high-curvature (-2), blanked blocks {-3} or valid ridge directions} omw - width (in blocks) of image maps omh - height (in blocks) of image maps obdata - resulting binarized image {0 = black pixel (ridge) and 255 = white pixel (valley)} obw - width (in pixels) of the binary image obh - height (in pixels) of the binary image Return Code: Zero - successful completion Negative - system error **************************************************************************/ int lfs_detect_minutiae(MINUTIAE **ominutiae, int **oimap, int **onmap, int *omw, int *omh, unsigned char **obdata, int *obw, int *obh, unsigned char *idata, const int iw, const int ih, const LFSPARMS *lfsparms) { unsigned char *pdata, *bdata; int pw, ph, bw, bh; DIR2RAD *dir2rad; DFTWAVES *dftwaves; ROTGRIDS *dftgrids; ROTGRIDS *dirbingrids; int *imap, *nmap, mw, mh; int ret, maxpad; MINUTIAE *minutiae; set_timer(total_timer); /******************/ /* INITIALIZATION */ /******************/ /* If LOG_REPORT defined, open log report file. */ if((ret = open_logfile())) /* If system error, exit with error code. */ return(ret); /* Determine the maximum amount of image padding required to support */ /* LFS processes. */ maxpad = get_max_padding(lfsparms->blocksize, lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, lfsparms->isobin_grid_dim); /* Initialize lookup table for converting integer IMAP directions */ /* to angles in radians. */ if((ret = init_dir2rad(&dir2rad, lfsparms->num_directions))){ /* Free memory allocated to this point. */ return(ret); } /* Initialize wave form lookup tables for DFT analyses. */ /* used for direction binarization. */ if((ret = init_dftwaves(&dftwaves, dft_coefs, lfsparms->num_dft_waves, lfsparms->blocksize))){ /* Free memory allocated to this point. */ free_dir2rad(dir2rad); return(ret); } /* Initialize lookup table for pixel offsets to rotated grids */ /* used for DFT analyses. */ if((ret = init_rotgrids(&dftgrids, iw, ih, maxpad, lfsparms->start_dir_angle, lfsparms->num_directions, lfsparms->blocksize, lfsparms->blocksize, RELATIVE2ORIGIN))){ /* Free memory allocated to this point. */ free_dir2rad(dir2rad); free_dftwaves(dftwaves); return(ret); } /* Pad input image based on max padding. */ if(maxpad > 0){ /* May not need to pad at all */ if((ret = pad_uchar_image(&pdata, &pw, &ph, idata, iw, ih, maxpad, lfsparms->pad_value))){ /* Free memory allocated to this point. */ free_dir2rad(dir2rad); free_dftwaves(dftwaves); free_rotgrids(dftgrids); return(ret); } } else{ /* If padding is unnecessary, then copy the input image. */ pdata = (unsigned char *)malloc(iw*ih); if(pdata == (unsigned char *)NULL){ /* Free memory allocated to this point. */ free_dir2rad(dir2rad); free_dftwaves(dftwaves); free_rotgrids(dftgrids); fprintf(stderr, "ERROR : lfs_detect_minutiae : malloc : pdata\n"); return(-430); } memcpy(pdata, idata, iw*ih); pw = iw; ph = ih; } /* Scale input image to 6 bits [0..63] */ /* !!! Would like to remove this dependency eventualy !!! */ /* But, the DFT computations will need to be changed, and */ /* could not get this work upon first attempt. */ bits_8to6(pdata, pw, ph); print2log("\nINITIALIZATION AND PADDING DONE\n"); /******************/ /* IMAP */ /******************/ set_timer(imap_timer); /* Generate IMAP for the input image. */ if((ret = gen_imap(&imap, &mw, &mh, pdata, pw, ph, dir2rad, dftwaves, dftgrids, lfsparms))){ /* Free memory allocated to this point. */ free_dir2rad(dir2rad); free_dftwaves(dftwaves); free_rotgrids(dftgrids); free(pdata); return(ret); } free_dir2rad(dir2rad); free_dftwaves(dftwaves); free_rotgrids(dftgrids); print2log("\nIMAP DONE\n"); /* Generate NMAP from the IMAP of the input image. */ if((ret = gen_nmap(&nmap, imap, mw, mh, lfsparms))){ /* Free memory allocated to this point. */ free(pdata); free(imap); return(ret); } print2log("\nNMAP DONE\n"); time_accum(imap_timer, imap_time); /******************/ /* BINARIZARION */ /******************/ set_timer(bin_timer); /* Initialize lookup table for pixel offsets to rotated grids */ /* used for directional binarization. */ if((ret = init_rotgrids(&dirbingrids, iw, ih, maxpad, lfsparms->start_dir_angle, lfsparms->num_directions, lfsparms->dirbin_grid_w, lfsparms->dirbin_grid_h, RELATIVE2CENTER))){ /* Free memory allocated to this point. */ free(pdata); free(imap); free(nmap); return(ret); } /* Binarize input image based on NMAP information. */ if((ret = binarize(&bdata, &bw, &bh, pdata, pw, ph, nmap, mw, mh, dirbingrids, lfsparms))){ /* Free memory allocated to this point. */ free(pdata); free(imap); free(nmap); free_rotgrids(dirbingrids); return(ret); } free_rotgrids(dirbingrids); /* Check dimension of binary image. If they are different from */ /* the input image, then ERROR. */ if((iw != bw) || (ih != bh)){ /* Free memory allocated to this point. */ free(pdata); free(imap); free(nmap); free(bdata); fprintf(stderr, "ERROR : lfs_detect_minutiae : binary image has bad dimensions : %d, %d\n", bw, bh); return(-431); } print2log("\nBINARIZATION DONE\n"); time_accum(bin_timer, bin_time); /******************/ /* DETECTION */ /******************/ set_timer(minutia_timer); /* Convert 8-bit grayscale binary image [0,255] to */ /* 8-bit binary image [0,1]. */ gray2bin(1, 1, 0, bdata, iw, ih); /* Allocate list of maximum number of minutia pointers. */ if((ret = alloc_minutiae(&minutiae, MAX_MINUTIAE))){ return(ret); } /* Detect the minutiae in the binarized image. */ if((ret = detect_minutiae(minutiae, bdata, iw, ih, imap, nmap, mw, mh, lfsparms))){ /* Free memory allocated to this point. */ free(pdata); free(imap); free(nmap); free(bdata); return(ret); } time_accum(minutia_timer, minutia_time); set_timer(rm_minutia_timer); if((ret = remove_false_minutia(minutiae, bdata, iw, ih, nmap, mw, mh, lfsparms))){ /* Free memory allocated to this point. */ free(pdata); free(imap); free(nmap); free(bdata); free_minutiae(minutiae); return(ret); } print2log("\nMINUTIA DETECTION DONE\n"); time_accum(rm_minutia_timer, rm_minutia_time); /******************/ /* RIDGE COUNTS */ /******************/ set_timer(ridge_count_timer); if((ret = count_minutiae_ridges(minutiae, bdata, iw, ih, lfsparms))){ /* Free memory allocated to this point. */ free(pdata); free(imap); free(nmap); free(bdata); free_minutiae(minutiae); return(ret); } print2log("\nNEIGHBOR RIDGE COUNT DONE\n"); time_accum(ridge_count_timer, ridge_count_time); /******************/ /* WRAP-UP */ /******************/ /* Convert 8-bit binary image [0,1] to 8-bit */ /* grayscale binary image [0,255]. */ gray2bin(1, 255, 0, bdata, iw, ih); /* Deallocate working memory. */ free(pdata); /* Assign results to output pointers. */ *oimap = imap; *onmap = nmap; *omw = mw; *omh = mh; *obdata = bdata; *obw = bw; *obh = bh; *ominutiae = minutiae; time_accum(total_timer, total_time); /******************/ /* PRINT TIMINGS */ /******************/ /* These Timings will print when TIMER is defined. */ /* print IMAP generation timing statistics */ print_time(stderr, "TIMER: IMAP time = %f (secs)\n", imap_time); /* print binarization timing statistics */ print_time(stderr, "TIMER: Binarization time = %f (secs)\n", bin_time); /* print minutia detection timing statistics */ print_time(stderr, "TIMER: Minutia Detection time = %f (secs)\n", minutia_time); /* print minutia removal timing statistics */ print_time(stderr, "TIMER: Minutia Removal time = %f (secs)\n", rm_minutia_time); /* print neighbor ridge count timing statistics */ print_time(stderr, "TIMER: Neighbor Ridge Counting time = %f (secs)\n", ridge_count_time); /* print total timing statistics */ print_time(stderr, "TIMER: Total time = %f (secs)\n", total_time); /* If LOG_REPORT defined, close log report file. */ if((ret = close_logfile())) return(ret); return(0); }
int grab_frame() { struct v4l2_format fmt; struct v4l2_buffer buf; struct v4l2_requestbuffers req; enum v4l2_buf_type type; fd_set fds; struct timeval tv; int r, fd = -1; unsigned int i, n_buffers; char *dev_name = "/dev/video1"; struct buffer *buffers; fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0); if (fd < 0) { perror("Cannot open device"); exit(EXIT_FAILURE); } printf("grabbing frame...\n"); CLEAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fmt.fmt.pix.width = 640; fmt.fmt.pix.height = 480; fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24; fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; xioctl(fd, VIDIOC_S_FMT, &fmt); if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_RGB24) { printf("Libv4l didn't accept RGB24 format. Can't proceed.\n"); exit(EXIT_FAILURE); } if ((fmt.fmt.pix.width != 640) || (fmt.fmt.pix.height != 480)) printf("Warning: driver is sending image at %dx%d\n", fmt.fmt.pix.width, fmt.fmt.pix.height); CLEAR(req); req.count = 100; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_MMAP; xioctl(fd, VIDIOC_REQBUFS, &req); buffers = calloc(req.count, sizeof(*buffers)); for (n_buffers = 0; n_buffers < req.count; ++n_buffers) { CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = n_buffers; xioctl(fd, VIDIOC_QUERYBUF, &buf); buffers[n_buffers].length = buf.length; buffers[n_buffers].start = v4l2_mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset); if (MAP_FAILED == buffers[n_buffers].start) { perror("mmap"); exit(EXIT_FAILURE); } } for (i = 0; i < n_buffers; ++i) { CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = i; xioctl(fd, VIDIOC_QBUF, &buf); } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; xioctl(fd, VIDIOC_STREAMON, &type); for (i = 0; i < req.count; i++) { do { FD_ZERO(&fds); FD_SET(fd, &fds); /* Timeout. */ tv.tv_sec = 2; tv.tv_usec = 0; r = select(fd + 1, &fds, NULL, NULL, &tv); } while ((r == -1 && (errno = EINTR))); if (r == -1) { perror("select"); return errno; } CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; xioctl(fd, VIDIOC_DQBUF, &buf); xioctl(fd, VIDIOC_QBUF, &buf); } binarize(buffers, buf); type = V4L2_BUF_TYPE_VIDEO_CAPTURE; xioctl(fd, VIDIOC_STREAMOFF, &type); for (i = 0; i < n_buffers; ++i) v4l2_munmap(buffers[i].start, buffers[i].length); v4l2_close(fd); return 0; }
// Computes distance function for the molecule. // The voxels corresponding to surface points are given zero distance void SurfaceShellDensityMap::resample() { // all scene voxels will be assigned the value -background_val_ //(which is positive and larger than 0) // TODO - change here, the value of the inner voxels should note be // should not be ns*2 but the largest of the inner shell IMP_LOG_VERBOSE("going to binarize\n"); binarize(num_shells_ * 2); IMP_LOG_VERBOSE("after binarize\n"); // find the voxels that are part of the surface, so we'll have // background, surface and interior voxels std::vector<long> curr_shell_voxels; // all of the voxels that are part of the current shell set_surface_shell(&curr_shell_voxels); // all of the voxels that are part of the next shell std::vector<long> next_shell_voxels; // keeps the shell index for each of the data voxels IMP_LOG_VERBOSE("resetting shell voxels\n"); std::vector<int> shell_voxels; shell_voxels.insert(shell_voxels.end(), get_number_of_voxels(), -1); for (long i = 0; i < get_number_of_voxels(); i++) { if (data_[i] == IMP_SURFACE_VAL) { shell_voxels[i] = 0; } } long n_voxel_ind, voxel_ind; float dist_from_surface; // the value is the distance of the voxel // from the surface std::vector<long> *curr_p = &curr_shell_voxels; std::vector<long> *next_p = &next_shell_voxels; std::vector<long> *tmp_p; long num_voxels = get_number_of_voxels(); IMP_LOG_VERBOSE("sampling shells\n"); for (int s_ind = 0; s_ind < num_shells_; s_ind++) { // update voxels with current layer distance and insert indexes // for next shell for (std::vector<long>::iterator it = curr_p->begin(); it != curr_p->end(); it++) { voxel_ind = *it; for (unsigned int j = 0; j < neighbor_shift_.size(); j++) { n_voxel_ind = voxel_ind + neighbor_shift_[j]; // the index of the neighbor if ((n_voxel_ind > -1) && (n_voxel_ind < num_voxels)) { dist_from_surface = data_[voxel_ind] + neighbor_dist_[j]; // if the stored distance of the voxel (voxel_ind) from the surface // is larger than the current calculated one, update if (data_[n_voxel_ind] > dist_from_surface) { data_[n_voxel_ind] = dist_from_surface; // set the voxels for the next shell if (shell_voxels[n_voxel_ind] < s_ind + 1) { next_p->push_back(n_voxel_ind); shell_voxels[n_voxel_ind] = s_ind + 1; } } } } } curr_p->clear(); tmp_p = curr_p; curr_p = next_p; next_p = tmp_p; } // zero outside for (long i = 0; i < num_voxels; i++) { if (data_[i] < 1.) { data_[i] = 0.; } } // in case we want to keep the shells and not the indexes // //now update the voxel data to be the shell index // for(long i=0;i<shell_voxels.size();i++) { // data_[i]=shell_voxels[i]; // } }
void operator()(const tree_type& source, tree_type& target) { binarize(source, target); }
bit_vector cosine_lsh(const common::sfv_t& sfv, uint32_t hash_num) { return binarize(random_projection(sfv, hash_num)); }
ZSwcTree* ZNeuronTracer::trace(Stack *stack, bool doResampleAfterTracing) { startProgress(); ZSwcTree *tree = NULL; //Extract seeds //First mask std::cout << "Binarizing ..." << std::endl; /* <bw> allocated */ Stack *bw = binarize(stack); C_Stack::translate(bw, GREY, 1); advanceProgress(0.05); std::cout << "Removing noise ..." << std::endl; /* <mask> allocated */ Stack *mask = bwsolid(bw); advanceProgress(0.05); /* <bw> freed */ C_Stack::kill(bw); //Thin line mask /* <mask2> allocated */ Stack *mask2 = NULL; if (m_enhancingMask) { std::cout << "Enhancing thin branches ..." << std::endl; mask2 = enhanceLine(stack); advanceProgress(0.05); } if (mask2 != NULL) { std::cout << "Making mask for thin branches ..." << std::endl; ZStackBinarizer binarizer; binarizer.setMethod(ZStackBinarizer::BM_LOCMAX); binarizer.setRetryCount(5); binarizer.setMinObjectSize(27); if (binarizer.binarize(mask2) == false) { std::cout << "Thresholding failed" << std::endl; C_Stack::kill(mask2); mask2 = NULL; } } /* <mask2> freed */ if (mask2 != NULL) { C_Stack::translate(mask2, GREY, 1); Stack_Or(mask, mask2, mask); C_Stack::kill(mask2); mask2 = NULL; } advanceProgress(0.05); //Trace each seed std::cout << "Extracting seed points ..." << std::endl; /* <seedPointArray> allocated */ Geo3d_Scalar_Field *seedPointArray = extractSeed(mask); m_mask = mask; advanceProgress(0.05); std::cout << "Sorting seeds ..." << std::endl; ZNeuronTraceSeeder seeder; setTraceScoreThreshold(TRACING_SEED); m_baseMask = seeder.sortSeed(seedPointArray, stack, m_traceWorkspace); #ifdef _DEBUG_2 C_Stack::write(GET_TEST_DATA_DIR + "/test.tif", m_baseMask); #endif advanceProgress(0.1); /* <seedPointArray> freed */ Kill_Geo3d_Scalar_Field(seedPointArray); std::vector<Local_Neuroseg>& locsegArray = seeder.getSeedArray(); std::vector<double>& scoreArray = seeder.getScoreArray(); std::cout << "Tracing ..." << std::endl; /* <chainArray> allocated */ std::vector<Locseg_Chain*> chainArray = trace(stack, locsegArray, scoreArray); if (m_recover > 0) { std::vector<Locseg_Chain*> newChainArray = recover(stack); chainArray.insert( chainArray.end(), newChainArray.begin(), newChainArray.end()); } advanceProgress(0.1); chainArray = screenChain(stack, chainArray); advanceProgress(0.3); /* <mask2> freed */ // C_Stack::kill(mask); std::cout << "Reconstructing ..." << std::endl; ZNeuronConstructor constructor; constructor.setWorkspace(m_connWorkspace); constructor.setSignal(stack); //Create neuron structure BOOL oldSpTest = m_connWorkspace->sp_test; if (chainArray.size() > 1000) { std::cout << "Too many chains: " << chainArray.size() << std::endl; std::cout << "Turn off shortest path test" << std::endl; m_connWorkspace->sp_test = FALSE; } /* free <chainArray> */ tree = constructor.reconstruct(chainArray); m_connWorkspace->sp_test = oldSpTest; advanceProgress(0.1); //Post process Swc_Tree_Remove_Zigzag(tree->data()); Swc_Tree_Tune_Branch(tree->data()); Swc_Tree_Remove_Spur(tree->data()); Swc_Tree_Merge_Close_Node(tree->data(), 0.01); Swc_Tree_Remove_Overshoot(tree->data()); if (doResampleAfterTracing) { ZSwcResampler resampler; resampler.optimalDownsample(tree); } advanceProgress(0.1); std::cout << "Done!" << std::endl; endProgress(); return tree; }
int main(int argc, char *argv[]) { FILE *fp, *fp_out; gray maxval; int format; int width = 0; int height = 0; int i, j; gray **pgm_data; int threshold = 127; int c; extern char *optarg; extern int optind; while((c = getopt(argc, argv, "t:")) != EOF) { switch( c ) { case 't': sscanf(optarg, "%d", &threshold); break; } } // printf("argc: %d\n", argc); // printf("optind: %d\n", optind); // printf("threshold: %d\n", threshold); // optind -- index in argv of the first argv-element that is not an option if((argc - optind) != 2) { fprintf(stderr, "Usage error\n"); fprintf(stderr, "Usage: %s <input image> <output image>\n", argv[0]); fprintf(stderr, "Option:\n"); fprintf(stderr, "-t <threshold>\n"); exit(1); } // all PGM programs must call pgm_init() just after invocation, // before they process their arguments. pgm_init(&argc, argv); // PBM function for reading, which is almost equivalent // to f = fopen(filename, "rb"); fp = pm_openr(argv[optind]); // read the PGM image header pgm_readpgminit(fp, &width, &height, &maxval, &format); printf("Succesfully read the header!\n\n"); printf("= PGM image information =\n"); printf("Width: %d\n", width); printf("Height: %d\n", height); printf("Max color: %d\n", maxval); // printf("Format: %c\n\n", PGM_FORMAT_TYPE(format)); // close then open file again for reading data fclose(fp); fp = pm_openr(argv[optind]); pgm_data = pgm_readpgm(fp, &width, &height, &maxval); printf("Succesfully get the PGM image data!\n\n"); tImage img; img.width = width; img.height = height; img.pixelType = GRAY8; img.pPixel = (UCHAR *)malloc(width * height * sizeof(UCHAR)); // copy data to our format for(i = 0; i < height; i++) { for(j = 0; j < width; j++) { img.pPixel[i * width + j] = pgm_data[i][j]; } } img = binarize(img, threshold); // convert back to the pgm format for(i = 0; i < height; i++) { for(j = 0; j < width; j++) { pgm_data[i][j] = img.pPixel[i * width + j]; } } fp_out = pm_openw(argv[optind + 1]); // forceplain is a logical value that tells pgm_writepgminit() to // write a header for a plain PGM format file, as opposed to a raw // PGM format file. // 1 -> not a binary format int forceplain = 0; pgm_writepgm(fp_out, pgm_data, width, height, maxval, forceplain); printf("Succesfully write the binarized PGM image to disk!\n\n"); free(img.pPixel); fclose(fp); fclose(fp_out); return 1; }
int eyelidDistance(Mat eye, double threshold) { int i; int j; int m = eye.rows; int n = eye.cols; Mat strechedEye = stretchHistogram(&eye); vector<int> summary = sum(&strechedEye, 2); vector<int> eyebrowPeaks; vector<int> eyebrowLocs; findPeaks(&summary, &eyebrowLocs, &eyebrowPeaks); Mat eyeBinary = binarize(&strechedEye, 55); if (!eyebrowLocs.empty()) { if (eyebrowLocs[0] != 1 && eyebrowLocs[0] < round(m / 2.2)) { eyeBinary.rowRange(0, eyebrowLocs[0] - 1) = 1; } } vector<double> mBinary = meanValue(&eyeBinary, 2); vector<double> sigmaBinary(m); for (i = 0; i < m; i++) { double tmpSum = 0; for (j = 0; j < n; j++) { tmpSum += (eyeBinary.at<uchar>(i, j) - mBinary[i])*(eyeBinary.at<uchar>(i, j) - mBinary[i]); } sigmaBinary[i] = tmpSum / n; } vector<double> difVarBinary = diff(&sigmaBinary); vector<double> pksBinaryPositive; vector<int> locsBinaryPositive; vector<double> pksBinaryNegative; vector<int> locsBinaryNegative; findPeaks(&difVarBinary, &locsBinaryPositive, &pksBinaryPositive); findPeaks(&(negateVector(difVarBinary)), &locsBinaryNegative, &pksBinaryNegative); vector<double> pksBinary = pksBinaryPositive; vector<double> negatedPeaks = negateVector(pksBinaryNegative); pksBinary.insert(pksBinary.end(), negatedPeaks.begin(), negatedPeaks.end()); vector<int> locsBinary = locsBinaryPositive; locsBinary.insert(locsBinary.end(), locsBinaryNegative.begin(), locsBinaryNegative.end()); int loc1, loc2; getDistance(pksBinary, locsBinary, &loc1, &loc2); int distance = abs(loc2 - loc1); double percent = 0; if (distance < threshold) { return 0; } else { if (loc1 != 0 || loc2 != 0) { if (loc1 < loc2) { Mat extract = eyeBinary.rowRange(loc1, loc2); vector<int> sumH = sum(&invert(&extract), 2); int boundariesH1; int boundariesH2; int boundariesV1; int boundariesV2; getBigInterval(sumH, &boundariesH1, &boundariesH2, 0.85); vector<int> sumV = sum(&invert(&extract), 1); getBigInterval(sumV, &boundariesV1, &boundariesV2, 0.65); Mat cut = extract(Range(boundariesH1, boundariesH2), Range(boundariesV1, boundariesV2)); percent = 100 * (sum(cut))[0] / (double)(cut.rows * cut.cols); } } if (percent > 25) { return 0; } else { return distance; } } }
int main(int argc, char *argv[]) { extern DocoptArgs args; extern char exclude_files[MAXEXCLUDEFILES][512]; extern char include_folders[MAXINCLUDEFOLDERS][512]; extern char muted_warnings[MAXWARNINGS][512]; int i; int j; char *halp[] = {argv[0], "-h"}; args = docopt(argc, argv, 1, VERSION); // Docopt doesn't yet support positional arguments if (argc < 4) docopt(2, halp, 1, VERSION); args.source = argv[argc - 2]; if (args.source[strlen(args.source) - 1] == PATHSEP) args.source[strlen(args.source) - 1] = 0; args.target = argv[argc - 1]; if (args.target[strlen(args.target) - 1] == PATHSEP) args.target[strlen(args.target) - 1] = 0; if ((args.source[0] == '-' && strlen(args.source) > 1) || (args.target[0] == '-' && strlen(args.target) > 1)) docopt(2, halp, 1, VERSION); // @todo strcpy(include_folders[0], "."); for (i = 0; i < argc - 1; i++) { if (strcmp(argv[i], "-x") == 0 || strcmp(argv[i], "--exclude") == 0) { for (j = 0; j < MAXEXCLUDEFILES && exclude_files[j][0] != 0; j++); strncpy(exclude_files[j], argv[i + 1], sizeof(exclude_files[j])); } if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--include") == 0) { for (j = 0; j < MAXINCLUDEFOLDERS && include_folders[j][0] != 0; j++); strncpy(include_folders[j], argv[i + 1], sizeof(include_folders[j])); if (include_folders[j][strlen(include_folders[j]) - 1] == PATHSEP) include_folders[j][strlen(include_folders[j]) - 1] = 0; } if (strcmp(argv[i], "-w") == 0 || strcmp(argv[i], "--warning") == 0) { for (j = 0; j < MAXWARNINGS && muted_warnings[j][0] != 0; j++); strncpy(muted_warnings[j], argv[i + 1], sizeof(muted_warnings[j])); } } if (args.binarize) return binarize(); if (args.build) return build(); if (args.unpack) return unpack(); if (args.derapify) return derapify(); docopt(2, halp, 1, VERSION); return 1; }