python - 如何更改图像上像素部分的 Alpha channel ?

标签 python image matplotlib rgb alpha

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

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

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

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

最佳答案

您会发现使用 PIL/Pillow 更容易。从菲奥娜的这张照片开始......

enter image description here

#!/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')

enter image description here

这是我们创建的 alpha 蒙版:

enter image description here

关于python - 如何更改图像上像素部分的 Alpha channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633087/

相关文章:

python - PyQt5:使用设计器创建多个 View 并将它们连接到一个应用程序中

image - 使用 Swift 创建随机图像生成器

python - 如何使用python中内置的numpy或matplotlib正确生成3d直方图?

python - Python 3.x 中的绘图

matplotlib - 如何删除 FancyArrowPatch 的箭头尖端和目标点之间的空白?

python - 'and' 和 '&' 在 python 集方面有区别吗?

python - 在 docker 容器中运行 python 脚本时没有 json 模块

python - Python 中的 Karatsuba 算法

c# - 将文件加载到位图但保持原始文件不变

android - 如何使用平移/缩放在某种表面上绘制大量图像?