Home > Blockchain >  How to use Numpy to compute the outer contour of binary image and fill inner area?
How to use Numpy to compute the outer contour of binary image and fill inner area?

Time:01-10

I want to use Numpy (without any other packages) to find the outer contour of the 1st binary image and fill the inside area so it looks like the 2nd image, basically filling the holes of the wheels but I don't know how to do it. Does anyone have any ideas?

enter image description here

enter image description here

CodePudding user response:

You're looking to implement the flood fill algorithm. The high-level idea is:

  1. Pick an origin point, say (0, 0).
  2. 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.
  3. 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.

  • Related