使用opencv畫框,標出座標

少侠不懂天文發表於2024-09-20
import cv2
import numpy as np


drawing, start_x, start_y = False, -1, -1
prev_point = None # 上一個點
history = list()


def draw_box(points, color=(0, 255, 0), thickness=1):
    if points:
        p1, p2 = points
        top_left, top_right, bottom_right, bottom_left = p1, (
            p2[0], p1[1]), p2, (p1[0], p2[1])
        cv2.line(mask, top_left, top_right, color, thickness)  # 上邊
        cv2.line(mask, top_right, bottom_right, color, thickness)  # 右邊
        cv2.line(mask, bottom_right, bottom_left, color, thickness)  # 下邊
        cv2.line(mask, bottom_left, top_left, color, thickness)  # 左邊


def mouse_event(event, x, y, flags, param):
    """
    滑鼠的回撥函式
    """
    global drawing, start_x, start_y, prev_point
    points = ((start_x, start_y), (x, y))
    # 透過 event 判斷具體是什麼事件,這裡是左鍵按下
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        start_x, start_y = x, y
        prev_point = None
    # 滑鼠移動,畫圖
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            # 清除拖動的框
            draw_box(prev_point, color=(0, 0, 0))
            # 畫框
            draw_box(points)
            prev_point = points
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        draw_box(prev_point, color=(0, 0, 0))
        draw_box(points)
        history.append(points)
        prev_point = points


img = cv2.imread("background.jpg")
cv2.namedWindow('image')
# 定義滑鼠的回撥函式
cv2.setMouseCallback('image', mouse_event)

# 建立掩碼,在掩碼上畫線
mask = np.zeros_like(img)


while True:
    cv2.imshow('image', cv2.bitwise_or(img, mask))
    # 按下 ESC 鍵退出
    if cv2.waitKey(20) == 27 or cv2.waitKey(20) == ord('q'):
        break
    elif cv2.waitKey(20) == ord('z'):
        if history:
            draw_box(history.pop(), color=(0, 0, 0))

for points in history:
    print(points)


相關文章