本文實例為大家分享了python-opencv鼠標(biāo)事件畫框圈定目標(biāo)的具體代碼,供大家參考,具體內(nèi)容如下
在視頻/相機(jī)中,用鼠標(biāo)畫矩形框,圈定目標(biāo),從而獲得鼠標(biāo)的起始坐標(biāo)點a、終止坐標(biāo)點b
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 27 09:32:02 2016
@author: http://blog.csdn.net/lql0716
"""
import cv2
import numpy as np
current_pos = None
tl = None
br = None
#鼠標(biāo)事件
def get_rect(im, title='get_rect'): # (a,b) = get_rect(im, title='get_rect')
mouse_params = {'tl': None, 'br': None, 'current_pos': None,
'released_once': False}
cv2.namedWindow(title)
cv2.moveWindow(title, 100, 100)
def onMouse(event, x, y, flags, param):
param['current_pos'] = (x, y)
if param['tl'] is not None and not (flags & cv2.EVENT_FLAG_LBUTTON):
param['released_once'] = True
if flags & cv2.EVENT_FLAG_LBUTTON:
if param['tl'] is None:
param['tl'] = param['current_pos']
elif param['released_once']:
param['br'] = param['current_pos']
cv2.setMouseCallback(title, onMouse, mouse_params)
cv2.imshow(title, im)
while mouse_params['br'] is None:
im_draw = np.copy(im)
if mouse_params['tl'] is not None:
cv2.rectangle(im_draw, mouse_params['tl'],
mouse_params['current_pos'], (255, 0, 0))
cv2.imshow(title, im_draw)
_ = cv2.waitKey(10)
cv2.destroyWindow(title)
tl = (min(mouse_params['tl'][0], mouse_params['br'][0]),
min(mouse_params['tl'][1], mouse_params['br'][1]))
br = (max(mouse_params['tl'][0], mouse_params['br'][0]),
max(mouse_params['tl'][1], mouse_params['br'][1]))
return (tl, br) #tl=(y1,x1), br=(y2,x2)
#讀取攝像頭/視頻,然后用鼠標(biāo)事件畫框
def readVideo(pathName, skipFrame): #pathName為視頻文件路徑,skipFrame為視頻的第skipFrame幀
cap = cv2.VideoCapture(0) #讀取攝像頭
if not cap.isOpened(): #如果為發(fā)現(xiàn)攝像頭,則按照路徑pathName讀取視頻文件
cap = cv2.VideoCapture(pathName) #讀取視頻文件,如pathName='D:/test/test.mp4'
c = 1
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if(c>=skipFrame):
mask = np.zeros(gray.shape, dtype=np.uint8) #掩碼操作,該矩陣與圖片大小類型一致,為初始化全0像素值,之后對其操作區(qū)域賦值為1即可
if(c==skipFrame):
(a,b) = get_rect(frame, title='get_rect') #鼠標(biāo)畫矩形框
img01, img02 = frame, frame
gray01, gray02 = gray, gray
else:
img1, img2 = prev_frame, frame
gray1, gray2 = prev_frame, frame
cv2.imshow('frame', frame)
c = c + 1
prev_gray = gray
prev_frame = frame
if cv2.waitKey(1) & 0xFF == ord('q'): #點擊視頻窗口,按q鍵退出
break
cap.release()
cv2.destroyAllWindows()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

