Ken
Ken

Reputation: 560

Detect if an image has a border, programmatically (return boolean)

First off, I have read this post. How to detect an image border programmatically? He seems to be asking a slightly different question, on finding the X/Y coordinates though.

I am just trying to find whether or not a solid border exists around a given photo. I've explored using ImageMagick, but is this the best option? I've never done any Image-related programming so I'm hoping there's just a simple api out there that can solve this problem. I'm also fairly new to how to use these libraries, so any advice is appreciated. I'd prefer solutions in Python or Java, anything is fine though.

Thanks!

Upvotes: 3

Views: 2901

Answers (3)

songofhawk
songofhawk

Reputation: 153

so, the correct code of last line should be :

 return all((bbox[0], bbox[1], bbox[2]) < im.size[0], bbox[3] < im.size[1]))

right? for the last two parameters of getbbox() func, are "right, and lower pixel coordinate of the bounding box", not width and height

Upvotes: 0

fraxel
fraxel

Reputation: 35289

I answered a related question here, that removes any border around an image, it uses PIL. You can easily adapt the code so it returns True or False for whether there is a border or not, like this:

from PIL import Image, ImageChops

def is_there_a_border(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    return bbox != (0,0,im.size[0],im.size[1])

However, this will return True even if only one side of an image has a border. But it sounds like you want to know if there is a border all the way around an image. To do that change the last line to:

    return all((bbox[0], bbox[1], (bbox[0] + bbox[2]) <= im.size[0], 
                                  (bbox[1] + bbox[3]) <= im.size[1]))

This only returns true if there is a border on every side.

For example:

False:

enter image description here

False:

enter image description here

True:

enter image description here

Upvotes: 4

Phil H
Phil H

Reputation: 20151

After seeing fraxel's answer, it occurs to me that if you don't care how wide the border is, you could crop out the outermost pixel of each side and check the colour is uniform. Should be very quick; by setting the background color to that of the pixel at 0,0, and cropping 1,1 to w-2,h-2, the remaining image should have exactly 1 colour.

Upvotes: 1

Related Questions