【问题标题】:How do I change the alpha channel of a section of pixels on my image?如何更改图像上部分像素的 Alpha 通道?
【发布时间】:2019-07-05 02:19:12
【问题描述】:

我正在尝试使用 matplotlibos.pathnumpy 裁剪图像(从学校图片中裁剪背景)。

我的想法是将图像分割成除我需要的部分之外的正方形,然后操纵 Alpha 通道以使这些区域透明,这样我剩下的就是我需要的部分。我开始编写代码,但遇到了相同的错误消息。

我尝试制作某种圆形蒙版来裁剪脸部,但蒙版的概念对我来说仍然很陌生,所以我认为这会更容易。

fig, ax = plt.subplots(1, 1)
# Show the image data in a subplot
ax.imshow(img, interpolation='none')
# Show the figure on the screen

row = len(img)
column = len(img[0])
for row in range(0, 231) :
    for column in range(0, 330) :
        img[row][column] = [0, 0, 0, 0]


fig.show()

 

Results: 26 for row in range(0, 231) :
         27     for column in range(0, 330) :
    ---> 28         img[row][column] = [0, 0, 0]
         29 
         30 
IndexError: index 288 is out of bounds for axis 0 with size 288

【问题讨论】:

  • 您确定要在 matplotlib 中执行此操作吗?我认为会有更好的工具可用于这项工作。例如,看看this

标签: python image matplotlib rgb alpha


【解决方案1】:

您会发现使用 PIL/Pillow 会更轻松。从这张菲奥娜的照片开始……

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Load image and get width and height
im = Image.open('fiona.png').convert('RGB')
w, h = im.size[0:2]

# Make empty black alpha mask same size, but with just one channel, not RGB
alpha = Image.new('L',(w,h))

# Draw white ellipse in mask - everywhere we paint white the original image will show through, everywhere black will be masked
draw = ImageDraw.Draw(alpha)
draw.ellipse([80,100,210,210],fill=255) 

# Add alpha mask to image and save
im.putalpha(alpha)
im.save('result.png')

这是我们创建的 alpha 蒙版:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2019-06-12
    • 2012-02-17
    • 2022-05-21
    相关资源
    最近更新 更多