img:在那个图像上画线
开始点,结束点:指定线的开始和结束的位置
颜色,线宽(-1表示的是填充),线型(-1,4,8,16)
shift:坐标比例缩放
填充多边形和之前的将线宽改为-1不同,有单独的API函数:cv2.fillpoly(img,点集,颜色)
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)
cv2.polylines(img, [pts], True, (0, 0, 255), 5, 16)
cv2.fillPoly(img, [pts], (0, 255, 0))
cv2.imshow('draw', img)
key = cv2.waitKey(0)
if key & 0xFF == ord('q'):
cv2.destroyAllWindows()
putText(img,字符串,起始点,字体,字号,.....)
import cv2
import numpy as np
img = cv2.imread('d:\\download\\2.jpg')
img1 = cv2.resize(img, (600, 400))
img2 = img1.copy()
# 绘制文本
# putText(img,字符串,起始点,字体,字号,颜色,线宽)
cv2.putText(img1, 'hello,world!', (100, 100), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 255, 0), 5)
res = np.hstack([img2, img1])
cv2.imshow('res', res)
key = cv2.waitKey(0)
if key & 0xFF == ord('q'):
cv2.destroyAllWindows()
运行结果:
# 基本功能
# 可以通过鼠标进行基本图形的绘制
# 1.可以画线:当用户按下l键,即选择了画线,此时,滑动鼠标即可画线
# 2.可以画圆:当用户按下c键,即选择了画圆,此时,滑动鼠标即可画圆
# 3.可以画矩形:当用户按下r键,即选择了画矩形,此时,滑动鼠标即可画矩形
import cv2
import numpy as np
curshape = 0
startpos = (0, 0)
img = np.zeros((480, 640, 3), np.uint8)
def mouse_callback(event, x, y, flags, userdata):
global curshape, startpos
# print(event, x, y, flags, userdata)
if event & cv2.EVENT_LBUTTONDOWN == cv2.EVENT_LBUTTONDOWN:
startpos = (x, y)
elif event & cv2.EVENT_LBUTTONUP == cv2.EVENT_LBUTTONUP:
if curshape == 0:
cv2.line(img, startpos, (x, y), (0, 0, 255), 5, 8)
elif curshape == 1:
cv2.rectangle(img, startpos, (x, y), (0, 255, 0), -1, 4)
elif curshape == 2:
a = (x - startpos[0])**2
b = (y - startpos[1])**2
r = int((a**2+b**2)**0.5)
cv2.circle(img, startpos, r, (255, 0, 0), 5, 8)
else:
print('error:no shape')
# 创建窗口
cv2.namedWindow("drawshape", cv2.WINDOW_NORMAL)
# 设置鼠标回调函数
cv2.setMouseCallback('drawshape', mouse_callback, '123')
while True:
cv2.imshow('drawshape', img)
key = cv2.waitKey(0) & 0xFF
if key == ord('q'):
break
elif key == ord('l'): # line
curshape = 0
elif key == ord('r'): # rectangle
curshape = 1
elif key == ord('c'): # circle
curshape = 2
cv2.destroyAllWindows()