I am using OpenCV 3.2 and compiling it with Visual Studio 2017.
I am trying to build a simple motion tracking code by thresholding a camera feed into a binary image, then using the OpenCV's findContours
function to detect the object. Unfortunately, I have been running into an error which says that there is an unhandled exception at the function.
(error message)
I have linked the OpenCV libraries by manually adjusting the project properties as following:
- C/C++ - General - Additional Include Directory -
C:\opencv320\build\include
- Linker - General - Additional Library Directory -
C:\opencv320\build\x64\vc14\lib
- Linker - Input - Additional Dependencies -
opencv_world320d.lib
andopencv_world320.lib
I have been testing different codes with the same findContours
function, but no matter the code, it seems to give the same error. I think it has to do with the heap, and how memory is allocated and deallocated, but I cannot seem to debug it myself.
Here is an example code that I have been testing:
#include "stdafx.h"
#include <opencv2\highgui.hpp>
#include <opencv2\videoio.hpp>
#include <opencv2\opencv.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
struct Component
{
cv::Rect boundingBox;
double area;
double circularity;
};
int main()
{
// Create a small image with a circle in it.
cv::Mat image(256, 256, CV_8UC3, cv::Scalar(0, 0, 0));
cv::circle(image, cv::Point(80, 110), 42, cv::Scalar(255, 127, 63), -1);
// Find canny edges.
cv::Mat cannyEdges;
cv::Canny(image, cannyEdges, 80, 60);
// Show the images.
cv::imshow("img", image);
cv::imshow("cannyEdges", cannyEdges);
// Find the contours in the canny image.
std::vector<cv::Vec4i> hierarchy;
// "Each contour is stored as a vector of points."
typedef std::vector<std::vector<cv::Point> > TContours;
TContours contours;
cv::findContours(cannyEdges, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
// cannyEdges is destroyed after calling cv::findContours
// Print number of found contours.
std::cout << "Found " << contours.size() << " contours." << std::endl;
// Convert contours to Components.
typedef std::vector<Component> TComponents;
TComponents components;
for (TContours::const_iterator it(contours.begin()); it != contours.end(); ++it)
{
Component c;
c.area = cv::contourArea(*it);
c.boundingBox = cv::boundingRect(*it);
c.circularity = 0.0; // Insert whatever you mean by circularity;
components.push_back(c);
}
for (TComponents::const_iterator it(components.begin()); it != components.end(); ++it)
std::cout << it->area << std::endl; // and whatever you want.
// Wait for user input.
cv::waitKey();
}