6.OpenCV的绘图
前言
OpenCV提供的绘图函数可用于绘制直线、矩形、圆、椭圆、多边形及文本等。
一、绘制直线
# 创建黑色画布
img = np.zeros((500,500,3),dtype='uint8')
#直线
cv2.line(img,(0,0),(500,500),(0, 0, 255), 3,cv2.LINE_AA)
cv2.line(img,(0,500),(500,0),(0, 255, 0), 10,cv2.LINE_AA)
cv2.imshow('Line',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
二、绘制矩形
# 创建黑色画布
img = np.zeros((500,500,3),dtype='uint8')
# 矩形
cv2.rectangle(img,(20,20),(100,150),(0,255,255),5)
cv2.rectangle(img,(200,200),(300,300),(255,255,0),-1)
cv2.imshow('Rectangle',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
三、绘制圆
# 创建黑色画布
img = np.zeros((500,500,3),dtype='uint8')
# 圆形
cv2.circle(img,(250,250),90,(255,255,255),-1)
cv2.circle(img,(250,250),120,(255,0,255),1)
cv2.circle(img,(250,250),150,(0,255,255),5)
cv2.imshow('Circle',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 绘制多个点
import cv2
# 创建黑色画布
img = np.zeros((300,300,3),dtype='uint8')
pts = [[[250,250],[253,250],[256,250],[259,250]],
[[251,210],[253,210],[256,210],[259,210]],
[[254,180],[253,180],[256,180],[249,180]]]
for i in range(len(pts)):
pt_color = [int(c) for c in np.random.randint(100, 240, 3)]
for p in pts[i]:
cv2.circle(img,p,1,pt_color,-1)
cv2.imshow('Circle',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
四、绘制椭圆
# 创建黑色画布
img = np.zeros((500,500,3),dtype='uint8')
# 椭圆形
cv2.ellipse(img,(250,250),(120, 50),0,90,360,(255,0,0),-1)
cv2.imshow('Ellipse',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
五、绘制多边形
# 创建黑色画布
img = np.zeros((500,500,3),dtype='uint8')
# 多边形
pts = np.array([[160,20],[20,100],[160,180],[300,100]], np.int32)
cv2.polylines(img,[pts],True,(255,0,255),5)
cv2.imshow('Polylines',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
六、绘制文本
# 创建白色画布
img = np.zeros((500,500,3),dtype='uint8') + 255
# 绘制文本
font1 = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX # 字体类型
font2 = cv2.FONT_HERSHEY_SCRIPT_COMPLEX
font3 = cv2.FONT_HERSHEY_PLAIN
cv2.putText(img, 'Python', (100,120), font1, 4, (255,0,0),2, cv2.LINE_AA)
cv2.putText(img, 'Python', (100,200), font2, 2, (255,0,0),2, cv2.LINE_AA, True)
cv2.putText(img, 'Python', (50,400), font3, 6, (255,0,0),4, cv2.LINE_AA)
cv2.imshow('PutText',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
七、绘制箭头
# 创建白色画布
img = np.zeros((500,500,3),dtype='uint8') + 255
# 箭头
cv2.arrowedLine(img,(100,100),(100,300),(0,0,255),2)
cv2.arrowedLine(img,(100,100),(400,100),(0,0,255),2)
cv2.imshow('ArrowedLine',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
八、OpenCV-Python资源下载
OpenCV-Python测试用图片、中文官方文档、opencv-4.5.4源码
总结
以上内容介绍了OpenCV-Python简单的绘图操作,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。