-4

enter image description hereImage from PIL module

I am new to the this image processing stuff. Why I am asking this question is because I have a code which works for RGB mode but doesnt for P mode ? So I came to conclusion that it is something related to modes. I did some basic research on modes.but did not find any simple explanation. Will be helpful if someone can help me understand this.

CODE:

image=Image.open('image.png')
image.load()

image_data = np.asarray(image)
image_data_bw = image_data.max(axis=2)
non_empty_columns = np.where(image_data_bw.max(axis=0)>0)[0]
non_empty_rows = np.where(image_data_bw.max(axis=1)>0)[0]
cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))

image_data_new = image_data[cropBox[0]:cropBox[1]+1, cropBox[2]:cropBox[3]+1 , :]

new_image = Image.fromarray(image_data_new)
new_image.save('cropped_image.png')

Codesource

Input to the code following Image:

Image_1 Output should be like the following image(It is cropped to the edges of the picture. Please click on the image for understanding):

Cropped_Image

This Image is in RGBA mode.so the code is working fine for such images. But not with the image in P mode.

ERROR: Error I get with P mode: axis 2 is out of bounds for array of dimension 2

Sushant
  • 160
  • 2
  • 10

2 Answers2

1

The answer you found greatly overcomplicates the process, by using numpy. The PIL library supports this usecase natively, with the image.getbbox() and image.crop() methods:

cropbox = image.getbbox()
new_image = image.crop(cropbox)

This works for all the different modes, regardless. The cropbox produced by image.getbbox() is exactly the same size as the one produced by the numpy route.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks Martijn. Above thing worked like a charm. I guess it doesnt work for alpha channel,so we need to remove that first then crop the image using getbbox. But for P mode it works perfectly. Thanks !! – Sushant Dec 18 '17 at 05:18
0
from PIL import Image

img = Image.open('Image.png')

print(x,y)
img.show()
cropbox_1 = img.getbbox()
new_image_1 = img.crop(cropbox_1)
new_image_1.save('Cropped_image,png')
new_image_1.show()

This code completely crops the image to the edges. Only if the images are having alpha channel, you might have to remove that channel by converting it.

ex. If it is a RGBA mode make it RGB and then use getbbox().

img = image.convert('RGB')
cropbox = img.getbbox()
image_1 = img.crop(cropbox)

addition of this should do the task.

Sushant
  • 160
  • 2
  • 10