Pytohn OpenCV 绘图函数

绘图函数都需要设置一些参数

img:想要绘制图形的那个图像

color:形状的颜色。

thickness:线条的粗细(如果给一个闭合图形设置为-1,那么这个图形会被填充)。默认值是1.

linetype:线条的类型,8连接,抗锯齿等。默认情况是8连接。cv2.LINE_AA为抗锯齿。

画线

cv2.line(图像,起点,终点,颜色,线条类型)

# -*- coding: utf-8 -*-

import cv2
import numpy as np

img = np.zeros((512, 512, 3), np.uint8)

#画一条线
cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)

cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

画矩形

cv2.rectangle(图像,左上角顶点,右下角顶点, 颜色,线条类型)

#画一个矩形
cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)

画圆

cv2.circle(图像, 圆心,半径,颜色,线条类型)

#画一个园
cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)

画椭圆

cv2.ellipse(图像,中心点坐标,长轴短轴,逆时针方向旋转角度,顺时针方向起始角度,顺时针方向结束角度,颜色, 线条类型)

#画一个椭圆
cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, (255, 0, 0), -1)

画多边形

需要指定每个顶点的坐标。

用坐标构造一个数组,行数就是点的数目。

数组的数据类型必须为int32

#画一个多边形
pts = np.array([[10,5], [20,30], [70,20], [50,10]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(img, [pts], True, (0, 255, 255))

如果第三个参数时False,那么多边形是不闭合的(首尾不相接)

在图片上添加文字

需要的参数:

要绘制的文字

绘制的位置

字体类型

字体大小

字体的属性(颜色,粗细,线条类型等)

#添加文字
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OpenCV', (10, 500), font, 4, (255, 255, 255), 2)

综合示例

# -*- coding: utf-8 -*-

import cv2
import numpy as np

img = np.zeros((512, 512, 3), np.uint8)

#画一条线
cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)

#画一个矩形
cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)

#画一个园
cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)

#画一个椭圆
cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, (255, 0, 0), -1)


#画一个多边形
pts = np.array([[10,5], [20,30], [70,20], [50,10]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(img, [pts], True, (0, 255, 255))

#添加文字
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OpenCV', (10, 500), font, 4, (255, 255, 255), 2)

winname = 'example'
cv2.namedWindow(winname)
cv2.imshow(winname, img)
cv2.waitKey(0)
cv2.destroyAllWindows()

猜你喜欢

转载自www.cnblogs.com/wbyixx/p/9393791.html