【问题标题】:how to put transparent image to another image using PIL without .paste() class如何使用没有 .paste() 类的 PIL 将透明图像放到另一个图像上
【发布时间】:2020-12-04 23:44:10
【问题描述】:

我是 PIL 的新手,所以对我来说很难理解我是如何做到的,有人可以帮助我。在代码中,我只拍了两张照片并调整了一张透明的大小。现在我不知道在没有 .paste() 类的情况下如何粘贴它

def get_web_image (url):
    img_data = requests.get(url).content
    with open('picture1(bg)_1200x800.png', 'wb') as handler:
        handler.write(img_data)
    return img_data


def paste_image (source, destination, x, y, omit_color="None"):
    im = Image.open(source)
    pixels_newpaste = []
    newsize = (200, 200)
    im = im.resize(newsize)
    im.save('picture2(done).png')
    im.show()



paste_image ('picture2(transparent)_840x841.png', main_image, 1, 1)
main_pic()
#my_img_object = get_web_image ('https://avante.biz/wp-content/uploads/Baseball-Wallpapers/Baseball-Wallpapers-015.jpg')

我尝试使用 .getpixel() 来制作它,但据我所知,它只需要绘制一种颜色。所以请帮我做这个功能

【问题讨论】:

  • 请问使用paste()有什么问题?请问结果应该是怎样的?
  • @Mark Setchell 这是一个测验,所以在要求中说你不能使用 paste() 将第二张图片放在第一张图片的某些部分,例如在中间。我现在正在学习这个框架,所以你可以给我一些提示,或者解释一下算法,我可以自己做的代码
  • 呃!您可以遍历所有像素,并在每个位置从背景和前景图像中获取像素。如果前景图像不透明,则使用前景图像中的值覆盖背景图像中的像素。如果在它运行时泡茶????或者使用 Numpy...stackoverflow.com/a/65035996/2836621
  • @Mark Setchell 非常感谢,我会尽快写下结果
  • 其实再想一想,如果在背景图像之上构建输出图像,则不需要获取背景像素。只需遍历像素以获得每个位置的前景像素,如果前景不透明,则用前景像素的 RGB 值覆盖背景像素。否则允许现有背景像素保持不变。

标签: python python-imaging-library


【解决方案1】:

以下是使用这两张经过适当调整大小且部分透明的图片的简化版本:

#!/usr/bin/env python3

from PIL import Image

# Open pitcher and pitch images
bg = Image.open('pitch.jpg')
fg = Image.open('pitcher.png').convert('RGBA')
w, h = fg.width, fg.height

# Iterate over rows and columns
for y in range(h):
   for x in range(w):
      # Get components of foreground pixel
      r, g, b, a = fg.getpixel((x,y))
      # If foreground is opaque, overwrite background with foreground
      if a>128:
          bg.putpixel((x,y), (r,g,b))

# Save result    
bg.save('result.png')

【讨论】:

  • 奇怪,你的代码给了我错误:File "/Users/apple/Desktop/projects/BariySatarov/test2.py", line 11, in <module> r, g, b, a = fg.getpixel((x,y)) ValueError: not enough values to unpack (expected 4, got 3)
  • 那是因为您使用了 JPEG(不支持透明度/alpha)作为前景,所以它只有 3 个通道(即 RGB)而不是 4 个通道(即 RGBA)。这就是为什么我制作并分享了一个带有 alpha/transparency 的 PNG。
  • 尝试使用您的图像 pitch.jpg,第二个 pitcher.png File "/Users/apple/Desktop/projects/BariySatarov/test2.py", line 15, in <module> if a > 128: TypeError: '>' not supported between instances of 'tuple' and 'int'
  • 等一下。 StackOverflow 似乎出于某种原因将我的 PNG 转换为 JPEG...
  • 我不知道发生了什么,但 StackOverflow 不断将我的 PNG 转换为我从未见过的 JPEG。我更改了一行代码以确保我现在上传的调色板版本变为 RGBA。
猜你喜欢
  • 2014-08-24
  • 2016-03-12
  • 2023-03-17
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多