我已经使用Python通过将白色像素的数量乘以单个像素的面积来计算黑白图像上的面积或不规则形状。
但是,现在我还需要计算这种不规则形状的周长。该形状中可能有孔。这是一个示例图像:
有什么想法可以解决这个问题吗?我不是一个完整的新手,但我也不是编码员。我猜经验丰富的初学者。
提前致谢。
编辑:有些事情我还是不明白,但这对我有用:
import cv2
import numpy as np
def import_image(filename):
original_image = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
return original_image
#getting original file
img = import_image('PerimeterImage.jpg')
#converting to gray
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 1
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
#find contours
image, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#create an empty image for contours
img_contours = np.zeros(img.shape)
perimeter = 0
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.0001 * peri, True)
cv2.drawContours(img_contours, [approx], -1, (0, 0, 255), 1)
perimeter = perimeter + peri
print(f'Perimeter = {int(round(perimeter,0))} pixels')
#show image
cv2.imshow('Output', img_contours)
cv2.waitKey(0)
#save image
cv2.imwrite('contours.jpg', img_contours)
cv.findContours
通常,仅用于查找白色区域的轮廓,您必须在之前做阈值findContours
,但是由于图像是黑白的,因此您可以忽略它。
对于周长,只需使用cv.arcLength
所需的轮廓即可。