簡體   English   中英

圖像處理:使用PIL.paste合並圖像

[英]Image Processing: Merging images with PIL.paste

我有一個2的png圖像列表,列出_c和列表_v。 我想使用如下代碼在_c上粘貼_v:

from PIL import Image

background = [Image.open(path, 'r') for path in glob.glob(list_c_path)]
foreground = [Image.open(path, 'r') for path in glob.glob(list_v_path)]

for im in range(len(background)):
    pasted = background[im].paste(foreground[im], (0, 0), foreground[im])

這段代碼不起作用,但它會給你和想法我想要的。 我還需要在粘貼之前將圖像以灰度格式讀取。

這是一個背景圖片的示例:

在此輸入圖像描述

這是前景圖像的示例:

在此輸入圖像描述

這是理想的結果:

在此輸入圖像描述

我使用以下代碼粘貼了這些圖片:

background = Image.open('1000_c.png')
foreground = Image.open('1000_v.png')


background.paste(foreground, (0, 0), foreground)
background.save('example.png')

我怎么能實現這個?

提前致謝

嗯......您的結果圖像與前景圖像相同,因為雖然前景圖像具有alpha /透明層,但它們完全不透明並且完全隱藏了您的背景。 你需要重新考慮一下!

您可以在終端中使用ImageMagick來檢查圖像。 那么,讓我們來看看你的前景圖片:

identify -verbose fg.png

樣本輸出

Image: fg.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: DirectClass
  Geometry: 118x128+0+0
  Units: Undefined
  Colorspace: sRGB
  Type: PaletteAlpha             <--- Image does have alpha/transparency layer
  Base type: Undefined
  Endianess: Undefined
  Depth: 8-bit
  Channel depth:
    Red: 8-bit
    Green: 8-bit
    Blue: 8-bit
    Alpha: 1-bit
  Channel statistics:
    Pixels: 15104
    Red:
      min: 30  (0.117647)
      ...
      ...
    Alpha:
      min: 255  (1)              <--- ... but alpha layer is fully opaque
      max: 255 (1)
      mean: 255 (1)
      standard deviation: 0 (0)
      kurtosis: 8.192e+51
      skewness: 1e+36
      entropy: 0

所以沒有必要在背景上粘貼完全不透明的圖像,因為它會完全隱藏它。

如果我們使用ImageMagick在前景圖像中打一個透明孔:

convert fg.png -region 100x100+9+14 -alpha transparent fg.png

它現在看起來像這樣:

在此輸入圖像描述

然后,如果我們運行您的代碼:

#!/usr/local/bin/python3

from PIL import Image
background = Image.open('bg.png')
foreground = Image.open('fg.png')

background.paste(foreground, (0, 0), foreground)
background.save('result.png')

有用:

在此輸入圖像描述

所以故事的寓意是你的前景圖像需要一些透明度以允許背景顯示,或者你需要使用一些混合模式來選擇每個位置的前景和背景圖像中的一個或另一個,或者選擇某種組合 - 例如兩者的平均值,或者兩者的亮度。


如果您要平均兩個圖像,或事實上,做任何其他的混合模式,你可以考慮使用枕頭的ImageChops模塊-文檔在這里 所以,平均值看起來像這樣:

#!/usr/local/bin/python3

from PIL import Image, ImageChops
bg = Image.open('bg.png')
fg = Image.open('fg.png')

# Average the two images, i.e. add and divide by 2
result = ImageChops.add(bg, fg, scale=2.0)
result.save('result.png')

在此輸入圖像描述

暫無
暫無

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

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