风魂8023 2020-03-22 16:52 采纳率: 28.6%
浏览 365
已采纳

python中现在是对实时图像选择目标,怎么修改代码能实现对已有视频按下空格可以选择目标,然后继续识别目标

import cv2

import numpy as np

xs,ys,ws,hs = 0,0,0,0 #selection.x selection.y

xo,yo=0,0 #origin.x origin.y

selectObject = False

trackObject = 0

def onMouse(event, x, y, flags, prams):

global xs,ys,ws,hs,selectObject,xo,yo,trackObject

if selectObject == True:

xs = min(x, xo)

ys = min(y, yo)

ws = abs(x-xo)

hs = abs(y-yo)

if event == cv2.EVENT_LBUTTONDOWN:

xo,yo = x, y

xs,ys,ws,hs= x, y, 0, 0

selectObject = True

elif event == cv2.EVENT_LBUTTONUP:

selectObject = False

trackObject = -1

videoFilePath = '1.avi'
#cap = cv2.VideoCapture(videoFilePath)
cap = cv2.VideoCapture(0)

ret,frame = cap.read()

cv2.namedWindow('imshow')

cv2.setMouseCallback('imshow',onMouse)

term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )

while(True):

ret,frame = cap.read()

if trackObject != 0:

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

mask = cv2.inRange(hsv, np.array((0., 30.,10.)), np.array((180.,256.,255.)))

if trackObject == -1:

track_window=(xs,ys,ws,hs)

maskroi = mask[ys:ys+hs, xs:xs+ws]

hsv_roi = hsv[ys:ys+hs, xs:xs+ws]

roi_hist = cv2.calcHist([hsv_roi],[0],maskroi,[180],[0,180])

cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)

trackObject = 1

dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)

dst &= mask

ret, track_window = cv2.CamShift(dst, track_window, term_crit)
pts = cv2.boxPoints(ret)

pts = np.int0(pts)
print(pts)

    cv2.drawContours(frame,[pts],0,(0,0,255),3)




if selectObject == True and ws>0 and hs>0:  
    cv2.imshow('imshow1',frame[ys:ys+hs,xs:xs+ws])  
    cv2.bitwise_not(frame[ys:ys+hs,xs:xs+ws],frame[ys:ys+hs,xs:xs+ws])  
cv2.imshow('imshow',frame)  
if  cv2.waitKey(10)==32:  
    break  

cv2.destroyAllWindows()

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-03-22 19:02
    关注

    elif event == cv2.EVENT_LBUTTONUP:
    这里是左边鼠标抬起,换成键盘按键即可
    https://blog.csdn.net/taily_duan/article/details/51006797

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal