问题
I want set alpha channel to a .jpg image and set its value to 0.5 or 50% or at 128 (0 to 1 total range or 0-255 range) and save it as .png using only opencv and numpy. I know how to do it using other libraries but we have been asked to perform the above question using only two library i.e. import cv2 and import numpy. i have added the alpha channel but i do not know how to set its value to 50% transparency, please help as I am new to opencv-python.
I have tried this code but I am getting a black image even when I open it with paint.
Reduce opacity of image using Opencv in Python
this is how I have added my alpha
import cv2
import numpy as np
img = cv2.imread('food.jpg')
bgra = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
print(bgra.shape)
回答1:
There are several ways of doing this... I'll start with this image:
Add blank alpha channel with OpenCV and set content with Numpy indexing:
import cv2
import numpy as np
img = cv2.imread('paddington.jpg')
# Add alpha layer with OpenCV
bgra = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
# Set alpha layer semi-transparent with Numpy indexing, B=0, G=1, R=2, A=3
bgra[...,3] = 127
# Save result
cv2.imwrite('result.png',bgra)
Alternatively, create a solid alpha layer filled with 128s and stack depth-wise with Numpy dstack()
:
import cv2
import numpy as np
img = cv2.imread('paddington.jpg')
# Create solid alpha layer, same height and width as "img", filled with 128s
alpha = np.zeros([img.shape[0],img.shape[1],1], dtype=np.uint8) + 128
# Depth-wise stack that layer onto existing 3 RGB layers
bgra = np.dstack((img,alpha))
# Save result
cv2.imwrite('result.png',bgra)
Alternatively, create a solid alpha layer filled with 128s and merge using OpenCV merge()
:
import cv2
import numpy as np
img = cv2.imread('paddington.jpg')
# Create solid alpha layer, same height and width as "img", filled with 128s
alpha = np.full_like(img[...,0], 128)
# Merge new alpha layer onto image with OpenCV "merge()"
bgra = cv2.merge((img,alpha))
# Save result
cv2.imwrite('result.png',bgra)
Note that, as expected, the OpenCV cvtColor()
method described first is fastest, by a factor of about 10x because it is hand optimised SIMD code. Timings with given image were as follows:
cv2.cvtColor()
- 48 microsecondsnp.dstack()
- 477 microsecondscv2.merge()
- 489 microseconds
Keywords: Python, image, image processing, Numpy, OpenCV, dstack, merge, cvtColor, add alpha channel, add transparency, set transparency, COLOR_BGR2BGRA, cv.COLOR_BGR2BGRA
来源:https://stackoverflow.com/questions/58638506/how-to-make-a-jpg-image-semi-transparent