*编辑:我将在下面保留代码,但是我想您有编解码器问题吗?我安装了xvid编解码器(这是示例Megamind.avi的编码方式),并且该程序可以在运行megamind视频的一个或两个线程中正常运行。您能使megamind视频在单线程版本中运行吗?
如果有帮助,这是有关opencv视频编解码器的文章。这是我使用的xvid下载(k-lite不适用于我)。
您编写的代码基本上对我有用。对于您和其他想要尝试的人,我做了以下工作:
VideoCapture.read可能还会出现其他错误,这些错误使值得使用read_attempt方法,但我只能找到文档中提到的两个错误。对于那些,它只返回false,代码已经对其进行了测试。
import os
import threading
import cv2
my_opencv_path = "C:/opencv2.4.3"
video_path_1 = os.path.join(my_opencv_path, "samples", "cpp", "tutorial_code",
"HighGUI", "video-input-psnr-ssim", "video",
"Megamind.avi")
video_path_2 = os.path.join(my_opencv_path, "samples", "c", "tree.avi")
assert os.path.isfile(video_path_1)
assert os.path.isfile(video_path_2)
class MyThread (threading.Thread):
maxRetries = 20
def __init__(self, thread_id, name, video_url, thread_lock):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.video_url = video_url
self.thread_lock = thread_lock
def run(self):
print "Starting " + self.name
window_name = self.name
cv2.namedWindow(window_name)
video = cv2.VideoCapture(self.video_url)
while True:
# self.thread_lock.acquire() # These didn't seem necessary
got_a_frame, image = video.read()
# self.thread_lock.release()
if not got_a_frame: # error on video source or last frame finished
break
cv2.imshow(window_name, image)
key = cv2.waitKey(50)
if key == 27:
break
cv2.destroyWindow(window_name)
print self.name + " Exiting"
def main():
thread_lock = threading.Lock()
thread1 = MyThread(1, "Thread 1", video_path_1, thread_lock)
thread2 = MyThread(2, "Thread 2", video_path_2, thread_lock)
thread1.start()
thread2.start()
print "Exiting Main Thread"
if __name__ == '__main__':
main()