编辑:我在发帖后不久就发现了,问一个问题能帮助你重新审视事物真是太神奇了。我在代码中注释了开关。在
我正在开发一个类,每隔几秒从motionjpeg流下载一帧。它工作得很好,直到我添加了一些代码,以便在加载一个jpeg时与流断开连接。现在“录像机”似乎在存储检索到的第一帧,而不是用新内容替换“图像”。每次我都可以销毁并重新创建对象来修复这个问题,但这不是一个非常优雅的解决方案。任何帮助都将不胜感激!在
以下是Recorder类的代码:
import cv2
import urllib2
import threading
from PIL import Image
import numpy as np
class MJpegCam:
def __init__(self, ip, timeout=5):
self.ip = ip
self.bytes= ''
self.image = ''
self.stream = None
self.stopcam = False
self.timeout = timeout
def start(self):
self.stream=urllib2.urlopen(self.ip, timeout=self.timeout)
def run():
while True:
if self.stopcam:
self.stopcam = False
return
try:
self.bytes+=self.stream.read(1024)
a = self.bytes.find('\xff\xd8')
b = self.bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = self.bytes[a:b+2]
self.bytes= self.bytes[b+2:]
cv2img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
try:
cv2RGB = cv2.cvtColor(cv2img,cv2.COLOR_BGR2RGB)
self.image = Image.fromarray(cv2RGB)
self.stop() #This is where the program was breaking
return #
except Exception as e:
pass
except AttributeError as e:
pass
thread = threading.Thread(target=run)
thread.start()
def stop(self):
self.stream.close()
self.stopcam = False #this needed to be switched to False
self.bytes = ''
def getImage(self):
return self.image
在实际程序中,我在不同的进程上运行多个对象,但基本思想如下:
^{pr2}$
目前没有回答
相关问题 更多 >
编程相关推荐