检查图像是否为灰度的可靠方法 [英] Reliable way to check if image is Grey scale
问题描述
我目前正在研究一个用例,需要确定上传的图像是灰度还是RGB。我发现了几种识别方法,但是不确定它们是否可靠,是否可以共同用于确认图像是否为灰度。
I am currently working on one use case where i need to determine if uploaded image is Grey Scale or RGB. I found couple of ways to identify this, but not sure if they are reliable and can be used collectively to confirm image is grey scale or not.
第1部分:读取图像
BufferedImage image = ImageIO.read(file);
Raster ras = image.getRaster();
int elem = ras.getNumDataElements();
我观察到elem的值在某些情况下为 1,但并非全部。
I observed value of elem is "1" in some cases, but not in all.
第2部分:检查每个像素的RGB值。如果R,G,B值与给定像素相同。
Part 2: Check RGB value of each pixel. If R , G, B value is same of given pixel.
BufferedImage image = ImageIO.read(file);
Raster ras = image.getRaster();
//Number of Color elements
int elem = ras.getNumDataElements();
int width = image.getWidth();
int height = image.getHeight();
int pixel,red, green, blue;
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
//scan through each pixel
pixel = image.getRGB(i, j);
red = (pixel >> 16) & 0xff;
green = (pixel >> 8) & 0xff;
blue = (pixel) & 0xff;
//check if R=G=B
if (red != green || green != blue ) {
flag = true;
break;
}
}
在这里我检查R,G,B值对于任何给定像素都是相同的,并且此行为在所有像素上都是一致的。
Here i check R, G,B values are same for any given pixel and this behavior is consistent across all pixels.
我正在使用这两种方法,但不确定它们的准确性如何。
请提出建议。
I am using these 2 approaches, but not sure how accurate they are. Kindly suggest..
推荐答案
下面的方法对我有用。谢谢大家的帮助。
Below approach is worked for me. Thanks guys for help.
BufferedImage image = ImageIO.read(file);
Raster ras = image.getRaster();
//Number of Color elements
int elem = ras.getNumDataElements();
int width = image.getWidth();
int height = image.getHeight();
int pixel,red, green, blue;
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
//scan through each pixel
pixel = image.getRGB(i, j);
red = (pixel >> 16) & 0xff;
green = (pixel >> 8) & 0xff;
blue = (pixel) & 0xff;
//check if R=G=B
if (red != green || green != blue ) {
flag = true;
break;
}
}
这篇关于检查图像是否为灰度的可靠方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!