您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中使用OpenCV访问轮廓边界内的像素值

在Python中使用OpenCV访问轮廓边界内的像素值

根据我们的评论,您可以做的是创建一个numpy数组列表,其中每个元素都是描述每个对象轮廓内部的强度。具体来说,对于每个轮廓,创建一个填充轮廓内部的二进制蒙版,找到(x,y)填充对象的坐标,然后索引到图像中并获取强度。

我不完全知道如何设置代码,但是假设您有一个名为的灰度图像img。您可能需要将图像转换为灰度,因为它cv2.findContours适用于灰度图像。这样,cv2.findContours通常调用

import cv2
import numpy as np

#... Put your other code here....
#....

# Call if necessary
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Call cv2.findContours
contours,_ = cv2.findContours(img, cv2.RETR_LIST, cv2.cv.CV_CHAIN_APPROX_NONE)

contours现在三维列表numpy阵列,其中每个是大小为N x 1 x 2其中N是针对每个对象轮廓点的总数。

这样,您可以像这样创建我们的列表:

# Initialize empty list
lst_intensities = []

# For each list of contour points...
for i in range(len(contours)):
    # Create a mask image that contains the contour filled in
    cimg = np.zeros_like(img)
    cv2.drawContours(cimg, contours, 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(img[pts[0], pts[1]])

对于每个轮廓,我们创建一个空白图像,然后在该空白图像中绘制 轮廓。您可以通过将thickness参数指定为-1来填充轮廓占用的区域。我将轮廓的内部设置为255。之后,我们用于numpy.where查找数组中符合特定条件的所有行和列位置。在我们的例子中,我们想找到等于255的值。之后,我们使用这些点索引图像,以捕获轮廓内部的像素强度。

lst_intensities包含一维numpy数组的列表,其中每个元素为您提供属于每个对象轮廓内部的强度。要访问每个数组,只需执行要访问的轮廓lst_intensities[i]在哪里i

python 2022/1/1 18:33:37 有217人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶