用opencv自带函数绘制直线,矩形,圆形,折线的程序示例及结果如下:
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 定义颜色,字典形式
colors = {
'blue':(255,0,0),
'green':(0,255,0),
'red':(0,0,255),
'yellow':(0,255,255),
'magenta':(255,0,255),
'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]
plt.title(title)
plt.imshow(img_RGB)
plt.show()
# 创建画布
canvas = np.zeros((400,400,3),np.uint8) # 默认背景为黑色
# 把黑色背景转换为白色白景,用键值'white'
canvas[:] = colors['white']
show_image(canvas,"Background")
# 画直线: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()")
# 画长方形:cv2.rectangle()
canvas = np.zeros((400,400,3),np.uint8)
canvas[:] = colors['white']
cv2.rectangle(canvas,(10,50),(70,120),colors['green'],3) # 两点表示左上角和右下角
cv2.rectangle(canvas,(150,50),(200,300),colors['blue'],-1) # -1表示填充颜色
show_image(canvas,"cv2.rectangle()")
# 画圆形:cv2.circle()
canvas = np.zeros((400,400,3),np.uint8)
canvas[:] = colors['white']
cv2.circle(canvas,(200,200),150,colors['black'],3)
cv2.circle(canvas,(200,200),50,colors['green'],-1)
show_image(canvas,"cv2.circle()")
# 画折线:cv2.polylines()
canvas = np.zeros((400,400,3),np.uint8)
canvas[:] = colors['white']
pts = np.array([[250,5],[220,80],[280,80]],np.int32)
pts = pts.reshape((-1,1,2))
pts2 = np.array([[150,200],[90,130],[280,180]],np.int32)
pts2 = pts2.reshape((-1,1,2))
cv2.polylines(canvas,[pts2],False,colors['black'],5) # False表示折线之间不闭合,不构成三角形
cv2.polylines(canvas,[pts],True,colors['green'],3) # True表示这线之间是闭合的,构成三角形
show_image(canvas,"cv2.polylines()")
线条类型:cv2.LINE_4,cv2.LINE_8,cv2.LINE_AA当显示字体模糊或者大小不合适时可以选用不同的线条类型。
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 定义颜色,字典形式
colors = {
'blue':(255,0,0),
'green':(0,255,0),
'red':(0,0,255),
'yellow':(0,255,255),
'magenta':(255,0,255),
'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]
plt.title(title)
plt.imshow(img_RGB)
plt.show()
# 创建画布
canvas = np.zeros((400,400,3),np.uint8) # 默认背景为黑色
canvas[:] = colors['light_gray'] # 或者canvas.fill(220)
# 往画布上面输入文本,(50,50)为起始位置,cv2.FONT_HERSHEY_SIMPLEX为字体,cv2.LINE_AA线条类型
cv2.putText(canvas,"Hello World",(50,50),cv2.FONT_HERSHEY_SIMPLEX,0.9,colors['red'],cv2.LINE_4)
cv2.putText(canvas,"Welcome to world",(5,150),cv2.FONT_HERSHEY_SIMPLEX,1.4,cv2.LINE_8)
cv2.putText(canvas,"MRN",(50,300),cv2.FONT_HERSHEY_SIMPLEX,1.9,cv2.LINE_AA)
# 线条类型:cv2.LINE_4,cv2.LINE_8,cv2.LINE_AA
show_image(canvas,"Canvas")