因此,在我的网络摄像头/视频期间,我希望在单击鼠标时在鼠标位置绘制一个矩形,并且矩形的大小固定为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()
答案 0 :(得分:0)
问题是您固定了矩形的一个点,而另一个点跟随了鼠标。在您的代码中,它将在这里:
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)