[英]How do I make my numpy image take an alpha channel value in python
我試圖使圖像的背景透明。 我已經將所有想要透明的部分切成黑色。 但是python給我一條關於僅服用RBG的錯誤消息。 我收到的錯誤消息是“無法將大小為4的序列復制到維度為3的數組軸上”那么如何使python識別alpha通道並允許我對其進行操作?
import matplotlib.pyplot as plt
import os.path
import numpy as np
import PIL
def mask(row, column) :
for row in range(0, 383) :
for column in range(0, 86) :
img[row][column] = [0, 0, 0]
for row in range(230, 383) :
for column in range(0, 286) :
img[row][column] = [0, 0, 0]
for row in range(0, 50) :
for column in range(0, 286) :
img[row][column] = [0, 0, 0]
for row in range(0, 383) :
for column in range(199, 286) :
img[row][column] = [0, 0, 0]
directory = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(directory, 'PicOfNick.jpg')
img = plt.imread(filename)
fig, ax = plt.subplots(1, 1)
mask(283, 287)
np_img = np.array(img)
width = len(img[0])
height = len(img)
for h in range(48, 230) :
for w in range(84, 200) :
if np_img[h][w][0] in range(50, 90) :
np_img[h][w] = (0, 0, 0)
if sum(np_img[h][w]) == 0 :
np_img[h][w] = (0, 0, 0)
ax.imshow(np_img, interpolation='none')
fig.show()
您確實應該嘗試避免使用Numpy / Python遍歷圖像,因為它速度慢且容易出錯。 這是使所有黑色像素透明的方法。
從此圖像開始:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
# Load image and ensure it is 3-channel RGB...
# ... not 1-channel greyscale, not 4-channel RGBA, not 1-channel palette
im = Image.open('start.png').convert('RGB')
# Make into Numpy array of RGB and get dimensions
RGB = np.array(im)
h, w = RGB.shape[:2]
# Add an alpha channel, fully opaque (255)
RGBA = np.dstack((RGB, np.zeros((h,w),dtype=np.uint8)+255))
# Make mask of black pixels - mask is True where image is black
mBlack = (RGBA[:, :, 0:3] == [0,0,0]).all(2)
# Make all pixels matched by mask into transparent ones
RGBA[mBlack] = (0,0,0,0)
# Convert Numnpy array back to PIL Image and save
Image.fromarray(RGBA).save('result.png')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.