Recently, due to the needs of the project, I often need to use OpenCV to read video. I often encounter a problem that an error will be reported after reading the video. Although it does not affect the code results, I really can’t stand being picky.
Error reporting procedures:
# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2
def read_video(video_path: str):
"""
OpenCV read video widget, solve the video read error problem
:param video_path: input the path of the video file to be read
:return: no return value
"""
print('Video path:', video_path)
cap = cv2.VideoCapture(video_path)
while cap.isOpened():
# get a frame
ret, frame = cap.read()
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print('Read through the video!')
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
path = r'D:\multi_insect_videos\multi_object00.mp4'
read_video(path)
You can read the video normally, but the result will output an error
Traceback (most recent call last):
File "E:/PyCharmDocument/create_ST_image/multi_insect_processing/crop_video_to_images.py", line 76, in <module>
read_video(path)
File "E:/PyCharmDocument/create_ST_image/multi_insect_processing/crop_video_to_images.py", line 65, in read_video
cv2.imshow("capture", frame)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-uzca7qz1\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
The reason is that after the video is finished, the imshow() function of OpenCV can’t read the frame and makes an error. Solution: add judgment before imshow(). Read-only when there are frames. Exit the loop directly when there are no frames.
Error-free code:
# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2
def read_video(video_path: str):
"""
OpenCV read video widget, solve the video read error problem
:param video_path: input the path of the video file to be read
:return: no return value
"""
print('Video path:', video_path)
cap = cv2.VideoCapture(video_path)
while cap.isOpened():
# get a frame
ret, frame = cap.read()
if not ret:
break
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print('Read through the video!')
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
path = r'D:\multi_insect_videos\multi_object00.mp4'
read_video(path)
Program output results:
Video path: D:\multi_insect_videos\multi_object00.mp4
Read through the video!
Process finished with exit code 0