从opencv-python中的特定枢轴切割轮廓

时间:2019-01-29 11:33:28

标签: python opencv image-processing

我有一个小程序,可以拍摄图像并在其中找到所有形状,然后找到并绘制每个形状的轮廓并计算这些轮廓的面积。

import numpy as np
import cv2
global p1x,p2x
global ratio
p1x=0
p2x=0
ratio=0
def DoCalibrate(event, x, y, flags, param):
    global p1x
    global p2x
    global ratio
    if event==cv2.EVENT_LBUTTONDOWN:
        if p1x==0:
            p1x=x
        elif p1x!=0 and p2x==0:
            p2x=x
            ratio=(abs((p1x-p2x))/2)**2
            for cnt in cnts:
                cv2.drawContours(image,cnts, -1, (0, 0, 255), 1)
                print('ratio is = ',ratio)
                print('are in cm =',cv2.contourArea(cnt)/ratio)

image = cv2.imread("area.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)

_,areaThresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY_INV)

im, cnts, hier = cv2.findContours(areaThresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

for cnt in cnts:
    cv2.drawContours(image,cnts, -1, (0, 0, 255), 1)
    print('area in pixel = ',cv2.contourArea(cnt))
cv2.namedWindow('frame', cv2.WINDOW_AUTOSIZE )

cv2.setMouseCallback("frame", DoCalibrate)
cv2.imshow("thresh", areaThresh)
cv2.imshow("frame", image)
cv2.waitKey(0)

enter image description here

现在,当通过特定的水平线切割时,我需要计算这些轮廓的面积,如下图所示:

enter image description here

0 个答案:

没有答案