opencv库图像基础4绘图-python

发布时间 2024-01-06 17:27:09作者: AndreaDO

opencv库图像基础4绘图-python

1.绘画线条和简单图形

创建颜色字典和一个画布

import cv2
import numpy as np
import matplotlib.pyplot as plt
# 颜色
colors={
  'blue':(255,0,0),
  'green':(0,255,0),
  'red':(0,0,255),
  'yellow':(0,255,255),
  'white':(255,255,255),
  'black':(0,0,0),
  'rand': np.random.randint(0,high=256,size=(3,)).tolist()
}
# 显示图像
def show_img(img,title):
  img_RGB = img[:,:,::-1]#BGR to RGB
  plt.title(title)
  plt.imshow(img_RGB)
  plt.show()

# 创建画布
def bg():
  canvas = np.zeros((400,400,3),np.uint8)
  canvas[:]=colors['white']
  show_img(canvas,'background')
  return canvas

画直线

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

画长方形

#画矩形
def rectangle(canvas):
  cv2.rectangle(canvas,(10,50),(70,120),colors['green'],3 )
  cv2.rectangle(canvas,(150,50),(170,120),colors['black'],-1) #填写-1表示填充
  show_img(canvas,"cv2.rectangle")

画圆形

 
def circle(canvas):
  cv2.circle(canvas,(200,200),150,colors['green'],3 )
  cv2.circle(canvas,(200,200),50,colors['black'],-1 )  #填写-1表示填充
  show_img(canvas,"cv2.rectangle")

画折线

def polyline(canvas):
  pts = np.array( [[250,5] ,[220,80],[280,80]],np.int32 )
  pts=pts.reshape( (-1,1,2) )
  cv2.polylines(canvas, [pts],True,colors['blue'],3 ) #True表示线封闭
  pts = np.array(  [[150,205] ,[90,130],[230,60]],np.int32 )
  pts=pts.reshape( (-1,1,2) )
  cv2.polylines(canvas, [pts],False,colors['rand'],3 ) #True表示线封闭
  show_img(canvas,"cv2.polylines")

2.在画板中添加文字

添加文字

def putText(canvas):
  # 背景图片 添加的文字 位置 字体 字体大小 字体颜色 字体粗细
  cv2.putText(canvas,"hello",(100,200) , cv2.FONT_HERSHEY_SIMPLEX,0.9,colors['blue'],2)
  show_img(canvas,"cv2.putText")

输出

函数原型
cv2.putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None)
参数介绍:
img:需要绘制文本的图像;
text:要绘制的文本内容;
org:表示要绘制的位置,图像中文本字符串的左下角;可以用一个元祖来表示x、y坐标,例如(10, 100)表示x=10,y=100。
fontFace:字体类型,如cv2.FONT_HERSHEY_SIMPLEX、cv2.FONT_HERSHEY_PLAIN等;对应的字体类型如下:

 cv2.FONT_ITALIC:斜体字的标志
 cv2.FONT_HERSHEY_PLAIN:小尺寸无衬线字体
 cv2.FONT_HERSHEY_SIMPLEX:正常大小的无衬线字体
 cv2.FONT_HERSHEY_DUPLEX:正常大小的无衬线字体(比FONT_HERSHEY_SIMPLEX更复杂)
 cv2.FONT_HERSHEY_COMPLEX:正常大小的衬线字体
 cv2.FONT_HERSHEY_TRIPLEX:正常大小的衬线字体(比FONT_HERSHEY_COMPLEX更复杂)
 cv2.FONT_HERSHEY_SCRIPT_SIMPLEX:手写体字体
 cv2.FONT_HERSHEY_SCRIPT_COMPLEX(比FONT_HERSHEY_SCRIPT_SIMPLEX的更复杂)

fontScale:字体的大小,字体比例因子乘以font-specific基本大小;
color:文本字体颜色,设置三通道的元组BGR,比如(255,0,0)
hickness:字体粗细,默认为1;
lineType:线条类型,默认为cv2.LINE_AA;
bottomLeftOrigin:坐标原点,如果为真,则图像数据原点位于左下角,否则它在左上角;
其中,org定义了文本起始位置,可以用一个元祖来表示x、y坐标,例如(10, 100)表示x=10,y=100。