Mus*_*sal 1 python opencv image-processing canny-operator opencv-contour
这是一片叶子
我想找到它的外围的长度,即它使用 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)
Run Code Online (Sandbox Code Playgroud)
HSV 颜色空间非常适合此图像,因为叶子和背景之间的色差非常大。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)
Run Code Online (Sandbox Code Playgroud)