void drawSimpleText(Mat img,String text) { //extract from http://docs.opencv.org/modules/core/doc/drawing_functions.html#gettextsize int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; double fontScale = 2; int thickness = 3; int baseline = 0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; // center the text Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/2); // draw the box /*rectangle(img, textOrg + Point(0, baseline), textOrg + Point(textSize.width, -textSize.height), Scalar(0,0,255));*/ // ... and the baseline first /*line(img, textOrg + Point(0, thickness), textOrg + Point(textSize.width, thickness), Scalar(0, 0, 255));*/ // then put the text itself putText(img, text, textOrg, fontFace, 2, Scalar::all(255), 1, CV_AA); }
void drawText(int i, image_pool* pool, const char* ctext) { // Use "y" to show that the baseLine is about string text = ctext; int fontFace = FONT_HERSHEY_COMPLEX_SMALL; double fontScale = .8; int thickness = .5; Mat img = *pool->getImage(i); int baseline = 0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; // center the text Point textOrg((img.cols - textSize.width) / 2, (img.rows - textSize.height * 2)); // draw the box rectangle(img, textOrg + Point(0, baseline), textOrg + Point( textSize.width, -textSize.height), Scalar(0, 0, 255), CV_FILLED); // ... and the baseline first line(img, textOrg + Point(0, thickness), textOrg + Point(textSize.width, thickness), Scalar(0, 0, 255)); // then put the text itself putText(img, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8); }
static void drawText(cv::Mat &img, string text) { int fontFace = FONT_HERSHEY_SIMPLEX; double fontScale = 1; int thickness = 3; int baseline=0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; // center the text const int row_offset = 20; Point textOrg((img.cols - textSize.width)/2, (textSize.height)/2 + row_offset); // draw the box // rectangle(img, textOrg + Point(0, baseline), // textOrg + Point(textSize.width, -textSize.height), // Scalar(0,0,255)); // ... and the baseline first // line(img, textOrg + Point(0, thickness), // textOrg + Point(textSize.width, thickness), // Scalar(0, 0, 255)); // then put the text itself putText(img, text, textOrg, fontFace, fontScale, Scalar(127, 127, 127, 0), thickness, 8); }
void drawLegend(vector<string> texts, vector<CvScalar> colorLine, Mat& img){ int fontFace = FONT_HERSHEY_SIMPLEX; double fontScale = 0.5; int thickness = 1; int baseline=0; int prevTextHeight = 0; int maxWidth = 0, totalHeight = 0, firstBaseLine = 0; //encontrando max y min para el rectangulo for (int i=0; i<texts.size(); i++) { baseline=0; cv::Size textSize = getTextSize(texts[i], fontFace, fontScale, thickness, &baseline); totalHeight += textSize.height; if (maxWidth<textSize.width) maxWidth = textSize.width; if (i==0) firstBaseLine = textSize.height+thickness; } maxWidth += 40; Point2i RectOrg(img.cols - maxWidth, img.rows - totalHeight); rectangle(img, Point2i(RectOrg.x, RectOrg.y-firstBaseLine), Point2i(RectOrg.x+maxWidth, RectOrg.y+totalHeight) , Scalar::all(255),CV_FILLED); for (int i=0; i<texts.size(); i++) { baseline=0; cv::Size textSize = getTextSize(texts[i], fontFace, fontScale, thickness, &baseline); baseline += thickness; Point2i textOrg(RectOrg.x+40, RectOrg.y+prevTextHeight); line(img, textOrg + Point2i(-35, thickness-6), textOrg + Point2i(-10, thickness-6), colorLine[i],3); putText(img, texts[i], textOrg, fontFace, fontScale, Scalar::all(0), thickness, 8); prevTextHeight += textSize.height+3; } }
void waterMark(const std::string& text, Mat & img) { int baseline = 0; Size textSize = getTextSize(text, CV_FONT_HERSHEY_PLAIN, 3, 2, &baseline); Point textOrg((img.cols - textSize.width) / 2, (img.rows + textSize.height) / 2); putText(img, text, textOrg, CV_FONT_HERSHEY_PLAIN, 3, Scalar::all(1), 2, 8); }
int Fall_Detection::falldetectiondistance(double vertical_dis) { int fall_det; if (pre_vertical_dis != vertical_dis) { frame_counter = 0; }else { frame_counter++; } int fontFace = FONT_HERSHEY_SIMPLEX; double fontScale = 1; int thickness = 3; cv::Point textOrg(20, 80); if (vertical_dis < fall_threshold) { fall_det = 1; }else { fall_det = 0; } if (fall_temp != fall_det) { fall_counter = 0; } else { fall_counter++; } fall_temp = fall_det; pre_vertical_dis = vertical_dis; if ((fall_counter > (fall_duration*25)) && (fall_det==1)&&(vertical_dis!= 0)) { fall_output_dis = 1; }else { fall_output_dis = 0; } return 0; }
Mat oneStr2oneImg (const string& text, int fontFace, int thickness, Scalar color) { double fontScale = 1; int baseline = 0; Size textSize = getTextSize(text, fontFace,fontScale, thickness, &baseline); // scale to fit Height = 1000; fontScale *= 1000 / textSize.height; baseline += thickness; textSize = getTextSize(text, fontFace,fontScale, thickness, &baseline); Mat img1(textSize.height*1.1, textSize.width*1.2, CV_8UC3, Scalar(0,0,0)); // center the text Point textOrg((img1.cols - textSize.width)/2,(img1.rows + textSize.height)/2); Mat img(textSize.height*1.5, textSize.width*1.2, CV_8UC3, Scalar(0,0,0)); // then put the text itself putText(img, text, textOrg, fontFace, fontScale,color, thickness, 8); /* namedWindow( "gg window", WINDOW_AUTOSIZE ); imshow( "gg window", img ); waitKey(0); */ return img; }
void PM_dem::detect( Mat &img, float score_thresh, bool show_hints, bool show_img, string save_img ) { if( score_thresh==DEFAULT_THRESH ) model.threshing = model.thresh; else model.threshing = score_thresh; hints = show_hints; // 1. Feature pyramid <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< prag_start = yuGetCurrentTime('M'); if( hints ){ printf("Calculating feature pyramid ...\n"); start_clock = prag_start; } featpyramid2( img, model, pyra ); if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for _featpyramid is %gs\n",(end_clock-start_clock)/1000.f); } // 2. Compute PCA projection of the feature pyramid <<<<<<<<<<<<<< if( hints ){ printf("Compute PCA projection of the feature pyramid ...\n"); start_clock = end_clock; } /*Mat Ctest = model.C2(Rect(0,155,32,1)); cout<<Ctest;*/ //project_pyramid( model, pyra ); if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for _project_pyramid() is %gs\n",(end_clock-start_clock)/1000.f); } if (hints) { end_clock = start_clock; printf("QT\n"); } qtpyra(model,pyra); if (hints) { end_clock = yuGetCurrentTime('M'); printf("%gs\n",(end_clock-start_clock)/1000.f); } if( pyra.num_levels!=pyra.feat.size() ){ printf("pyra.num_levels!=pyra.feat.size()\n"); throw runtime_error(""); } // 3. Precompute location/scale scores <<<<<<<<<<<<<<<<<<<<<<< Mat loc_f = loc_feat( model, pyra.num_levels ); pyra.loc_scores.resize( model.numcomponents ); for( int c=0; c<model.numcomponents; c++ ){ Mat loc_w( 1, model.loc[c].w.size(), CV_32FC1, &(model.loc[c].w[0]) ); // loc_w = model.loc[c].w pyra.loc_scores[c] = loc_w * loc_f; } // 4. Gather PCA root filters for convolution <<<<<<<<<<<<<<<<<<< if( hints ){ printf("Gathering PCA root filters for convolution ...\n"); start_clock = end_clock; } if( rootscores[0].size()!=pyra.num_levels ){ vector<Mat> tmp_rootscores(pyra.num_levels); rootscores.assign(model.numcomponents,tmp_rootscores); } // ofstream f1("pj.txt"); int numrootlocs = 0; int s = 0; // will hold the amount of temp storage needed by cascade() for( int i=0; i<pyra.num_levels; i++ ){ s += pyra.feat[i].rows * pyra.feat[i].cols; if( i<model.interval ) continue; static vector<Mat> scores; //fconv( pyra.projfeat[i], rootfilters, 0, numrootfilters, scores ); fconv_root_qt(model, pyra.qtfeat[i], scores); for( int c=0; c<model.numcomponents; c++ ){ int u = model.components[c].rootindex; int v = model.components[c].offsetindex; float tmp = model.offsets[v].w + pyra.loc_scores[c].at<float>(i); rootscores[c][i] = scores[u] + Scalar(tmp); numrootlocs += scores[u].total(); } } cout<<numrootlocs<<endl; s = s * model.partfilters.size(); if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for gathering PCA root filters is %gs\n",(end_clock-start_clock)/1000.f); } // 5. Cascade detection in action <<<<<<<<<<<<<<<<<<<<<<< if( hints ){ printf("Cascade detection in action ...\n"); start_clock = end_clock; } //Mat coords = cascade(model, pyra, rootscores, numrootlocs, s); Mat coords = cascade_qt(model, pyra, rootscores, numrootlocs, s); //cout<<coords; //cout<<"??"<<endl; if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for _cascade() is %gs\n",(end_clock-start_clock)/1000.f); if( coords.empty() ){ printf("No Detection!\n"); return; } } // 6. Detection results <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Mat boxes = getboxes( model, img_color, coords ); Mat x1 = boxes.col(0); Mat y1 = boxes.col(1); Mat x2 = boxes.col(2); Mat y2 = boxes.col(3); Mat Score = boxes.col( boxes.cols-1 ); detections.resize( x1.rows ); for( int i=0; i<x1.rows; i++ ){ detections[i][0] = x1.at<float>(i); detections[i][1] = y1.at<float>(i); detections[i][2] = x2.at<float>(i); detections[i][3] = y2.at<float>(i); detections[i][4] = Score.at<float>(i); } if( hints ){ prag_end = yuGetCurrentTime('M'); printf("Total detection time is : %gs\n",(prag_end-prag_start)/1000.f); } // 6. Draw and show <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if( show_img || !save_img.empty() ){ //showboxes( img_color, boxes ); // const int fontFace = CV_FONT_HERSHEY_PLAIN; const double fontScale = 1; const Scalar drawColor = CV_RGB(255,0,0); const Scalar fontColor = CV_RGB(30,250,150); // for( int i=0; i!=detections.size(); i++ ){ float x1 = detections[i][0], y1 = detections[i][1], x2 = detections[i][2], y2 = detections[i][3]; float _score = detections[i][4]; // Point2f UL( x1, y1 ); Point2f BR( x2, y2 ); rectangle( img_color, UL, BR, drawColor, 2 ); printf("----------------------------\n"); printf("%g %g %g %g %g\n", x1, y1, x2, y2, _score ); // x1 = int(x1*10+0.5) / 10.f; // ½ö±£Áô1λСÊý y1 = int(y1*10+0.5) / 10.f; x2 = int(x2*10+0.5) / 10.f; y2 = int(y2*10+0.5) / 10.f; _score = int(_score*100+0.5) / 100.f; // char buf[50] = { 0 }; sprintf_s( buf, 50, "%d", i ); string text = buf; int baseline = 0; Size textSize = getTextSize( text, fontFace, fontScale, 1, &baseline ); Point2f textOrg2( x1, y1+textSize.height+2 ); putText( img_color, text, textOrg2, fontFace, fontScale, fontColor ); // sprintf_s( buf, 50, "%d %g %g %g %g %g", i, x1, y1, x2, y2, _score ); text = buf; textSize = getTextSize( text, fontFace, fontScale, 1, &baseline ); Point2f textOrg(5,(i+1)*(textSize.height+3)); putText( img_color, text, textOrg, fontFace, fontScale, fontColor ); } { char buf[30] = { 0 }; sprintf_s( buf, 30, "time : %gs", (prag_end-prag_start)/1000.f ); string time_text = buf; int baseline = 0; Size textSize = getTextSize( time_text, fontFace, fontScale, 1, &baseline ); Point2f time_orig(5,(detections.size()+1)*(textSize.height+3)); putText( img_color, time_text, time_orig, fontFace, fontScale, fontColor ); } if( show_img ) imshow( "OK", img_color ); if( !save_img.empty() ) imwrite( save_img, img_color ); } }
void genHardNegatives(string retrainAppendFile, FeatGen* ldgFeatGen,const path& baseDir, datasets currDataset, bool writeOutWins, bool viz,string modelfile, double negBoundary) { bool debugOnlySomeWins = false; vector<path> negativePaths; vector<path> negTrainPaths; vector<path> negTestPaths; FrameId firstTestFrame; // separates training and testing data string learnFileStem; vector<path> normPosWinPathsTrain; // if any use folder with normalized cropped windows vector<path> normPosWinPathsTest; // if any use folder with normalized cropped windows getLearnInfos(baseDir, currDataset, negativePaths, negTrainPaths, negTestPaths,normPosWinPathsTrain, normPosWinPathsTest, learnFileStem, firstTestFrame); path negTrainFolder = baseDir / "learning" / "train_neg_hard"; remove_all(negTrainFolder); create_directories(negTrainFolder); //std::ios_base::openmode mode = ; //fs::ofstream trainFile((baseDir / "learning" / learnFileStem).string(), std::ios_base::out | ios_base::app); //fs::ofstream trainFilesFile((baseDir / "learning" / learnFileStem).string() + ".files", std::ios_base::out | ios_base::app); //fs::ofstream trainFileHard((baseDir / "learning" / learnFileStem).string() + "_hard"); fs::ofstream trainFileHard(retrainAppendFile,std::ios_base::out | ios_base::app); if ( !(modelfile.length() > 0 ) ) { modelfile = (baseDir / "learning" / learnFileStem).string() + ".model"; } path mfp(modelfile); if ( !exists(mfp)) { cerr << "Modelfile does not exist: " << modelfile << endl; exit(EXIT_FAILURE); } Detector pd(ldgFeatGen); pd.setStartScale(1); pd.setScaleStep(1.0718); pd.loadSVMWeights(modelfile); if ( negBoundary < 0 ) negBoundary *= -1.0; float decThresh = -negBoundary; int countedWindows = 0; int nww = ldgFeatGen->getWinW(); int nwh = ldgFeatGen->getWinH(); cout << "genHardNegatives using model: " << mfp.string() << " dec: " << decThresh << endl; for ( vector<path>::iterator pit(negTrainPaths.begin()); pit != negTrainPaths.end(); ++pit) { path np = *pit; vector<path> v; copy(directory_iterator(np),directory_iterator(),back_inserter(v)); sort(v.begin(),v.end()); size_t featSize = ldgFeatGen->getWindowFeatLen(); // feature size int processedImages = 0; cout << "0% "; cout.flush(); for ( vector<path>::iterator it (v.begin()); it != v.end(); ++it) { if ( processedImages % 10 == 0 ) { cout << floor((processedImages/(double) v.size()* 100.0 )) << "% "; cout.flush(); } if (debugOnlySomeWins && processedImages > 30) { break; } //if ( processedImages/(double) v.size()* 100.0 < 62.9 ) /*if ( processedImages < 770) { processedImages++; continue; }*/ path nf = *it; string filePre = nf.parent_path().parent_path().stem().string() + nf.parent_path().stem().string() + "_" + nf.filename().stem().string(); Mat img = imread(nf.string(),CV_LOAD_IMAGE_COLOR); vector< pair<Detection,double*> > detections; vector<Detection> alldetections; pd.detect(img,detections,alldetections,decThresh,true); // pick random windows vector<size_t> randPicks; const int numPicks = 10; if ( detections.size() > numPicks ) { int picks = 0; int dSize = detections.size(); while(picks != numPicks) { int randPick = rand() % dSize; bool exists = false; for ( int i = 0; i < randPicks.size(); i++ ) { if ( randPicks[i] == randPick) { exists = true; break; } } if ( !exists ) { picks++; randPicks.push_back(randPick); } } } else { for ( int i = 0; i < detections.size(); i++ ) { randPicks.push_back(i); } } for ( size_t i = 0; i < randPicks.size(); i++) { pair < Detection,double* > mp = detections[randPicks[i]]; Detection det = mp.first; Rect r = det.r; double* f = mp.second; writeFeatToSVMStream(f,trainFileHard,featSize,false); countedWindows++; } // free cached features for ( size_t i = 0; i < detections.size(); i++) { pair < Detection,double* > mp = detections[i]; double* f = mp.second; delete [] f; } if ( viz || writeOutWins ) { Mat vizImg = img.clone(); for ( vector< Detection >::iterator it(alldetections.begin()); it != alldetections.end(); it++) { Detection det = *it; Rect r = det.rNormWin; //cout << r.x << " " << r.y << " " << r.width << "x" << r.height << " scale:" << det.scale << " decisionValue:" << det.decisionValue << endl; rectangle(vizImg,r,Scalar(255,50,50),1,8); } for ( size_t i = 0; i < detections.size(); i++) { Detection det = detections[i].first; Rect r = det.r; rectangle(vizImg,r,Scalar(0,0,255),1,8); // render detection score ostringstream detscoretxt; detscoretxt.precision(3); detscoretxt << det.decisionValue; string text = detscoretxt.str(); int fontFace = FONT_HERSHEY_DUPLEX; double fontScale = 0.5; int thickness = 0; int baseline=0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; Point textOrg(det.r.x + (det.r.width - textSize.width)/2.0, det.r.y + (det.r.height - textSize.height)/2.0); bool isPicked = false; for ( size_t k = 0; k < randPicks.size(); k++ ) { if ( randPicks[k] == i ) { isPicked = true; break; } } if (isPicked ) { rectangle(vizImg, textOrg + Point(0, baseline-3), textOrg + Point(textSize.width, -textSize.height), Scalar(80,200,80), CV_FILLED); } else { rectangle(vizImg, textOrg + Point(0, baseline-3), textOrg + Point(textSize.width, -textSize.height), Scalar(0,0,255), CV_FILLED); } // ... and the baseline first //line(img, textOrg + Point(0, thickness), // textOrg + Point(textSize.width, thickness), // Scalar(0, 0, 255)); putText(vizImg, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8); } if ( writeOutWins && detections.size() > 0 ) { string fileNameOnly = (filePre +"_hard.png"); path nwPath = negTrainFolder / fileNameOnly; imwrite(nwPath.string(),vizImg); } if ( viz ) { imshow("negative training image",vizImg); waitKey(0); } } processedImages++; } cout << "100% " << endl; } //trainFile.close(); trainFileHard.close(); cout << countedWindows << " hard negatives found." << endl; }
int main() { std::vector<ContourWithData> allContoursWithData; std::vector<ContourWithData> validContoursWithData; cv::Mat matClassificationFloats; cv::FileStorage fsClassifications("classifications.xml", cv::FileStorage::READ); if (fsClassifications.isOpened() == false) { std::cout << "error, unable to open training classifications file, exiting program\n\n"; return(0); } fsClassifications["classifications"] >> matClassificationFloats; fsClassifications.release(); cv::Mat matTrainingImages; cv::FileStorage fsTrainingImages("images.xml", cv::FileStorage::READ); if (fsTrainingImages.isOpened() == false) { std::cout << "error, unable to open training images file, exiting program\n\n"; return(0); } fsTrainingImages["images"] >> matTrainingImages; fsTrainingImages.release(); cv::Ptr<cv::ml::KNearest> kNearest = cv::ml::KNearest::create(); cv::Ptr<cv::ml::TrainData> trainingData = cv::ml::TrainData::create(matTrainingImages, cv::ml::SampleTypes::ROW_SAMPLE, matClassificationFloats); kNearest->setIsClassifier(true); kNearest->setAlgorithmType(cv::ml::KNearest::Types::BRUTE_FORCE); kNearest->setDefaultK(101); cv::Mat matResults(0, 0, CV_32F); kNearest->train(trainingData); cv::Mat matTestingNumbers = cv::imread("test_numbers.png"); if (matTestingNumbers.empty()) { std::cout << "error: image not read from file\n\n"; return(0); } cv::Mat matGrayscale; cv::Mat matBlurred; cv::Mat matThresh; cv::Mat matThreshCopy; cv::cvtColor(matTestingNumbers, matGrayscale, CV_BGR2GRAY); threshold(matGrayscale, matThresh, 10, 255, CV_THRESH_BINARY_INV); matThreshCopy = matThresh.clone(); std::vector<std::vector<cv::Point> > ptContours; std::vector<cv::Vec4i> v4iHierarchy; cv::findContours(matThreshCopy, ptContours, v4iHierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_TC89_KCOS); for (int i = 0; i < ptContours.size(); i++) { ContourWithData contourWithData; contourWithData.ptContour = ptContours[i]; contourWithData.boundingRect = cv::boundingRect(contourWithData.ptContour); contourWithData.fltArea = cv::contourArea(contourWithData.ptContour); allContoursWithData.push_back(contourWithData); } for (int i = 0; i < allContoursWithData.size(); i++) { if (allContoursWithData[i].checkIfContourIsValid()) { validContoursWithData.push_back(allContoursWithData[i]); } } std::sort(validContoursWithData.begin(), validContoursWithData.end(), ContourWithData::sortByBoundingRectXPosition); std::string strFinalString; for (int i = 0; i < validContoursWithData.size(); i++) { cv::rectangle(matTestingNumbers, validContoursWithData[i].boundingRect, cv::Scalar(0, 255, 0), 2); cv::Mat matROI = matThresh(validContoursWithData[i].boundingRect); cv::Mat matROIResized; cv::resize(matROI, matROIResized, cv::Size(RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT)); cv::Mat matROIFloat; matROIResized.convertTo(matROIFloat, CV_32FC1); float fltCurrentChar = kNearest->findNearest(matROIFloat.reshape(1,1), kNearest->getDefaultK(), matResults); strFinalString = strFinalString + char(int(fltCurrentChar)); } cv::Mat string_box(100,500,CV_8UC3, cv::Scalar::all(0)); int baseLine = 0; cv::Size string_size = cv::getTextSize(strFinalString, CV_FONT_HERSHEY_DUPLEX, 1, 2, &baseLine); baseLine += 2; cv::Point textOrg((string_box.cols - string_size.width) / 2, (string_box.rows + string_size.height) / 2); cv::putText(string_box, strFinalString, textOrg, CV_FONT_HERSHEY_DUPLEX, 1, cv::Scalar::all(255), 2, 8); cv::imshow("result", string_box); cv::imshow("matTestingNumbers", matTestingNumbers); cv::waitKey(0); return(0); }
void greenDetect(HWND hwnd) { int fontFace = cv::FONT_HERSHEY_SCRIPT_SIMPLEX; double fontScale = 1; int thickness = 1; cv::Point textOrg(500, 25); cv::Mat frame, hsv, thresholded; int numWhite = 0; int iLowH = 75; int iHighH = 104; /* int iLowH = 32; int iHighH = 51; */ int iLowS = 29; int iHighS = 142; int iLowV = 38; int iHighV = 255; cv::namedWindow("Control", cv::WINDOW_AUTOSIZE); //create a window called "Control" //Create trackbars in "Control" window cv::createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179) cv::createTrackbar("HighH", "Control", &iHighH, 179); cv::createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255) cv::createTrackbar("HighS", "Control", &iHighS, 255); cv::createTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255) cv::createTrackbar("HighV", "Control", &iHighV, 255); cv::VideoCapture cap(0); // open the default camera if(cap.isOpened()) { cv::namedWindow("thresholded", 1); cv::waitKey(1000); // Wait for camera so frame won't be empty for (;;) { try { boost::this_thread::interruption_point(); } catch(boost::thread_interrupted&) { break; } cap >> frame; // get a new frame from capture cv::cvtColor(frame, hsv, cv::COLOR_BGR2HSV); cv::inRange(hsv, cv::Scalar(iLowH, iLowS, iLowV), cv::Scalar(iHighH, iHighS, iHighV), thresholded); //Threshold the image //morphological opening (remove small objects from the foreground) cv::erode(thresholded, thresholded, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)) ); cv::dilate(thresholded, thresholded, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)) ); //morphological closing (fill small holes in the foreground) cv::dilate(thresholded, thresholded, getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)) ); cv::erode(thresholded, thresholded, getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)) ); numWhite = cv::countNonZero(thresholded); cv::putText(thresholded, boost::lexical_cast<std::string>(numWhite), textOrg, fontFace, fontScale, cv::Scalar::all(255), thickness, 8); if (numWhite > 10000 ) { if (activeKey == NULL && selectedKey != NULL) { activeKey = selectedKey; sendBoundKey(activeKey->virtualKey, TRUE); InvalidateRect(hwnd, 0, TRUE); } } else { if (activeKey != NULL) { sendBoundKey(activeKey->virtualKey, FALSE); activeKey = NULL; InvalidateRect(hwnd, 0, TRUE); } } cv::imshow("thresholded", thresholded); cv::waitKey(30); } }