Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to convert image grayscale pixel values to alpha values in python using libraries like OpenCV, Pillow and scikit-image?

This is a test program using OpenCV:

path = "e:/python/sampleImage.tif"
src = cv2.imread(path, -1)
print("shape: ",src.shape)
print("co_pixel value3: ",src[970,1000])
cv2.imshow("Displaying only blue channels",src)
cv2.waitKey(0)
cv2.destroyAllWindows()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
271 views
Welcome To Ask or Share your Answers For Others

1 Answer

An image with alpha channel is just an image with 4 channels: 3 colors (B, G, R in OpenCV), and the alpha channel. So let's say you have your color image src. Then

import numpy as np
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
img_w_alpha = np.dstack( (src, gray) )

np.dstack adds the alpha channel as the 4th channel to your color image.

I don't understand though, why you'd want to do that, so if that doesn't answer your question, maybe you need to elaborate on it.

EDIT: Following your comments, maybe you're looking for alpha blending?

import cv2
# Load the tiff
tif = cv2.imread('tmp/Nixon.tif')
h,w,c = tif.shape
alpha = cv2.cvtColor(tif, cv2.COLOR_BGR2GRAY)  
tif_a = cv2.cvtColor(tif, cv2.COLOR_BGR2BGRA)
tif_a[:,:,3] = alpha  #  now you have an image whose alpha channel equals the greyscale values, 
#                        but I'm not sure what good that is
# load a background image
img = cv2.imread('tmp/PA110602.JPG')
img = cv2.resize(img, (w,h))  #  for blending, both images need to be of same size
# blend the two images, using the greyscale version of tif as alpha values
blend = cv2.add(
        alpha.reshape((*alpha.shape,1))/255.0*tif.astype(float),
        (1.0-alpha.reshape((*alpha.shape,1))/255.0)*img.astype(float),
        dtype=cv2.CV_8UC1)

Foreground, background, and blended image

As you can see, where Nixon's image is almost black, e.g. in his jacket and hair, the background image is visible, and where Nixon's image is bright, e.g. his collar and face, the background image is barely visible.

The code for blending looks so awkward, because

  • we can not multiply a h-by-w image with a h-by-w-by-c image, but we CAN multiply a h-by-w-by-1 image with a h-by-w-by-c image, so we have to add the dimension to alpha using reshape.
  • for the blending, we have to convert the image from uint to float, but once we're done, we want to have uint again.

But do some Googling for "alpha blending" if this is what you're after.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...