计算图像的颜色数 [英] Count the number of colors of images
问题描述
我有三个不同的图片(jpeg或bmp)。
我试图根据每个图像的颜色数量预测每个图像的复杂性。
我如何使Java成为可能?
谢谢。
I have three different images (jpeg or bmp). I'm trying to predict the complexity of each image based on the number of color of each. How could I make it possible with Java? Thank you.
UPDATE:
这些代码不工作..输出显示1312种颜色只有纯红色和白色
UPDATE: These codes doesn't work .. the output shows 1312 colors even it only plain red and white
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class clutters {
public static void main(String[] args) throws IOException {
ArrayList<Color> colors = new ArrayList<Color>();
BufferedImage image = ImageIO.read(new File("1L.jpg"));
int w = image.getWidth();
int h = image.getHeight();
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
int pixel = image.getRGB(x, y);
int red = (pixel & 0x00ff0000) >> 16;
int green = (pixel & 0x0000ff00) >> 8;
int blue = pixel & 0x000000ff;
Color color = new Color(red,green,blue);
//add the first color on array
if(colors.size()==0)
colors.add(color);
//check for redudancy
else {
if(!(colors.contains(color)))
colors.add(color);
}
}
}
system.out.printly("There are "+colors.size()+"colors");
}
}
推荐答案
代码基本正确,而过于复杂。您可以简单地使用 Set
并向其添加 int
值,因为将忽略现有值。您也不需要为每种颜色计算RGB值,因为 getRGB
返回的 int
值是唯一的
The code is basically right, whereas too complicated. You could simply use a Set
and add the int
value to it, as existing values are ignored. You also don't need to calculate the RGB values for each color, as the int
value returned by getRGB
is unique by itself:
Set<Integer> colors = new HashSet<Integer>();
BufferedImage image = ImageIO.read(new File("test.png"));
int w = image.getWidth();
int h = image.getHeight();
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
int pixel = image.getRGB(x, y);
colors.add(pixel);
}
}
System.out.println("There are "+colors.size()+" colors");
您所获得的奇怪颜色数量应归功于图像压缩(在您的示例中为JPEG)和其他原因,如图像编辑软件的反锯齿。即使您仅以红色和白色绘制,生成的图像可能在边缘上的这两个值之间包含许多颜色。
The "strange" number of colors you are getting is owed to image compression (JPEG in your example) and maybe other reasons like anti-aliasing of your image editing software. Even if you paint only in red and white, the resulting image may contain a lot of colors in between of these two values on the edges.
这意味着代码将返回特定图片中使用的真实颜色数量。您还可以查看不同的图像文件格式和无损和有损压缩算法。
That means the code will return the real count of colors used in a particular image. You might also want to have a look on the different image file formats and lossless and lossy compression algorithms.
这篇关于计算图像的颜色数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!