opencv将图片转换为RGBA格式

import cv2
import numpy as np
import os

for file in os.listdir('/home/lhq/mb'):
    img1 = cv2.imread("/home/lhq/mb/{}".format(file))
    img = cv2.GaussianBlur(img1,(25,25),15)
    ret, thresh = cv2.threshold(img, 254, 255, 0)
    thresh = cv2.cvtColor(thresh,cv2.COLOR_BGR2GRAY)
    thresh = ~thresh
    index = np.where(thresh == 0)
    # cv2.imshow('',thresh)
    # cv2.waitKey(0)
    # exit()
    b_channel, g_channel, r_channel = cv2.split(img1)

    alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
    # 最小值为0
    # alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
    alpha_channel[index] = 0

    img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))

    cv2.imwrite("/home/lhq/mb1/{}.png".format(file.split('.')[0]), img_BGRA)
import cv2
import numpy as np
import os

for file in os.listdir('/home/lhq/mb'):
    img1 = cv2.imread("/home/lhq/mb/{}".format(file))
    # img = cv2.GaussianBlur(img1,(25,25),15)
    ret, thresh = cv2.threshold(img1, 240, 255, 0)
    thresh = cv2.cvtColor(thresh,cv2.COLOR_BGR2GRAY)
    thresh = ~thresh
    binary = np.zeros(shape=img1.shape[:-1])

    contours, heriachy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for i, contour in enumerate(contours):
        # 最后一个参数是像素值,设为-1时,会将整个轮廓都填充为相应的颜色
        cv2.drawContours(binary, contours, i, (255), -1)

    # cv2.imshow('',binary)
    # cv2.waitKey(0)
    index = np.where(binary == 0)
    b_channel, g_channel, r_channel = cv2.split(img1)

    alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
    # 最小值为0
    # alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
    alpha_channel[index] = 0

    img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
    cv2.imwrite("/home/lhq/mb4/{}.png".format(file.split('.')[0]), img_BGRA)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值