omegalul
omegalul

Reputation: 37

How do I make my numpy image take an alpha channel value in python

I am trying to make the background of an image transparent. I have sectioned off all the part I want to be transparent in black. But python gives me an error message about only taking RBG. The error message I get is "cannot copy sequence with size 4 to array axis with dimension 3" So how do I make python recognize the alpha channel and allow me to manipulate it?

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()

Upvotes: 0

Views: 9526

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

You really should try and avoid looping over images with Numpy/Python, it is slow and error-prone. Here is how you can make all black pixels transparent.

Starting with this image:

enter image description here

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

enter image description here

Upvotes: 7

Related Questions