绘制图形
绘制直线
- line(img, 开始点, 结束点, 颜色, 线宽, 线型(默认8,4显示锯齿))
- 线型(4, 8, 16三种)
import cv2
import numpy as np
img = np.zeros((640, 480, 3), np.uint8)
# 画线,坐标点为(x, y)
cv2.line(img, (10, 20), (300, 400), (0, 0, 255), 5, 4)
# 16 线条更平滑
cv2.line(img, (90, 100), (380, 480), (0, 0, 255), 5, 16)
cv2.imshow('img', img)
cv2.waitKey(0)
- rectangle
import cv2
import numpy as np
img = np.zeros((640, 480, 3), np.uint8)
# 画矩形
cv2.rectangle(img, (10, 10), (100, 100), (0, 0, 255), -1)
cv2.imshow('img', img)
cv2.waitKey(0)
绘制椭圆
- ellipse(img, 中心点, 长宽的一半, 角度, 从哪个角度开始, 从哪个角度结束, ...)
import cv2
import numpy as np
img = np.zeros((640, 480, 3), np.uint8)
# 画椭圆
# 度是按顺时针计算的
# 0度是从左侧开始的
cv2.ellipse(img, (320, 240), (100, 50), 15, 0, 360, (0, 0, 255), -1)
cv2.imshow('img', img)
cv2.waitKey(0)
绘制多边形
- fillPoly(img, 点集, 是否闭环, 颜色, ...)
import cv2
import numpy as np
img = np.zeros((640, 480, 3), np.uint8)
#画多边形
pts = np.array([(300, 10), (150, 100), (450, 100)], np.int32)
cv2.polylines(img, [pts], True, (0, 0, 255))
#填充多边形
cv2.fillPoly(img, [pts], (255, 255, 0))
cv2.imshow('img', img)
cv2.waitKey(0)
绘制文本
- putText(img, 字符串, 起始点, 字体, 字号, ...)
import cv2
import numpy as np
img = np.zeros((640, 480, 3), np.uint8)
#绘制广本
cv2.putText(img, "Hello ElasticNotes!", (10, 400), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0))
cv2.imshow('img', img)
cv2.waitKey(0)
实现鼠标绘制基本图形
#基本功能:
# 可以通过鼠标进行基本图形的绘制
# 1. 可以画线: 当用户按下l键,即选择了画线。此时,滑动鼠标即可画线。
# 2. 可以画矩形:当用户按下r键,即可选择画矩形。此时,滑动鼠标即可画矩形。
# 3. 可以画圆:当用户按下c键,即可选择画圆。此时,滑动鼠标即可画圆。
# ....
# curshape: 0-drawline, 1-drawrectangle, 2-drawcircle
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):
#print(event, x, y, flags, userdata)
global curshape, startpos
if (event & cv2.EVENT_LBUTTONDOWN == cv2.EVENT_LBUTTONDOWN):
startpos = (x, y)
elif (event & cv2.EVENT_LBUTTONUP == cv2.EVENT_LBUTTONUP):
if curshape == 0: #drawline
cv2.line(img, startpos, (x,y), (0,0,255))
elif curshape == 1: #drawrectangle
cv2.rectangle(img, startpos, (x,y), (0,0,255))
elif curshape == 2: #drawcircle
a = (x - startpos[0])
b = (y - startpos[1])
r = int((a**2+b**2)**0.5)
cv2.circle(img, startpos, r, (0,0,255))
else:
print('error:no shape')
#创建窗口
cv2.namedWindow('drawshape', cv2.WINDOW_NORMAL)
#设置鼠标回调
cv2.setMouseCallback('drawshape', mouse_callback)
while True:
cv2.imshow('drawshape', img)
key = cv2.waitKey(1) & 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()