您好,登錄后才能下訂單哦!
這篇文章的內容主要圍繞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
感謝你的閱讀,相信你對“OpenCV讀取視頻報錯的問題怎么解決”這一問題有一定的了解,快去動手實踐吧,如果想了解更多相關知識點,可以關注億速云網站!小編會繼續為大家帶來更好的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。