1.代码速记
- cv2.line()
- cv2.rectangle()
- cv2.circle()
- cv2.ellipse()
- cv2.polylines()
- cv2.putText()
- cv2.setMouseCallback()
参数解释:
-img:原图。
-color:形状颜色,多色传入元组。
-thickness:线条粗细。给闭合图形设置为-1,则该图形会被填充。默认值为1.
-linetype:线条的类型。默认是8连接。从cv2.LINE_AA为抗锯齿。
-所有的绘图函数的返回值都是None
2.画图
def draw(self):
img = np.zeros((512, 512, 3), np.uint8)
# 【1】线
cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) # 原图、起点、终点、蓝色、粗细
#【2】长方形
cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3) # 原图,左上角、右下角、绿色、粗细
#【3】圆
cv2.circle(img, (447, 63), 63, (0, 0, 255), -1) # 原图、圆心、半径、红色、粗细
#【4】椭圆
cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, (255,0,255),-1)#紫色
# 原图、中心点、长轴/短轴长度、椭圆沿逆时针方向旋转的角度、
# 椭圆弧沿顺时针方向起始的角度和结结束角度(0-360是整个椭圆)、颜色、粗细
#【5】多边形
pts = np.array([[100, 200], [200, 350], [300, 202], [500, 100]], np.int32)
pts = pts.reshape((-1, 1, 2))
# 这里reshape 的第一个参数为-1, 表明这一维的长度是根据后面的维度的计算出来的。
cv2.polylines(img,[pts],True,(0,255,255),2)#黄色
# 【6】文字
font = cv2.FONT_HERSHEY_COMPLEX
cv2.putText(img, 'OpenCV', (10, 500), font, 4, (255, 255, 255), 2)#白色
cv2.imshow('image',img)
cv2.waitKey(0)
3.把鼠标当画笔
#查看所有被支持的鼠标事件
events=[i for i in dir(cv2) if 'EVENT'in i]
print(events)
根据我们选择的模式在拖动鼠标时绘制矩形或者是圆圈:
import cv2
import numpy as np
drawing = False # 鼠标左键按下为真
mode = True # 为真,画长方形。 按下m来选择
ix,iy = -1,-1
# 鼠标回调函数
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN:#左键按下事件
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:#鼠标移动事件
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:#左键抬起事件
drawing = False
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv2.destroyAllWindows()