Search code examples
pythonnumpyopencvimage-processingscikit-image

Find pixel indices within a shape: Opencv and Python


Suppose I have a mask of a hollow, curved (and not necessarily convex) shape that I've received from my pre-processing steps:

Hollow circle mask

I now want to try and select all pixels that occur inside that shape and add them to the mask, as so:

Filled circle mask

How can I do this in Python?


Code for generating the examples:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Parameters for creating the circle
COLOR_BLUE = (255, 0, 0)
IMAGE_SHAPE = (256, 256, 3)
CIRCLE_CENTER = tuple(np.array(IMAGE_SHAPE) // 2)[:-1]
CIRCLE_RADIUS = 30
LINE_THICKNESS = 5 # Change to -1 for example of filled circle

# Draw on a circle
img = np.zeros(IMAGE_SHAPE, dtype=np.uint8)
img_circle = cv2.circle(img, CIRCLE_CENTER, CIRCLE_RADIUS, COLOR_BLUE, LINE_THICKNESS)
circle_mask = img_circle[:, :, 0]

# Show the image
plt.axis("off")
plt.imshow(circle_mask)
plt.show()

Solution

  • Use floodFill to fill the outside of the circle. Then use np.where to find the pixels within the circle

    cv2.floodFill(circle_mask, None, (0, 0), 1)
    np.where(circle_mask == 0)