如何更改图像上一部分像素的 Alpha 通道?
How do I change the alpha channel of a section of pixels on my image?
我正在尝试使用 matplotlib
、os.path
和 numpy
.
裁剪图像(从学校图片中裁剪背景)
我的想法是将图像分成正方形,而不是我需要的部分,然后操纵 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
您会发现使用 PIL/Pillow 会容易得多。从这张 Fiona 的照片开始...
#!/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 蒙版:
我正在尝试使用 matplotlib
、os.path
和 numpy
.
我的想法是将图像分成正方形,而不是我需要的部分,然后操纵 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
您会发现使用 PIL/Pillow 会容易得多。从这张 Fiona 的照片开始...
#!/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 蒙版: