您好,登錄后才能下訂單哦!
小編這次要給大家分享的是python opencv鼠標(biāo)事件如何實(shí)現(xiàn)畫框圈定目標(biāo)獲取坐標(biāo)信息,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
在視頻/相機(jī)中,用鼠標(biāo)畫矩形框,圈定目標(biāo),從而獲得鼠標(biāo)的起始坐標(biāo)點(diǎn)a、終止坐標(biāo)點(diǎn)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像素值,之后對(duì)其操作區(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'): #點(diǎn)擊視頻窗口,按q鍵退出 break cap.release() cv2.destroyAllWindows()
看完這篇關(guān)于python opencv鼠標(biāo)事件如何實(shí)現(xiàn)畫框圈定目標(biāo)獲取坐標(biāo)信息的文章,如果覺得文章內(nèi)容寫得不錯(cuò)的話,可以把它分享出去給更多人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。