求叶子的周长
Find the perimeter of the leaf
这是一片叶子
我想找到它的外围长度,即它是使用 openCV 的周长,Python.I 尝试编写代码但它没有给出所需的 result.I 必须为每个示例重置阈值并且它也没有给出一个封闭的 contour.I 希望它成为一个通用代码来处理所有这些叶子。请在这里帮助我:
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)
HSV 颜色 space 非常适合此图像,因为叶子和背景之间的颜色差异很大。 HSV的Hue层只关心颜色,不关心光的强弱,所以这里用它。
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)
这是一片叶子
我想找到它的外围长度,即它是使用 openCV 的周长,Python.I 尝试编写代码但它没有给出所需的 result.I 必须为每个示例重置阈值并且它也没有给出一个封闭的 contour.I 希望它成为一个通用代码来处理所有这些叶子。请在这里帮助我:
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)
HSV 颜色 space 非常适合此图像,因为叶子和背景之间的颜色差异很大。 HSV的Hue层只关心颜色,不关心光的强弱,所以这里用它。
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)