900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python png 背景透明_去除白色背景得到透明背景png的示例代码

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

时间:2019-07-21 17:40:39

相关推荐

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

【实例简介】

去除图像中的白色背景,得到透明背景的保留主体的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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。