在Python中使用openCV检测红色和黄色三角形

在Python中使用openCV检测红色和黄色三角形,python,opencv,colors,Python,Opencv,Colors,我试图在Python中使用openCV检测红色三角形和黄色三角形,以区分它们。我是初学者 我想,在第一手,检测,计数(黄色和红色),并用一个矩形标记所有相机可以看到的三角形。我也想找到他们的群众中心 目前,我一次只检测到一个三角形,没有找到它的颜色。 我的质心计算不起作用,给了我一个错误: centroid_x = int(M['m10']/M['m00']) ZeroDivisionError: float division by zero 我从web上的示例中获得灵感,编写了以下代

我试图在Python中使用openCV检测红色三角形和黄色三角形,以区分它们。我是初学者

我想,在第一手,检测,计数(黄色和红色),并用一个矩形标记所有相机可以看到的三角形。我也想找到他们的群众中心

目前,我一次只检测到一个三角形,没有找到它的颜色。 我的质心计算不起作用,给了我一个错误:

    centroid_x = int(M['m10']/M['m00'])
ZeroDivisionError: float division by zero
我从web上的示例中获得灵感,编写了以下代码

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

print cap.get(3)
print cap.get(4)

# changing display size
ret = cap.set(3,320)
ret = cap.set(4,240)


def getthresholdedimg(hsv):
    yellow = cv2.inRange(hsv,np.array((10,100,100)),np.array((30,255,255)))
    red = cv2.inRange(hsv,np.array((0,0,0)),np.array((190,255,255)))
    both = cv2.add(yellow,red)
    return both


def nothing(x):
    pass

# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')

while(True):
    thr1 = 50
    thr2 = 110


    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    gaussian_blur = cv2.GaussianBlur(gray,(5,5),0)

    # Our operations on the frame come here
    canny = cv2.Canny(gray,thr1,thr2)
    canny_blur = cv2.Canny(gaussian_blur,thr1,thr2)


    # Our operations on the frame come here
    contours,hier = cv2.findContours(canny,1,2)
    for cnt in contours:
        approx = cv2.approxPolyDP(cnt,0.02*cv2.arcLength(cnt,True),True)
        if len(approx)==3:
            cv2.drawContours(frame,[cnt],0,(0,255,0),2)
            tri = approx

    M = cv2.moments(cnt)
    centroid_x = int(M['m10']/M['m00'])
    centroid_y = int(M['m01']/M['m00'])
    cv2.circle(img,(centroid_x,centroid_y),3,255,-1)

    for vertex in tri:
        cv2.circle(frame,(vertex[0][0],vertex[0][1]),3,(64,0,128),-1)
        cv2.line(img,(vertex[0][0],vertex[0][1]),(centroid_x,centroid_y),(0,0,255),1)


    # Display the resulting frame
    cv2.imshow('normal flux',frame)
    cv2.imshow('gray conversion',gray)
    cv2.imshow('canny edges conversion',canny)
    cv2.imshow('canny edges gaussian blur',canny_blur)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
你能帮我吗?

也许你想做什么
M=cv2.力矩(tri)

而不是
M=cv2.moments(cnt)

您的相机可能没有读取它

在cap=cv2后尝试此操作。视频捕获(0):

while(1):

#Gets retval and frames from each video 

ret ,frame = cap.read()

#Check to see if retval is not None or empty
if not ret
    break;