Python屏幕捕获错误(Python screen capture error)

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

断言isinstance(数据,字节)'应用程序必须写入字节'AssertionError:应用程序必须写入字节

我应该做些什么改变才能发挥作用?

这就是我迄今为止所做的 -

<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]

完整的错误: 链接


I am trying to modify the code given here for screen streaming. In the above tutorial it was for reading images from disk whereas I am trying to take screenshots. I receive this error.

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

What changes should I make for it to work?

This is what I've done so far -

<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]

Full error : Link


原文:https://stackoverflow.com/questions/40060653
2023-06-09 14:06

满意答案

尝试使用UnmanagedMemoryStream

此类支持使用现有的基于流的模型访问非托管内存,并且不要求将非托管内存中的内容复制到堆中。

这意味着您将寻找/读取/重置流,但这避免了编组。 它仍然不是你希望在.NET属性中包含这些访问的意义上的。

另一种选择:也许你可以在获得非托管指针后使用System.Buffer 。 你可能需要做一些聪明的演员。


Try using the UnmanagedMemoryStream:

This class supports access to unmanaged memory using the existing stream-based model and does not require that the contents in the unmanaged memory be copied to the heap.

This means you will be seeking/reading/resetting the stream, but this avoids the marshalling. It's still not live in the sense you'd want to probably want to wrap these accesses in .NET properties.

Another alternative: maybe you could use System.Buffer, after getting the unmanaged pointer. You may need to do some clever casting.

相关问答

更多

Nios 2“Hello World”?(Nios 2 “Hello World”?)

该程序正在电路板上运行。 从节目评论... 这个例子将'Hello from Nios II'打印到STDOUT流。 这种情况下的STDOUT流是软件终端。 因此,Nios II板正在运行hello world程序并将输出发送到计算机。 要使用电路板上的屏幕,您必须使用SOPC构建器将LCD显示器包含在配置中,然后直接写入LCD屏幕。 The program IS running on the board. From the program comments... This example pri...

在C#中释放非托管代码(Freeing up of unmanaged code in C#)

您可以使用Marshal.Copy方法(IntPtr,Double [],Int32,Int32)将double值数组从非托管ptr复制到托管ffData数组。 IntPtr ptr = ComputeFFTW(packetSig, packetSig.Length, (int)samplFrequency,(int)fftPoints); Marshal.Copy(ptr, fftData, 0, fftData.Length); 如果ComputeFFTW返回指向动态分配内存的指针,则需...

将结构数组编组到C#中的指针(Marshalling an array of structs to a pointer in C#)

尝试这个: [DllImport("data.dll")] internal static unsafe extern int MyExternalFunction(DATA[] pData); 并完全省略C#指针。 编辑:我没有测试,但它是有道理的指针的方式将无法正常工作,因为托管数组的内存布局是不相同的非托管的。 编组人员必须有机会获取数组并将其转换为本地格式,然后再转回。 我不确定在这种情况下是否需要ref修饰符,但它可能是一个选项。 try this: [DllImport("data....

编组结构,嵌入指针从C#到非托管驱动程序(Marshalling struct with embedded pointer from C# to unmanaged driver)

编组具有内联指针的结构时,需要将该值定义为IntPtr而不是数组 [StructLayout(LayoutKind.Sequential)] public struct IoctlWriteRegsIn { public uint Address; public IntPtr Buffer; public uint Size; } When marshaling a struct which has an inline pointer, you need to defin...

C#结构中的事件?(Are Events in C# structs?)

像EventHandler这样的委托类型是不可变的类型。 当您使用赋值( = )或复合赋值( += )时,会创建一个新实例。 该字典保留旧的实例。 委托类型是引用类型,但重要的是它们的不变性。 当你有一个event ,使用+=语法甚至不是一个赋值。 它是对add访问器或事件的调用。 它将以线程安全的方式重新分配后台字段(新实例)。 请记住,你可以自己编写你的事件访问器。 例如: public static event EventHandler TestEvent { add { l...

来自C#的Hello World世界到Twitter(Hello World to Twitter from C#)

绝对使用Linq2Twitter - http://linqtotwitter.codeplex.com/ 它的UpdateStatus方法有11个重载 - 整个实现非常好。 所以你的例子是: var tweet = twitterCtx.UpdateStatus("Hello world"); Definitely use Linq2Twitter - http://linqtotwitter.codeplex.com/ It's UpdateStatus method has 11 over...

在非托管C ++代码中使用C#属性(Use C# properties in unmanaged C++ code)

我在我的工作中处理类似的问题,我的主要任务是编写托管接口到某些高性能,低延迟dll,这涉及到简单的情况,我必须使用简单的c ++ / cli包含原生类,其中包含一个指向本地类或更复杂的问题,其中本机代码是服务器端发布者,托管代码必须使用委托来订阅它,即它们必须转换为本地回调。 据我所知,底层.NET是一个复杂的COM服务器。 可以使用将ComVisible属性设置为true编写.net程序集,然后将其作为传统的COM组件,然后可以将其从本地C ++代码用作COM组件。 可以使用DllImport属...

非托管C#与C ++ [关闭](Unmanaged C# versus C++ [closed])

C#中的不安全代码不适用于开发单独的应用程序。 您可以将不安全的代码用于某种时间关键型操作,但通常它不是最有效和最方便的方法。 恕我直言,它主要是为了给C#提供与非托管动态链接库和非托管代码集成的机会,因此从我的观点来看,主要原因是INTEGRATION。 我可以看到托管和非托管代码集成的3种常用方法: C#和P / Invoke中的 不安全代码 。 在已编译的非托管DLL上构建C#包装器。 托管C ++ 。 通过现有的C / C ++代码构建托管程序集。 COM互操作。 从.NET客户端调用Ru...

来自非管理世界的C#结构能否“实时” - 更新?(Can C# structs coming from the unmanaged world be “live”-updating?)

尝试使用UnmanagedMemoryStream : 此类支持使用现有的基于流的模型访问非托管内存,并且不要求将非托管内存中的内容复制到堆中。 这意味着您将寻找/读取/重置流,但这避免了编组。 它仍然不是你希望在.NET属性中包含这些访问的意义上的。 另一种选择:也许你可以在获得非托管指针后使用System.Buffer 。 你可能需要做一些聪明的演员。 Try using the UnmanagedMemoryStream: This class supports access to unma...

Spring MVC Samples中的“Hello World”来自哪里?(Where is the “Hello World” coming from in Spring MVC Samples)

看起来神奇的事情发生在JSP代码底部的jQuery中。 对于Hello World教程来说,这有点复杂,但除此之外。 单击链接,使用AJAX从服务器请求数据: $("a.textLink").click(function(){ var link = $(this); $.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text...

相关文章

更多

eclipse里报:An internal error occurred during:

eclipse里报:An internal error occurred during: Buildi ...

The connection to adb is down, and a severe error has occured.

启动android模拟器时.有时会报The connection to adb is down, an ...

solr error logs org.apache.solr.common.SolrException: ERROR: [doc=17] unknown field alias

在solr中 添加新的索引词语时,报如标题所示错误,指定是插入的字段没有在solr索引字段里 可以修改 ...

python2和python3的区别

python2和python3的区别,1.性能 Py3.0运行 pystone benchmark的速 ...

Solr安装异常:SolrException: Error loading class 'solr.VelocityResponseWriter'

解决方法安装Solr过程出现错误,报异常 org.apache.solr.common.SolrExc ...

error C2668: 'M' : ambiguous call to overloaded function

以下是代码: #include&lt;iostream&gt;using namespace std ...

Python 写的Hadoop小程序

该程序是在python2.3上完成的,python版本间有差异。 Mapper: import sys ...

spark--scala-douban模仿做了个python的版本

初识spark-基本概念和例子 | _yiihsia[互联网后端技术] 初 ...

win8安装VirtualBox-4.2.18提示Installation failed!error:系统找不到指定的路径

在win8上安装VirtualBox-4.2.4-81684-Win.exe,提示Installati ...

Hadoop 异常记录 ERROR: org.apache.hadoop.hbase.MasterNotRunningException: Retried 7 times

当我把Hadoop、hbase安装配置(具体参考这里)好了之后,启动hbase的shell交互模式,输 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本