05. 绘制基本的图像

2022/6/23 23:22:18

本文主要是介绍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()


这篇关于05. 绘制基本的图像的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程