python - 在 Python 中将徽标添加到猫图像
问题描述
对于标题,这是代码(由 Automate the Boring Stuff 提供),我对其进行了一些调整。
import os
from PIL import Image
SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size
# Loop over all files in the working directory.
for filename in os.listdir('.'):
if not (filename.endswith('.png') or filename.endswith('.jpg')) \
or filename == LOGO_FILENAME:
continue # skip non-image files and the logo file itself
im = Image.open(filename)
width, height = im.size
# Add logo.
print('Adding logo to %s...' % (filename))
im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)
# Save changes.
im.save('Cat with Logo.png')
由于某种原因,未能在最后添加徽标。save
命令 有问题吗?
解决方案
我意识到resizeAndAddLogo.py
调整徽标粘贴到的文件的大小,而不是与文件成比例的徽标大小。我们不希望那样。因此,我更改了脚本以将徽标大小更改为图像文件的 1/5。
...
# Resize the logo.
print(f'Resizing logo to fit {filename}...')
sLogo = logoIm.resize((int(width / 5), int(height / 5)))
sLogoWidth, sLogoHeight = sLogo.size
# Add the logo.
print(f'Adding logo to {filename}...')
im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo)
...
此时,我不需要SQUARE_FIT_SIZE = 300
,所以我将其删除并缩短了代码。这是我的完整脚本。
import os
from PIL import Image
LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir():
if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME:
continue
im = Image.open(filename)
width, height = im.size
# Resize the logo.
print(f'Resizing logo to fit {filename}...')
sLogo = logoIm.resize((int(width / 5), int(height / 5)))
sLogoWidth, sLogoHeight = sLogo.size
# Add the logo.
print(f'Adding logo to {filename}...')
im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo)
# Save changes.
im.save(os.path.join('withLogo', filename))
请注意,应分配调整大小的徽标以在循环中使用。
这是结果图像之一。
推荐阅读
- python - 使用热门词/关键字开始录制语音识别
- python - 如何分析应用程序的cpu利用率
- node.js - Microsoft Graph API beta 不适用于节点
- node.js - 仅当密钥不存在时如何插入到 DynamoDb
- sql - SQL Presto 查询 - 检索所有可能的行组合?
- python - Azure loganalytics python SDK 总是抛出 MissingApiVersionParameter 异常
- c - 创建 Netfilter 内核模块时出现编译错误
- javascript - 解决路径问题,js文件未连接
- python - 有效地将函数应用于 Pandas 系列中的每个可能配对
- javascript - tf.loadModel 不是函数