How to read image colorspace?

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?".
Locked
stroker
Posts: 16
Joined: 2008-04-07T11:24:55-07:00

How to read image colorspace?

Post by stroker »

I have a dilemma reading colorspace from images. I you use the standard way identify -format "%[colorspace]%" you will sometimes get wrong result.

For example i you have a RGB image with a RGB profile sRGB you might sometime get colorspace: GRAY instead of RGB if the internal image consists of only grayscale pixels. I think this have to do ImageMagick being "smart" and comparing each pixel channels and returning gray if each channel is the same. But this breaks the standard, a grayscale image can newer have RGB profile. I you do some convert command on this image and then save it you will end up with incorrect profile data. You can solve this by using -type truecolor and force to save to RGB.

So my question is how do I read this image as a RGB colorspace?

I have come up with a solution that works 95% of the times

identify -format "%r"
This will result in one of following values 'DirectClassRGB', 'PseudoClassRGB', 'PseudoClassGray', 'DirectClassGray'

if image class is DirectClassRGB or PseudoClassRGB the colorspace is always RGB.
if image class is PseudoClassGray the colorspace is always GRAY
if image class is DirectClassGray the colorspace is most_of_the_times RGB but now always

Do anyone have a solution that works 100% of the times?

User avatar
fmw42
Posts: 26383
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: How to read image colorspace?

Post by fmw42 »

I have done pretty much the same as you. Either a combo of colorspace and type or %r.

But I just noticed some other things that could be checked from the verbose info:

convert rose: -colorspace gray rose_gray.png

identify -verbose rose_gray.png
Image: rose_gray.png
Format: PNG (Portable Network Graphics)
Class: PseudoClass
Geometry: 70x46+0+0
Resolution: 72x72
Print size: 0.972222x0.638889
Units: Undefined
Type: Grayscale
Base type: Grayscale
Endianess: Undefined
Colorspace: RGB
Depth: 8-bit
Channel depth:
gray:
8-bit
Channel statistics:
gray:
min: 37 (0.145098)
max: 255 (1)
mean: 105.14 (0.412313)
standard deviation: 47.3907 (0.185846)
kurtosis: 2.54124
skewness: 1.52215


You could check on these items and see how consistent they are with you imagery.

Locked