python 基于opencv 实现一个鼠标绘图小程序
作者:我坚信阳光灿烂 时间:2021-06-20 18:13:05
需求
在画布上用鼠标画图,可以画圆或矩形,按m键在两种模式下切换。左键按下时开始画图,移动到哪儿画到哪儿,左键释放时结束画图。
实现思想
用鼠标画图:需要定义鼠标的回调函数mouse_event
画圆或矩形:需要定义一个画图的模式mode
左键单击、移动、释放:需要捕获三个不同的事件
开始画图,结束画图:需要定义一个画图的标记位drawing
实现代码
import cv2 as cv
import numpy as np
drawing = False # 是否开始画图
mode = True # True:画矩形,False:画圆
start = (-1, -1)
# 鼠标的回调函数的参数格式是固定的,不要随意更改。
def mouse_event(event, x, y, flags, param):
global start, drawing, mode
# 左键按下:开始画图
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
start = (x, y)
# 鼠标移动,画图
elif event == cv.EVENT_MOUSEMOVE:
if drawing:
if mode:
cv.rectangle(img, start, (x, y), (0, 255, 0), -1)
else:
cv.circle(img, (x, y), 5, (0, 0, 255), -1)
# 左键释放:结束画图
elif event == cv.EVENT_LBUTTONUP:
drawing = False
if mode:
cv.rectangle(img, start, (x, y), (0, 255, 0), -1)
else:
cv.circle(img, (x, y), 5, (0, 0, 255), -1)
img = np.zeros((512, 512, 3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image', mouse_event)
while(True):
cv.imshow('image', img)
# 按下m切换模式
if cv.waitKey(1) == ord('m'):
mode = not mode
# 按ESC键退出程序
elif cv.waitKey(1) == 27:
break
实验结果
来源:https://www.cnblogs.com/wojianxin/p/12593418.html
标签:python,opencv,绘图
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Javascript简写条件语句(推荐)
2023-09-01 04:10:25
如何让WML页面自己更新?
2008-05-21 13:35:00
可用性测试过程中需要关注的一些细节
2009-03-06 12:38:00
jQuery使用手册--核心篇(Core)
2007-11-22 22:05:00
一个sql查询器,自动画表格填字段
2011-04-10 10:58:00
Python程序退出方式小结
2021-12-21 19:29:55
![](https://img.aspxhome.com/file/2023/6/79486_0s.jpg)
python继承threading.Thread实现有返回值的子类实例
2023-06-07 19:01:15
使用Cython中prange函数实现for循环的并行
2023-04-13 05:31:55
![](https://img.aspxhome.com/file/2023/3/76773_0s.png)
利用python实现周期财务统计可视化
2022-03-19 21:30:41
![](https://img.aspxhome.com/file/2023/0/69450_0s.jpg)
基于PHP RSA密文过长加密解密 越过1024的解决方法
2023-09-07 02:57:56
php中关于hook钩子函数底层理解
2023-06-12 06:49:55
通过python检测字符串的字母
2023-01-11 22:49:47
sqlalchemy实现时间列自动更新教程
2021-08-18 20:12:58
ASP基础知识介绍
2009-02-11 13:44:00
如何控制弹出一个NTLM验证窗口?
2009-12-16 19:01:00
![](https://img.aspxhome.com/file/UploadPic/200912/16/ntlm-36s.gif)
PHP完全二叉树定义与实现方法示例
2023-07-04 10:49:10
![](https://img.aspxhome.com/file/2023/8/55378_0s.jpg)
IE下修改<p>标签的innerHTML出错
2007-11-11 10:12:00
Python中scatter散点图及颜色整理大全
2022-10-06 02:17:51
![](https://img.aspxhome.com/file/2023/2/83832_0s.png)
python匹配两个短语之间的字符实例
2022-08-31 04:49:57
asp将数据库中的信息存储至XML文件中
2007-09-19 12:54:00