OpenCV画基本图形

OpenCV画基本图形,第1张

OpenCV画基本图形 1. 画直线 cv2.line() 2. 画长方形 cv2.rectangle() 3. 画圆型 cv2.circle() 4. 画折线 cv2.polylines() 代码实现
# 1 导入库
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 2 定义颜色(字典形式)
colors={'blue':(255, 0, 0),
        'green':(0, 255, 0),
        'red':(0, 0, 255),
        'yellow':(0, 255, 255),
        'magenta':(255, 0, 255),
        'cyan':(255, 255, 0),
        'white':(255, 255, 255),
        'black':(0, 0, 0),
        'gray':(125, 125,125),
        'rand':np.random.randint(0, high=256, size=(3,)).tolist(),
        'dark_gray':(50, 50, 50),
        'light_gray':(220, 220, 220)}
 # 定义:显示图像
def show_image(image, title):
    img_RGB = image[:, :, ::-1]# BGR to RGB
    plt.title(title)
    plt.imshow(img_RGB)
    plt.show()
# 4 创建画布
canvas = np.zeros((400, 400, 3), np.uint8)#默认背景为黑色
canvas[:] = colors['white']
show_image(canvas, "Background")


# 5 画直线 cv2.line()
cv2.line(canvas, (0, 0), (400, 400),colors['green'], 5)
cv2.line(canvas, (0, 400), (400, 0),colors['black'], 5)
show_image(canvas, "cv2.line()")



# 6 画长方形 cv2.rectangle()
# 创建画布
canvas = np.zeros((400, 400, 3), np.uint8)#默认背景为黑色
canvas[:] = colors['white']
show_image(canvas, "Background")
cv2.rectangle(canvas, (10, 50),(70, 120), colors['green'], 3)
cv2.rectangle(canvas, (150, 50),(200, 300), colors['blue'], -1)

show_image(canvas, "cv2.rectangle()")
  

# 7 画圆型 cv2.circle()
# 创建画布
canvas = np.zeros((400, 400, 3), np.uint8)#默认背景为黑色
canvas[:] = colors['white']
show_image(canvas, "Background")  
cv2.circle(canvas, (200, 200), 150, colors['black'], 3)
cv2.circle(canvas, (200, 200), 50, colors['green'], -1)
show_image(canvas, "cv2.circle()")


# 8 画折线 cv2.polylines()
# 创建画布
canvas = np.zeros((400, 400, 3), np.uint8)#默认背景为黑色
canvas[:] = colors['white']
show_image(canvas, "Background")
pts = np.array([[250, 5], [220, 80], [280, 80]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(canvas, [pts], True, colors['green'], 3)

pts2 = np.array([[150, 200], [90, 130], [280, 180]], np.int32)
pts2 = pts2.reshape((-1, 1, 2))
cv2.polylines(canvas, [pts2], False, colors['black'], 3)
show_image(canvas,   "cv2.polylines()")

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5701342.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存