前言:总纲请查看《计算机视觉学习路》
line(img,开始点, 结束点, 颜色, 线宽, 线型)
线型可选: -1 4 8 16 可自行尝试
import cv2
import numpy as np
# 这里虽然写的是480*640 但是numpy是反着来的,img真实大小是640*480
img = np.zeros((480, 640, 3), np.uint8)
# 画线 红色的线 这里的坐标就是真实坐标
cv2.line(img, (0, 240), (640, 240), (0, 0, 255))
# 画一条蓝色的线 线宽 5
cv2.line(img, (320, 0), (320, 480), (255, 0, 0),5)
cv2.imshow('line', img)
cv2.waitKey()
rectangle(img , 开始点, 结束点, 颜色, 线宽, 线型)
线宽如果填 -1 就是填充效果:
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# 绘制一个矩形,线宽5
cv2.rectangle(img,(0,0),(200,200),(0,0,255),5)
# 如果改成 -1 这个矩形就是填充矩形
cv2.rectangle(img,(500,10),(620,300),(0,0,255),-1)
cv2.imshow('rect',img)
cv2.waitKey()
circle(img , 开始点 , 半径, 颜色,线宽,线型)
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# 绘制一个填充圆
cv2.circle(img,(320,240),150,(255,255,0),-1)
cv2.imshow('rect',img)
cv2.waitKey()
ellipse(img , 中心点, 长宽的一半,角度, 起始角度, 终止角度,颜色,线宽,线型)
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# 绘制一个椭圆
cv2.ellipse(img, (320, 240), (200, 100), 0, 0, 360, (0, 0, 255), 2)
cv2.imshow('ellipse', img)
cv2.waitKey()
polylines(img , 点集 , 是否闭环 , 颜色, 线宽,线型)
注意:多边形绘制,线宽-1无法填充,应该用下面的命令
fillPoly(img , 点集, 颜色)
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# 画一个等腰三角形
points = np.array([(300, 10), (150, 100), (450, 100)], np.int32) # 存放点
cv2.polylines(img, [points], True, (0, 0, 255),3)
cv2.fillPoly(img,[points],(255,0,0))
cv2.imshow('img', img)
cv2.waitKey()
putText(img,字符串, 起始点, 字体, 字号, ...)
字体可选:0 1 2 3 4 5 6 7 16
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# 绘制文本
cv2.putText(img,"Hello world!",(10,240),1,5,(0,0,255),2)
cv2.imshow('img', img)
cv2.waitKey()
通过鼠标进行图形绘制:
1.当用户按下l键,用户可以画线
2.当用户输入r键,可以画矩形
3.当用户输入c键,可以画圆
4.按下中键清空屏幕
import cv2
import numpy as np
curshape = 0
startpoint = (0, 0)
img = np.zeros((480, 640, 3), np.uint8)
cv2.namedWindow('draw', cv2.WINDOW_NORMAL)
# 定义鼠标回调函数
def mouse_callback(event, x, y, flags, userdata):
global curshape, startpoint, img # 声明全局变量
# 在起始点和终止点之间,鼠标按下点--鼠标抬起点
if event == cv2.EVENT_LBUTTONDOWN:
startpoint = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
# 左键抬起,开始画图型,先判断是什么图形
if curshape == 0:
cv2.line(img, startpoint, (x, y), (0, 0, 255))
elif curshape == 1:
cv2.rectangle(img, startpoint, (x, y), (0, 255, 255))
elif curshape == 2:
a = x - startpoint[0]
b = y - startpoint[1]
r = int((a ** 2 + b ** 2) ** 0.5)
cv2.circle(img, startpoint, r, (255, 0, 0))
else:
print('没有这个图形')
elif event == cv2.EVENT_MBUTTONDOWN: # 中键清空屏幕
img = np.zeros((480, 640, 3), np.uint8)
cv2.setMouseCallback('draw', mouse_callback, "a")
while True:
cv2.imshow('draw', img)
key = cv2.waitKey(1)
# if key>0:
# print('key=', key) # q 113 l 108 c 99 r 114
if key == 113:
break
elif key == 108:
curshape = 0 # 线
elif key == 114:
curshape = 1 # 矩形
elif key == 99:
curshape = 2 # 圆
cv2.destroyAllWindows()