简体   繁体   中英

Contour Area Finding

I am developing an defect analysis system where in the area of the defected fruit can be found. I am in the initial stages of its development. I am using opencv and python.

I used the following code for finding contours:

im = cv2.imread('Mango_49_A.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(im, contours, -1, (0,255,0), 3)

For finding the area i use the following code:

if len(contours) != 0:
    for (i, c) in enumerate(contours):
        area = cv2.contourArea(c)
        if area < area_of_the_mango1:
            print(area)
            area_of_the_defected_region1 += area
            cv2.drawContours(img, c, -1, (255,255,0), 12)

The result: 在此输入图像描述

I want to calculate the contour only inside the mango. The result i am getting calculates the contour area for: 1. Complete image boundary 2. Mango 3. Defects in the mango

Since it calculates area of the above three, the area of the defected region is higher than that of the area of the mango.

Help me out to calculate the contour area inside the mango alone.

The fact that you're getting the external border and some tiny contours as part of the background points to the fact that the threshold value isn't ideal to separate the foreground from the background.

For this line:

ret, thresh = cv2.threshold(imgray, 127, 255, 0)

play with value 127 so you no longer see contours between the outer edges of the foreground object and the background

Additionally you can use morphological filters (eg erode) to clean up threshold a bit

The main issue with how you currently retrieve contours is this: cv2.RETR_TREE . According to the findContours documentation you can retrieve only the external contours which is what you're after:

im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

As a next step you can look at more Contour Features like contourArea which you're already using, but also contour approximation and convex hull.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM