Python uses opencv to extract each frame and the last frame in the video and store it as a picture

Extract each frame of the video and store the picture

Recently I have been working on a video detection problem. When I save the video frame as a picture, the picture can be saved, but there will be (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'problems and it cannot run normally. After checking the code, checking the path and other measures to no avail, I learned about the video frame. The problem was solved after using the principle. The reason was the lack of judgment conditions for the end of the frame. Before writing, add:

if frame is None;
           break
else:

Insert image description here

import cv2

# 读取视频并分帧为图片
video = cv2.VideoCapture("python/video/video2.mp4")
save_path = "python/img2"
index = 0
if video.isOpened():
    f = int(video.get(cv2.CAP_PROP_FPS))  # 读取视频帧率
    print("The video's fps is ", f)  # 显示视频帧率
    rval, frame = video.read()  # 读取视频帧
else:
    rval = False
while rval:
    print(index)
    rval,frame = video.read()
    
    cv2.imwrite(save_path + "/"+ str(index)+".jpg",frame)
        index += 1  

The reason for the error is very simple. When rval,framereading the frames of the video, the frame pictures are saved in framethe corresponding index. When writing pictures, no judgment conditions are added. After the video is divided into frames, cv2.imread函数blank information is still being written to the folder, so an error will occur. Therefore, as long as cv2.imwrite(save_path + "/"+ str(index)+".jpg",frame)a judgment condition is added to the previous line of the code, it will be judged that the framing has ended. After that, just stop writing. Add judgment conditions:

if frame is None:
            break
else:

You can correctly import the framed pictures.

The correct complete code is as follows:

import cv2

# 读取视频并分帧为图片

video = cv2.VideoCapture("python/video/video2.mp4")
save_path = "python/img2"
index = 0
if video.isOpened():
    f = int(video.get(cv2.CAP_PROP_FPS))  # 读取视频帧率
    print("The video's fps is ", f)  # 显示视频帧率
    rval, frame = video.read()  # 读取视频帧
else:
    rval = False


while rval:
    print(index)
    rval,frame = video.read()
    if frame is None:
        break
    else:
        cv2.imwrite(save_path + "/"+ str(index)+".jpg",frame)
    index += 1

Correctly output the framed picture and save it in the folder:

Insert image description here

Extract the last frame of the video and store the picture

Complete code:

import cv2

# 打开视频文件
cap = cv2.VideoCapture('python/video/video2.mp4')

# 读取视频文件中的所有帧
frames = []
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    frames.append(frame)

# 检查是否有帧可用
if len(frames) > 0:
    # 提取最后一帧并将其保存为图像
    last_frame = frames[-1]
    cv2.imwrite('python/img/last.jpg', last_frame)
    print("last picture over")
else:
    print("错误:无法提取任何帧")

# 释放视频文件句柄
cap.release()

In this code, we first read all the frames from the video file and store them in a list. We then check if any frames are available in the list. If there is, then extract the last frame and save it as an image. Otherwise, we print an error message.

Note here that in this code, we do not use a while loop to iterate through all frames, but read all frames into a list. This ensures that we get the last frame correctly and don't miss any frames.

If you still can't extract the last frame, make sure the video file exists and is readable and try testing with a different video file.

Guess you like

Origin blog.csdn.net/weixin_45277161/article/details/135130286