import cv2 as cv
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# 1. 画线,坐标点为(X,Y),与图像的坐标(480,640)相反,5为线宽,4为线型(其中还有参数4,16)
cv.line(img, (10, 20), (300, 400), (0, 0, 255), 5, 16)
# 2. 画圆
cv.circle(img, (400, 400), 50, (0, 255, 154), -1)
# 3. 画矩形
cv.rectangle(img, (150, 20), (100,100), (0, 0, 255), -1)
# 4. 画椭圆, 长方形旋转角度是按照顺时针计算的,0度是从左侧开始的
cv.ellipse(img, (320, 240), (100, 50), 10, 0, 360, (0, 0, 255), -1)
# 5. 画多边形,pts的类型必须为 int32
pts = np.array([(300, 10), (150, 100), (450, 100)], np.int32) # 创建点集
cv.polylines(img, [pts], True, (0, 0, 255))
cv.fillPoly(img, [pts], (255, 0, 0)) # 内部填充
# 6. 画文本
cv.putText(img, 'hello word', (340, 340), 0, 1, (0, 124, 255))
cv.imshow('img', img)
cv.waitKey(0)
cv.destroyWindow('img')
可以通过鼠标进行基本图形的绘制
"""
可以通过鼠标进行基本图形的绘制
1. 可以画线,当用户按下l键,即选择选择了画线。此时,滑动鼠标即可画线
2. 可以画矩形,当用户按下r键,即选择选择了画矩形。此时,滑动鼠标即可画矩形
3. 可以画圆,当用户按下c键,即选择选择了画圆。此时,滑动鼠标即可画圆
4. curShape: 0-DrawLine, 1-DrawRectangle, 2-DrawCircle
"""
import cv2 as cv
import numpy as np
curShape = 0
startPos = (0, 0)
img = np.zeros((640, 480, 3), np.uint8)
def mouse_callback(event, x, y, flags, userdata):
# print(event, x, y, flags, userdata)
global startPos, curShape
if event & cv.EVENT_LBUTTONDOWN == cv.EVENT_LBUTTONDOWN:
startPos = (x, y)
if event & cv.EVENT_LBUTTONUP == cv.EVENT_LBUTTONUP:
if curShape == 0:
cv.line(img, startPos, (x, y), (0, 0, 255))
elif curShape == 1:
cv.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)
cv.circle(img, startPos, r, (0, 0, 255))
else:
print("error no shape")
# 创建窗口
cv.namedWindow('DrawShape', cv.WINDOW_NORMAL)
# 设置鼠标回调
cv.setMouseCallback("DrawShape", mouse_callback, "123")
while True:
cv.imshow("DrawShape", img)
key = cv.waitKey(1)
if key & 0xFF == ord('q'):
break
elif key == ord('l'):
curShape = 0
elif key == ord('r'):
curShape = 1
elif key == ord('c'):
curShape = 2
cv.destroyWindow()