gpt4 book ai didi

python - cv2.setMouseCallback() 的参数应该是什么

转载 作者:太空宇宙 更新时间:2023-11-03 21:25:10 28 4
gpt4 key购买 nike

我一直在研究 opencv 并通过了 cv2.setMouseCallback() 。以下是鼠标点击画圆的代码。
导入cv2 将 numpy 导入为 np

def draw_circle(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(image,(x,y),(100,100),(255,0,0),-1)
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow("image")
cv2.setMouseCallback("image",draw_circle)

while True:
cv2.imshow("image",image)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()`

请解释

  1. 如何在不传递所有参数的情况下调用函数 draw_circle
  2. 函数有五个参数,只有两个变量可以赋值
  3. 创建 cv2.namedWindow("image") 的目的是什么

谢谢!

最佳答案

  1. 你不调用draw_circle , openCV 将在具有适当事件和坐标的鼠标事件上为您调用它,您只需在 setMouseCallback 中指定要为哪个窗口调用哪个函数即可。

  2. 如果您需要额外的变量,您可以通过 param 发送它们

  3. 您可以有多个窗口,每个窗口具有不同的鼠标操作集

我希望这个例子能对偶然发现的人有所帮助:

import cv2
import numpy as np
from math import sqrt

def calc_distance(p1, p2):
(x1, y1) = p1
(x2, y2) = p2
return round(sqrt((x1-x2)**2 + (y1-y2)**2))

# param contains the center and the color of the circle
def draw_red_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
center = param[0]
radius = calc_distance((x, y), center)
cv2.circle(img, center, radius, param[1], 2)


def draw_blue_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
center = (100,100)
radius = calc_distance((x, y), center)
cv2.circle(img, center, radius, (255, 0, 0), 2)

img = np.zeros((512,512,3), np.uint8)

# create 2 windows
cv2.namedWindow("img_red")
cv2.namedWindow("img_blue")

# different doubleClick action for each window
# you can send center and color to draw_red_circle via param
param = [(200,200),(0,0,255)]
cv2.setMouseCallback("img_red", draw_red_circle, param)
cv2.setMouseCallback("img_blue", draw_blue_circle) # param = None


while True:
# both windows are displaying the same img
cv2.imshow("img_red", img)
cv2.imshow("img_blue", img)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()

关于python - cv2.setMouseCallback() 的参数应该是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114360/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com