Avec matplotlib on a vu comment ajuster automatiquement les bords d'une figure dans un précèdent article. Cependant avec matplotlib les possibilités pour ajuster une figure sont un peu limitées et le résultat parfois insatisfaisant. Pour remédier à cela il est possible d'utiliser le module python: PIL qui permet de travailler facilement avec des images. Voici un exemple simple de script python permettant de rogner une image (la variable add_pad définie la distance entre la figure et les bords de l'image):

import Imageim = Image.open("input.png") #Can be many different formats.pix = im.load()im_size = im.sizeprint im_size #Get the width and hight of the image for iterating overx_min = im_size[0]x_max = 0y_min = im_size[1]y_max = 0for x in range(im_size[0]):for y in range(im_size[1]):if pix[x,y] != (255, 255, 255, 255) :if x < x_min :x_min = xif x > x_max :x_max = xif y < y_min :y_min = yif y > y_max :y_max = yprint x_min, x_maxprint y_min, y_maxadd_pad = 40x_min = x_min - add_padx_max = x_max + add_pady_min = y_min - add_pady_max = y_max + add_padleft = x_mintop = y_minwidth = x_max - x_minheight = y_max - y_minbox = (left, top, left+width, top+height)area = im.crop(box)area.show()print area.sizearea.save("input_adjusted.png", "PNG")
Recherches associées
| Liens | Site |
|---|---|
| PIL | PIL module |
| Trouble using python PIL library to crop and save image | stackoverflow |
| Read the RGB value of a given pixel in Python, Programatically | stackoverflow |
| Python: PIL replace a single RGBA color | stackoverflow |
| Using PIL to make all white pixels transparent? | stackoverflow |
| PIL Best Way To Replace Color? | stackoverflow |
| Remove background colour from image using Python/PIL | stackoverflow |


