OpenCV with Visual Studio 2013(C++): findContours breakpoint error - c++

I am using OpenCV version 2.4.10.
When I debug I get the breakpoint error: wkernelbase.pdb not loaded.
Furthermore, I get this error in the output of Visual Studio:
First-chance exception at 0x7543C42D in Perspective.exe: Microsoft C++ exception: cv::Exception at memory location 0x003FEDDC.
Unhandled exception at 0x7543C42D in Perspective.exe: Microsoft C++ exception: cv::Exception at memory location 0x003FEDDC.
In my application, the command line prints this out:
OpenCV Error: Assertion failed <0 <= contourIdx< <int>last> in cv::drawContours, file...\..\..\..\opencv\imgproc\src\contours.cpp, line 1810
Any suggestions as to how to deal with this? Here is my code:
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "iostream"
using namespace cv;
using namespace std;
int main()
{
Mat image;
image = imread("shape.jpg", 1);
namedWindow("Display window", CV_WINDOW_AUTOSIZE);
imshow("Display window", image);
Mat gray;
cvtColor(image, gray, CV_BGR2GRAY);
Canny(gray, gray, 100, 200, 3);
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
RNG rng(12345);
findContours(gray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Draw contours
Mat drawing = Mat::zeros(gray.size(), CV_8UC3);
for (int i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
imshow("Result window", drawing);
waitKey(0);
return 0;
}
I know my image is in the correct directory as well.

This is a known compatibility issue between vs2013 and opencv
Try to replace
vector<vector<Point> > contours;
with
vector<cv::Mat> coutours;
That works in my case.

I tried your code.
This example (probably) doesn't make sense, but your code works.
This entire thing about VC10, VC12, ... can be quite messy. My suggestion is to try to follow the OpenCV HOWTO for Windows and Visual Studio. Maybe that way you will get around the problems you described in your question (or even find out what's wrong).

Related

OpenCV C++ VS2010: FindContours throws exception

Hi I am trying to run a simple OpenCV program to detect contours in a picture. however, findcontours keeps throwing exceptions.
here is my code:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <opencv2\opencv.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
/** #function main */
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <math.h>
#include <string.h>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char * argv[]) {
IplImage* img = cvLoadImage("C:\\Users\\310217955\\Documents\\Visual Studio 2010\\Projects\\aviTest\\Debug\\Pictures\\Capture.jpg");
cv::Mat image = cv::cvarrToMat(img);
if (!image.data) {
std::cout << "Image file not found\n";
return 1;
}
//Prepare the image for findContours
cv::cvtColor(image, image, CV_BGR2GRAY);
cv::threshold(image, image, 128, 255, CV_THRESH_BINARY);
//Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
//std::vector<std::vector<cv::Point> > contours;
vector<cv::Mat> contours;
cv::Mat contourOutput = image.clone();
cv::findContours( contourOutput, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );
//Draw the contours
cv::Mat contourImage(image.size(), CV_8UC3, cv::Scalar(0,0,0));
cv::Scalar colors[3];
colors[0] = cv::Scalar(255, 0, 0);
colors[1] = cv::Scalar(0, 255, 0);
colors[2] = cv::Scalar(0, 0, 255);
for (size_t idx = 0; idx < contours.size(); idx++) {
cv::drawContours(contourImage, contours, idx, colors[idx % 3]);
}
cv::imshow("Input Image", image);
cvMoveWindow("Input Image", 0, 0);
cv::imshow("Contours", contourImage);
cvMoveWindow("Contours", 200, 0);
cv::waitKey(0);
system("PAUSE");
return 0;
}
here is an image of the exception:
how can I get around this? is there a dll file im missing or some settings i need to resolve?
I did the following changes to the code
vector<Vec4i> hierarchy;
findContours( contourOutput, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
but now I get the following exception:
Well your code works perfectly fine.I only commented out the header files stdafx.h and nonfree.hpp in my project file . This is the output i gotenter image description here
Make sure you providing the correct path to the input img or paste your input image in your visual studio solution directory and just load the image directly.
The problem may be with one of the modules. I would suggest reinstalling opencv(try downloading the latest version) and try again. Make sure you are adding xyzd.lib files like opencv_highgui330d.lib opencv_imgproc330d.lib
in linker>>Input>> additional dependencies. the version might differ for you.
Hope this helps you!

OpenCV last convexity defect not right

I am trying to write code to track hands. I am using the convexity defects function to find fingers, but for some reason, there seems to always be a problem with the last defect.
Here is a picture of what I'm talking about (sorry, i''m new to the forum, so cannot post images)
The cyan line is the contours, the yellow line is the hull points, and the red lines are the defect points. As you can see the last defect point detects the defect from the wrong side of the contour.
Here is my code:
#include "opencv2\opencv.hpp"
using namespace cv;
using namespace std;
int main() {
VideoCapture cap(0);
Mat src, gray, background, binary, diff;
cap >> background;
cvtColor(background, background, CV_BGR2GRAY);
vector<vector<Point>> contours;
vector < vector<int>> hullI = vector<vector<int>>(1);
vector < vector<Point>> hullP = vector<vector<Point>>(1);
vector<Vec4i> defects;
while (waitKey(30)!='q') {
cap >> src;
cvtColor(src, gray, CV_BGR2GRAY);
blur(gray, gray, Size(3, 3));
absdiff(gray, background, diff);
threshold(diff, binary, 15, 255, THRESH_BINARY);
erode(binary, binary, Mat(Size(5, 5), CV_8U));
imshow("binary", binary);
findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
if (!contours.empty()) {
sort(contours.begin(), contours.end(), [](vector<Point> a, vector<Point> b) { return a.size() > b.size(); });
drawContours(src, contours, 0, Scalar(255, 255, 0));
convexHull(contours[0], hullI[0]);
convexHull(contours[0], hullP[0]);
drawContours(src, hullP, 0, Scalar(0, 255, 255));
if (hullI[0].size() > 2) {
convexityDefects(contours[0], hullI[0], defects);
for (Vec4i defect : defects) {
line(src, contours[0][defect[0]], contours[0][defect[2]], Scalar(0, 0, 255));
line(src, contours[0][defect[1]], contours[0][defect[2]], Scalar(0, 0, 255));
}
}
}
imshow("src", src);
char key = waitKey(30);
if (key == 'q')break;
else if (key == 'p') waitKey();
else if (key == 'b') {
cap >> background;
cvtColor(background, background, CV_BGR2GRAY);
}
}
}
I have confirmed through experiments that it is always the last defect in the defect vector that this happens too. Is this a bug in opencv or am I doing something wrong?
i tested your code (with a small modification) with the image below (OpenCV version is 3.2).
as you can see on the result image it works as expected. probably you are using an old version of OpenCV and getting a buggy result. (i think it was a bug recently fixed)
#include "opencv2\opencv.hpp"
using namespace cv;
using namespace std;
int main() {
//VideoCapture cap(0);
Mat src, gray, background, binary, diff;
//cap >> background;
//cvtColor(background, background, CV_BGR2GRAY);
vector<vector<Point> > contours;
vector < vector<int> > hullI = vector<vector<int> >(1);
vector < vector<Point> > hullP = vector<vector<Point> >(1);
vector<Vec4i> defects;
src = imread("hand.png");
cvtColor(src, gray, CV_BGR2GRAY);
blur(gray, gray, Size(3, 3));
threshold(gray, binary, 150, 255, THRESH_BINARY_INV);
//erode(binary, binary, Mat(Size(5, 5), CV_8U));
imshow("binary", binary);
findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
if (!contours.empty()) {
sort(contours.begin(), contours.end(), [](vector<Point> a, vector<Point> b) { return a.size() > b.size(); });
drawContours(src, contours, 0, Scalar(255, 255, 0));
convexHull(contours[0], hullI[0]);
convexHull(contours[0], hullP[0]);
drawContours(src, hullP, 0, Scalar(0, 255, 255));
if (hullI[0].size() > 2) {
convexityDefects(contours[0], hullI[0], defects);
for (Vec4i defect : defects) {
line(src, contours[0][defect[0]], contours[0][defect[2]], Scalar(0, 0, 255));
line(src, contours[0][defect[1]], contours[0][defect[2]], Scalar(0, 0, 255));
}
}
}
imshow("result", src);
char key = waitKey(0);
return 0;
}
I have a solution which involves detecting the skin using OpenCV. I implemented it using python, which you can convert easily to C++.
I obtained the HSV values of the image you uploaded using:
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
This the range for the HSV values of human skin:
l = np.array([0, 48, 80], dtype = "uint8")
u = np.array([20, 255, 255], dtype = "uint8")
skin_img = cv2.inRange(hsv_img, l, u)
cv2.imshow("Hand", skin_img)
I then performed morphological dilation and obtained the following:
You can now apply contour hull and find convexity defects.

Unspecified error (The function is not implemented.)

I want any advice how to solve this Error
I'm trying a sample code to check the opencv_contrib Extra modules using CMake
This is the error message:
And this is the sample code which I used
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);
/// Function header
void thresh_callback(int, void*);
/** #function main */
int main(int argc, char** argv)
{
/// Load source image and convert it to gray
src = imread("Baraya.jpg", 1);
/// Convert image to gray and blur it
cvtColor(src, src_gray, CV_BGR2GRAY);
blur(src_gray, src_gray, Size(3, 3));
/// Create Window
char* source_window = "Source";
namedWindow(source_window, CV_WINDOW_AUTOSIZE);
imshow(source_window, src);
createTrackbar(" Threshold:", "Source", &thresh, max_thresh, thresh_callback);
thresh_callback(0, 0);
waitKey(0);
return(0);
}
/** #function thresh_callback */
void thresh_callback(int, void*)
{
Mat threshold_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Detect edges using Threshold
threshold(src_gray, threshold_output, thresh, 255, THRESH_BINARY);
/// Find contours
findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Approximate contours to polygons + get bounding rects and circles
vector<vector<Point> > contours_poly(contours.size());
vector<Rect> boundRect(contours.size());
vector<Point2f>center(contours.size());
vector<float>radius(contours.size());
for (int i = 0; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
boundRect[i] = boundingRect(Mat(contours_poly[i]));
minEnclosingCircle((Mat)contours_poly[i], center[i], radius[i]);
}
/// Draw polygonal contour + bonding rects + circles
Mat drawing = Mat::zeros(threshold_output.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point());
rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0);
circle(drawing, center[i], (int)radius[i], color, 2, 8, 0);
}
/// Show in a window
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
}
There is no error in the code you posted. It works well if you installed OpenCV properly. This error is because you didn't build with any windowing system .
This error is from here:
#if defined (HAVE_WIN32UI) // see window_w32.cpp
#elif defined (HAVE_GTK) // see window_gtk.cpp
#elif defined (HAVE_COCOA) // see window_carbon.cpp
#elif defined (HAVE_CARBON)
#elif defined (HAVE_QT) // see window_QT.cpp
#elif defined (WINRT) && !defined (WINRT_8_0) // see window_winrt.cpp
#else
// No windowing system present at compile time ;-(
//
// We will build place holders that don't break the API but give an error
// at runtime. This way people can choose to replace an installed HighGUI
// version with a more capable one without a need to recompile dependent
// applications or libraries.
void cv::setWindowTitle(const String&, const String&)
{
CV_Error(Error::StsNotImplemented, "The function is not implemented. "
"Rebuild the library with Windows, GTK+ 2.x or Carbon support. "
"If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script");
}
So re-run CMAKE with WITH_WIN32UI, since you are on Windows, and eventually with WITH_QT.

BackgroundSubtractorMOG2 , can i save image from it. i am getting error while saving images from BackgroundSubtractorMOG2

i am using backgroundMOG2 to save the images with background , but the program shows the countrs , i need to save the images with backgorund.
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <opencv2/video/background_segm.hpp>
int main()
{
cv::Mat frame;
cv::Mat back;
cv::Mat fore;
//cv::Mat img;
cv::VideoCapture cap("C:\\Users\\Pavilion\\Documents\\Visual Studio 2013\\Projects\\dynamic\\sherlock outtakes.avi");
cv::BackgroundSubtractorMOG2 bg;
bg.set("nmixtures", 3);
//bg.bShadowDetecction=false;
std::vector<std::vector<cv::Point>>countours;
//cv::imread("C:\\Users\\Pavilion\\Documents\\Visual Studio 2013\\Projects\\video\\video\\frames\\frame122.jpg");
//cv::VideoCapture Cap;
//std::vector<std::vector<cv::point> >contours;
cv::namedWindow("frame");
cv::namedWindow("background");
for (;;)
{
cap >> frame;
bg.operator()(frame, fore);
bg.getBackgroundImage(back);
cv::erode(fore, fore, cv::Mat());
cv::dilate(fore, fore, cv::Mat());
cv::findContours(fore,countours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::drawContours(frame, countours, -1, cv::Scalar(0, 0, 255), 1);
cv::imshow("frame", back);
// cv::imwrite("background",back);
cv::imshow("background", frame);
if (cv::waitKey(30) >=0) break;
}
return 0;
}
this is the code i am getting error while saving image .
can someone help me to solve this
You need to specify an extension (jpg, png, ...).
For example:
cv::imwrite("background.jpg",back);

debug assertion error when using findcontour function of opencv with kinect 2

I want to use kinect sdk 2.0 with opencv for shape detection. for that i want to get contour of for the image frame. But i am getting assertion error when I use findcontour function of opencv.
here is the code I used:
void Kinect::ProcessColor(RGBQUAD* pBuffer, int nWidth, int nHeight)
{
// Make sure we've received valid data
if (pBuffer && (nWidth == cColorWidth) && (nHeight == cColorHeight))
{
// Draw the data with OpenCV
Mat ColorImage(nHeight, nWidth, CV_8UC4, pBuffer);
//Mat ColorImage;
//ColorImage = imread("C:/Users/IWP/Desktop/Untitled.png", CV_LOAD_IMAGE_COLOR);
//imshow("ColorImage", ColorImage);
// Convert it to gray
Mat src_gray;
cvtColor(ColorImage, src_gray, CV_BGR2GRAY);
// Canny
Mat src_canny;
Canny(src_gray, src_canny, 75, 125, 3);
//threshold(src_gray, src_canny, 128, 255, CV_THRESH_BINARY);
// find the contours
vector< vector<Point> > contours;
findContours(src_canny, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
Mat showImage;
resize(src_canny, showImage, Size(nWidth / 2, nHeight / 2));
imshow("ColorImage", showImage);////imshow("ColorImage", ColorImage);
}
}