opencv 学习通过OpenCV图形界面基础
用的函数有
cv.line(), cv.circle(),cv.rectangle(), cv.ellipse(),cv.putText()
常用参数
- img : 想要绘制图形的图片
- color: 图形的颜色, BGR
- thickness:厚度
- lineType: 线的类型, 8-connected、anti-aliased 等
绘制线段
import numpy as np
import cv2 as cv
# 创建一个黑色的图片
img = np.zeros((512,512,3), np.uint8)
# 绘制一个蓝色5px对角线
cv.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
绘制矩形
cv.rectangle(img,(384, 0), (510, 128), (0,255,0), 3)
绘制圆
cv.circle(img,(447, 63), 63, (0, 0, 255), -1)
绘制椭圆
cv.ellipse(img, (256,256), (100, 50), 0, 0, 180, 255, -1)
绘制多边形
pts = np.array([[10, 5], [20, 30], [70, 20],[50, 10], np.int32])
pts = pts.reshape((-1, 1, 2))
cv.polylines(img, [pts], True, (0, 255, 255))
Adding Text to Images:
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img,'OpenCV', (10, 500), font, 4, (255, 255, 255), 2, cv.LINE_AA)
opencv监听鼠标事件
import numpy as np
import cv2 as cvevents = [i for i in dir(cv) if 'EVENT' in i]
print(events) # 遍历所有鼠标事件drawing = False
mode = True
ix, iy, = -1, -1# 监听鼠标按、移动、抬起动作
def draw_circle(event, x, y, flags, param):global ix, iy, drawing, modeif event == cv.EVENT_LBUTTONDOWN:drawing = Trueix, iy = x, yif event == cv.EVENT_LBUTTONDBLCLK:if drawing:if mode:cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)else:cv.circle(img, (x, y), 5, (0, 0, 255), -1)elif event == cv.EVENT_LBUTTONUP:drawing = Falseif mode:cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)else:cv.circle(img, (x, y), 5, (0, 0, 255), -1)img = np.zeros((512, 512, 3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image', draw_circle)while 1:cv.imshow('image', img)k = cv.waitKey(1) & 0xFFif k == ord('m'):#监听键盘m键mode = not modeelif k == 27:#监听escbreak
cv.destroyAllWindows()
opencv 绑定视图进度条
import numpy as np
import cv2 as cvdef nothing(x):passimg = np.zeros((300, 512, 3), np.uint8)
cv.namedWindow('image')cv.createTrackbar('R', 'image', 0, 255, nothing)
cv.createTrackbar('G', 'image', 0, 255, nothing)
cv.createTrackbar('B', 'image', 0, 255, nothing)switch = '0 : 0FF \n1 : ON'
cv.createTrackbar(switch, 'image', 0, 1, nothing)while 1:cv.imshow('image', img)k = cv.waitKey(1) & 0xFFif k == 27:breakr = cv.getTrackbarPos('R', 'image')g = cv.getTrackbarPos('G', 'image')b = cv.getTrackbarPos('B', 'image')s = cv.getTrackbarPos(switch, 'image')if s == 0:img[:] = 0else:img[:] = [b, g, r]cv.destroyAllWindows()