我的程序遇到了一个小问题,因为它似乎无法在直方图中找到最高值来计算直方图所应的比例,所以现在整个直方图已超出范围
我真的希望有人可以帮助我,因为它让我发疯了
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.filter.*;
public class Oblig3_Oppg2 implements PlugInFilter {
public int setup(String arg, ImagePlus im) {;
return DOES_8G + NO_CHANGES;
}
public void run(ImageProcessor ip) {
final int W = 256;
final int H = 100;
final int H1 = 140;
int[] hist = ip.getHistogram();
int[] KH = new int[W]; //Cumulative Histogram Array
int maxVal;
//Calculates the highest pixel count in the Histogram
for (int i = 0; i < W; i++){
if (hist[i] > maxVal){
maxVal = i;
}
}
KH[0] = hist[0];
for(int i = 1; i < W; i++) {
KH[i] = KH[i-1] + hist[i];
}
ImageProcessor histIp = new ByteProcessor(W, H1);
histIp.setValue(255);
histIp.fill();
int max = KH[255];
for(int j = 0; j < W; j++){
KH[j] = (KH[j]*100)/max; //Scales the Cumulative Histogram
hist[j] = (hist[j]*100)/maxVal; // Scales the Histogram
}
for (int k = 0; k < W; k++){
histIp.setValue(0);
histIp.drawLine(k, H, k, H-KH[k]);
}
for (int k = 0; k < W; k++){
histIp.setValue(0);
histIp.drawLine(k, H, k, H-hist[k]);
}
for (int l = 0; l < W; l++){
histIp.setValue(l);
histIp.drawLine(l, 140, l, 102);
}
histIp.setValue(0);
histIp.drawLine(W, H, W, 0);
// Display the histogram image:
String hTitle = "Histogram";
ImagePlus histIm = new ImagePlus(hTitle, histIp);
histIm.show();
}
}
答案 0 :(得分:3)
您应该将maxVal
设置为实际的值,而不是循环中的当前索引:
for (int i = 0; i < W; i++){
if (hist[i] > maxVal){
maxVal = hist[i]; // <-- here
}
}
此外,最好将循环限制为hist.length
而不是W
。如果您将W
设置为与ip.getHistogram()
返回的数组长度不同的某个值,则可以防止出现错误。
由于您没有提供可运行的示例(即整个Java类;我假设您实现了ij.plugin.filter.PlugInFilter
),我没有测试代码,并且它并不完全向我明确你想要达到的目标。