python opencv 为图片添加alpha通道并设置透明,判断是否存在alpha通道

 读取图片
使用函数cv2.imread(filepath,flags)读入一副图片
filepath:要读入图片的完整路径
flags:读入图片的标志
cv2.IMREAD_COLOR:默认参数,读入一副彩色图片,忽略alpha通道
cv2.IMREAD_GRAYSCALE:读入灰度图片
cv2.IMREAD_UNCHANGED:顾名思义,读入完整图片,包括alpha通道

import numpy as np

import cv2

img = cv2.imread(‘1.jpg’,cv2.IMREAD_GRAYSCALE)

opencv 读取图片后通道为BGR的格式,这里做个示范将图片的左半边设置为透明效果。

import cv2
import numpy as np
 
img = cv2.imread("/home/shuai/Desktop/lena.jpg")
 
b_channel, g_channel, r_channel = cv2.split(img)
 
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
# 最小值为0
alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
 
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
 
cv2.imwrite("lena.png", img_BGRA)

 

import cv2
import numpy as np
def get_channel():
    for fil in os.listdir(r'C:\Users\83815\Desktop\LR'):
        file=os.path.join(r'C:\Users\83815\Desktop\\LR',fil)
        img=cv2.imread(file,cv2.IMREAD_UNCHANGED)
        print(img.shape)

 

(120, 125, 3)输出为3表示没有alpha通道,如果是4表示有alpha通道

 

posted on 2021-04-23 17:56  星河赵  阅读(2364)  评论(0编辑  收藏  举报

导航