OpenCV处理视频文件

发布时间:2024年01月24日

OpenCV处理视频

开启摄像头:

import cv2
# 打开笔记本内置摄像头
capture = cv2.VideoCapture(0)
while (capture.isOpened()):
    # 从摄像头中实时读取视频
    retval, image = capture.read()
    # 在窗口中显示读取到的视频
    cv2.imshow("Video", image)
    # 窗口的图像刷新时间为1毫秒
    key = cv2.waitKey(1)
    # 按下空格就终止
    if key == 32:
        break
capture.release()
cv2.destroyAllWindows()

彩色视频转换为灰度视频:

import cv2
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while (capture.isOpened()):
    retval, image = capture.read()
    # 把彩色视频转换为灰度视频
    image_Gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    if retval == True: 
        cv2.imshow("Video", image)
        cv2.imshow("Video_Gray", image_Gray) 
    key = cv2.waitKey(1)
    if key == 32: 
        break
capture.release() 
cv2.destroyAllWindows()

保存视频图像:

import cv2
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while (cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow("Video", frame) 
    k = cv2.waitKey(1)
    if k == 32:
        cap.release() 
        cv2.destroyWindow("Video")
        cv2.imwrite("路径", frame) # 保存按下空格键时摄像头视频中的图像
        cv2.waitKey() # 刷新图像
        break
cv2.destroyAllWindows() # 销毁显示图像的窗口

播放视频文件:

import cv2
video = cv2.VideoCapture("视频路径")
while (video.isOpened()):
    retval, image = video.read()
    # 设置“Video”窗口的宽为800,高为600
    cv2.namedWindow("Video", 0)
    cv2.resizeWindow("Video", 800, 600)
    if retval == True:
        # 在窗口中显示读取到的视频文件
        cv2.imshow("Video", image)
    else:
        break
    key = cv2.waitKey(1)
    # 按下ESC退出
    if key == 27: 
        break
video.release()
cv2.destroyAllWindows()

视频文件转换为灰度的:

import cv2
video = cv2.VideoCapture("视频路径")
while (video.isOpened()): 
    retval, img_Color = video.read()
    cv2.namedWindow("Gray", 0)
    cv2.resizeWindow("Gray", 800, 600)
    if retval == True: 
        img_Gray = cv2.cvtColor(img_Color, cv2.COLOR_BGR2GRAY)
        cv2.imshow("Gray", img_Gray)
    else: 
        break
    key = cv2.waitKey(1) 
    if key == 27: 
        break
video.release()
cv2.destroyAllWindows()
文章来源:https://blog.csdn.net/weixin_44144773/article/details/135813721
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。