opencv detectMultiScale - c++

Im trying to learn opencv and object detection. I used objecdetection.cpp in opencv samples and when I run it I get this error
The cascade loads perfectly fine and also the camera the only problem is detectmultiscale because whenever i commented it out the program doesn't crash
here is the code of objectdecetion2.cpp
#include "opencv2/objdetect.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay(Mat frame);
/** Global variables */
String face_cascade_name = "..\\Debug\\haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "..\\Debug\\haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
String window_name = "Capture - Face detection";
/**
* #function main
*/
int main(void)
{
VideoCapture capture;
Mat frame;
//-- 1. Load the cascade
if (!face_cascade.load(face_cascade_name)){ printf("--(!)Error loading face cascade\n"); return -1; };
if (!eyes_cascade.load(eyes_cascade_name)){ printf("--(!)Error loading eyes cascade\n"); return -1; };
//-- 2. Read the video stream
capture.open(0);
if (!capture.isOpened()) { printf("--(!)Error opening video capture\n"); return -1; }
while (capture.read(frame))
{
if (frame.empty())
{
printf(" --(!) No captured frame -- Break!");
break;
}
//-- 3. Apply the classifier to the frame
detectAndDisplay(frame);
//-- bail out if escape was pressed
int c = waitKey(10);
if ((char)c == 27) { break; }
}
return 0;
}
/**
* #function detectAndDisplay
*/
void detectAndDisplay(Mat frame)
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0, Size(80, 80));
imshow(window_name, frame);
}

You are likely experiencing an OpenCV bug, described here: http://code.opencv.org/issues/3710
The code you posted looks OK to me, otherwise.

The code you posted is right! But I doubt that your opencv configuration is not right! If you work on windows, Please check your .dll files and lib files!

Related

C++ OPENCV 4.3.0 x64 Why face_cascade throws error?

I am using OpenCV to add a face recognition feature to my C++ program. I have never used it before and I cant seem to get the cascade feature for facial recognition to work. I am wondering if they have made some changes for the FLAGS in the new version. I can display an image but when that comes to the cascade it always throws an error. Can anyone tell me what am I missing?
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <stdio.h>
#include <iostream>
#include <opencv2\objdetect.hpp>
using namespace std;
using namespace cv;
String face_cascade_name = "sources/data/haarcascades/haarcascade_frontalface_default.xml";
String eyes_cascade_name = "sources/data/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
String smile_cascade_name = "sources/data/haarcascades/haarcascade_smile.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
CascadeClassifier smile_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);
int main()
{
//-- 1. Load the cascades
if (!face_cascade.load(face_cascade_name)) { printf("--(!)Error loading file 1\n"); return -1; };
if (!eyes_cascade.load(eyes_cascade_name)) { printf("--(!)Error loading file 2\n"); return -1; };
if (!smile_cascade.load(smile_cascade_name)) { printf("--(!)Error loading file 3\n"); return -1; };
std::string image_path = samples::findFile("test.jpg");
Mat img = imread(image_path, IMREAD_COLOR);
Mat img_gry;
if (img.empty())
{
std::cout << "Could not read the image: " << image_path << std::endl;
return 1;
}
imshow("Display window", img);
// Detect faces
std::vector<Rect> faces;
cvtColor(img, img_gry, COLOR_BGR2GRAY);
equalizeHist(img, img_gry);
//I GET ERROR HERE
face_cascade.detectMultiScale(img_gry, faces, 1.1, 2, CASCADE_SCALE_IMAGE, Size(30, 30), Size(130, 130)); //I GET ERROR HERE
/*...REST WILL BE PARSING faces...*/
int g_key = waitKey(0); // Wait for a keystroke in the window
if (g_key == 's')
{
imwrite("starry_night.png", img); //save image in same path
}
return 0;
}
I modified the code as:
/*...
OTHER CODE
...*/
std::vector<Rect> faces;
cvtColor(img, img_gry, COLOR_BGR2GRAY);
equalizeHist(img_gry, img_gry);
face_cascade.detectMultiScale(img_gry, faces);
for (size_t i = 0; i < faces.size(); i++)
{
/*...PARSE...*/
}
imshow("Display window", img);
As #SourceCode mentioned :
equalizeHist( smallImg, smallImg); //my variable is img_gry instead.
But also, I modified :
face_cascade.detectMultiScale(img_gry, faces, 1.1, 2, CASCADE_SCALE_IMAGE, Size(30, 30), Size(130, 130));
To
face_cascade.detectMultiScale(img_gry, faces);
Otherwise it does not work in my case.
Source if that helps: https://docs.opencv.org/3.4/db/d28/tutorial_cascade_classifier.html
Have you tried using something like:
face_cascade.detectMultiScale(img_gry, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30));

Debug Assertion failed ! in detectAndDisplay function of face recognition openCv

I am trying to run the program and is building well but not able to debug. Capturing first frame and then giving below error.
I tried to check in debug mode and could figure out that
imshow(window_name, frame);
Error !!!
Here is the working code that is copied from OpenCV blog.
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/** 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(CV_CAP_ANY);
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);
}
Error when value chosen in
capture = cvCaptureFromCAM(-1)
is -1.
I am getting GRey window with no Error.
imshow with Grey Window, No Error
I changed the Platform Toolset from Visual Studio 2015(v140) to Visual Studio 2013(v120) as in the figure attached. I do not know why but it worked.
Visual Studio 2015(v140)
Visual Studio 2013(v120)
It may happen, if your face ROI, out of frame bounds.
Because you trying to copy this region you getting memory error.
if(faces[i].x>=0 && faces[i].y >= 0 && faces[i].x+faces[i].width<frame_gray.cols && faces[i].y+faces[i].height < frame_gray.rows)
{
faceROI=frame_gray(faces[i]);
}

Visual Studio 2010 console window closes immediately using opencv

I'm developing a project with visual studio 2010 and opencv. Here is my problem: i acquire a video from webcam, analize it, do some operation on it and then i show the result in another window (Object Tracking). The code is ok, no compiling errors but as soon as i start the program the console windows it closes immediately and i cannot see both the original and the modified video. If i debug the code i can see the webcam works and acquire images but obviously i ned to do this in real time. Any suggestion?
Can you give any code?
Are you write and compile any video player program like this?
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
//Video Capture cap(path_to_video); // open the video file
if(!cap.isOpened()) // check if we succeeded
return -1;
namedWindow("Video",1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
imshow("Video", frame);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
Try this:
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main() {
VideoCapture cap(0);
while (true)
{
Mat imgOriginal;
Mat imgHSV;
bool bSuccess = cap.read(imgOriginal);
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
imshow("Thresholded Image", imgHSV);
imshow("Original", imgOriginal);
waitKey(33);
}
return 0;
}

Unable to read video file in OpenCV

I am trying to capture a video and store it in a file and then read the same video file. I am able to write it but not able to read the same file. On pressing escape, the program is supposed to quit the webcam and play the recorded video but displays the following error instead:
mpeg1video # 0x2a16f40] ac-tex damaged at 14 28
[mpeg1video # 0x2a16f40] Warning MVs not available
OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in cvGetMat, file /home/ujjwal/Downloads/OpenCV-2.4.0/modules/core/src/array.cpp, line 2482
terminate called after throwing an instance of 'cv::Exception'
what(): /home/ujjwal/Downloads/OpenCV-2.4.0/modules/core/src/array.cpp:2482: error: (-206) Unrecognized or unsupported array type in function cvGetMat
The code is:
#include <sstream>
#include <string>
#include <iostream>
#include <opencv/highgui.h>
#include <opencv/cv.h>
using namespace cv;
int main(int argc, char* argv[])
{
Mat inputVideo;
Mat frame;
Mat HSV;
Mat tracking;
char checkKey;
VideoCapture capture;
capture.open(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,480);
VideoWriter writer("OutputFile.mpeg", CV_FOURCC('P','I','M','1'), 50, Size(640, 480));
while(1){
capture.read(inputVideo);
imshow("Original Video",inputVideo);
writer.write(inputVideo);
checkKey = cvWaitKey(20);
if(checkKey == 27)
break;
}
capture.open("OutputFile.mpeg");
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,480);
while(1){
capture.read(inputVideo);
imshow("Tracking Video", inputVideo);
}
return 0;
}
Can someone please help me? Thanks!
You need to correct several things to make it work:
You have to create the window before showing images in the window.
You have to close the writer to finish writing before open it later.
You need to add cvWaitKey(20) for the second image showing (check out here for why this is essential).
The whole fixed code is as follows:
#include <sstream>
#include <string>
#include <iostream>
#include <opencv/highgui.h>
#include <opencv/cv.h>
using namespace cv;
int main(int argc, char* argv[])
{
Mat inputVideo;
Mat frame;
Mat HSV;
Mat tracking;
char checkKey;
VideoCapture capture;
capture.open(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,480);
VideoWriter writer("OutputFile.mpeg", CV_FOURCC('P','I','M','1'), 50, Size(640, 480));
namedWindow("Original Video", WINDOW_AUTOSIZE );
while(1){
capture.read(inputVideo);
imshow("Original Video",inputVideo);
writer.write(inputVideo);
checkKey = cvWaitKey(20);
if(checkKey == 27)
break;
}
writer.release();
capture.open("OutputFile.mpeg");
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,480);
namedWindow("Tracking Video", WINDOW_AUTOSIZE );
while(1){
capture.read(inputVideo);
if (!inputVideo.empty())
{
imshow("Tracking Video", inputVideo);
checkKey = cvWaitKey(20);
}
else
break;
}
return 0;
}

OpenCV unable to capture image from isight webcam

I can not capture image from my webcam using following OpenCV code.
The code can show images from a local AVI file or a video device. It works fine on a "test.avi" file.
When I make use my default webcam(CvCapture* capture =cvCreateCameraCapture(0)), the program can detected the size of the image from webcam,but just unable to display the image.
/I forgot to mention that I can see the iSight is working because the LED indicator is turn on/
Anyone encounter the same problem?
cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE );
CvCapture* capture =cvCreateFileCapture( "C:\\test.avi" ) ;// display images from avi file, works well
// CvCapture* capture =cvCreateCameraCapture(0); //display the frame(images) from default webcam not work
assert( capture );
IplImage* image;
while(1) {
image = cvQueryFrame( capture );
if( !image ) break;
cvShowImage( "Example2", image );
char c = cvWaitKey(33);
if( c == 27 ) break;
}
cvReleaseCapture( &capture );
cvDestroyWindow( "Example2" );
opencv 2.2
Debug library *d.lib
WebCam isight
Macbook OS win7 32
VS2008
I'm working on opencv 2.3 with Macbook pro Mid 2012 and I had that problem with the Isight cam. Somehow I managed to make it work on opencv by simply adjusting the parameters of the Cvcapture and adjusting the frame width and height:
CvCapture* capture = cvCaptureFromCAM(0);
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 500 );
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 600 );
You can also change these numbers to the frame width and height you want.
Did you try the example from the opencv page?
namely,
#include "cv.h"
#include "highgui.h"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
Works on a macbook pro for me (although on OS X). If it doesn't work, some kind of error message would be helpful.
Try this:
int main(int, char**) {
VideoCapture cap(0); // open the default camera
if (!cap.isOpened()) { // check if we succeeded
cout << "===couldn't open camera" << endl;
return -1;
}
Mat edges, frame;
frame = cv::Mat(10, 10, CV_8U);
namedWindow("edges", 1);
for (;;) {
cap >> frame; // get a new frame from camera
cout << "frame size: " << frame.cols << endl;
if (frame.cols > 0 && frame.rows > 0) {
imshow("edges", frame);
}
if (waitKey(30) >= 0)
break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
Latest update! Problem solved!
This happen to be one of OpenCV 2.2′s bug
Here is how to fix it:
http://dusijun.wordpress.com/2011/01/11/opencv-unable-to-capture-image-from-isight-webcam/
Why dont you try
capture=cvCaptureFromCam(0);
I think this may work.
Let me know about wheather its working or not.