简体   繁体   English

确定图像是否是Java中的灰度

[英]Determine whether an image is grayscale in Java

I'm using something along the lines of this to do a (naive, apparently) check for the color space of JPEG images: 我正在使用类似的东西做一个(天真的,显然)检查JPEG图像的颜色空间:

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. 不幸的是,对于( 视觉上 )仅显示灰色的图像,这会报告false

What check would do the right thing? 什么检查会做正确的事情?

图像看起来像灰色,因为r=g=b但实际上它是一个全彩色图像,它有三个通道rgbreal gray图像只有一个通道

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. 如果elems的数量返回1,那么它是一个灰度图像。 If it returns 3, then its a color image. 如果它返回3,那么它是一个彩色图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM