Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

python - Converting image grayscale pixel values to alpha values

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...