1

How can I crop the border of an image using PIL?

From an image like this
Start

I want make to this
Result

Thanks.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
Nolik
  • 4,337
  • 5
  • 18
  • 14

1 Answers1

2
img = Image.open('your_wonderful_image.png')
nonwhite_positions = [(x,y) for x in range(img.size[0]) for y in range(img.size[1]) if img.getdata()[x+y*img.size[0]] != (255,255,255)]
rect = (min([x for x,y in nonwhite_positions]), min([y for x,y in nonwhite_positions]), max([x for x,y in nonwhite_positions]), max([y for x,y in nonwhite_positions]))
img.crop(rect).save('out.png')
Bemmu
  • 17,849
  • 16
  • 76
  • 93