opencv学习笔记03-鼠标回调与trackbar
opencv 简易笔记 3--鼠标回调与 trackbar
1.设置鼠标回调函数
import cv2
import numpy
def mouse_callback(event, x, y, flags, userdata):
if event == 1:
print(event, x, y, flags, userdata)
# 窗口命名
cv2.namedWindow("mouse", cv2.WINDOW_NORMAL)
# 设置鼠标回调函数
a = cv2.setMouseCallback("mouse", mouse_callback, "userdata")
# 显示窗口
img = numpy.zeros((500, 500, 3), numpy.uint8)
while True:
cv2.imshow("mouse", img)
key = cv2.waitKey(0)
# 销毁
if key & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
简单说明一下代码逻辑,首先需要定义一个鼠标回调函数,即 mouse_callback(event, x, y, flags, userdata),该函数原型应为:
#void on_Mouse(int event, int x, int y, int flags, void* param);
def mouse_callback(event, x, y, flags, userdata):
print(event, x, y, flags, userdata)
其中,像event,flags均有定义:
![](https://img2023.cnblogs.com/blog/2549937/202306/2549937-20230601021546682-900179264.png)
![](https://img2023.cnblogs.com/blog/2549937/202306/2549937-20230601021554094-613173244.png)
1.1 setMouseCallback(winname,callback,para) -> None
(1) winname: 即窗口名字
(2) callback: 需要设置的回调函数
(3) para: 参数,暂定,这个 param 是 onMouse 和 setMouseCallback 之间的参数通信接口。
2.trackBar 介绍
import cv2
import numpy
def callback(any):
pass
# 窗口命名
cv2.namedWindow("trackbar", cv2.WINDOW_NORMAL)
cv2.createTrackbar("R", "trackbar", 20, 255, callback)
cv2.createTrackbar("G", "trackbar", 20, 255, callback)
cv2.createTrackbar("B", "trackbar", 20, 255, callback)
# 显示窗口
img = numpy.zeros((500, 500, 3), numpy.uint8)
while True:
# 获取当前trackbar的值
r = cv2.getTrackbarPos("R", "trackbar")
g = cv2.getTrackbarPos("G", "trackbar")
b = cv2.getTrackbarPos("B", "trackbar")
print(type(r))
# 改变背景图片颜色
img[:] = [b, g, r]
cv2.imshow("trackbar", img)
key = cv2.waitKey(10)
# 销毁
if key & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
2.1 createTrackbar(trackbarName,windowName,value,count,onchange) ->
(1) trackbarName: trackbar 名字
(2) windowName: 窗口名字
(3) value: trackbar 当前值
(4) count: trackbar 最大值
(5) onchange: 一个回调函数,在值改变时触发
2.2 getTrackbarPos() -> (int)pos
(1) trackbarName: trackbar 名字
(2) windowName: 窗口名字