1

I'm using something along the lines of this to do a (naive, apparently) check for the color space of JPEG images:

import java.io.*;
import java.awt.color.*;
import java.awt.image.*;
import javax.imageio.*;

class Test
{
    public static void main(String[] args) throws java.lang.Exception
    {
        File f = new File(args[0]);

        if (f.exists())
        {
            BufferedImage bi = ImageIO.read(f);
            ColorSpace cs = bi.getColorModel().getColorSpace();

            boolean isGrayscale = cs.getType() == ColorSpace.TYPE_GRAY;
            System.out.println(isGrayscale);
        }
    }
}

Unfortunately this reports false for images that (visually) appear gray-only.

What check would do the right thing?

Tomalak
  • 332,285
  • 67
  • 532
  • 628

2 Answers2

2

the image looks like gray beacuse the r=g=b but actually it is a full color image, it has three channel r g b and the real gray image only have one channel

Patato
  • 1,464
  • 10
  • 12
  • Yes, I figured that out already. ;) The question is, is there a smarter check that does the right thing? – Tomalak Nov 19 '13 at 16:07
  • the simplest way is to check the r g b when it have three channels – Patato Nov 19 '13 at 16:10
  • @Tomalak examine each individual pixel using information from http://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image and evaluate whether R, G, and B are all equal for every pixel. – Compass Nov 19 '13 at 16:12
2

You can use this code:

File input = new File("inputImage.jpg");

BufferedImage image = ImageIO.read(input); 

Raster ras = image.getRaster();

int elem = ras.getNumDataElements();

System.out.println("Number of Elems: " + elem);

If the number of elems returns 1, then its a greyscale image. If it returns 3, then its a color image.

Mel
  • 5,837
  • 10
  • 37
  • 42
  • 1
    Will this recognize images that are saved in full color, but contain gray pixels only? – Tomalak Oct 06 '15 at 10:59
  • No. But, this will serve as the first step of filtering out the images have one channel. For the next stage you just copy the pixels into a 3D array and check the elements. After it has gone through this stage as well, it becomes a fool proof way of determining it. – ASM Hendrix Oct 06 '15 at 12:28
  • if (numofChannels == 3){ int[][][] Imagepixelinfo = new int[imWidth][imHeight][numofChannels]; // 3d array with the pixel info imageArray(image);// sets the array colorORbw = typeChecker(Imagepixelinfo); // tells if the image is b/w or color by returning true or false after checking the individual elements } – ASM Hendrix Oct 06 '15 at 12:35
  • Makes sense, thank you. The situation that question was for is no longer relevant for me, but I'll switch the accepted answer anyway because your post contains usable code. – Tomalak Oct 06 '15 at 13:42
  • Thank :). I appreciate the gesture. – ASM Hendrix Oct 06 '15 at 13:55