目录
方法一:
from PIL import Image
def add_white_bg(img_fg, img_bg):
im = Image.open(img_fg)
x, y = im.size
try:
# 使用白色来填充背景(255, 255, 255)
img = Image.new('RGBA', im.size, (255, 255, 255))
img.paste(im, (0, 0, x, y), im)
img.save(img_bg)
img.show()
except Exception as e:
print(e)
pass
if __name__ == '__main__':
img_one = r"D:\1.PNG" # 无背景图片
save_path = r"D:\bg.png"
add_white_bg(img_one, save_path)
方法二:
def alphabg2white_PIL(img):
img = img.convert('RGBA')
img.show()
sp = img.size
width = sp[0]
height = sp[1]
print(sp)
for yh in range(height):
for xw in range(width):
dot = (xw, yh)
color_d = img.getpixel(dot)
if (color_d[3] == 0):
color_d = (255, 255, 255, 255)
img.putpixel(dot, color_d)
return img
if __name__ == '__main__':
img = Image.open(r'D:\1.PNG')
img.show()
whitebg = alphabg2white_PIL(img)
whitebg.show()
方法三:
import cv2
def alpha2white_opencv2(img):
sp = img.shape
width = sp[0]
height = sp[1]
for yh in range(height):
for xw in range(width):
color_d = img[xw, yh]
if (color_d[3] == 0):
img[xw, yh] = [255, 255, 255, 255]
return img
if __name__ == '__main__':
img = cv2.imread(r'D:\1.PNG', -1)
whitebg = alpha2white_opencv2(img)
cv2.imshow("whitebg", whitebg)
cv2.waitKey(0)