利用OpenCV提供的绘制图形API可以轻松在图像上绘制各种图形,比如直线,矩形,圆,椭圆等图形. cv2.line(img, pt1, pt2, color, thickness, lineType, shift)画直线 o img:在哪个图像上画线 o pt1, pt2:开始点结束点.指定线的开始与结束位置 o color:颜色 o thickness:线宽 o lineType:线型.线型为-1,4, 8,16,默认为8 o shift:坐标缩放比例. cv2.rectangle)参数同上画矩形 cv2.circle(img, center, radius, color[ thickness[, lineType[, shift]ll)中括号内参数表示可选参数.画圆 cv2.ellipse(img,中心点,长宽的一半,角度,从哪个角度开始,从哪个角度结束..) cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]l)画多边形 · fillpoly填充多边形 . putText(img, text, org, fontFace, fontScale, color[l thickness[, lineType[, bottomLeftOrigin]l)绘制文本 o text要绘制的文本 o org文本在图片中的左下角坐标 o fontFace字体类型即字体 o fontScale字体大小
# 绘制各种图形
import cv2
import numpy as np
# 创建纯黑的背景图用来画图形
img = np.zeros((480, 640, 3), np.uint8)
# 划线
# cv2.line(img, ptq, pt2, color , thickness, lineType, shift) shift是缩放比 可以不写
cv2.line(img, (10, 20), (300,400), (0, 0, 255), 5, 4)
cv2.line(img, (80, 100), (380,480), (0, 0, 255), 5, 16)
# 画矩形
cv2.rectangle(img, (80, 100), (380, 380), (0, 255, 0), 5)
# 画圆 需要传圆心坐标 半径大小
# circle(img, center, radius, color, thickness[, lineType, shift]]])
cv2.circle(img, (320, 240), 50, (0, 0, 255), 5, 16)
# 画椭圆ellipse
# ellipse(img, 中心点, 长度的一半, 角度, 从哪个角度开始, 从哪个角度结束...) 这里的角度是逆时针的角度
cv2.ellipse(img, (120, 240), (100, 50), 0, 0, 360, [0, 0, 255], 5, 16)
cv2.ellipse(img, (120, 240), (100, 50), 45, 0, 360, [0, 0, 255], 5, 16)
cv2.ellipse(img, (200, 250), (100, 50), 0, 0, 180, [0, 0, 255], 5, 16)
# 绘制多边形
# pts多边形的点集,必须是Int32位的, 注意pts是三维的
pts = np.array([(250, 100), (150, 300), (50, 280)], np.int32)
cv2.polylines(img, [pts], True, (0, 0, 255), 5)
cv2.polylines(img, [pts], False, (0, 0, 255), 5)
# 填充多边形
cv2.fillPoly(img, [pts], (0, 0, 255))
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()