根据我们的评论,您可以做的是创建一个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
现在是一个 3D 数组的列表,其中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