繁体   English   中英

在 Python 中将图像区域转换为白色,将 rest 转换为黑色

[英]Convert an image area to white and the rest to black in Python

我正在制作一个复制“异常”图像并将其粘贴到原始图像中的随机位置的脚本。 像这样:

原始图像

原始图像

异常图像:

异常图像

Output 图像示例:

输出图像示例

但在生成带有异常的图像的同时,我需要生成一个蒙版,其中我粘贴的异常区域为白色,图像的 rest 为黑色。 像这样(我在 Gimp 中手动完成):

Output 图像掩码示例:

输出图像掩码示例

如何在生成异常图像的同时自动执行此操作? 在我正在使用的代码下方:

from PIL import Image
import random

anomaly = Image.open("anomaly_transp.png")  # anomaly image with transparent background
image_number = 1 # number of images
w, h = anomaly.size
offset_x, offset_y = 480-w, 512-h # offsets to avoid incorrect paste area from original image

for i in range(image_number):
    original = Image.open("Crop_120.png") # original good image
    x1 = random.randint(0,offset_x)
    y1 = random.randint(0,offset_y)
    area = (x1, y1, x1+w, y1+h)
    original.paste(anomaly, area, anomaly)
    original.save("output_"+str(i)+".png") # save output image
    original.close()

您可以使用

alpha = anomaly.split()[-1]

获取透明图像的 alpha 平面。 然后,您可以将其粘贴到正确尺寸的全黑图像中以获取您的蒙版。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM