Ask Your Question
1

Colour + Contour Detection

asked 2015-11-25 07:39:36 -0600

grisi gravatar image

updated 2015-11-30 10:29:15 -0600

hey pklab,

sorry for late reply, eclipse stated some really weird errors, now it's finally building: The actual code is this one ( I replaced my TrackingObject function with yours):

the picture looks as following. Would you suggest to improve the code or to go back to the old one? Can you explain me, why the picture looks like that?

contours.jpg

#include <cv.h>
#include <highgui.h>
#include <iostream>
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;


//initial min and max HSV filter values.
//these will be changed using trackbars
int H_MIN = 0;
int H_MAX = 256;
int S_MIN = 0;
int S_MAX = 256;
int V_MIN = 0;
int V_MAX = 256;

//default capture width and height
const int FRAME_WIDTH = 640;
const int FRAME_HEIGHT = 480;
//max number of objects to be detected in frame
const int MAX_NUM_OBJECTS=50;
//minimum and maximum object area
const int MIN_OBJECT_AREA = 5*5;
const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH/1.5;
//names that will appear at the top of each window
const string windowName = "Original Image";
const string windowName1 = "HSV Image";
const string windowName2 = "Thresholded Image";
const string windowName3 = "After Morphological Operations";
const string trackbarWindowName = "Trackbars";
void on_trackbar( int, void* )
{//This function gets called whenever a
    // trackbar position is changed
 }
string intToString(int number){


    std::stringstream ss;
    ss << number;
    return ss.str();
}
void createTrackbars(){
    //create window for trackbars


    namedWindow(trackbarWindowName,0);


    //create trackbars and insert them into window
    //3 parameters are: the address of the variable that is changing when the trackbar is moved(eg.H_LOW),
    //the max value the trackbar can move (eg. H_HIGH),
    //and the function that is called whenever the trackbar is moved(eg. on_trackbar)
    //                                  ---->    ---->     ---->
    createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_trackbar );
    createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_trackbar );
    createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_trackbar );
    createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_trackbar );
    createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_trackbar );
    createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_trackbar );




}
void drawObject(int x, int y,Mat &frame){

    //use some of the openCV drawing functions to draw crosshairs
    //on your tracked image!

    //UPDATE:JUNE 18TH, 2013
    //added 'if' and 'else' statements to prevent
    //memory errors from writing off the screen (ie. (-25,-25) is not within the window!)

    circle(frame,Point(x,y),20,Scalar(0,255,0),2);
    if(y-25>0)
    line(frame,Point(x,y),Point(x,y-25),Scalar(0,255,0),2);
    else line(frame,Point(x,y),Point(x,0),Scalar(0,255,0),2);
    if(y+25<FRAME_HEIGHT)
    line(frame,Point(x,y),Point(x,y+25),Scalar(0,255,0),2);
    else line(frame,Point(x,y),Point(x,FRAME_HEIGHT),Scalar(0,255,0),2);
    if(x-25>0)
    line(frame,Point(x,y),Point(x-25,y),Scalar(0,255,0),2);
    else line(frame,Point(x,y),Point(0,y),Scalar(0,255,0),2);
    if(x+25<FRAME_WIDTH)
    line(frame,Point(x,y),Point(x+25,y),Scalar(0,255,0),2);
    else line(frame,Point(x,y),Point(FRAME_WIDTH,y),Scalar(0,255,0),2);

    putText(frame,intToString(x)+","+intToString(y),Point(x,y+30),1,1 ...
(more)
edit retag flag offensive close merge delete

Comments

please provide the code you already used. and a sample image will be helpful

sturkmen gravatar imagesturkmen ( 2015-11-25 08:12:58 -0600 )edit

You could use someting like my recent answer here.This detects all red objects.

You can select wanted object filtering by Circularity or Size. You could also consider that between 2 consecutive frames the ball will move very little. Use this information to track objects between frames and select/discard them. Finally you could try Motion Analysis and Object Tracking with opencv.

pklab gravatar imagepklab ( 2015-11-25 09:20:39 -0600 )edit

Hello sturkmen,

thanks for ur help and sorry for the late reply

unfortunately I can't post it in the comment section since the amount of characters is restricted. I could post it in the answer-section but I need to wait 2 days before I can answer my own question

best, bibof

grisi gravatar imagegrisi ( 2015-11-26 05:48:19 -0600 )edit

@Bibof you could edit your question

pklab gravatar imagepklab ( 2015-11-26 09:40:21 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2015-11-27 10:38:55 -0600

pklab gravatar image

updated 2015-12-02 09:51:06 -0600

You are mixing contours and circles from HoughCircles in a obscure way. Detected circles OR contours and select your favourite.

  • If you want to filter circles by area you can get it from radius or not ?
  • If you want to filter contours by circularity calculate it as circularity = 4 * PI * area / perimeter^2
  • use findContours with CV_RETR_EXTERNAL and forget forget about hierarchy
  • you are looking for largest area. Maybe it isn't the ball. Sure your control var objectFound id bad managed because it can become false after it has been true.

here is a ready to use function for contour circularity

/**
* @brief Calculates circularity measure of a contour using common standard method
* The circularity is calculated with common method as relation between area and perimeter as:
*
* Circularity = (4 * PI * area) / (perimeter^2)
*
* @returns ranges over [0, 1] where 1 means that the contour is a perfect circle
* if area or perimeter is <=0 than circularity will be 0
*
* @note this returns 0.785 for squares
*/
double CircularityStandard(double area,double perimeter)
{
    if( (area<=0) || (perimeter<=0)) return 0;
    return (4 * CV_PI*area) / (perimeter*perimeter);
}
double CircularityStandard(const vector<cv::Point> &contour)
{
    double area = cv::contourArea(contour);
    if (area == 0) return 0.0;
    double perimeter = cv::arcLength(contour, true);
    if (perimeter == 0) return 0.0;
    return (4 * CV_PI*area) / (perimeter*perimeter);
}

here is a code I could write (EDIT: small bug removed)

result image description

void trackFilteredObject(int &x, int &y, const Mat &threshold, Mat &cameraFeed)
{
    vector< vector<Point> > contours;
    vector<Vec4i> hierarchy;

    // find external contours ignores holes
    cv::findContours(threshold, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

    //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter
    if (contours.size() > MAX_NUM_OBJECTS)
    {
        putText(cameraFeed, "TOO MUCH NOISE! ADJUST FILTER", Point(0, 50), 1, 2, Scalar(0, 0, 255), 2);
        return;
    }


    double refArea = 0;
    bool objectFound = false;
    double circularity;
    //int largest = -1;
    double minCircularity = 0.85; //use something > 0.85
    for (size_t i = 0; i < contours.size(); i++)
    {
        // Mat src;
        // Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
        // draw all contours in red
        cv::drawContours(cameraFeed, contours, i, cv::Scalar(255, 255, 0), 2);

        cv::Moments moment = moments(contours[i]);
        double area = moment.m00;
        double perimeter = cv::arcLength(contours[i], true);
        //circularity = CircularityStandard(contours[i]); //alternative overload
        circularity = CircularityStandard(area, perimeter);
        putText(cameraFeed, "Circularity="+to_string(circularity), 
            contours[i][0], 2, 1, Scalar(255, 255, 0), 1);
        if (circularity < minCircularity) //use something > 0.85
            continue;

        // draw all circles in blue
        int cx = cvRound(moment.m10 / area);
        int cy = cvRound(moment.m01 / area);
        cv::Point center(cx, cy);
        int radius = cvRound(sqrt(area / CV_PI));
        // circle center
        circle(cameraFeed, center, 3, Scalar(0, 255, 0), -1, 8, 0);
        // circle outline
        circle(cameraFeed, center, radius, Scalar(255, 0, 0), 3, 8, 0);

        //if the area is less than 20 px by 20px then it is probably just noise
        //if the area is the same as the 3/2 of the image size, probably just a bad filter
        //object wanted with the largest area so a reference area ...
(more)
edit flag offensive delete link more

Comments

Hello,

thank you very much. I deleted my answer as whished. I will have a look at your code now and answer later on!! :-)

Best, chris

grisi gravatar imagegrisi ( 2015-11-28 09:07:48 -0600 )edit

hey pklab,

I'm have troubling with setting up openCV in eclipse on my windows machine. (usually I'm working on eclipse in linux at university) so I can't run that code now, but on monday when I'm back at uni.

i got a short question:

"You are mixing contours and circles from HoughCircles in a obscure way. Detected circles OR contours and select your favourite."

I'm searching for a condition that "combines" both cases, just to filter out everything that is red and not a ball.

there must always be one tracked object, because the coordinates of that will be sent to a pid controller which adjusts the flight direction of the drone.

thanks :) chris

grisi gravatar imagegrisi ( 2015-11-28 12:17:26 -0600 )edit

ok do it your comparison, try your HoughCircles+countour with countour filtered by circularity and let us know ;)

pklab gravatar imagepklab ( 2015-11-28 13:31:38 -0600 )edit

hello :)

yes I will let you know by tomorrow!! Thanks in advance, have a nice sunday

best chris

grisi gravatar imagegrisi ( 2015-11-29 09:31:10 -0600 )edit

hey pklab,

"ok do it your comparison, try your HoughCircles+countour with countour filtered by circularity and let us know ;)"

I'm not sure how to implement this.

maybe here? :

if(area>MIN_OBJECT_AREA && area<MAX_OBJECT_AREA && area>refArea &&  CircularityStandard > 0.7   )

may you also tell me what you mean with: "you are looking for largest area. Maybe it isn't the ball. Sure your control var objectFound id bad managed because it can become false after it has been true."

thank you!!

best, chris

grisi gravatar imagegrisi ( 2015-11-30 03:06:53 -0600 )edit

You can do as you want. I done it before with if (circularity < minCircularity). About "largest area" I refer to your old code

pklab gravatar imagepklab ( 2015-11-30 06:17:59 -0600 )edit
1
  1. please don't use questions like email !
  2. don't do copy&paste than ask just doesn't work !
  3. a bit of debug will help you !!!! there is a bug.
    • replace cx, cy in cv::Point center(x, y);
    • replace area in int radius = cvRound(sqrt(refArea / CV_PI));
    • remember that red has 2 ranges in HSV. Again: Look at this for right inRange usage with red
    • try using lower circularity minCircularity = 0.85 . If it's work accept the answer..

BTW I suggest to track the motion or the position between frames instead of circles

pklab gravatar imagepklab ( 2015-11-30 12:10:12 -0600 )edit

thx, sorry I'm just really new to opencv and c++. everything takes a bit longer.

I will continue with working by tomorrow and then I can give you a feedback. thank you

grisi gravatar imagegrisi ( 2015-12-01 14:09:55 -0600 )edit

hello,

I implemented your corrections, but there is no change so far. i will try to fix it and post the status afterwards

greetings, bibof

grisi gravatar imagegrisi ( 2015-12-02 06:42:28 -0600 )edit

"BTW I suggest to track the motion or the position between frames instead of circles"

May you tell me why you would suggest that?

grisi gravatar imagegrisi ( 2015-12-02 07:20:29 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2015-11-25 07:39:09 -0600

Seen: 1,814 times

Last updated: Dec 02 '15