Python OpenCV将黑边图像转为透明边

import cv2
import os
import datetime

def change_size2(read_file):

    image=cv2.imread(read_file,1) #读取图片  
    b=cv2.threshold(image,15,255,cv2.THRESH_BINARY)   
    binary_image=b[1]               #二值图,具有三通道
    binary_image=cv2.cvtColor(binary_image,cv2.COLOR_BGR2GRAY)
    print(binary_image.shape)       #改为单通道

    x=binary_image.shape[0]
    print("高度x=",x)
    y=binary_image.shape[1]
    print("宽度y=",y)
    edges_x=[]
    edges_y=[]
    for i in range(x):
        for j in range(y):
            if binary_image[i][j]==255:
                
                edges_x.append(i)
                edges_y.append(j)

    left=min(edges_x)               #左边界
    right=max(edges_x)              #右边界
    width=right-left                #宽度
    bottom=min(edges_y)             #底部
    top=max(edges_y)                #顶部
    height=top-bottom               #高度

    pre1_picture=image[left:left+width,bottom:bottom+height]        #图片截取
    
    h,w = pre1_picture.shape[:2]  
    h_old,w_old= image.shape[:2] #254 *309
    top_size,bottom_size,left_size,right_size = (int((h_old-h)/2)-1,int((h_old-h)/2)+1,int((w_old-w)/2)-1,int((w_old-w)/2)+1)   
    constant = cv2.copyMakeBorder(pre1_picture,top_size,bottom_size,left_size,right_size,cv2.BORDER_CONSTANT,value=(255,255,255))

    # Point 1: 生成与白色部分对应的mask图像
    mask = np.all(constant[:,:,:] == [255, 255, 255], axis=-1)
 
    # Point 2: 将图片从三通道转为四通道
    dst = cv2.cvtColor(constant, cv2.COLOR_BGR2BGRA)
 
    # Point3:  以mask图像为基础,使白色部分透明化
    dst[mask,3] = 0
    
    return dst                                            #返回图片数据
source_path="130\\"                                    #图片来源路径
save_path="out2\\"                                     #图片修改后的保存路径

if not os.path.exists(save_path):
    os.mkdir(save_path)

file_names=os.listdir(source_path)

starttime=datetime.datetime.now()
for i in range(len(file_names)):
    if file_names[i].endswith(".BMP"):
        x=change_size2(source_path + file_names[i])        #得到文件名
        cv2.imwrite(save_path+file_names[i][:-3]+'png',x)
        print("修改:",file_names[i])
        print("修改数量:",i)
        
print("修改完毕")
endtime = datetime.datetime.now()#记录结束时间
endtime = (endtime-starttime).seconds
print("修改总用时",endtime)

转换前:

​​​​​​​

 

转换后:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值