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()")
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值