簡體   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