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