[英]Make Python open a picture from URL
我做了这个项目,你训练机器学习来回应你对它说的话。
这是我得到的 Python 代码:
from PIL import Image
import requests
def classify(text):
key = "#my credits activation key"
url = "https://machinelearningforkids.co.uk/api/scratch/"+ key + "/classify"
response = requests.get(url, params={ "data" : text })
if response.ok:
responseData = response.json()
topMatch = responseData[0]
return topMatch
else:
response.raise_for_status()
input = input("What do you want to tell me? > ")
recognized = classify(input)
label = recognized["class_name"]
if label == "kind_things":
print ("Mmm, thanks")
img = Image.open("happy.png")
img.show()
else:
print ("Well screw you too!")
img = Image.open("sad.png")
img.show()
这样它就可以工作,所以我假设我已经正确安装了所有东西(pip、Pillow 等)。
现在,我想更进一步,用它制作一个可执行文件(使用 PyInstaller,我做了),然后把它作为一个笑话发送给我的朋友。 这个想法是,如果他们写得很好,他们会得到很好的回应,我微笑的照片是从 URL 打开的。 如果他们说刻薄的话,那么他们会得到刻薄的回应,我的愤怒画面就会打开。
这是我尝试过的:
if label == "kind_things":
print ("Mmm, thanks")
url = "#url of the picture"
response = requests.get(url)
img = Image.open(response.raw)
img.show()
else:
print ("Well screw you too!")
url = "#url of the other picture"
response = requests.get(url)
img = Image.open(response.raw)
img.show()
它不起作用。 我在 python 中遇到的错误:
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0000023B5072C180>
我读到了urllib
或bytesIO
或StringIO
类的东西,但不确定在这种情况下如何使用它们中的任何一个。
如果您需要远程访问 web 上的图像,这应该可以:
from io import BytesIO
import requests
from PIL import Image
response = requests.get('http://the/url')
img = Image.open(BytesIO(response.content))
img.show()
也就是说, 将图像与可执行文件一起包含可能更有意义。 您可以使用--onefile
选项将它们打包到 .exe 文件中,而不是将它们放在一个文件夹中,以稍微掩盖工作原理。 (我想如果你的朋友在你给他们程序的时候看到图像,你会失去一些有趣的惊喜效果。)
一种方法是下载图像。 然后用 PIL 展示它。
要下载图像,您可以使用urllib.request.urlretrieve(url, filename)
。 稍后您应该通过os.remove
将其删除。
把它们放在一起:
from os import remove
from urllib.request import urlretrieve
from PIL import Image
tmp_path = "path to where you want to save it"
urlretrieve("path to your image", tmp_path)
Image.open(tmp_path).show()
remove(tmp_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.