您好,登錄后才能下訂單哦!
這篇文章的內(nèi)容主要圍繞OpenCV讀取視頻報錯的問題怎么解決進(jìn)行講述,文章內(nèi)容清晰易懂,條理清晰,非常適合新手學(xué)習(xí),值得大家去閱讀。感興趣的朋友可以跟隨小編一起閱讀吧。希望大家通過這篇文章有所收獲!
最近由于項(xiàng)目的需要,經(jīng)常需要使用opencv讀視頻操作,會經(jīng)常遇到一個問題,就是視頻讀完之后會出現(xiàn)報錯的情況,雖然不影響代碼結(jié)果,但是對于吹毛求疵的我實(shí)在忍受不了。
會報錯的程序:
# -*-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)
可以把視頻正常讀完,但是結(jié)果會輸出錯誤
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'
原因是視頻結(jié)束后,opencv的imshow()函數(shù)讀不了幀就出錯了。解決方法:在imshow()之前加入判斷,只有當(dāng)有幀時才讀,沒有幀時直接退出循環(huán)。
不會報錯的代碼:
# -*-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)
程序輸出結(jié)果:
視頻路徑: D:\multi_insect_videos\multi_object00.mp4 視頻讀完! Process finished with exit code 0
感謝你的閱讀,相信你對“OpenCV讀取視頻報錯的問題怎么解決”這一問題有一定的了解,快去動手實(shí)踐吧,如果想了解更多相關(guān)知識點(diǎn),可以關(guān)注億速云網(wǎng)站!小編會繼續(xù)為大家?guī)砀玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。