python-3.x - 在 Python 中使用 PIL 或 OpenCV 将图像粘贴到具有改变不透明度的两个给定坐标处的另一个图像
问题描述
我有两个带有给定点的图像,每个图像一个点,需要对齐,以便结果图像是两个图像的总和,而图像 2 以 40% 的不透明度粘贴在图像 1 上。我已经考虑了这个问题,但我们的案例并不完全匹配,因为图像坐标是由用户提供的,并且图像的尺寸范围很广。
为此,我尝试img.paste()
了 PIL 的功能并替换 cv2 中 numpy 图像数组中的值,两者都给出了远非预期的结果。
解决方案
我用ImageMagick制作了两个输入图像,如下所示:
magick -size 300x400 xc:"rgb(1,204,255)" -fill red -draw "point 280,250" 1.png
magick -size 250x80 xc:"rgb(150,203,0)" -fill red -draw "point 12,25" 2.png
然后运行以下代码:
#!/usr/bin/env python3
"""
Paste one image on top of another such that given points in each are coincident.
"""
from PIL import Image
# Open images and ensure RGB
im1 = Image.open('1.png').convert('RGB')
im2 = Image.open('2.png').convert('RGB')
# x,y coordinates of point in each image
p1x, p1y = 280, 250
p2x, p2y = 12, 25
# Work out how many pixels of space we need left, right, above, below common point in new image
pL = max(p1x, p2x)
pR = max(im1.width-p1x, im2.width-p2x)
pT = max(p1y, p2y)
pB = max(im1.height-p1y, im2.height-p2y)
# Create background in solid white
bg = Image.new('RGB', (pL+pR, pT+pB),'white')
bg.save('DEBUG-bg.png')
# Paste im1 onto background
bg.paste(im1, (pL-p1x, pT-p1y))
bg.save('DEBUG-bg+im1.png')
# Make 40% opacity mask for im2
alpha = Image.new('L', (im2.width,im2.height), int(40*255/100))
alpha.save('DEBUG-alpha.png')
# Paste im2 over background with alpha
bg.paste(im2, (pL-p2x, pT-p2y), alpha)
bg.save('result.png')
结果是这样的:
保存图片名称开头"DEBUG-xxx.png"
的行只是为了方便调试,可以去掉。我可以轻松地查看它们以了解代码发生了什么,并且可以通过删除"DEBUG*png"
.
推荐阅读
- jquery - 在 IIS(远程系统)上部署应用程序后转换为日期不起作用
- sql-server - SQL Server 2014 - 合并 - 语法错误
- python - 将不同的日期格式字符串转换为日期时间格式
- browser - 什么是“现代浏览器”?
- java - 无法检查索引状态:index=master_game_Product_flip
- antlr - ANTLR4 中部分跳过字符
- react-native - 找不到 support-v4.aar (com.android.support:support-v4:25.2.0)
- javascript - 将组件整体的onClick和组件内的按钮分开
- mysql - 如何更改 MYSQL 数据库列归档排序规则
- mysql - MySQL 空行仅在表为空时显示