首页 > 解决方案 > 查找形状内的像素索引:Opencv 和 Python

问题描述

假设我有一个空心、弯曲(不一定是凸面)形状的面具,我从我的预处理步骤中收到:

空心圆面罩

我现在想尝试选择出现该形状内的所有像素并将它们添加到蒙版中,如下所示:

实心圆蒙版

我怎样才能在 Python 中做到这一点?


生成示例的代码:

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()

标签: pythonnumpyopencvimage-processingscikit-image

解决方案


用于floodFill填充圆圈的外部。然后用于np.where查找圆圈内的像素

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

推荐阅读