Augmented Image.getbbox method? #7327
Replies: 3 comments 1 reply
-
As an aside, for the reference image you mentioned, a simpler solution would be to just invert the white to become black, and then get the bounding bbox. from PIL import Image, ImageOps
im = Image.open("input.png")
bbox = ImageOps.invert(im.convert("RGB")).getbbox()
im.crop(bbox).save("output.png") |
Beta Was this translation helpful? Give feedback.
-
If you were just talking about a different color, I'd suggest making changes to Maybe a variation on my |
Beta Was this translation helpful? Give feedback.
-
Closing, as a lack of response here indicates that there may not be a strong need for this feature. |
Beta Was this translation helpful? Give feedback.
-
I have made a matplotlib script for plotting PXRD measurements and I thought it would be neat if I could add an image of a molecule to the upper right of the plot. So what I did is to use RDKit to generate a raster image (PIL image) from a SMILES code of a molecule. That gets passed to the OffsetImage class and then to the AnnotationBox class so that it can be displayed in the upper right.
There was a particular problem though that irked me while implementing this: The images that come from RDKit always have a white background and aren't cropped to the content of the image. I found out that PIL provides the
Image.getbbox()
method, but that only works for, as I understand, perfect black pixels an completely transparent pixels, if the right keyword is used.It didn't work for my white bg image, which I apparently can only obtain as a white bg image (a limitation by RDKit). That is why I wrote my own hacky code to find out where the edges of my image are. Those can then be cropped using the
Image.crop()
method.So I started thinking: Can the concept of "cropping to content" not be extended to an arbitrary background color and paired with a tolerance factor in case the provided image is a little grainy?
The general idea is the following: Create a stand-alone function, or method, which takes both a user provided color and a tolerance factor and then crops the image according to the following logic:
So it's basically a generalisation of the existing method regarding the background color as well as a tweak to how precise the match between bg and match color needs to be.
This is what I have implemented so far, but it is far from polished:
This is the reference image I'm using:
This is an additional function for generating a PIL image from a SMILES code, if you are interested/have RDKit installed:
Is this a good idea?
Beta Was this translation helpful? Give feedback.
All reactions