OpenCV实现基本图形绘制
画线
- line(img,开始点,结束点,颜色…)
- img:在哪个图像上画线
- 开始点,结束点:指定线的开始与结束位置
- 颜色、线宽、线型
- Shift:坐标缩放比例
import cv2
import numpy as np
img = np.zeros((480,640,3),np.uint8)
cv2.line(img,(10,20),(10,400),(0,0,255))
cv2.line(img,(10,20),(300,400),(0,0,255),5,4)
cv2.imshow('draw',img)
cv2.waitKey(0)
画椭圆
- ellipse(img,中心点,长款的一半,角度,从哪个角度开始,到哪个角度结束,…)
cv2.ellipse(img,(320,240),(100,50),0,0,360,(0,0,255))
cv2.rectangle(img,(10,10),(100,100),(0,0,255),-1)
cv2.circle(img,(320,240),100,(0,0,255))
cv2.circle(img,(320,240),5,(0,0,255),-1)
画多边形
- polylines(img,点集,是否闭环,颜色…)
- 填充多边形:fillPoly(img,点集,颜色)
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))
画文本
- putText(img,字符串,起始点,字体,字号,…)
cv2.putText(img,"Hello World",(10,400),cv2.FONT_HERSHEY_PLAIN,1,(255,255,0))
【实战】鼠标绘制基本图像
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
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))
elif curshape == 1:
cv2.rectangle(img,startpos,(x,y),(0,0,255))
elif curshape == 2:
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'):
curshape = 0
elif key == ord('r'):
curshape = 1
elif key == ord('c'):
curshape = 2
cv2.destroyAllWindows()