gpt4 book ai didi

python - 从视频opencv python中计算红色对象

转载 作者:行者123 更新时间:2023-12-02 17:41:13 24 4
gpt4 key购买 nike

我正在尝试从该视频中计算多少红色条

tes1.mp4

这是我通过计算对象的中心来计算对象的功能

def count(frame):
frame = imutils.resize(frame,640,480)
hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
mask=cv2.inRange(hsv, lower, upper)
contours,_ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP,cv2.CHAIN_APPROX_TC89_L1)
center=[]

for i in range(len(contours)):
c = max(contours, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
if M["m00"]==0:
M["m00"]=0.6
cx=int (M["m10"]/M["m00"])
cy=int(M["m01"] / M["m00"])
print "center",len(center)

center.append((cx,cy))
cv2.circle(frame, center[-1],3,(0,0,0),-1)

但问题是 len(center) 出现超过 300。任何人都可以帮助计算红色条的数量。任何解决方案都会有所帮助。

最佳答案

我是这样做的:首先,从红色 channel 中减去蓝色和绿色 channel 以找到“红色”像素。结果如下所示:

enter image description here

显然,Threshold 在这方面效果很好:

enter image description here

从这里我们可以找到轮廓:

enter image description here

数一数,这就是条纹的数量。但也有connectedComponents功能,它可以计算那些没有找到轮廓。

import cv2
import numpy as np

#load a frame as int16 array to avoid overflow etc. when subtracting
img = cv2.imread("test_images/redbars.png").astype(np.int16)

#separating into blue, green and red channels
img_b = img[:, :, 0]
img_g = img[:, :, 1]
img_r = img[:, :, 2]

#for a red stripe, the red component should be much bigger than the rest
res_br = img_r - img_b
res_gr = img_r - img_g
res = np.maximum(res_br, res_gr)
res[res < 0] = 0
res = res.astype(np.uint8) #convert back to uint8 for findContours etc.

ret, thresh = cv2.threshold(res, 50, 1, cv2.THRESH_BINARY)

#find contours and count them
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#gives the correct output of 5
print(len(contours))

#alternatively, count connected components with this:
ncomp, nimg = cv2.connectedComponents(thresh)
print(ncomp - 1) #it counts the background as one of the components, so subtract 1

关于python - 从视频opencv python中计算红色对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com