创建一个窗口并显示图片
import cv2
cv2.namedWindow("My Window",cv2.WINDOW_NORMAL)
img = cv2.imread('./picture/1.jpg')
cv2.imshow("My Window",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
读取摄像头信息并显示
import cv2
cv2.namedWindow("Video Stream", cv2.WINDOW_NORMAL)
cap = cv2.VideoCapture(1)
if not cap.isOpened():
print("无法打开摄像头")
exit()
while True:
ret, frame = cap.read()
if not ret:
print("Failed to read video stream")
break
if frame is None:
print("No video frame captured")
continue
cv2.imshow("Video Stream", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
摄像头获取视频
import cv2
cv2.namedWindow("Video Stream", cv2.WINDOW_NORMAL)
cap = cv2.VideoCapture("/home/book/Desktop/Opencv/video/test.mp4")
if not cap.isOpened():
print("无法打开摄像头")
exit()
while True:
ret, frame = cap.read()
if not ret:
print("Failed to read video stream")
break
if frame is None:
print("No video frame captured")
continue
cv2.imshow("Video Stream", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
摄像头获取的视频流保存到文件中
import cv2
cap = cv2.VideoCapture("/home/book/Desktop/Opencv/video/test.mp4")
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
fps = 20.0
out = cv2.VideoWriter('video/output.mp4', fourcc, fps, (1920, 1032))
while True:
ret, frame = cap.read()
if ret:
out.write(frame)
cv2.imshow("Video Stream", frame)
if cv2.waitKey(1) == ord('q'):
break
else:
print("无法获取摄像头的视频流")
break
cap.release()
out.release()
cv2.destroyAllWindows()
鼠标点击事件
import cv2
import numpy as np
def on_mouse_click(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print("鼠标左键点击:({}, {})".format(x, y))
elif event == cv2.EVENT_RBUTTONDOWN:
print("鼠标右键点击:({}, {})".format(x, y))
img = np.zeros((500, 500, 3), np.uint8)
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", on_mouse_click)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
实战滑动条调色板
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
while True:
r = cv2.getTrackbarPos('R', 'image')
g = cv2.getTrackbarPos('G', 'image')
b = cv2.getTrackbarPos('B', 'image')
img[:] = [b, g, r]
cv2.imshow('image', img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()