『OpenCV-Python鼠标画笔』

OpenCV-Python教程链接: https://opencv-python-tutorials.readthedocs.io/

示例一:图片上双击的位置绘制一个圆圈

首先创建一个鼠标事件回调函数,鼠标事件发生时就会被执行。鼠标事件可以是鼠标上的任何动作,比如左键按下,左键松开,左键双击等。通过鼠标事件获得与鼠标对应的图片上的坐标。根据这些信息可以做任何想做的事。通过执行下列代码查看所有被支持的鼠标事件:

复制代码
import numpy as np
import cv2 as cv

# mouse callback function
def draw_circle(event,x,y,flags,param):
    if event == cv.EVENT_LBUTTONDBLCLK:
        b, g, r = np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255)
        l = np.random.randint(2, 100)
        cv.circle(img,(x,y),l,(b, g, r),-1)

# Create a black image, a window and bind the function to window
img = np.zeros((1080,960,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)

while(1):
    cv.imshow('image',img)
    if cv.waitKey(20) & 0xFF == 27:
        break
cv.destroyAllWindows()

效果图:

示例二:拖动鼠标时绘制矩形或者是圆圈

这是一个典型的例子,它可以帮助我们更好的理解与构建人机交互式程序,比如物体跟踪,图像分割等。任务是根据选择的模式在拖动鼠标时绘制矩形或者是圆圈(就像画图程序中一样)。因此回调函数包含两部分:一部分画矩形,一部分画圆圈。 将此鼠标回调函数绑定到OpenCV窗口。在主循环中,把按键'm'设置为切换绘制矩形还是圆形。参考以下代码:

复制代码
import numpy as np
import cv2 as cv

drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1

# mouse callback function
def draw_circle(event,x,y,flags,param):
    global ix,iy,drawing,mode
    if event == cv.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y
    elif event == cv.EVENT_MOUSEMOVE:
        if drawing == True:
            if mode == True:
                cv.rectangle(img,(ix,iy),(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 == True:
            cv.rectangle(img,(ix,iy),(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',draw_circle)

while(1):
    cv.imshow('image',img)
    k = cv.waitKey(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == 27:
        break
cv.destroyAllWindows()

效果图:

本文由mdnice多平台发布

相关推荐
小刘在重生~4 分钟前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python
大汉堡玩测试44 分钟前
langfuse测试实战(一): 配置一个简单的项目快速落地
python·测试工具
一位正在转型AI全栈的前端工程师1 小时前
AI 全栈学习之旅 -Week 8:从单 Agent 到多 Agent 协作:LangGraph 实战与记忆持久化
前端·python
长江后浪博客1 小时前
Python + YOLOv8 疲劳驾驶 AI 视觉检测入门:从模型训练到 ONNX 实时摄像头检测完整实战
人工智能·python·yolo·疲劳驾驶检测·onnx·yolov8
hhzz1 小时前
【OpenCV 入门到精通 01】认识 OpenCV 与计算机视觉:从零建立全局认知
人工智能·python·opencv·计算机视觉·开源
一马平川的大草原2 小时前
如何实现SVG转Mermaid图
python·svg·格式转换·mermaid
PFFstronger2 小时前
基于 Dify 知识库 + Ollama 大模型,自动生成测试用例并导出 XMind 的完整方案
人工智能·python·测试用例·xmind
SomeBottle3 小时前
【小记】图片托管从又拍云迁移到腾讯云 EO + COS(兼容图片处理参数)
python·计算机网络·学习笔记·对象存储·cdn·折腾
cts6183 小时前
FDE架构师前端选型指南
python
2601_962293794 小时前
【Python教程:自动化处理文件】
python·自动化·编程·文件处理·os模块