ROI坐标点提取(python)

import cv2

pts= []  # 用于存放点

def roi(event, x, y, flags, param):
    img2 = img.copy()
    if event == cv2.EVENT_LBUTTONDOWN:  # 左键点击,选择点
        pts.append((x, y))
    if event == cv2.EVENT_RBUTTONDOWN:  # 右键点击,取消最近一次选择的点
        pts.pop()
    if event == cv2.EVENT_MBUTTONDOWN:  # 点击滚轮,打印当前已存坐标
        print({
    
    "ROI": pts})
        pts.clear()

    if len(pts) > 0:
        # 将pts中的最后一点画出来
        cv2.circle(img2, pts[-1], 3, (0, 0, 255), -1)

    if len(pts) > 1:
        # 画线
        for i in range(len(pts) - 1):
            cv2.circle(img2, pts[i], 5, (0, 0, 255), -1)  # x ,y 为鼠标点击地方的坐标
            cv2.line(img=img2, pt1=pts[i], pt2=pts[i + 1], color=(255, 0, 0), thickness=2)
    cv2.imshow('image', img2)


path=r"./1111.png" #需要提取roi的图像
img = cv2.imread(path)
cv2.namedWindow('image')
cv2.setMouseCallback('image', roi)
print('''1 左键点击选点
2 右键点击删除点
3 中间滚轮显示当前区域坐标,接着可进行下一个区域的选取
4 按 ESC 退出
''')

while True:
    key = cv2.waitKey(1) & 0xFF
    if key == 27:
        break

cv2.destroyAllWindows()

おすすめ

転載: blog.csdn.net/weixin_48994268/article/details/120513857