python opencv 滑鼠事件 畫框圈定目標

2021-07-25 21:12:05 字數 2297 閱讀 2308

# -*- coding: utf-8 -*-

"""created on tue dec 27 09:32:02 2016

@author:

"""import cv2

import numpy as np

current_pos = none

tl = none

br = none

#滑鼠事件

defget_rect

(im, title='get_rect'):

# (a,b) = get_rect(im, title='get_rect')

mouse_params =

cv2.namedwindow(title)

cv2.movewindow(title, 100, 100)

defonmouse

(event, x, y, flags, param):

param['current_pos'] = (x, y)

if param['tl'] is

notnone

andnot (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

notnone:

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)

defreadvideo

(pathname, skipframe):

cap = cv2.videocapture(0) #讀取攝像頭

if 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畫素值,之後對其操作區域賦值為1即可

if(c==skipframe):

(a,b) = get_rect(frame, title='get_rect') #滑鼠畫矩形框

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

break

cap.release()

cv2.destroyallwindows()

python opencv 安裝整理

這兩天比較有空,在公司內想學習一下opencv,又不想安裝vc 所以就那個python看opencv。安裝環境本來很簡單 但是我python是64的 估計也很多 而opencv的安裝要有乙個numpy庫 這個在官網上只有32位的 所以,事情變得複雜起來。網上找了一下,只道有提供64位版的numpy庫...

python opencv 輪廓檢測

輪廓 contours 指的是有相同顏色或者密度,連線所有連續點的一條曲線。檢測輪廓的工作對形狀分析和物體檢測與識別都非常有用。在輪廓檢測之前,首先要對進行二值化或者canny邊緣檢測。在opencv中,尋找的物體是白色的,而背景必須是黑色的,因此預處理時必須保證這一點。import cv2 讀入i...

python opencv 輪廓屬性

import cv2 import numpy as np 高寬比 函式cv2.moments 會給你乙個字典,包含所有矩值 m cv2.moments cnt 這是目標的邊界矩形的寬高比 x,y,w,h cv2.boundingrect cnt aspect ratio float w h ext...