Introduction
In this blog post, I’ll show you how to use Python and OpenCV to fill a circle, rectangle, or any random shape in an image. You may wonder why we require this type of operation! The answer is that sometimes you receive a mask or return a contour/edge of an object, but the mask is empty on the inside, as shown below:
And for your project, you may require the same circle but with a full inside, as shown below:
So the role of this blog post is to show you how you can do this operation.
Requirements
We’ll be using the Python programming language for this task, so install it first if you don’t already have it.
- OpenCV:
pip install opencv-python
- NumPy:
pip install numpy
Coding
Open Image
The first thing to do is to import the libraries and then read the image using opencv.
cv.threshold
The function applies fixed-level thresholding to a multiple-channel array. The function is typically used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for this purpose) or for removing a noise, that is, filtering out pixels with too small or too large values. There are several types of thresholding supported by the function. They are determined by type parameter.
cv.floodFill
The function cv::floodFill fills a connected component starting from the seed point with the specified color. The connectivity is determined by the color/brightness closeness of the neighbor pixels.
Now the output mask is ready, you can just show it or write it using cv2.imwrite( ).
You can get the whole code here.