Detect non-white pixels in image

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
jchan
Posts: 1
Joined: 2016-10-06T15:22:42-07:00
Authentication code: 1151

Detect non-white pixels in image

Post by jchan »

Given an image, I want to detect whether it has any non-white pixels (basically anything that's not #FFFFFF). Any transparent pixels should also be ignored.

Is there a way to do this, maybe somehow parsing the data given from the code below?

Code: Select all

convert sample.png -format %c histogram:info:-
Thanks!
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Detect non-white pixels in image

Post by fmw42 »

What do you mean by "detect"? Do you just want to know if there are any non-white pixels or any transparent pixels? Or do you need the locations of every one?

Please always provide your IM version and platform, since syntax may differ.

An image will have non-white pixels if the mean value is not 1 in the following.

Unix syntax:

Code: Select all

test1=`convert image -alpha off -scale 1x1 -format "%[fx:u]" info:`
if [ "$test1" = "1" ]; then
echo "white"
else
echo "non-white"
fi
An image has transparent pixels if the result of the following is not 1

Code: Select all

test2=`convert image -alpha extract -scale 1x1 -format "%[fx:u]" info:`
if [ "$test1" = "1" ]; then
echo "fully opaque"
else
echo "has transparency"
fi
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Detect non-white pixels in image

Post by snibgo »

Assuming your are not using HDRI, simply find the minimum pixel value: %[fx:minima]. If this isn't #ffffff or whatever your Q is, all the pixels are white.
snibgo's IM pages: im.snibgo.com
Post Reply