做强光特征分析,需要在一个视频中画多个框,而且是在视频中间出现强光时画框。因此画框的回调函数中有一些标志鼠标动作的参数必须传到主程序中来。如下我用了flag列表,才将参数传出来。如果简单的定义全局变量,这些参数是传不出来的,不知道为什么。程序如下:
import numpy as np
import cv2
dotLoc = [[col for col in range(4)] for row in range(4)]
flag =[0 ,0 ,0]
def draw_rect(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
flag[0] = 1
dotLoc[flag[1]][0], dotLoc[flag[1]][1] = x, y
elif event == cv2.EVENT_LBUTTONUP:
flag[0] = 0
cv2.rectangle(frame, (dotLoc[flag[1]][0], dotLoc[flag[1]][1]), (x, y), (0, 255, 0), 1)
dotLoc[flag[1]][2], dotLoc[flag[1]][3] = x, y
flag[1] += 1 #把框的参数依此传入dotloc列表
cap = cv2.VideoCapture('D:\\strong_light.avi')
cv2.namedWindow('frame') #imshow时如果前面没有namedWindow,会默认先运行nameWindow,但这里必须要有,因为下一句
cv2.setMouseCallback('frame', draw_rect) #必须要有window才能画框
while(cap.isOpened()):
ret, frame = cap.read()
if flag[2]:
for i in range(flag[1]):
cv2.rectangle(frame, (dotLoc[i][0], dotLoc[i][1]), (dotLoc[i][2], dotLoc[i][3]), (0, 255, 0), 1)
if ret:
cv2.imshow('frame',frame)
while flag[0]: #当检测到鼠标左键按下时,imshow就不刷新了,直到左键松开
flag[2] = 1 #当检测到画了至少一个框时,flag[1]置1,在接下来的frame中加框显示
cv2.waitKey(20)
else:
break
if cv2.waitKey(40) == ord('q'): #waitKey(0) 无限等待 ord()函数,将字符转换为ASKII码
break
print(dotLoc)
cap.release()
cv2.destroyAllWindows()