基本信息
源码名称:去除白色背景得到透明背景png的示例代码
源码大小:3.25KB
文件格式:.py
开发语言:Python
更新时间:2020-10-12
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

去除图像中的白色背景,得到透明背景的保留主体的png图像的python代码;

原图

去除白色背景后得到的图片

def remove_white_bg(img_list, output_dir):
    for img_path in img_list:
        img = cv2.imread(img_path)
        if img is None:
            print(img_path)
            continue
        ## (1) Convert to gray, and threshold
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        th, threshed = cv2.threshold(gray, 235, 255, cv2.THRESH_BINARY_INV)

        ## (2) Morph-op to remove noise
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2,2))
        morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
        print(morphed.shape)

        w,h,c=img.shape
        img=np.transpose(img,[2,0,1])
        z = np.ones([1,w,h]).astype(img.dtype)*255
        img = np.vstack((img,z))
        img = np.transpose(img,[1,2,0])

        cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
        stencil = np.zeros([w,h,4]).astype(img.dtype)
        color = [255, 255, 255,255]
        cv2.fillPoly(stencil, cnts, color)

        result = cv2.bitwise_and(img, img, mask=morphed)
        result = cv2.bitwise_and(result, stencil)
        result = CropImage(result, result.shape[0],result.shape[1])[0]

        output_path = os.path.join(output_dir, os.path.split(img_path)[-1] '.png')
        cv2.imwrite(output_path, result)