*编辑:我将保留下面的代码,但我猜您有编解码器问题?我安装了 xvid 编解码器(这是示例 Megamind.avi 的编码方式),并且该程序在运行 megamind 视频的一个或两个线程上运行良好。你能让超级大智者视频在单线程版本中运行吗?
Here is 关于 opencv 视频编解码器的 SO 帖子如果有帮助的话。这里是xvid下载我用过(k-lite 不适合我)。
你写的代码基本上对我有用。对于您和其他想要尝试的人,我做了以下操作:
- 应用 PEP 8 建议
- 删除了不必要的读取尝试代码(这也删除了工作视频最后一帧后误导性的线程重新读取警告)
- 使用了一个视频文件,也许每个使用 opencv 的人都有
- 删除了线程锁定,这对 opencv 来说似乎并不重要,至少在我的系统上
- 移动了一些其他的小东西
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()