python - 生成器无法与 Python 中的字节连接

标签 python flask generator

我有一个类,它使用 get_frame 方法从相机获取帧。在网络环境中,我需要在每个帧周围添加一些数据,然后再将其流式传输到浏览器。当我尝试向帧添加额外信息(一些字节)时,我收到TypeError:无法将字节连接到生成器。如何连接这些数据?

def gen():
    camera = VideoCamera()
    while True:
        frame = camera.get_frame() 
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

class VideoCamera():
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def get_frame(self):        
        while(True):
            ret, frame = self.video.read()
            #that face is the list, which has all the detected faces in the frame, using dlib library
            face = detector(gray, 0)
            for (J, rect) in enumerate(face):
                 ret, jpeg = cv2.imencode('.jpg', frame)
                 yield jpeg.tobytes()

最佳答案

如前所述,调用 get_frame 返回一个生成器,而不是单个帧。您需要迭代该生成器以获取各个帧,然后您可以将其与其他数据一起生成。

def gen():
    camera = VideoCamera()
    for frame in camera.get_frame():
        yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n'
        yield frame
        yield b'\r\n\r\n'

关于python - 生成器无法与 Python 中的字节连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49782828/

相关文章:

python - 如何使用属性装饰器设置属性?

python scrapy shell 异常 : address "' http:"not found: [Errno 11001] getaddrinfo failed

python - url_for 使用 & 创建一个 url 查询字符串

python - 客户端,Google Flex App Engine和Cloud SQL之间的高延迟

协程中的 Python 循环

python - 如何在 Python 中显式检测生成器端?

c - C 中的伪随机数生成器 - 使用时间函数播种

python - 屏蔽营业时间以外的时间序列

python - TensorFlow 中 LSTM 的权重和偏差维度

python - Flask-用户注册 : add one more mail id