.getbbox()
In the Pillow library, the ..getbbox()
method returns the bounding box as a 4-tuple (left, upper, right, lower)
that encloses all non-zero (non-background) regions of the image. It is commonly used for cropping or identifying the area of interest.
If the image is empty (i.e., all pixels are zero or the image is fully transparent), the .getbbox()
method will return None
, indicating that there is no non-zero region to define a bounding box for.
Common Use Cases
The .getbbox()
method is particularly useful for:
- Automatic cropping: Remove unnecessary blank borders around images to focus on the actual content.
- Content detection: Identify where the meaningful content is located within an image.
- Optimization: Reduce file size by trimming away empty space before saving.
- Layout analysis: Determine the boundaries of content regions for further processing.
- Document scanning: Detect and extract the actual document area from a scanned image.
Syntax
Image.getbbox()
Parameters:
The .getbbox()
method takes no parameters.
Return Value:
- Returns a 4-tuple
(left, upper, right, lower)
that defines the rectangular bounding box containing all non-zero pixels. - Returns
None
if the image is completely zero-valued (empty or fully transparent).
Example
The image to be used for this example is:
In this example, the .getbbox()
method returns the non-zero region of an image:
from PIL import Image# Open the image fileimg = Image.open("nature.png")# Get the bounding box of the non-zero areasbbox = img.getbbox()print(bbox)
This code produces the following output:
(0, 0, 672, 322)
The output indicates that the non-zero (non-backround) area of the image starts at (0, 0) and extends to (672, 322).
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pillow on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours