face detection using HAAR classifier - opencv

Iam working on face detection in openCV with HAAR classifier. Here is my code
#include "stdafx.h"
#include <opencv2\objdetect\objdetect.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv\cv.h>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
void detectAndDisplay(Mat frame);
String face_cascade_name = "haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eye_cascade;
string window_name = "Capture- Face detection";
int _tmain(int argc, _TCHAR* argv[])
{
Mat frame = imread("C:/Users/Public/Pictures/Sample Pictures/lena.png");
imshow("original picture", frame);
if (face_cascade.load(face_cascade_name))
{
cout << "\n Error loading " << endl;
}
if (eye_cascade.load(eyes_cascade_name))
{
cout << "\n Error Loading " << endl;
}
if (!frame.empty())
{
detectAndDisplay(frame);
}
waitKey(0);
return 0;
}
void detectAndDisplay(Mat frame)
{
vector<Rect>faces;
imshow("lena.png", frame);
Mat frame_gray;
cvtColor(frame, frame_gray, CV_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
imshow("Gray Color Image", frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(20, 20));
int k = faces.size();
for (size_t i = 0; i <faces.size(); i++)
{
Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
ellipse(frame, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255, 0, 0));
Mat faceROI = frame_gray(faces[i]);
vector<Rect>eyes;
eye_cascade.detectMultiScale(faceROI, eyes, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));
for (int j = 0; j < eyes.size(); j++)
{
Point center(faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5);
int radius = cvRound((eyes[j].width + eyes[j].height)*0.25);
circle(frame, center, radius, Scalar(0, 0,255), 4, 8, 0);
}
}
imshow(window_name, frame);
}
Here My code is not working. face is not being detected. iam trying get int k=faces.size() which is getting '0' value. what could be the possible error.

That is because your if-condition to load the cascade is not logic:
Yours is:
if (face_cascade.load(face_cascade_name))
{
cout << "\n Error loading " << endl;
}
if (eye_cascade.load(eyes_cascade_name))
{
cout << "\n Error Loading " << endl;
}
But it should be:
if (!face_cascade.load(face_cascade_name))
{
cout << "\n Error loading " << endl;
}
if (!eye_cascade.load(eyes_cascade_name))
{
cout << "\n Error Loading " << endl;
}
You forget the '!' in the conditions.

face_cascade.load(face_cascade_name) obviously returns FALSE when classifier successfully loaded. You can find it in one of the samples provided with OpenCV library facedetect.cpp
This is why you don't see that the loading process failed and you provided wrong path to haarcascade file.

Related

LNK2019 error when using cuda::calcHist() opencv4.1.0+cuda [duplicate]

I'm pretty new to OpenCV and I wanted to implement houghlines for a project. I pulled the houghlines.cpp from the OpenCV Docs. When I run the source file I seem to get an error. I run it on Visual Studios 15 and am using OpenCV 3.1. I don't really know much about Cuda and have just been introduced into the world of OpenCV, so I do require a more thorough guidance. Thank You.
#include <cmath>
#include <iostream>
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/cudaimgproc.hpp"
using namespace std;
using namespace cv;
using namespace cv::cuda;
static void help()
{
cout << "This program demonstrates line finding with the Hough transform." << endl;
cout << "Usage:" << endl;
cout << "./gpu-example-houghlines <image_name>, Default is ../data/pic1.png\n" << endl;
}
int main(int argc, const char* argv[])
{
const string filename = argc >= 2 ? argv[1] : "../data/pic1.png";
Mat src = imread(filename, IMREAD_GRAYSCALE);
if (src.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
Mat mask;
cv::Canny(src, mask, 100, 200, 3);
Mat dst_cpu;
cv::cvtColor(mask, dst_cpu, COLOR_GRAY2BGR);
Mat dst_gpu = dst_cpu.clone();
vector<Vec4i> lines_cpu;
{
const int64 start = getTickCount();
cv::HoughLinesP(mask, lines_cpu, 1, CV_PI / 180, 50, 60, 5);
const double timeSec = (getTickCount() - start) / getTickFrequency();
cout << "CPU Time : " << timeSec * 1000 << " ms" << endl;
cout << "CPU Found : " << lines_cpu.size() << endl;
}
for (size_t i = 0; i < lines_cpu.size(); ++i)
{
Vec4i l = lines_cpu[i];
line(dst_cpu, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
}
GpuMat d_src(mask);
GpuMat d_lines;
{
const int64 start = getTickCount();
Ptr<cuda::HoughSegmentDetector> hough = cuda::createHoughSegmentDetector(1.0f, (float)(CV_PI / 180.0f), 50, 5);
hough->detect(d_src, d_lines);
const double timeSec = (getTickCount() - start) / getTickFrequency();
cout << "GPU Time : " << timeSec * 1000 << " ms" << endl;
cout << "GPU Found : " << d_lines.cols << endl;
}
vector<Vec4i> lines_gpu;
if (!d_lines.empty())
{
lines_gpu.resize(d_lines.cols);
Mat h_lines(1, d_lines.cols, CV_32SC4, &lines_gpu[0]);
d_lines.download(h_lines);
}
for (size_t i = 0; i < lines_gpu.size(); ++i)
{
Vec4i l = lines_gpu[i];
line(dst_gpu, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
}
imshow("source", src);
imshow("detected lines [CPU]", dst_cpu);
imshow("detected lines [GPU]", dst_gpu);
waitKey();
return 0;
}
Error LNK2019
unresolved external symbol "struct cv::Ptr __cdecl cv::cuda::createHoughSegmentDetector(float,float,int,int,int)" (?createHoughSegmentDetector#cuda#cv##YA?AU?$Ptr#VHoughSegmentDetector#cuda#cv###2#MMHHH#Z) referenced in function main
An additional library must be linked when compiling.
In Windows, the library name is opencv_cudaimgproc310.lib. If one is using Visual Studio, the library name must be added at [Configuration Properties] -> [Linker] -> [Input] -> [Additional Dependencies].
In Linux, it is typically libopencv_cudaimgproc.so, which is a symbolic link to libopencv_cudaimgproc.so.3.1, which in turn is a symbolic link to libopencv_cudaimgproc.so.3.1.0, which is the actual library. If one is using g++, -lopencv_cudaimgproc must be added to g++ command.
I'm assuming that, in both environment, library search path is set properly, that is, it contains path to the OpenCV libraries.

The result of opencv3.3 dnn module not match the caffe prediction

I used opencv dnn classification, but the result do not match the caffe prediction. What confused me was that some images could get similar result to caffe,a small number of images not.When I changed BGR to RGB, Most of the results ware wrong.
similar result:
different result:
blobFromImage(norm_img, 1.0, cv::Size(64, 64));when used default parameters changed BGR to RGB ,but the result would wrong .so I used like this blobFromImage(norm_img, 1.0, cv::Size(64, 64), cv::Scalar(),false); .most of result would matched caffe prediction,why a small number of images not?
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/utils/trace.hpp>
using namespace cv;
using namespace cv::dnn;
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
/* Find best class for the blob (i. e. class with maximal probability) */
static void getMaxClass(const Mat &probBlob, int *classId, double *classProb)
{
Mat probMat = probBlob.reshape(1, 1); //reshape the blob to 1x1000 matrix
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
static std::vector<String> readClassNames(const char *filename = "./config/type.txt")
{
std::vector<String> classNames;
std::ifstream fp(filename);
if (!fp.is_open())
{
std::cerr << "File with classes labels not found: " << filename << std::endl;
exit(-1);
}
std::string name;
while (!fp.eof())
{
std::getline(fp, name);
if (name.length())
classNames.push_back(name.substr(name.find(' ') + 1));
}
fp.close();
return classNames;
}
int main(int argc, char **argv)
{
CV_TRACE_FUNCTION();
String modelTxt = "./config/HCCR3755_res20_deploy.prototxt";
String modelBin = "./config/HCCR3755-res20_iter_790000.caffemodel";
String imageFile = "./config/b9.jpg";
Net net = dnn::readNetFromCaffe(modelTxt, modelBin);
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt: " << modelTxt << std::endl;
std::cerr << "caffemodel: " << modelBin << std::endl;
exit(-1);
}
Mat img = imread(imageFile);
FileStorage fs("./config/mean.xml", FileStorage::READ);
Mat _mean;
fs["vocabulary"] >> _mean;
if (img.empty())
{
std::cerr << "Can't read image from the file: " << imageFile << std::endl;
exit(-1);
}
cv::Mat img_resize;
resize(img, img_resize, Size(64, 64));
cv::Mat img_float;
img_resize.convertTo(img_float, CV_32FC3);
cv::Mat norm_img;
cv::subtract(img_float, _mean, norm_img);
Mat inputBlob = blobFromImage(norm_img, 1.0, cv::Size(64, 64), cv::Scalar(),false); //Convert Mat to batch of images
Mat prob;
cv::TickMeter t;
for (int i = 0; i < 1; i++)
{
CV_TRACE_REGION("forward");
//! [Set input blob]
net.setInput(inputBlob, "data"); //set the network input
//! [Set input blob]
t.start();
//! [Make forward pass]
prob = net.forward("prob");
//std::cout << prob << std::endl;//compute output
//! [Make forward pass]
t.stop();
}
int classId;
double classProb;
getMaxClass(prob, &classId, &classProb);//find the best class
//! [Gather output]
//! [Print results]
std::vector<String> classNames = readClassNames();
std::cout << "Best class: #" << classId << " '" << classNames.at(classId) << "'" << std::endl;
std::cout << "Probability: " << classProb * 100 << "%" << std::endl;
//! [Print results]
std::cout << "Time: " << (double)t.getTimeMilli() / t.getCounter() << " ms (average from " << t.getCounter() << " iterations)" << std::endl;
getchar();
return 0;
} //main

Application error(0xc000007b) when runnning Opencv example in Visual Studio 2015

I am running canny edge example in Visual Studio 2015 and i got this error.
The application was unable to start correctly (0xc000007b).
And then visual studio show to this error.
Unhandled exception at 0x77A2D5B2 (ntdll.dll) in Canny Edge.exe: 0xC000007B: %hs is either not designed to run on Windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0x.
I quite sure this coding is working as i ran this coding before in Visual Studio 2013. Here is my coding.
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <algorithm>
using namespace cv;
using namespace std;
void help()
{
cout << "\nThis program demonstrates line finding with the Hough transform.\n"
"Usage:\n"
"./houghlines <image_name>, Default is pic1.jpg\n" << endl;
}
bool less_by_y(const cv::Point& lhs, const cv::Point& rhs)
{
return lhs.y < rhs.y;
}
int main(int argc, char** argv)
{
const char* filename = argc >= 2 ? argv[1] : "pic1.jpg";
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Rect roi;
Mat src = imread("test_4_1.png");
if (src.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
Mat dst, cdst;
Canny(src, dst, 50, 200, 3);
cvtColor(dst, cdst, CV_GRAY2BGR);
findContours(dst, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
//vector<Vec2f> lines;
//HoughLines(dst, lines, 1, CV_PI / 180, 50, 0, 0);
//for (size_t i = 0; i < lines.size(); i++)
//{
// float rho = lines[i][0], theta = lines[i][1];
// Point pt1, pt2;
// double a = cos(theta), b = sin(theta);
// double x0 = a*rho, y0 = b*rho;
// pt1.x = cvRound(x0 + 1000 * (-b));
// pt1.y = cvRound(y0 + 1000 * (a));
// pt2.x = cvRound(x0 - 1000 * (-b));
// pt2.y = cvRound(y0 - 1000 * (a));
// line(cdst, pt1, pt2, Scalar(0, 0, 255), 1, CV_AA);
// cout << pt1 << " " << pt2 << endl;
//}
vector<Vec4i> lines;
HoughLinesP(dst, lines, 1, CV_PI / 180, 30, 50, 10);
for (size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
line(cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
cout << l << endl;
}
cout << endl << lines.size() << endl;
cout << arcLength(contours[0], true) << endl;
cout << dst.size() << endl << endl;
for (int a = 0; a < contours[0].size(); a++){
cout << contours[0][a] << " ";
}
vector<Point> test = contours[0];
auto mmx = std::minmax_element(test.begin(), test.end(), less_by_y);
cout << endl << *mmx.first._Ptr << endl << *mmx.second._Ptr;
vector<Point> test2 = contours[1];
auto mmx_1 = std::minmax_element(test2.begin(), test2.end(), less_by_y);
cout << endl << *mmx_1.first._Ptr << endl << *mmx_1.second._Ptr;
imshow("source", src);
imshow("detected lines", cdst);
/* ROI by creating mask for the parallelogram */
Mat mask = cvCreateMat(dst.size().height, dst.size().width, CV_8UC1);
// Create black image with the same size as the original
for (int i = 0; i < mask.cols; i++)
for (int j = 0; j < mask.rows; j++)
mask.at<uchar>(Point(i, j)) = 0;
cout <<endl<<endl<< *mmx.first._Ptr << *mmx.second._Ptr << *mmx_1.first._Ptr << *mmx_1.second._Ptr << endl;
// Create Polygon from vertices
vector<Point> ROI_Vertices = { *mmx.first._Ptr, *mmx.second._Ptr, *mmx_1.first._Ptr, *mmx_1.second._Ptr};
vector<Point> ROI_Poly;
approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, false);
// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);
cout << ROI_Poly.size() << endl;
// Create new image for result storage
Mat imageDest = cvCreateMat(dst.size().height, dst.size().width, CV_8UC3);
// Cut out ROI and store it in imageDest
src.copyTo(imageDest, mask);
imshow("mask", mask);
imshow("image", imageDest);
waitKey();
return 0;
}
Actually my comment is the answer, with some additions
What OpenCV Libs are you linking to? Are you linking to vs12? Because
you need to upgrade your linker to vs13 for MSVS 2015
OpenCV Doesn't come with Visual Studio 15 pre-builds, so you need to build OpenCV yourself for VS2015
This person seems to have had a similar problem and talks you through how to compile for VS2015

opencv-face detection-save the video

I have code for detection of a face.. How do I save the video which is being captured? I'm posting the code for face detection below..
where do I insert the code which saves the the video?
thhis code works in detecting a face with ubuntu and opencv. Please do help!
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
VideoCapture cap;
cv::VideoWriter output_cap("/home/unifyadmin/Documents/MyVideo.avi",
input_cap.get(CV_CAP_PROP_FOURCC),
input_cap.get(CV_CAP_PROP_FPS),
cv::Size(input_cap.get(CV_CAP_PROP_FRAME_WIDTH),
input_cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
if (!output_cap.isOpened())
{
std::cout << "!!! Output video could not be opened" << std::endl;
return;
}
// This part would be similar to your imshow part of your code
while (true)
{
if (!input_cap.read(frame))
break;
output_cap.write(frame);
}
/** Function Headers */
void detectAndDisplay( Mat frame );
/** Global variables */
String face_cascade_name = "haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);
/** #function main */
int main( int argc, const char** argv )
{
CvCapture* capture;
Mat frame;
//-- 1. Load the cascades
if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
//-- 2. Read the video stream
capture = cvCaptureFromCAM( 0 );
if( capture )
{
while( true )
{
frame = cvQueryFrame( capture );
//-- 3. Apply the classifier to the frame
if( !frame.empty() )
{ detectAndDisplay( frame ); }
else
{ printf(" --(!) No captured frame -- Break!"); break; }
int c = waitKey(10);
if( (char)c == 'c' ) { break; }
}
}
return 0;
}
/** #function detectAndDisplay */
void detectAndDisplay( Mat frame )
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
//-- Detect faces
face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t i = 0; i < faces.size(); i++ )
{
Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
Mat faceROI = frame_gray( faces[i] );
std::vector<Rect> eyes;
//-- In each face, detect eyes
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t j = 0; j < eyes.size(); j++ )
{
Point center( faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5 );
int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
circle( frame, center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 );
}
}
//-- Show what you got
imshow( window_name, frame );
}
There are three library methods that you require:
VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
VideoWriter::open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
void VideoWriter::write(const Mat& image)
Here is a short example on how to use them:
// Do this near the start of your code
cv::VideoWriter output_cap(C:/MyVideo.avi,
input_cap.get(CV_CAP_PROP_FOURCC),
input_cap.get(CV_CAP_PROP_FPS),
cv::Size(input_cap.get(CV_CAP_PROP_FRAME_WIDTH),
input_cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
if (!output_cap.isOpened())
{
std::cout << "!!! Output video could not be opened" << std::endl;
return;
}
// This part would be similar to your imshow part of your code
while (true)
{
if (!input_cap.read(frame))
break;
output_cap.write(frame);
}
Edit: - My last contribution to this question:
You need your creation of objects into the main function, that includes the VideoWriter
Im not sure how any of this code even works:
VideoCapture cap;
cv::VideoWriter output_cap("/home/unifyadmin/Documents/MyVideo.avi",
input_cap.get(CV_CAP_PROP_FOURCC),
input_cap.get(CV_CAP_PROP_FPS),
cv::Size(input_cap.get(CV_CAP_PROP_FRAME_WIDTH),
input_cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
if (!output_cap.isOpened())
{
std::cout << "!!! Output video could not be opened" << std::endl;
return;
}
// This part would be similar to your imshow part of your code
while (true)
{
if (!input_cap.read(frame))
break;
output_cap.write(frame);
}
You need to think about what you are actually coding and where you are writing code. Don't just take examples from the internet and try and stick them together.

How to detect specific number from image with OPENCV?

I live in Turkey, and in Turkey, TV commercials are making some countdowns which tells us how many minutes left to the tv program or film starts.
What I'am trying to do is catch the 00:59 seconds or just the 2nd "0" on the counter. The alghoritm must understand that the "0" is "0" not any other number.
After that I've tried template matching with template images but it detects wrong numbers too.
So I couldn't figured out which is the best way to do it...
I am trying to detect from these frames:
as you see it detects "1" instead of "0".
Below is my code with template matching;
#include<opencv2/highgui/highgui.hpp>
#include <iostream>
#include <stdio.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <sstream>
using namespace cv;
using namespace std;
Mat frame;
Mat img;
Mat templ;
Mat templ_resized;
Mat templ_resized_bw;
Mat result;
cv::Mat sel;
cv::Mat img_final;
//**************
int main(int argc, char** argv)
{
VideoCapture cap("/home/semih/Desktop/OPENCV_ON_LINUX/dizifiles/yenisoncalismalar/kanaldkucukaga.avi");
if ( !cap.isOpened() )
{
cout << "Cannot open the video file" << endl;
return -1;
}
double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
cout << "Frame per seconds : " << fps << endl;
namedWindow("1",CV_WINDOW_AUTOSIZE);
namedWindow("2",CV_WINDOW_AUTOSIZE);
namedWindow("3",CV_WINDOW_AUTOSIZE);
namedWindow("4",CV_WINDOW_AUTOSIZE);
namedWindow("5",CV_WINDOW_AUTOSIZE);
int counter=0;
int check_counter=0;
std::string s;
cv::Rect myROI(699, 474, 10,16); //location of the countdown Timer
cv::Mat cropped;
templ = imread("/home/semih/Desktop/OPENCV_ON_LINUX/dizifiles/yenisoncalismalar/sifir00.png",CV_LOAD_IMAGE_COLOR);
cv::resize(templ,templ_resized,Size(8,11),CV_INTER_LINEAR); //8 11
Mat cropped_bw;
double minVal;
double maxVal;
Point minLoc;
Point maxLoc;
Point matchLoc;
cv::Mat pic;
while(1)
{
bool bSuccess = cap.read(frame);
if (!bSuccess)
{
cout << "Cannot read the frame from video file" << endl;
break;
}
counter=counter+1;
cv::Mat croppedRef(frame, myROI);
cvtColor(croppedRef,cropped_bw,CV_RGB2GRAY);
cropped_bw = cropped_bw > 200;
cvtColor(templ_resized,templ_resized_bw,CV_RGB2GRAY);
templ_resized_bw=templ_resized_bw>200;
imshow("1",cropped_bw);
imshow("2",frame);
imshow("3",templ);
imshow("4",templ_resized_bw);
int result_cols = cropped_bw.cols - templ_resized_bw.cols + 1;
int result_rows = cropped_bw.rows - templ_resized_bw.rows + 1;
result.create( result_cols, result_rows, CV_32FC1 );
matchTemplate( cropped_bw,templ_resized_bw, result, CV_TM_SQDIFF_NORMED);
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
matchLoc=minLoc;
int dogrula;
if(matchLoc.x>0){
check_counter=check_counter+1;
}
if(check_counter>20){ // if it stays 20 frames, assume "detected
cout<<"0 number detected"<<endl;
}
rectangle(cropped_bw, matchLoc, Point( matchLoc.x + templ_resized_bw.cols , matchLoc.y + templ_resized_bw.rows ), Scalar::all(100), 1, 8, 0 );
imshow("5",cropped_bw);
if(waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
As I am trying to search specific and same number I found this solution.
Which is comparing two images as if they are same.
#include<opencv2/highgui/highgui.hpp>
#include <iostream>
#include <stdio.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <sstream>
using namespace cv;
using namespace std;
Mat frame;
Mat img;
Mat templ;
Mat templ_resized;
Mat templ_resized_bw;
Mat result;
cv::Mat sel;
cv::Mat img_final;
//**************
int detect()
{
VideoCapture cap("/home/semih/Desktop/OPENCV_ON_LINUX/dizifiles/yenisoncalismalar/Final/kucukaga2.avi");
if ( !cap.isOpened() )
{
cout << "Cannot open the video file" << endl;
return -1;
}
double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
cout << "Frame per seconds : " << fps << endl;
int counter=0;
int check_counter=0;
std::string s;
cv::Rect myROI(702, 476, 11,16); // location of countdown timer
cv::Mat cropped;
templ = imread("/home/semih/Desktop/OPENCV_ON_LINUX/dizifiles/yenisoncalismalar/Final/thresh747.png",CV_LOAD_IMAGE_COLOR);
cv::resize(templ,templ_resized,Size(45,45),CV_INTER_LINEAR); //8 11
Mat cropped_bw;
double minVal;
double maxVal;
Point minLoc;
Point maxLoc;
Point matchLoc;
cv::Mat pic;
while(1)
{
bool bSuccess = cap.read(frame);
if (!bSuccess)
{
cout << "Cannot read the frame from video file" << endl;
break;
}
counter=counter+1;
cv::Mat croppedRef(frame, myROI);
cvtColor(croppedRef,cropped_bw,CV_RGB2GRAY);
cv::resize(cropped_bw,cropped_bw,Size(45,45),CV_INTER_LINEAR);
cropped_bw = cropped_bw > 200;
cvtColor(templ_resized,templ_resized_bw,CV_RGB2GRAY);
templ_resized_bw=templ_resized_bw>200;
cv::Mat result2;
Mat croppedsimilar;
Mat templ_resized_re;
Mat templ_cvt;
cvtColor(templ_resized, templ_cvt, CV_BGR2GRAY);
cv::resize(templ_cvt,templ_resized_re,Size(45,45),CV_INTER_LINEAR);
cv::resize(cropped_bw,croppedsimilar,Size(45,45),CV_INTER_LINEAR);
templ_resized_re=templ_resized_re>200;
croppedsimilar=croppedsimilar>200;
imshow("111",croppedsimilar);
imshow("222",templ_resized_re);
int threshold = (double)(templ_resized_re.rows * templ_resized_re.cols) * 0.97;
// Search for almost same match
cv::compare(croppedsimilar , templ_resized_re , result2 , cv::CMP_EQ );
int similarPixels = countNonZero(result2);
if ( similarPixels > threshold ) {
cout << "number '0' found !!!!!" << endl;
}
if(waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}

Resources