原理:参考1.1和1.2
import cv2 import os import numpy as np 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] != 255: # 找到alpha通道不為255的像素 img[xw, yh] = [255, 255, 255, 255] # 改變這個像素 return img def cut_img(img, full_file_path_to_save): loc = np.where(img < 255) # 内容为非白色部分(有意义部分) lx = [] ly = [] for pt in zip(*loc[::-1]): # pt 为每个像素点的坐标 lx.append(pt[1]) ly.append(pt[2]) sx = min(lx) bx = max(lx) sy = min(ly) by = max(ly) cv2.imwrite(full_file_path_to_save, img[sy:by, sx:bx]) # 保存时只保留有意义部分 if __name__ == '__main__': filePath = 'Icons-dp/' file_name_list = [] for i, j, k in os.walk(filePath): file_name_list = k for file in file_name_list: full_file_path = filePath + file image = cv2.imread(full_file_path, cv2.IMREAD_UNCHANGED) # 第二个参数保留Alpha通道 image = alpha2white_opencv2(image) cut_img(image, 'd' + full_file_path) # 確認路徑'dIcons-dp' 存在,如不存在程序不會報錯也不會寫入圖片