clear.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import os
  2. from PIL import Image
  3. def clear_save_image(image_path):
  4. image = Image.open(image_path)
  5. image = clear_image(image)
  6. image = image.convert('L') #灰度处理
  7. file_name = os.path.splitext(os.path.basename(image_path))[0]
  8. save_path = os.path.join(os.path.dirname(image_path), '../clear_image', file_name + '.jpg')
  9. image.save(save_path) #图片转换成tif保存到clear_image文件夹中
  10. def clear_image(image):
  11. image = image.convert('RGB')
  12. width = image.size[0]
  13. height = image.size[1]
  14. noise_color = get_noise_color(image)
  15. for x in range(width):
  16. for y in range(height):
  17. #清除边框和干扰色
  18. if (x == 0 or y == 0 or x == width - 1 or y == height - 1
  19. or image.getpixel((x, y)) == noise_color):
  20. image.putpixel((x, y), (255, 255, 255))
  21. #背景调整为白色
  22. if (image.getpixel((x, y))[0] > 180 and image.getpixel((x, y))[1] > 180 and image.getpixel((x, y))[2] > 180):
  23. image.putpixel((x, y), (255, 255, 255))
  24. return image
  25. def get_noise_color(image):
  26. for y in range(1, image.size[1] - 1):
  27. # 获取第2列非白的颜色
  28. (r, g, b) = image.getpixel((2, y))
  29. if r < 255 and g < 255 and b < 255:
  30. return (r, g, b)
  31. if __name__ == '__main__':
  32. os.makedirs('./clear_image/', exist_ok=True)
  33. for file_path in os.listdir('image'):
  34. file_path = os.path.join('image', file_path)
  35. if os.path.isfile(file_path):
  36. clear_save_image(file_path)
  37. print("clear end.")