修掉有透明和非透明部分的图案的白边
'''
去边后白色地方变成透明色
星火讯飞、阿夏
20240817
'''
import os
from PIL import Image
path = r'C:\Users\jg2yXRZ\OneDrive\桌面\20241110一款校服'
folder_path = path + r'\01要放大'
output_folder = path + r'\02切边图'
os.makedirs(output_folder, exist_ok=True)
# 留一点白边
white_edge = 0
def find_non_white_pixel(image):
width, height = image.size
left, right, top, bottom = width, 0, height, 0
for y in range(height):
for x in range(width):
pixel = image.getpixel((x, y))
if len(pixel) == 4: # RGBA
r, g, b, a = pixel
else: # RGB
r, g, b = pixel
a = 255 # Assuming fully opaque if no alpha channel
if not (r > 200 and g > 200 and b > 200): # Adjust threshold as needed
if x < left:
left = x
if x > right:
right = x
if y < top:
top = y
if y > bottom:
bottom = y
return left, right, top, bottom
def crop_image(image, left, right, top, bottom):
return image.crop((left - white_edge, top - white_edge, right + white_edge, bottom + white_edge))
for file_name in os.listdir(folder_path):
if file_name.endswith(".jpg") or file_name.endswith(".png"):
input_path = os.path.join(folder_path, file_name)
image = Image.open(input_path)
left, right, top, bottom = find_non_white_pixel(image)
cropped_image = crop_image(image, left, right, top, bottom)
output_path = os.path.join(output_folder, file_name)
cropped_image.save(output_path)
# '''
# 去边后白色地方变成透明色,透明图片统一大小
# 星火讯飞、阿夏
# 20240817
# '''
# print('----2、图片放大成为1024*1024------')
# import os
# from PIL import Image
# # path=r'C:\Users\jg2yXRZ\OneDrive\图片\20240817饮料圆形'
# # input_folder = path+r'\圆形切边图'
# # output_folder = path+r'\圆形切边图透明'
# # input_folder = path+r'\05切边图'
# output_folder =path+r'\02切边图'
# # output_folder = path+r'\04透明图'
# newput_folder =path+r'\03统一图'
# os.makedirs(newput_folder,exist_ok=True)
# # 提取最大宽度的那张图片的尺寸
# def get_max_width_and_height(fold_path):
# max_width = 0
# max_height = 0
# for file_name in os.listdir(fold_path):
# if file_name.endswith(".png") or file_name.endswith(".jpg") or file_name.endswith(".jpeg"):
# file_path = os.path.join(fold_path, file_name)
# img = Image.open(file_path)
# width, height = img.size
# if width > max_width:
# max_width = width
# max_height = height
# return max_width, max_height
# fold_path = output_folder
# max_width, max_height = get_max_width_and_height(fold_path)
# print("最大宽度:", max_width)
# print("最大高度:", max_height)
# # 最大宽度: 724
# # 最大高度: 869
# # # 自定义长宽
# # max_width=622
# # max_height=877
# # 统一所有图片大小
# def resize_image(image_path, output_folder, new_image_name):
# img = Image.open(image_path)
# new_img = img.resize((max_width,max_height))
# new_img.save(os.path.join(output_folder, new_image_name))
# for file in os.listdir(output_folder):
# if file.endswith('.png'):
# input_image_path = os.path.join(output_folder, file)
# new_image_name = f"{file[:-4]}.png"
# resize_image(input_image_path, newput_folder, new_image_name)
# '''
# 图片上下翻转
# '''
标签:max,image,无标题,width,file,path,folder From: https://blog.csdn.net/reasonsummer/article/details/143659820