import os from PIL import Image def clear_save_image(image_path): image = Image.open(image_path) image = clear_image(image) image = image.convert('L') #灰度处理 file_name = os.path.splitext(os.path.basename(image_path))[0] save_path = os.path.join(os.path.dirname(image_path), '../clear_image', file_name + '.jpg') image.save(save_path) #图片转换成tif保存到clear_image文件夹中 def clear_image(image): image = image.convert('RGB') width = image.size[0] height = image.size[1] noise_color = get_noise_color(image) for x in range(width): for y in range(height): #清除边框和干扰色 if (x == 0 or y == 0 or x == width - 1 or y == height - 1 or image.getpixel((x, y)) == noise_color): image.putpixel((x, y), (255, 255, 255)) #背景调整为白色 if (image.getpixel((x, y))[0] > 180 and image.getpixel((x, y))[1] > 180 and image.getpixel((x, y))[2] > 180): image.putpixel((x, y), (255, 255, 255)) return image def get_noise_color(image): for y in range(1, image.size[1] - 1): # 获取第2列非白的颜色 (r, g, b) = image.getpixel((2, y)) if r < 255 and g < 255 and b < 255: return (r, g, b) if __name__ == '__main__': os.makedirs('./clear_image/', exist_ok=True) for file_path in os.listdir('image'): file_path = os.path.join('image', file_path) if os.path.isfile(file_path): clear_save_image(file_path) print("clear end.")