2016-01-30 236 views
1

我非常适合数字图像处理和编程的初学者。我正在尝试使用光栅来查找图像的平均值。说实话,这是在黑暗中真正的刺,但我真的迷失在这里做什么。查找图像Java的平均值

我的代码目前没有返回任何内容,我不确定它是否甚至在做任何事情。我对它正在做什么的解释是,读取图像文件,然后使用栅格根据高度和宽度共同提取该图像的细节。我希望它能够在控制台上输出平均值。

所以有人可以告诉我我做错了什么,为什么我的代码没有返回图像的意思?我一直在挖掘资源来尝试和学习,但与图像处理相关的任何东西似乎都不适合新手,而且我发现它很难。因此,如果任何人有任何可以开始的地方,我们将不胜感激。

最终,我想计算一个图像上的平均值,然后我想要针对其他图像的文件目录运行该图像。这一点就是根据平均值查看哪些图像最相似。但我觉得我有点偏离自己想去的地方。

这里是我的代码

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.awt.image.Raster; 
import java.io.File; 
import java.io.IOException; 

import javax.imageio.ImageIO; 

public class calculateMean { 

static BufferedImage image; 
static int width; 
static int height; 
public static void main(String[] args) throws Exception{ 
    try{ 
     File input = new File("C:\\Users\\cbirImages\\jonBon2.jpg"); 
     image = ImageIO.read(input); 
     width = image.getWidth(); 
     height = image.getHeight(); 
}catch (Exception c){} 
} 

private double sum; 

public double imageToCalculate(){ 
    int count = 0; 
    for(int i=0; i<height; i++){ 

    for(int j=0; j<width; j++){ 
     count++; 
     Raster raster = image.getRaster(); 
     double sum = 0.0; 

     for (int y = 0; y < image.getHeight(); ++y){ 
      for (int x = 0; x < image.getWidth(); ++x){ 
      sum += raster.getSample(x, y, 0); 
      } 
     } 
     return sum/(image.getWidth() * image.getHeight()); 

     } 
} 
    System.out.println("Mean Value of Image is " + sum); 
    return sum; 

} 

}

+0

感谢您的宝贵意见@gpasch – user1167596

+0

您在哪里调用imageToCalculate方法? –

回答

1

你在你的方法imageToCalculate经过的所有像素的两倍。这个简单的代码就足以计算图像的平均:

for (int y = 0; y < image.getHeight(); ++y) 
    for (int x = 0; x < image.getWidth(); ++x) 
     sum += raster.getSample(x, y, 0) ; 
return sum/(image.getWidth() * image.getHeight()); 

但通常情况下,最好是给图像作为方法的参数:

public double Average(BufferedImage image) 

并为最终目的的项目,平均无法给你一个好的结果。假设您有两个图像:第一个像素为127,第二个像素为0,另一个像素为255。

+1

完美的答案,谢谢:) :) – user1167596

+0

有没有其他方式做到这一点?我已经实现了这一点,但是我已经面临改善的挑战。有任何想法吗?我不知道其他计算平均值比上述。 – user1167596

+0

两种解决方案。 1 /在Java中最快的是使用DataBuffer(image.getRaster()。getDataBuffer()),因为您可以直接访问像素而不使用Raster。 2 /使用JNI来调用C/C++函数。速度要快得多,特别是如果您的映像很大并且使用OpenMP。 – FiReTiTi