Python OpenCV讀取視頻報錯的問題解決
最近由於項目的需要,經常需要使用opencv讀視頻操作,會經常遇到一個問題,就是視頻讀完之後會出現報錯的情況,雖然不影響代碼結果,但是對於吹毛求疵的我實在忍受不瞭。
會報錯的程序:
# -*-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讀視頻小工具,解決視頻讀完報錯的問題 :param video_path: 輸入需要讀取的視頻文件路徑 :return: 沒有返回值 """ print('視頻路徑:', 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('視頻讀完!') cap.release() cv2.destroyAllWindows() if __name__ == '__main__': path = r'D:\multi_insect_videos\multi_object00.mp4' read_video(path)
可以把視頻正常讀完,但是結果會輸出錯誤
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'
原因是視頻結束後,opencv的imshow()函數讀不瞭幀就出錯瞭。解決方法:在imshow()之前加入判斷,隻有當有幀時才讀,沒有幀時直接退出循環。
不會報錯的代碼:
# -*-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讀視頻小工具,解決視頻讀完報錯的問題 :param video_path: 輸入需要讀取的視頻文件路徑 :return: 沒有返回值 """ print('視頻路徑:', 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('視頻讀完!') cap.release() cv2.destroyAllWindows() if __name__ == '__main__': path = r'D:\multi_insect_videos\multi_object00.mp4' read_video(path)
程序輸出結果:
視頻路徑: D:\multi_insect_videos\multi_object00.mp4 視頻讀完! Process finished with exit code 0
到此這篇關於Python OpenCV讀取視頻報錯的問題解決的文章就介紹到這瞭,更多相關Python OpenCV讀取視頻報錯內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- python通過opencv調用攝像頭操作實例分析
- opencv-python圖像處理安裝與基本操作方法
- Python+OpenCV讀寫視頻的方法詳解
- 如何使用Python的OpenCV庫處理圖像和視頻
- 利用python調用攝像頭的實例分析