根据我们的评论,您可以做的是创建一个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
。