我正在尝试开发一种采用2d阵列的OCR,用于通过灰度单位测量的光强度值。我使用的方法的目标是准确找出字母在图像2d阵列的水平轴上的位置。但是,我不断在holdArraySum += image[row + addRow][col + addCol];
我已经使用了两个四个循环来循环遍历起始位置,这些起始位置在给定尺寸的子数组中可能出现,以试图避免超出范围。我再使用两个for循环在子数组的维度的高度和宽度之间循环以找到其总和,然后将它们与先前找到的总和进行比较以找到最大的和。我已经实现了What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?中提到的做法,但为什么仍然会出现ArrayIndexOutOfBoundsException,我仍然感到困惑。
/**
* Finds the rectangle of height h and width w within the band
* row0 <= row < row0 + h with the most "ink" in it, or the largest sum in it
* @param int[][] image - A 2d array of light intensity values of each pixel in an image
* @param int h, w - Dimensions of the specified sub-array with height h and width w
* @param int row0 - the index of where it should start constructing sub-arrays
* @return The index of the leftmost column of the sub-array with the smallest sum
*/
public int findHorzPosition(int[][] image, int row0, int h, int w) {
int holdArraySum = 0;
int largestArraySum = 0;
int columnHold = 0;
int columnLargest = row0;
for(int row = row0; row < row0 + h; row++) {
for(int col = 0; col <= image[row].length - 1 - w; col++) {
for(int addRow = 0; addRow < h; addRow++) {
for(int addCol = 0; addCol < w; addCol++) {
holdArraySum += image[row + addRow][col + addCol];
}
}
columnHold = col;
} if(holdArraySum > largestArraySum) {
columnLargest = columnHold;
largestArraySum = holdArraySum;
}
holdArraySum = 0;
columnHold = 0;
}
return columnLargest;
}
解释为什么会发生这种情况会对我有很大帮助。