这是一片叶子
我想使用openCV和Python查找外围的长度,即周长。我尝试编写代码,但没有得到理想的结果。我必须重置每个示例的阈值,也没有给出封闭的我希望它是可以在所有此类叶子上工作的通用代码。请在这里帮助我
import cv2
#reading the image
col = cv2.imread("leaf2.jpg")
width,height,channels = col.shape
col=cv2.resize(col,(width,height),interpolation=cv2.INTER_CUBIC)
image=cv2.pyrMeanShiftFiltering(col,10,100,3)
edged = cv2.Canny(image, 0,10)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)
#finding_contours
image, contours, hierarchy = cv2.findContours(closed, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
perimeter=0
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
perimeter = perimeter+cv2.arcLength(c,True)
print(perimeter)
cv2.imshow("Output", image)
cv2.waitKey(0)
答案 0 :(得分:4)
HSV颜色空间是此图像的理想选择,因为叶子和背景之间的颜色差异很大。 HSV的色相层仅与颜色有关,而与光的强度无关,因此我们在这里使用它。
image = cv2.imread('image.jpg',cv2.IMREAD_UNCHANGED)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv = cv2.split(hsv)
gray = hsv[0]
gray = cv2.GaussianBlur(gray, (3,3), sigmaX=-1, sigmaY=-1)
ret,binary = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
contours = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
cv2.drawContours(image, contours, -1, (255,0,0), thickness = 2)