Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to black out everything outside a circle in Open CV

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?

like image 823
Sebastian Boldt Avatar asked Aug 27 '13 07:08

Sebastian Boldt


2 Answers

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
like image 104
Sebastian Boldt Avatar answered Nov 19 '22 09:11

Sebastian Boldt


you can make the background the color you want

image=cv::Scalar(red_value, green_value, blue_value);

then draw your circles

like image 3
jambono Avatar answered Nov 19 '22 11:11

jambono