OpenCV Python距离计算奇怪的平方检测

时间:2019-06-26 11:15:56

标签: python opencv

使用树莓派pi和pi相机读取pi对象之间的距离(方框)。我用轮廓的周长除以4得到一侧的长度,然后按距离=(长度x已知长度)/计算出的一侧的长度。

我总是有一个正方形,它是摄像头窗口的整个框架,并且有一段距离。如何避免整个框架窗口变成正方形。

https://drive.google.com/open?id=15-kd32Zd_tZeMPWQ2I1s9_NJGYg3v_9l

知道它为什么来以及如何消除它吗?

import cv2
import numpy as np
import time

def nothing(x):
    # any operation
    pass

cap = cv2.VideoCapture(0)

font = cv2.FONT_HERSHEY_COMPLEX

while True:
    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    l_h = 0
    l_s = 0
    l_v = 42
    u_h = 180
    u_s = 255
    u_v = 255

    lower_red = np.array([l_h, l_s, l_v])
    upper_red = np.array([u_h, u_s, u_v])

    mask = cv2.inRange(hsv, lower_red, upper_red)
    kernel = np.ones((5, 5), np.uint8)
    mask = cv2.erode(mask, kernel)


    # Contours detection
    contours, _ = cv2.findContours(mask, cv2.RETR_TREE,    cv2.CHAIN_APPROX_SIMPLE)


    for cnt in contours:
        area = cv2.contourArea(cnt)
        approx = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt, True), True)
        x = approx.ravel()[0]
        y = approx.ravel()[1]
        perimeter = cv2.arcLength(cnt,True)


        if area > 200:
            cv2.drawContours(frame, [approx], 0, (0, 0, 0), 5)

        if len(approx) == 3:
            cv2.putText(frame, "triangle " , (x, y), font, 1, (0, 0, 0))
            print("Traingle is detected and distance is = ",((154*58)/(perimeter/3))*0.2645 , "mm")
        elif len(approx) == 4:
            cv2.putText(frame, "square", (x, y), font, 1, (0, 0, 0))
            #print(perimeter/4)
            print("Square is detected and distance is = ",((154*58)/(perimeter/4))*0.2645 , "mm")
            #print("square distance is = ",((149*58)/(perimeter/4))*0.2645 , "mm")
        elif len(approx) == 5:
            cv2.putText(frame, "Pentogon", (x, y), font, 1, (0, 0, 0))
            print("Pentogon is detected and distance is = ",((151*58)/(perimeter/5))*0.2645 , "mm")
        elif len(approx) == 6:
            cv2.putText(frame, "6angle", (x, y), font, 1, (0, 0, 0))


    cv2.imshow("Frame", frame)
    cv2.imshow("Mask", mask)

    key = cv2.waitKey(1)
    if key == 0:
        break

cap.release()
cv2.destroyAllWindows()

0 个答案:

没有答案