You need to enable JavaScript to run this app. 基于OpenCV和Python实现鼠标绘线及直线移动的方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

基于OpenCV和Python实现鼠标绘线及直线移动的方案咨询

基于OpenCV+Python实现鼠标绘制与移动直线方案

核心思路

  • 维护直线列表存储所有已绘制的直线,每条直线记录起点、终点及选中状态
  • 通过OpenCV的setMouseCallback绑定鼠标事件,区分三类核心交互:
    • 左键按下+拖动+释放:完成新直线的绘制
    • 右键点击:选中距离鼠标最近的直线(通过点到直线的垂直距离判断)
    • 左键拖动选中的直线:通过偏移量同步更新直线的起点和终点,实现整体移动
  • 实时刷新图像,叠加不同状态的直线绘制效果,提供清晰视觉反馈

完整代码实现

import cv2
import numpy as np

# 全局状态变量
img = None
temp_line = None  # 绘制中的临时直线
lines = []        # 存储已完成直线,格式: {'start': (x,y), 'end': (x,y), 'selected': False}
selected_idx = -1  # 当前选中的直线索引
drag_origin = None # 拖动时的鼠标起始位置

def point_to_line_dist(point, line_start, line_end):
    """计算点到直线的垂直距离,用于判断是否选中直线"""
    x0, y0 = point
    x1, y1 = line_start
    x2, y2 = line_end
    numerator = abs((y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 - y2*x1)
    denominator = np.sqrt((y2 - y1)**2 + (x2 - x1)**2)
    if denominator == 0:
        return np.sqrt((x0 - x1)**2 + (y0 - y1)**2)
    return numerator / denominator

def mouse_event_handler(event, x, y, flags, param):
    global img, temp_line, lines, selected_idx, drag_origin

    if event == cv2.EVENT_LBUTTONDOWN:
        if selected_idx == -1:
            # 未选中直线,启动新直线绘制
            temp_line = {'start': (x, y), 'end': (x, y)}
        else:
            # 已选中直线,记录拖动起始点
            drag_origin = (x, y)
    elif event == cv2.EVENT_LBUTTONUP:
        if temp_line is not None:
            # 完成直线绘制,加入列表
            lines.append({'start': temp_line['start'], 'end': (x, y), 'selected': False})
            temp_line = None
        drag_origin = None
    elif event == cv2.EVENT_MOUSEMOVE:
        if temp_line is not None:
            # 实时更新绘制中的直线终点
            temp_line['end'] = (x, y)
            # 刷新图像
            display_img = img.copy()
            # 绘制已完成直线
            for line in lines:
                color = (0, 0, 255) if line['selected'] else (0, 255, 0)
                cv2.line(display_img, line['start'], line['end'], color, 2)
            # 绘制临时直线
            cv2.line(display_img, temp_line['start'], temp_line['end'], (255, 0, 0), 2)
            cv2.imshow('Microscope Image', display_img)
        elif drag_origin is not None and selected_idx != -1:
            # 计算拖动偏移量,更新选中直线的坐标
            dx = x - drag_origin[0]
            dy = y - drag_origin[1]
            lines[selected_idx]['start'] = (lines[selected_idx]['start'][0]+dx, lines[selected_idx]['start'][1]+dy)
            lines[selected_idx]['end'] = (lines[selected_idx]['end'][0]+dx, lines[selected_idx]['end'][1]+dy)
            drag_origin = (x, y)
            # 刷新图像
            display_img = img.copy()
            for line in lines:
                color = (0, 0, 255) if line['selected'] else (0, 255, 0)
                cv2.line(display_img, line['start'], line['end'], color, 2)
            cv2.imshow('Microscope Image', display_img)
    elif event == cv2.EVENT_RBUTTONDOWN:
        # 右键点击选中最近的直线
        min_dist = float('inf')
        selected_idx = -1
        # 清除之前的选中状态
        for line in lines:
            line['selected'] = False
        # 遍历寻找距离最近的直线
        for idx, line in enumerate(lines):
            dist = point_to_line_dist((x, y), line['start'], line['end'])
            if dist < 10 and dist < min_dist: # 10为距离阈值,可根据图像分辨率调整
                min_dist = dist
                selected_idx = idx
        # 设置选中状态并刷新图像
        if selected_idx != -1:
            lines[selected_idx]['selected'] = True
            display_img = img.copy()
            for line in lines:
                color = (0, 0, 255) if line['selected'] else (0, 255, 0)
                cv2.line(display_img, line['start'], line['end'], color, 2)
            cv2.imshow('Microscope Image', display_img)

if __name__ == '__main__':
    # 加载显微镜图像(替换为你的图像路径)
    img = cv2.imread('microscope_sample.jpg')
    if img is None:
        # 图像加载失败时,用黑色画布替代
        img = np.zeros((600, 800, 3), dtype=np.uint8)
    cv2.namedWindow('Microscope Image')
    cv2.setMouseCallback('Microscope Image', mouse_event_handler)
    cv2.imshow('Microscope Image', img)
    # 等待ESC键退出
    while True:
        if cv2.waitKey(1) & 0xFF == 27:
            break
    cv2.destroyAllWindows()

关键细节说明

  1. 直线选中判定:通过点到直线的垂直距离计算,设置合理阈值(默认10),适配显微镜图像的精细操作需求
  2. 拖动逻辑:通过记录拖动起始点与当前点的偏移量,同步更新直线的起点和终点,保证直线整体移动不改变长度和角度
  3. 视觉区分:选中的直线用红色标记,绘制中的临时直线用蓝色,已完成未选中的直线用绿色,清晰区分不同交互状态
  4. 场景适配:可直接替换加载的图像为显微镜成像,阈值参数可根据图像分辨率和操作精度调整

内容的提问来源于stack exchange,提问作者Naruto uzumaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:35:35