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

25 篇文章 6 订阅

 读取图片

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

  1. import numpy as np

  2. import cv2

  3. 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通道

 

参考:

https://blog.csdn.net/qq_34840129/article/details/91128420

https://blog.csdn.net/helloworld1108/article/details/88563457

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值