簡體   English   中英

在 Python 中將文本圖像覆蓋到臟背景圖像

[英]Overlay Text Image to A Dirty Background Image in Python

我有兩個圖像:一個帶有文本的圖像和一個作為臟背景的圖像。

干凈的圖像

在此處輸入圖片說明

骯臟的背景圖片

在此處輸入圖片說明

如何使用 Python 將干凈的圖像疊加到臟的背景圖像上? 請假設干凈的圖像與臟的背景圖像相比具有較小的尺寸。

有一個叫做pillow的庫(它是PIL一個分支)可以為你做這件事。 您可以稍微調整一下位置,但我認為它看起來不錯。


# Open your two images
cleantxt = Image.open('cleantext.jpg')
dirtybackground = Image.open('dirtybackground.jpg')

# Convert the image to RGBA
cleantxt = cleantxt.convert('RGBA')
# Return a sequence object of every pixel in the text
data = cleantxt.getdata()

new_data = []
# Turn every pixel that looks lighter than gray into a transparent pixel
# This turns everything except the text transparent
for item in data:
    if item[0] >= 123 and item[1] >= 123 and item[2] >= 123:
        new_data.append((255, 255, 255, 0))
    else:
        new_data.append(item)

# Replace the old pixel data of the clean text with the transparent pixel data
cleantxt.putdata(new_data)
# Resize the clean text to fit on the dirty background (which is 850 x 555 pixels)
cleantxt.thumbnail((555,555), Image.ANTIALIAS)
# Save the clean text if we want to use it for later
cleantxt.save("cleartext.png", "PNG")
# Overlay the clean text on top of the dirty background
## (0, 0) is the pixel where you place the top left pixel of the clean text
## The second cleantxt is used as a mask
## If you pass in a transparency, the alpha channel is used as a mask
dirtybackground.paste(cleantxt, (0,0), cleantxt)
# Show it! 
dirtybackground.show()
# Save it!
dirtybackground.save("dirtytext.png", "PNG")

這是輸出圖像: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM