Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Fill the outer part of the detected contour/crop the detected contour

Now, I found the pupil of the fish to examine its freshness by counting the pixels on it. My first idea is to black the outer contour to count the white pixels inside the contour(pupil). The second idea is to crop the contour part I've found. But the problem is I don't how to do it. Please somebody edit my code or give me a step instruction how to do it.

image description

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
int main(int argc, char** argv)
{
RNG rng(12345);
// Load image
Mat src = imread("D:/sapsaphead.jpg");

// Invert the source image and convert to grayscale
Mat gray;
cvtColor(~src, gray, CV_BGR2GRAY);

// Convert to binary image by thresholding it
threshold(gray, gray, 220, 255, THRESH_BINARY);

// Find all contours
vector<vector<Point> > contours;
findContours(gray.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

for (int i = 0; i < contours.size(); i++)
{
    double area =contourArea(contours[i]);
    Rect rect = boundingRect(contours[i]);
    int radius = rect.width/2;

    // If contour is big enough and has round shape
    // Then it is the pupil
    if (area >= 30 && abs(1 - ((double)rect.width / (double)rect.height)) <= 0.2)   
    {

         Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255),
rng.uniform(0,255) );
        // contour
         drawContours( src, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
    }
}

cv::imshow("image", src);
cv::waitKey(0);

return 0;
}