1、图像读取、展示、写入
- 使用cv.imread()函数读取图像
- 使用函数cv.imshow()在窗口中显示图像
- 使用函数cv.imwrite()保存图像
import numpy as np
import cv2 as cv
img = cv.imread('image.png',0)
cv.namedWindow("image",cv.WINDOW_NORMAL)
cv.imshow('image',img)
k = cv.waitKey(0) & 0xFF
if k == 27: # 等待ESC退出
cv.destroyAllWindows()
elif k == ord('s'): # 等待关键字,保存和退出
cv.imwrite('test2.png',img)
cv.destroyAllWindows()
其中cv.waitKey()
是一个键盘绑定函数。其参数是以毫秒为单位的时间。cv.destroyAllWindows()
只会破坏我们创建的所有窗口。cv.namedWindow()
,则可以调整窗口大小。
2、视频读取、展示、写入
-
cv.VideoCapture() 读取视频和摄像头
-
cv.VideoWriter() 保存处理过后的视频或者摄像头视频
读取处理本地视频
import numpy as np
import cv2 as cv
cap = cv.VideoCapture('res.avi')
fps =int(cap.get(cv.CAP_PROP_FPS))
size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))
# 定义编解码器并创建VideoWriter对象
fourcc = cv.VideoWriter_fourcc('X','V','I','D')
out = cv.VideoWriter('output.avi', fourcc, fps, size)
if not cap.isOpened():
print("Cannot open camera")
exit()
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Processing Completed ...")
break
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow('frame', gray)
out.write(gray)
if cv.waitKey(fps) & 0xFF == 27:
break
# 完成工作后释放所有内容
cap.release()
out.release()
cv.destroyAllWindows()
读取海康威视网络摄像头
import numpy as np
import cv2 as cv
cap = cv.VideoCapture("rtsp://admin:摄像头密码@192.168.7.102:554/Streaming/Channels/1")
fps =int(cap.get(cv.CAP_PROP_FPS))
size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))
# 定义编解码器并创建VideoWriter对象
fourcc = cv.VideoWriter_fourcc('X','V','I','D')
out = cv.VideoWriter('haikang.avi', fourcc, fps, size)
if not cap.isOpened():
print("Cannot open camera")
exit()
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Processing completed ...")
break
# 写翻转的框架
cv.imshow('frame', frame)
out.write(frame)
if cv.waitKey(fps) & 0xFF == 27:
break
# 完成工作后释放所有内容
cap.release()
out.release()
cv.destroyAllWindows()