python png 背景透明_去除白色背景得到透明背景png的示例代码

【实例简介】

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

【实例截图】

原图

1a35be6fb6bcc647fc589cfd6d2286b1.png

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

95177361dcf2ce9d77b59acd564acfcb.png

【核心代码】

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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值