05. 绘制基本的图像

绘制基本的图形

  • 直线line()
  • 矩形rectangle()
  • 圆circle()
  • 椭圆ellipse()
  • 多边形polylines()
  • 填充的多边形fillPoly()
  • 文本putText()

示例:动态绘制一个矩形框(通过键盘选择矩形、圆),要求实时性,基本不延迟

import cv2
import numpy as np

bg = cv2.imread('./images/bg.jpg')
print(bg.shape)

# 绘制背景色
window_name = 'window'
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(window_name, (800, 450))
cv2.imshow(window_name, bg)

start_pos = None
end_pos = None
button_status = 0
def mouse_callback(event, x, y, flags, userdata):
    global start_pos, end_pos, button_status
    if event == cv2.EVENT_LBUTTONDOWN:
        start_pos = (x, y)
        end_pos = (x, y)
        button_status = 1
    if event == cv2.EVENT_LBUTTONUP:
        end_pos = (x, y)
        button_status = 0
    if event == cv2.EVENT_MOUSEMOVE and button_status==1:
        end_pos = (x, y)
graphic_shape = 1
cv2.setMouseCallback(window_name, mouse_callback)
# 鼠标动态绘制
while True:
    key = cv2.waitKey(5)
    if key == ord('q'):
        break
    elif key == ord('r'):
        graphic_shape = 1  # 表示矩形
        start_pos = None
        end_pos = None
    elif key == ord('c'):
        graphic_shape = 2  # 表示圆
        start_pos = None
        end_pos = None
    bg2 = bg.copy()
    if graphic_shape == 1 and start_pos is not None and end_pos is not None:
        cv2.rectangle(bg2, start_pos, end_pos, (0, 0, 255), 3)
    elif graphic_shape == 2 and start_pos is not None and end_pos is not None:
        r = int(((end_pos[0]-start_pos[0])**2+(end_pos[1]-start_pos[1])**2)**0.5)
        cv2.circle(bg2, start_pos, r, (0, 0, 255), 3)
    cv2.imshow(window_name, bg2)

cv2.destroyAllWindows()
posted @ 2022-06-23 22:21  理舞  阅读(56)  评论(0编辑  收藏  举报