python - 我可以向用户询问一个号码,然后将对应号码的图像粘贴到空白图像中吗?

标签 python python-imaging-library

我想为图像分配字母或数字,例如字母:“A”是带有A的图像,数字“0”是带有0的图像等等。 我想询问输入一个数字,例如 0,python 会将该数字链接到正确的图像(带有 0 的图像)并将该图像粘贴到空白图像。

我已经知道如何将图像与另一个图像合并(或组合),我使用 Pillow:

from PIL import Image

background_img = Image.open("blanc.png")   # the blanc image
IM0 = Image.open("0.jpg")   # The image with a 0
area2 = (0, 208)  # Where the 0 will go on the blanc image
background_img.paste(IM0, area2)   # Paste the 0
background_img.save("Final.png")   # Save the final image

我知道如何通过输入来提问

number = input("what number do you want ?")

但我不知道如何将我将在输入中写入的数字分配(或链接)到特定图像..

有人可以帮我吗?

最佳答案

从代码的外观来看,缺少的只是图像的名称。例如,如果用户输入了值“1”,则需要查找名称为“1.jpg”的图像。

如果这是正确的,您可以通过以下方式轻松完成:

file_name_fmt = "{v}.jpg"
val = input()
file_name = file_name_fmt.format(v=val)
if file_name in list_of_images:
    img = Image.open(file_name)

编辑

from PIL import Image

file_name_fmt = "{v}.jpg"

area2 = (0, 208)  # Where the 0 will go on the blanc image
background_img = Image.open("blanc.png")   # the blanc image

val = input("Enter a character for an image representation: ")
file_name = file_name_fmt.format(v=val)
if file_name in list_of_images:
    img = Image.open(file_name)
else:
    raise FileNotFoundError("The file specified doesn't exist")

background_img.paste(img, area2)   # Paste the 0
background_img.save("Final.png")   # Save the final image

关于python - 我可以向用户询问一个号码,然后将对应号码的图像粘贴到空白图像中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952629/

相关文章:

python - 导入错误 : cannot import name 'Deconvolution3D' from 'keras.layers' (/home/mona/venv/fall/lib/python3. 8/site-packages/keras/layers/__init__.py)

python - 我可以用来在本地存储页面的好应用程序?

python - 如何在Python中随机化字符串并将其转换为列表

python - 将 TIFF 图像加载为 numpy 数组

python - 为什么我的 _getexif() 返回 None?

python - PIL image.open() 不适用于我的 .png

python - 为什么我的目录是嵌套的?

python - 使用 Python/numpy 过滤 CSV 数据

python - 使用 PIL 转换具有透明度的灰度 png

用于检测损坏图像的 Python 脚本