How to black out everything outside a circle in Open CV

Sebastian Boldt picture Sebastian Boldt · Aug 27, 2013 · Viewed 7.7k times · Source

I am currently trying to black out everything outside a circle. I am drawing the circle using the following lines of code:

cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); // CVRound converts floating numbers to integer
int radius = cvRound(circles[i][2]);                              // Radius is the third parameter [i][0] = x [i][1]= y [i][2] = radius
circle( image, center, 3, cv::Scalar(0,255,0), -1, 8, 0 );        // Drawing little circle to Image Center , next Line of Code draws the real circle
circle( image, center, radius, cv::Scalar(0,0,255), 3, 8, 0 );    // Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)

What is the best approach of painting everything of the circly black, if I have a radius and the center of my circle? Does OpenCV provide an easy mechanism of doing this or should I iterate through all the pixels of my image and depending on the position color them black or not?

Answer

Sebastian Boldt picture Sebastian Boldt · Aug 27, 2013

Thanks to Abid for the hint, i ended up with this approach. Everything works fine:

cv::Mat src = someMethodThatReturnsSrcImage(); // src Image 
cv::Mat maskedImage; // stores masked Image
std::vector<cv::Vec3f> circles = someMethodThatReturnsCircles(src);    
cv::Mat mask(srcImageForDimensions.size(),srcImageForDimensions.type());  // create an Mat that has same Dimensons as src
mask.setTo(cv::Scalar(0,0,0));                                            // creates black-Image
    // Add all found circles to mask
for( size_t i = 0; i < circles.size(); i++ )                          // iterate through all detected Circles
       {
         cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); // CVRound converts floating numbers to integer
         int radius = cvRound(circles[i][2]);                              // Radius is the third parameter [i][0] = x [i][1]= y [i][2] = radius
         cv::circle( mask, center, radius, cv::Scalar(255,255,255),-1, 8, 0 );    // Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)
       }

src.copyTo(maskedImage,mask); // creates masked Image and copies it to maskedImage