[CV2] [Dataset] Code for converting video to pictures

Function : Making a data set requires a lot of photos, you can record a video, and then save the photos from the video, and these photos can be used to make a data set

Idea: The code uses the OpenCV library to read the video and display and save the image . First read a video file and display images on each video frame. At the same time, allow the user to press the space bar to save some frames in the video as pictures. The program will exit and close all windows after n pictures are saved or the user presses the esc key.

code show as below:

# 导入OpenCV库
import cv2

# 打开视频文件
camera = cv2.VideoCapture("E:\\004_Picture\\VID_20230508_194531.mp4")  # ^_^需要改目录

# 读取第一帧图像
ret, img = camera.read()

# 初始化计数器
i = 0

# 获取视频的帧率
fps = camera.get(cv2.CAP_PROP_FPS)

# 循环读取视频帧
while True:
    # 读取下一帧图像
    ret, img = camera.read()

    # 显示当前帧
    cv2.imshow("img", img)

    # 等待一定的时间
    key = cv2.waitKey(int(600 / fps))

    # 如果用户按下空格键
    if key == ord(' '):
        # 计数器加1
        i += 1

        # 将当前帧保存为图片
        cv2.imwrite('jpg/' + 'line_' + str(i) + '.jpg', img)  # ^_^jpg是所在项目下创建的文件夹

    # 如果计数器达到10,或者用户按下esc键, 数字的大小可以改成自己需要截取的张数
    if i == 10 or key == 27:
        print('esc break...')
        # 释放摄像头
        camera.release()
        # 关闭所有窗口
        cv2.destroyAllWindows()
        # 退出循环
        break

# 释放摄像头
camera.release()

# 关闭所有窗口
cv2.destroyAllWindows()

Guess you like

Origin blog.csdn.net/weixin_49601301/article/details/130568063