gpt4 book ai didi

Python OpenCV - 在二值图像中查找黑色区域

转载 作者:太空狗 更新时间:2023-10-29 17:13:50 24 4
gpt4 key购买 nike

Opencv 的 python 包装器中有任何方法/函数可以找到二进制图像中的黑色区域吗? (就像 Matlab 中的 regionprops)到目前为止,我加载源图像,通过阈值将其转换为二值图像,然后反转它以突出显示黑色区域(现在是白色)。

我不能使用第三方库,例如 cvblobslob 或 cvblob

最佳答案

基本上,您使用 findContours 功能,结合 OpenCV 提供的许多其他功能,特别是用于此目的。

使用的有用函数(惊喜,惊喜,它们全部出现在 OpenCV 文档的 Structural Analysis and Shape Descriptors 页面上):

示例代码(我有来自 Matlab 的 regionprops 的所有属性,除了 WeightedCentroidEulerNumber - 你可以通过在 EulerNumber 中使用 cv2.RETR_TREE 并查看结果层次结构来计算 findContours,我我相信 WeightedCentroid 也不会那么难。

# grab contours
cs,_ = cv2.findContours( BW.astype('uint8'), mode=cv2.RETR_LIST,
method=cv2.CHAIN_APPROX_SIMPLE )
# set up the 'FilledImage' bit of regionprops.
filledI = np.zeros(BW.shape[0:2]).astype('uint8')
# set up the 'ConvexImage' bit of regionprops.
convexI = np.zeros(BW.shape[0:2]).astype('uint8')

# for each contour c in cs:
# will demonstrate with cs[0] but you could use a loop.
i=0
c = cs[i]

# calculate some things useful later:
m = cv2.moments(c)

# ** regionprops **
Area = m['m00']
Perimeter = cv2.arcLength(c,True)
# bounding box: x,y,width,height
BoundingBox = cv2.boundingRect(c)
# centroid = m10/m00, m01/m00 (x,y)
Centroid = ( m['m10']/m['m00'],m['m01']/m['m00'] )

# EquivDiameter: diameter of circle with same area as region
EquivDiameter = np.sqrt(4*Area/np.pi)
# Extent: ratio of area of region to area of bounding box
Extent = Area/(BoundingBox[2]*BoundingBox[3])

# FilledImage: draw the region on in white
cv2.drawContours( filledI, cs, i, color=255, thickness=-1 )
# calculate indices of that region..
regionMask = (filledI==255)
# FilledArea: number of pixels filled in FilledImage
FilledArea = np.sum(regionMask)
# PixelIdxList : indices of region.
# (np.array of xvals, np.array of yvals)
PixelIdxList = regionMask.nonzero()

# CONVEX HULL stuff
# convex hull vertices
ConvexHull = cv2.convexHull(c)
ConvexArea = cv2.contourArea(ConvexHull)
# Solidity := Area/ConvexArea
Solidity = Area/ConvexArea
# convexImage -- draw on convexI
cv2.drawContours( convexI, [ConvexHull], -1,
color=255, thickness=-1 )

# ELLIPSE - determine best-fitting ellipse.
centre,axes,angle = cv2.fitEllipse(c)
MAJ = np.argmax(axes) # this is MAJor axis, 1 or 0
MIN = 1-MAJ # 0 or 1, minor axis
# Note: axes length is 2*radius in that dimension
MajorAxisLength = axes[MAJ]
MinorAxisLength = axes[MIN]
Eccentricity = np.sqrt(1-(axes[MIN]/axes[MAJ])**2)
Orientation = angle
EllipseCentre = centre # x,y

# ** if an image is supplied with the BW:
# Max/Min Intensity (only meaningful for a one-channel img..)
MaxIntensity = np.max(img[regionMask])
MinIntensity = np.min(img[regionMask])
# Mean Intensity
MeanIntensity = np.mean(img[regionMask],axis=0)
# pixel values
PixelValues = img[regionMask]

关于Python OpenCV - 在二值图像中查找黑色区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9056646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com