I have to deal with a lot of images and I'm looking for a way to detect the border color. For example, take this image:
is it somehow possible to determine that the image has a white background? A workaround can be to extract a border of 1px and check if the color of that extracted border is equally white. But I don't think the shave
-feature of ImageMagick supports this, right?
There are lots of techniques...
Let's make a test image 200x100:
convert xc:red xc:lime +append \( xc:blue xc:white +append \) -append -scale 200x100\! image.png
Here are some ways of getting the corner pixels:
# Top left pixel
magick image.png -format "%[hex:u.p{0,0}]\n" info:
FF0000
# Top right pixel
magick image.png -crop "1x1+%[fx:w-1]+0" -format "%[hex:u.p{0,0}]\n" info:
00FF00
# Bottom left pixel
magick image.png -crop "1x1+0+%[fx:h-1]+0" -format "%[hex:u.p{0,0}]\n" info:
0000FF
# Bottom right pixel
magick image.png -crop "1x1+%[fx:w-1]+%[fx:h-1]" -format "%[hex:u.p{0,0}]\n" info:
FFFFFF
Now let's look at the top, bottom, left and right edges for which we could use a better sample image:
convert -size 256x256 gradient:red-yellow image.png
# Top row mean and standard deviation
magick image.png +repage -crop x1\!+0+0 -format "%[fx:mean],%[fx:standard_deviation]\n" info:
0.333333,0
Standard deviation is zero, so all pixels are the same in this row.
# Bottom row mean and standard deviation
magick image.png +repage -crop "x1\!+0+%[fx:h-1]" -format "%[fx:mean],%[fx:standard_deviation]\n" info:
0.666667,0
Standard deviation is zero, so all pixels are the same in this row, but brighter (0.6666 vs 0.3333) because both the red and green pixels are on - making yellow.
# Left edge mean and standard deviation
magick image.png +repage -crop "1\!x+0+0" -format "%[fx:mean],%[fx:standard_deviation]\n" info:
0.5,0.0967909
There is some deviation down the edge because the colours are changing.
# Right edge mean and standard deviation
magick image.png +repage -crop "1\!x+%[fx:w-1]+0" -format "%[fx:mean],%[fx:standard_deviation]\n" info:
0.5,0.0967909