下面是一个python函数,用于检测对象并返回其边界框坐标:
def back_project_dilation(hist1,hist2,hsv,min_area,max_area,min_aspect,max_aspect,min_rect,max_rect):
Ratio=hist1/hist2
#calculating the M_blue
#spliting the target channels
h,s,v = cv2.split(hsv)
#backprojecting the R_red hist
B = Ratio[h.ravel(),s.ravel()]
B = np.minimum(B,1)
B = B.reshape(hsv_1.shape[:2])
B[B >0 ]+=1
B = np.minimum(B,1)
Open=cv2.morphologyEx(B,cv2.MORPH_OPEN,kernel)
dilation = cv2.dilate(Open,kernel,iterations = 2)
#dilation_special=dilation_special.astype(np.uint8)
dilation*= 255
dilation=dilation.astype(np.uint8)
contours =cv2.findContours(dilation, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cntss = imutils.grab_contours(contours)
if len(cntss) > 0:
# print('ture')
for cr in cntss:
area=cv2.contourArea(cr)
(x,y,w,h)=cv2.boundingRect(cr)
aspect=w/float(h)
if area>=min_area and area<=max_area and aspect>=min_aspect and aspect<=max_aspect:
center, (width,height),_=cv2.minAreaRect(cr)
rect=area/float((width*height))
if rect>=min_rect and rect<=max_rect:
coordi = cv2.boundingRect(cr)
return coordi
函数内部使用的检测方法称为“直方图反投影”
该函数在while循环中被调用四次,因为该函数用于同时检测两个视频中的小型汽车
while True:
ret1,frame1=cap1.read()
ret2,frame2=cap2.read()
cv2.imwrite('image22.jpg',frame1)
if ret1 and ret2 !=True:
print('cannot open Videos, please cheack your source')
break
else:
hsv_1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2HSV)
hsv_hist_1 = cv2.calcHist([hsv_1.copy()],[0,1],None,[180,256],[0,180,0,256])
hsv_2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2HSV)
hsv_hist_2 = cv2.calcHist([hsv_2.copy()],[0,1],None,[180,256],[0,180,0,256])
B_red_coord=back_project_dilation(hist_red,hsv_hist_1,hsv_1,619,1090,1.2432432432432432,3.0588235294117645,0.7296458280876743,1)
B_red_2_coord = back_project_dilation(hist_red,hsv_hist_2,hsv_2,619,1090,1.2432432432432432,3.0588235294117645,0.7296458280876743,1)
B_blue_coord = back_project_dilation(hist_blue,hsv_hist_1,hsv_1,522,903,0.875,2.68,0.76504332843943325,1.000000410476877)
B_blue_2_coord = back_project_dilation(hist_blue,hsv_hist_2,hsv_2,522,903,0.875,2.68,0.76504332843943325,1.000000410476877)
因此,当函数调用4次时,我应该获得4个输出(这是两个视频中两辆车的质心坐标)
运行代码时,出现以下错误:
<module>
B_red_2_coord = back_project_dilation(hist_red,hsv_hist_2,hsv_2,619,1090,1.2432432432432432,3.0588235294117645,0.7296458280876743,1)
back_project_dilation
return coordi
UnboundLocalError: local variable 'coordi' referenced before assignment
我在stack overflow中查找了这个问题,发现了类似的问题,但是我不知道如何针对我的问题提出建议的解决方案
因此,我将感谢一些帮助和提前感谢
哈立德·杰巴利
我通过将变量“coordi”设置为global解决了这个问题
相关问题 更多 >
编程相关推荐