Find the perimeter of the leaf

Question:

Here is a leaf

I want to find the length of it’s periphery i.e. it’s perimeter using openCV and Python.I tried writing a code but it is not giving the desired result.I have to reset the threshold for every example and also it’s not giving a closed contour.I want it to be a generalized code to work on all such leaves. Please help me here:

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)
Asked By: Muskan Bansal

||

Answers:

The HSV color space is ideal for this image because the color difference between the leaf and the background is extreme. The Hue layer of HSV is only concerned with color and not the intensity of light so we use it here.

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)

binary result

Answered By: zindarod