2016-10-15 124 views
0

我正在尝试修改给定屏幕流here的代码。在上面的教程中,它用于从磁盘读取图像,而我试图截取屏幕截图。我收到此错误。Python屏幕捕获错误

assert isinstance(data, bytes), 'applications must write bytes' AssertionError: applications must write bytes

我应该对它做些什么改变?

这是我到目前为止已经完成 -

<br>index.html<br> 
<html> 
    <head> 
    <title>Video Streaming Demonstration</title> 
    </head> 
    <body> 
    <h1>Video Streaming Demonstration</h1> 
    <img src="{{ url_for('video_feed') }}"> 
    </body> 
</html> 


app.py

#!/usr/bin/env python 
from flask import Flask, render_template, Response 
import time 
# emulated camera 
from camera import Camera 

# Raspberry Pi camera module (requires picamera package) 
# from camera_pi import Camera 

app = Flask(__name__) 


@app.route('/') 
def index(): 
    """Video streaming home page.""" 
    return render_template('index.html') 


def gen(camera): 
    """Video streaming generator function.""" 
    while True: 
     time.sleep(0.1) 
     frame = camera.get_frame() 
     yield (frame) 


@app.route('/video_feed') 
def video_feed(): 
    """Video streaming route. Put this in the src attribute of an img tag.""" 
    return Response(gen(Camera()), 
        mimetype='multipart/x-mixed-replace; boundary=frame') 


if __name__ == '__main__': 
    app.run(host='0.0.0.0', debug=True, threaded=True) 


camera.py

from time import time 

from PIL import Image 
from PIL import ImageGrab 
import sys 

if sys.platform == "win32": 
    grabber = Image.core.grabscreen 

class Camera(object): 

    def __init__(self): 
     #self.frames = [open('shot0' + str(f) + '.png', 'rb').read() for f in range(1,61)] 
     self.frames = [ImageGrab.grab() for f in range(1,61)] 

    def get_frame(self): 
     return self.frames[int(time()) % 3] 

完整的错误: Link

+0

您可以发布完整的堆栈跟踪的错误? – xli

+0

@xli添加堆栈跟踪 – user6945506

回答

0

响应负载必须是一个字节序列。在该示例中,返回的图像是JPEG,如bytes对象。

但是,由ImageGrab.grab()返回的图像是一些PIL图像类而不是字节。所以,尽量保存图像的JPEG为bytes

import io 

采取截图仅适用于创每次迭代:

class Camera(object): 
    def get_frame(self): 
     frame = ImageGrab.grab() 
     img_bytes = io.BytesIO() 
     frame.save(img_bytes, format='JPEG') 
     return img_bytes.getvalue() 

创功能:

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

它仍然不显示任何输出,但没有错误。 – user6945506

+0

您应该使用原始示例中的yield语句,该语句的内容类型为:yield(b' - frame \ r \ n' b'Content-Type:image/jpeg \ r \ n \ r \ n' + frame + b'\ r \ n')' – xli

+0

查看更新后的答案。 – xli