【发布时间】:2018-11-23 15:52:06
【问题描述】:
我在存储为 2D numpy 数组的图像上绘制了一组轮廓点。轮廓由 x 和 y 坐标的 2 个 numpy 浮点值数组表示。 These coordinates 不是整数,也不能与像素完美对齐,但它们确实可以告诉您轮廓点相对于像素的位置。
我希望能够选择轮廓内的像素。我写了一些与这里给出的答案几乎相同的代码:Access pixel values within a contour boundary using OpenCV in Python
temp_list = []
for a, b in zip(x_pixel_nos, y_pixel_nos):
temp_list.append([[a, b]]) # 2D array of shape 1x2
temp_array = np.array(temp_list)
contour_array_list = []
contour_array_list.append(temp_array)
lst_intensities = []
# For each list of contour points...
for i in range(len(contour_array_list)):
# Create a mask image that contains the contour filled in
cimg = np.zeros_like(pixel_array)
cv2.drawContours(cimg, contour_array_list, i, color=255, thickness=-1)
# Access the image pixels and create a 1D numpy array then add to list
pts = np.where(cimg == 255)
lst_intensities.append(pixel_array[pts[0], pts[1]])
当我运行这个时,我得到一个错误error: OpenCV(3.4.1) /opt/conda/conda-bld/opencv-suite_1527005509093/work/modules/imgproc/src/drawing.cpp:2515: error: (-215) npoints > 0 in function drawContours
我猜测此时 openCV 对我不起作用,因为我的轮廓是浮点数,而不是整数,openCV 无法处理 drawContours。如果我将轮廓的坐标转换为整数,我会损失很多精度。
那么我怎样才能得到落在轮廓内的像素呢?
这应该是一项微不足道的任务,但到目前为止我还没有找到一种简单的方法来完成它。
【问题讨论】:
-
如果您的像素是浮点数,那么理论上有无限数量的像素落在轮廓内,因为现在位置是连续的。你想施加什么约束来限制这个像素列表的长度?还要记住,轮廓像素列表是这样的,每个元素都需要是一个具有单一第二维的 3d 数组(即另一篇文章中提到的 N x 1 x 2 数组)。
-
@rayryeng 我的像素不连续。它们是整数。轮廓是浮动的。我猜这是因为这些轮廓是由一个人在绘制轮廓时放大图像手动绘制的。
-
啊,我明白了。但是,您的轮廓列表看起来并不正确。请参阅我之前关于它们是 3d 数组的说明。
-
有趣。我需要进行实验。我现在不在电脑前,所以我要等到今晚晚些时候才能尝试。您是否碰巧在某处有可用的轮廓数据?
-
@CrisLuengo 目前我并不关心计算效率。如果您能向我展示完成此操作的代码,我将不胜感激。
标签: python numpy image-processing contour opencv-contour