Hello There! I am trying to find the location of a green ball in the frame of a video stream. I am using a logitech webcam for the program. I am first thresholding the green ball out of the video frame and performing countour finding. Then I am trying to perform enclosing circles function but my program crashes before at the approxPolyDP() function. I am programming in C++, with Opencv 4.1.0.
#include <QCoreApplication>
#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace cv;
//Declaring variables globally
Mat frame,frame_copy,frame_down,frame_blur,frame_hsv, frame_gray, frame_threshold, frame_erode, frame_dilate, frame_canny ;
const int max_value_H = 360/2;
const int max_value = 255;
int low_H = 29, low_S = 86, low_V = 6;
int high_H = 64, high_S = max_value, high_V = max_value;
RNG rng(12345);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
VideoCapture stream = VideoCapture(1); //Opening video streaming from external camera
if(!stream.isOpened()){cout<<"VideoStream not available!"<<endl; return 0;}
while(true)
{
stream.read(frame);
frame_copy = frame;
pyrDown(frame,frame_down,Size(frame.cols/2,frame.rows/2));
blur(frame_down, frame_blur, Size(3,3));
cvtColor(frame_blur,frame_hsv,COLOR_BGR2HSV);
inRange(frame_hsv, Scalar(low_H, low_S, low_V), Scalar(high_H, high_S, high_V), frame_threshold);
Mat element = getStructuringElement( MORPH_OPEN,Size(5, 5) );
erode( frame_threshold, frame_erode, element );
dilate( frame_erode, frame_dilate, element );
Canny(frame_dilate,frame_canny,100,200);
imshow("Canny",frame_canny);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
vector<vector<Point>> contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
vector<Point2f>centers( contours.size() );
vector<float>radius( contours.size() );
findContours( frame_canny, contours, RETR_TREE, CHAIN_APPROX_SIMPLE );
Mat drawing = Mat::zeros( frame_canny.size(), CV_8UC3 );
if(contours.size()>0)
{
for( size_t i = 0; i< contours.size(); i++ )
{
approxPolyDP(contours[i],contours_poly[i],3,true);
// boundRect[i] = boundingRect( contours_poly[i] );
minEnclosingCircle( contours_poly[i], centers[i], radius[i] );
}
for( size_t i = 0; i< contours.size(); i++ ) //Drawing contours that were found
{
Scalar color = Scalar( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );
// drawContours( drawing, contours_poly, (int)i, color );
// rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2 );
circle( drawing, centers[i], (int)radius[i], color, 2 );
}
}
imshow("threshold",frame_dilate);
imshow("contours",drawing);
waitKey(1);
}
return a.exec();
}
Please can anyone guide me as to what I am doing wrong and/or suggest anything better?
Thanks!