You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python与OpenCV实现鼠标自动选图像圆形区域并裁剪保存

OpenCV+Python实现鼠标选圆形区域裁剪存储的方案

1. 依赖安装

首先安装所需的第三方库:

pip install opencv-python numpy

2. 完整实现代码

import cv2
import numpy as np

# 全局状态变量
is_dragging = False  # 标记是否正在拖拽选框
center_x, center_y = 0, 0  # 圆形选区圆心坐标
radius = 0  # 圆形选区半径
origin_img = None  # 原始图片
preview_img = None  # 实时预览用的临时图片

# 鼠标事件回调函数
def mouse_event_handler(event, x, y, flags, param):
    global is_dragging, center_x, center_y, radius, origin_img, preview_img
    # 左键按下:记录圆心位置,开启拖拽状态
    if event == cv2.EVENT_LBUTTONDOWN:
        is_dragging = True
        center_x, center_y = x, y
    # 鼠标移动:拖拽状态下实时更新预览圆
    elif event == cv2.EVENT_MOUSEMOVE:
        if is_dragging:
            preview_img = origin_img.copy()
            # 计算当前拖拽位置对应的圆半径
            radius = int(np.sqrt((x - center_x)**2 + (y - center_y)**2))
            # 绘制蓝色预览圆,线宽2
            cv2.circle(preview_img, (center_x, center_y), radius, (255, 0, 0), 2)
            cv2.imshow("Select Circle Area", preview_img)
    # 左键松开:结束拖拽,裁剪并保存选区
    elif event == cv2.EVENT_LBUTTONUP:
        is_dragging = False
        h, w = origin_img.shape[:2]
        # 生成透明通道掩码:圆形区域为不透明,其余区域为透明
        mask = np.zeros((h, w), dtype=np.uint8)
        cv2.circle(mask, (center_x, center_y), radius, 255, -1)
        # 合并原图和透明通道,得到仅保留圆形选区的图片
        b, g, r = cv2.split(origin_img)
        output_img = cv2.merge((b, g, r, mask))
        # 保存结果,默认保存为支持透明背景的PNG格式
        cv2.imwrite("cropped_circle.png", output_img)
        print("选区已保存为 cropped_circle.png")

if __name__ == "__main__":
    # 替换为你本地待处理的图片路径
    img_path = "test.jpg"
    origin_img = cv2.imread(img_path)
    if origin_img is None:
        print("图片读取失败,请检查路径是否正确")
        exit()
    # 为原图预先添加透明通道,方便后续生成带透明背景的结果
    origin_img = cv2.cvtColor(origin_img, cv2.COLOR_BGR2BGRA)
    preview_img = origin_img.copy()
    # 绑定窗口和鼠标回调事件
    cv2.namedWindow("Select Circle Area")
    cv2.setMouseCallback("Select Circle Area", mouse_event_handler)
    # 主循环,按q键退出
    while True:
        cv2.imshow("Select Circle Area", preview_img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()

3. 操作说明

  • 运行前先将代码中的img_path替换为你本地待处理的图片路径
  • 运行代码后会弹出图片展示窗口,按住鼠标左键从你想要的圆形中心位置开始拖拽
  • 拖拽过程中会实时展示蓝色的圆形选区预览,调整到合适大小后松开左键即可自动保存选区
  • 按键盘q键可关闭窗口结束程序

4. 可选调整说明

如果需要保存为不支持透明背景的JPG格式,可将裁剪逻辑替换为如下代码,得到黑底的圆形选区图片:

# 替换左键松开事件中的合并通道代码
output_img = cv2.bitwise_and(origin_img, origin_img, mask=mask)
# 保存时修改后缀为jpg即可
cv2.imwrite("cropped_circle.jpg", output_img)

内容的提问来源于stack exchange,提问作者r h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:15:03