gpt4 book ai didi

python - 在 pyglet 或 PIL/python 中从远程服务器加载图像

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:16 24 4
gpt4 key购买 nike

我想将图像从远程计算机输入到 pyglet 中(尽管我对其他平台持开放态度,在这些平台上我可以呈现图像并记录用户的鼠标点击和击键)。目前,我正在尝试在远程服务器上使用 Flask 来完成此操作,并使用请求将其拉下来

import requests

from PIL import Image
import io
import pyglet
import numpy as np

r = requests.get('http://{}:5000/test/cat2.jpeg'.format(myip),)

这不起作用:

im = pyglet.image.load(io.StringIO(r.text))

# Error:
File "/usr/local/lib/python3.4/dist-packages/pyglet/image/__init__.py", line 178, in load
file = open(filename, 'rb')

TypeError: invalid file: <_io.StringIO object at 0x7f6eb572bd38>

这也不起作用:

im = Image.open(io.BytesIO(r.text.encode()))

# Error:
Traceback (most recent call last):

File "<ipython-input-68-409ca9b8f6f6>", line 1, in <module>
im = Image.open(io.BytesIO(r.text.encode()))

File "/usr/local/lib/python3.4/dist-packages/PIL/Image.py", line 2274, in open
% (filename if filename else fp))

OSError: cannot identify image file <_io.BytesIO object at 0x7f6eb5a8b6a8>

是否有另一种方法可以在不将文件保存到磁盘上的情况下实现此目的?

最佳答案

第一个示例无法正常工作,因为我遇到了编码问题。但这将使您开始使用手动 ImageData 对象来操作图像:

import pyglet, urllib.request

# == The Web part:
img_url = 'http://hvornum.se/linux.jpg'
web_response = urllib.request.urlopen(img_url)
img_data = web_response.read()

# == Loading the image part:
window = pyglet.window.Window(fullscreen=False, width=700, height=921)
image = pyglet.sprite.Sprite(pyglet.image.ImageData(700, 921, 'RGB', img_data))

# == Stuff to render the image:
@window.event
def on_draw():
window.clear()
image.draw()
window.flip()

@window.event
def on_close():
print("I'm closing now")

pyglet.app.run()

现在,更方便、更少手动的操作方法是使用 io.BytesIO 虚拟文件句柄并将其放入 pyglet.image.load() 中code> 和参数 file=dummyFile 如下所示:

import pyglet, urllib.request
from io import BytesIO

# == The Web part:
img_url = 'http://hvornum.se/linux.jpg'
web_response = urllib.request.urlopen(img_url)
img_data = web_response.read()
dummy_file = BytesIO(img_data)

# == Loading the image part:
window = pyglet.window.Window(fullscreen=False, width=700, height=921)
image = pyglet.sprite.Sprite(pyglet.image.load('noname.jpg', file=dummy_file))

# == Stuff to render the image:
@window.event
def on_draw():
window.clear()
image.draw()
window.flip()

@window.event
def on_close():
print("I'm closing now")

pyglet.app.run()

对我来说有效,而且速度也相当快。
最后一点,尝试将图像放入 pyglet.sprite.Sprite 对象中,它们往往更快,更容易使用,并为您提供了一大堆漂亮的功能(例如轻松定位, spr.scale 和旋转函数)

关于python - 在 pyglet 或 PIL/python 中从远程服务器加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44636251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com