How to use Numpy to compute the outer contour of binary image and fill inner area?
Question:
Answers:
You’re looking to implement the flood fill algorithm. The high-level idea is:
- Pick an origin point, say (0, 0).
- Run a breath-first or depth-first search from the origin to collect a list of points with the same RGB value. You pick a pixel (starting with the origin), find it’s horizontal and vertical neighbours, and if the colour is the same, repeat on the new pixel.
- Set every pixel that wasn’t identified in the search to white.
This operation has been implemented many times before. If you are not opposed to using a new library, take a look at findContours
and drawContours
in OpenCV. OpenCV operates on numpy arrays so you won’t have to transform the data.
You’re looking to implement the flood fill algorithm. The high-level idea is:
- Pick an origin point, say (0, 0).
- Run a breath-first or depth-first search from the origin to collect a list of points with the same RGB value. You pick a pixel (starting with the origin), find it’s horizontal and vertical neighbours, and if the colour is the same, repeat on the new pixel.
- Set every pixel that wasn’t identified in the search to white.
This operation has been implemented many times before. If you are not opposed to using a new library, take a look at findContours
and drawContours
in OpenCV. OpenCV operates on numpy arrays so you won’t have to transform the data.