Bounding Box in PIL (Python Image Library)

Bounding Box in PIL(Python Image Library) :
Bounding Box function of PIL can be very useful for removing unused pixels from an image.
Eg. If we want to remove unused pixels based on alpha channel of an image, we can use following code.
 
im = Image.open(imagePath)
r,g,b,a = im.split()
left,upper,right,lower = a.getbbox()
tempImage = im.crop((left,upper,right,lower))
newPath = imagePath.split(".")[0]+"_Cropped" + "." + imagePath.split(".")[1]
tempImage.save(newPath)


To understand which values, getbbox() function returns and what do they look like on an image, I created an image showing the values returned by the function.

left,upper,right,lower = image.getbbox()







Suppose you have a point in an original image and you want to find out the new position of the same point in the cropped image, lets see how we can do it.



Suppose the point is at (300,450) position in an original image, so after cropping its new position will be : (300-left , 450-upper) and we get left and upper from getbbox().


So the final code will look like : 

def cropImage(imagePath, registrationPoint=(0,0)):
     im = Image.open(imagePath)
     r,g,b,a = im.split()
     left,upper,right,lower = a.getbbox()
     tempImage = im.crop((left,upper,right,lower))
     newPath = imagePath.split(".")[0]+"_Cropped" + "." + imagePath.split(".")[1]
     tempImage.save(newPath)
     x = registrationPoint[0]
     y = registrationPoint[1]
     newRegistrationPoint = (x - left,y-upper)
     return newPath,newRegistrationPoint

 



Comments

Farhan said…
This was very useful, thanks for sharing!
suman said…
nice information.thank you.
learn python

Popular posts from this blog

Dictionary vs KeyValuePair vs Struct - C#

Rendering order and Z-sorting