我正在尝试使用 matplotlib
、os.path
和 numpy
裁剪图像(从学校图片中裁剪背景) .
我的想法是将图像分割成除我需要的部分之外的正方形,然后操纵 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 更容易。从菲奥娜的这张照片开始......
#!/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 蒙版:
关于python - 如何更改图像上像素部分的 Alpha channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633087/