【发布时间】:2019-07-11 08:56:43
【问题描述】:
我使用 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)
【问题讨论】:
-
看看 OpenCV
findContours()... stackoverflow.com/a/37746356/2836621 和这里 docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html -
见my blog post on the subject。它包含 MATLAB 代码,但至少应该告诉您足够的信息,以避免出现下面答案中的解决方案。
-
谢谢,建议的最后一种方法对我有用。