3 绘制图形
常用API:
- cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]:画直线
- cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]):画矩形
- cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]):画圆
- cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]):画椭圆
3.1 绘制图形具体演示
import cv2
import numpy as np
#创建纯黑背景图
img = np.zeros((480, 640, 3), np.uint8)
#背景图,起始地址,结束地址,颜色,线宽,线型(-1,4,8,16 默认是8)越小线上锯齿状越明显,坐标缩放比例
cv2.line(img, (10, 20), (300, 400), (0, 0, 255), 5, 4)
cv2.rectangle(img, (80, 100), (380, 380), (0, 255, 0), 5)
#背景图,圆心坐标,半径,颜色,线宽,线型
cv2.circle(img, (320, 240), 100, (0, 0, 255), 5, 16)
#背景图,中心点,长宽的一半,角度,从哪个角度开始,到哪个角度结束
cv2.ellipse(img, (320, 240), (100, 50), 0, 0, 360, (0, 0, 255), 5, 16)
cv2.imshow('draw', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.2 绘制多边形
- cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]):画多边形
- cv2.fillPoly(img, pts, color[, lineType[, shift[, offset]]]):填充多边形
- cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]):绘制文本
import cv2
import numpy as np
#创建纯黑背景图
img = np.zeros((480, 640, 3), np.uint8)
#背景图,点集(必须是int32位及以上),是否闭合,颜色....
pts = np.array([(300, 10), (150, 100), (450, 100)], np.int32)
#注意pts是3维的
cv2.polylines(img, [pts], True, (0, 0, 255), 5)
#填充多边形
cv2.fillPoly(img, [pts], (0, 0, 255))
#绘制文本:背景图,要绘制的文本,文本左下角的坐标,字体,颜色
#注意字体里面没有中文
cv2.putText(img, 'Hello OpenCV', (50, 400), cv2.FONT_HERSHEY_COMPLEX, 2, (0, 0, 255))
cv2.imshow('draw', img)
cv2.waitKey(0)
cv2.destroyAllWindows()