[英]Click mouse and draw fixed rectangle at mouse position in Video (python_opencv)
因此,在網絡攝像頭/視頻期間,我想在單擊鼠標時在鼠標位置繪制一個矩形,並且矩形的大小固定為ex。 80 X80。在我當前的代碼中,矩形跟隨鼠標,但大小始終不同。 當我單擊視頻中的幀時,我希望在鼠標位置恰好有固定的大小。
這是我的代碼。
import os
import numpy as np
import cv2
from PIL import Image
import re
print('kaishi')
flag=0
drawing = False
point1 = ()
point2 = ()
ref_point = []
xvalues=[];
yvalues=[];
ref_point = []
cx=0;
cy=0;
def mouse_drawing(event, x, y, flags, params):
global point1, point2,
drawing,ref_point2,flag,refPt,cropping,cx,cy
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
point1 = (x, y)
xvalues.append(x)
yvalues.append(y)
cx =x;
cy=y;
elif event == cv2.EVENT_MOUSEMOVE:
if drawing is True:
point2 = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
flag+=1;
print('finished square')
cap = cv2.VideoCapture(0)
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", mouse_drawing)
while True:
_, frame = cap.read()
if point1 and point2 :
cv2.rectangle(frame,(200,cy),(cx,128),(0,0,255),0)
print(cx,cy)
flag=0;
cv2.imshow("Frame", frame)
key = cv2.waitKey(25)
if key== 13:
print('done')
elif key == 27:
break
cap.release()
cv2.destroyAllWindows()
問題是您固定了矩形的一個點,而另一個點跟隨了鼠標。 在您的代碼中它將在這里:
cv2.rectangle(frame,(200,cy),(cx,128),(0,0,255),0)
現在,這將取決於矩形的形狀,單擊左上角的點是該點嗎? 如果是,那么應該是這樣的:
cv2.rectangle(frame,(cx,cy),(cx + 80, cy +80),(0,0,255),0)
此示例適用於80 x 80的矩形。...在您的代碼中,單擊時將發生這種情況。
但是,您的代碼中有很多未使用的代碼...我會做這樣的事情:
import numpy as np
import cv2
drawing = False
point = (0,0)
def mouse_drawing(event, x, y, flags, params):
global point, drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
point= (x, y)
cap = cv2.VideoCapture(0)
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", mouse_drawing)
while True:
_, frame = cap.read()
if drawing :
cv2.rectangle(frame,point,(point[0]+80, point[1]+80),(0,0,255),0)
cv2.imshow("Frame", frame)
key = cv2.waitKey(25)
if key== 13:
print('done')
elif key == 27:
break
cap.release()
cv2.destroyAllWindows()
如果您希望矩形在單擊后跟隨鼠標,並在釋放按鈕后停止跟隨,請更改我在mouse_drawing
函數之前提供的代碼,如下所示:
def mouse_drawing(event, x, y, flags, params):
global point, drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
point = (x, y)
elif event == cv2.EVENT_MOUSEMOVE:
if drawing is True:
point = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
point = (x, y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.