opencv-python画直线、圆、矩形、椭圆形、多边形以及参数介绍
画直线
cv2.line(img,pt1,pt2,color,thickness)
- img:画布
- pt1:直线起点(x,y)(opencv中图像的坐标原点在左上角,横轴为x轴,纵轴为y轴)
- pt2:直线终点
- color:直线的颜色
- thickness=1:线条粗细,默认是1
实现代码:
img = np.zeros((200,200,3), dtype=np.uint8)
img = cv2.line(img, (25, 189), (99, 18), (0, 0, 255), 2)
显示结果:
画圆
cv2.circle(img,center,radius,color, thickness)
- img:画布
- center:圆心
- radius:半径
- color:直线的颜色
- thickness=1:线条粗细,默认是1.如果一个闭合图形设置为-1,那么整个图形就会被填充。
当不填充圆形时:
img = np.zeros((200,200,3), dtype=np.uint8)
img = cv2.circle(img,(100,100), 63, (100,0,255), 2)#最后一个参数代表线宽
显示结果:
当填充圆形时:
img = np.zeros((200,200,3), dtype=np.uint8)
img = cv2.circle(img,(100,100), 63, (100,0,255), -1)# 最后一个参数为-1时,表示填充
显示结果:
画矩形
cv2.rectangle(img, pt1, pt2, color, thicknes)
- img:画布
- pt1:矩形的左上顶点
- pt2:矩形的右下顶点
- color:直线的颜色
- thickness=1:线条粗细,默认是1。等于-1时表示填充
实现代码:
img = np.zeros((170,200,3), dtype=np.uint8)
img = cv2.rectangle(img,(32,10),(168,128),(0,255,0),3)
显示结果:
画椭圆
cv2.ellipse(img,center, axes,angle,startAngle,endAngle,color,thickness)
- img:画布
- center:椭圆中心点的坐标
- axes:长轴和短轴的长度
- angle:椭圆沿逆时针选择角度
- startAngle:椭圆沿顺时针方向起始角度
- endAngle:椭圆沿顺时针方向结束角度
- color:颜色
- thickness:线条的粗细
实现代码:
img = np.zeros((200,200,3), dtype=np.uint8)
img = cv2.ellipse(img,(100,100),(80,30),100,-180,180,(100,0,255),-1)
显示结果:
画多边形
cv2.polylines(img, pts, isClosed, color, thickness)
- img:画布
- pts:包含多边形上点的数组,pts reshape为(-1, 1, 2)后,显示的是点,[pts]显示的是多边形
- isClosed:bool型,决定所绘制的多边形是否闭合。若为 True ,则画若干个闭合多边形;若为 False ,则画一条连接所有点的折线
- color:多边形颜色
- thickness:多边形线的粗细,这里thickness不能取-1
实现代码:
img = np.zeros((200,200,3), dtype=np.uint8)
pts = np.array([[20, 10], [40, 180], [140, 140], [80, 20]], np.int32)
pts = pts.reshape((-1, 1, 2))
img = cv2.polylines(img,pts=[pts],isClosed=True, color=(0, 0, 200), thickness=2)
Image.fromarray(img)
显示结果:
填充多边形
cv2.fillPoly(img, pts, color)
- img:画布
- pts:包含多边形上点的数组
- color:多边形颜色
实现代码:
img = np.zeros((200,200,3), dtype=np.uint8)
pts = np.array([[20, 10], [40, 180], [140, 140], [80, 20]], np.int32)
pts = pts.reshape((-1, 1, 2))
img = cv2.fillPoly(img,[pts],(255,255,255))
Image.fromarray(img)
显示结果: