Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

python - Opencv contour area returns wrong result

I am currently working on a opencv project which determines the contour area. I tried to make a proper threshold and apply cv2.findContours on it. However, I found that when the contour is intersecting the borders of the image, the area is drastically underestimated using cv2.contourArea. How can solve this issue? (Please check the attached images which demonstrates the wrong result on a sample image)

import cv2
import numpy as np

def midpoint(ptA, ptB):
    return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)

Input = cv2.imread("Thresh.png")
Thresh = cv2.cvtColor(Input,cv2.COLOR_BGR2GRAY)

contours, hierarchy = cv2.findContours(Thresh,  cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
minArea = 0
for cnt in contours:
    area = cv2.contourArea(cnt)
    print(area)
    if (area > minArea) :
        x,y,w,h = cv2.boundingRect(cnt)
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        Input = cv2.drawContours(Input,[box],0,(255,0,0),2)
        (tl, tr, br, bl) = box
        (tltrX, tltrY) = midpoint(tl, tr)
        cv2.putText(Input, "{:1f}".format(area),
        (int(tltrX), int(tltrY)), cv2.FONT_HERSHEY_SIMPLEX,
        0.65, (0, 255, 0), 2)
        cv2.imshow('Input',Input)
cv2.waitKey(0)
cv2.destroyAllWindows()

Input threshold image Determined contours (bounding rectangle) with written contour areas on it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...