我想知道第31行上loc位置的公式,但我無法弄清楚。任何人都可以指導我解決問題嗎?處理:由於嵌套循環而在陣列中定義位置時遇到的困難
PImage theImage;
int cellSize = 6; // dimension of a cell where logic is applied
int cols, rows; // number of rows and columns based on cellsize
int col; // column in the cell
int row; // row in the cell
float edgeR; // (amount of red in the corners)
float edgeB; // (amount of blue in the corners)
float edgeG; // (amount of green in the corners)
float middleR; // (amount of red in the center)
float middleB; // (amount of blue in the center)
float middleG; // (amount of green in the center)
void setup()
{
size(1570,1112); // fits the image
theImage = loadImage("im.png"); // load the image
cols = width/cellSize ; // number of colums in the grid of the image
rows = height/cellSize ; // number of rows in the grid of the image
}
void draw()
{
background(0);
loadPixels();
theImage.loadPixels(); // load every pixel of the image in an array
image(theImage,0,0); // display the image at pos 0 0
for (int i=0; i< rows;i++) {
for (int j = 0; j< cols;j++) { // loop matrix of cells
for (int x = i*cellSize; x<i*cellSize+cellSize;x++) {
for (int y = j*cellSize; y<j*cellSize+cellSize;y++) { //
loop every pixel of the cell
---> int loc = (i*cellSize+x) +
(j*cellSize*width+y*cellSize*width); // grrrrr <-----
float r = red(theImage.pixels[loc]); // red value
float g = green(theImage.pixels[loc]); // green value
float b = blue(theImage.pixels[loc]); // blue value
if (x - i*cellSize <= cellSize /3) { // it is in a column 1
col = 1;
}
else if (x - i*cellSize >= cellSize*2/3) { // it is in a column 3
col = 3;
}
else {
col = 2; // it is in a column 2
}
if (y - j*cellSize <= cellSize /3) { // it is in row 1
row = 1;
}
else if (y - j*cellSize >= cellSize*2/3) { // it is in row 3
row = 3;
}
else { // in row 2
row = 2;
}
if (col == 1 & row ==1 || (col == 3 & row == 3) || (col == 1 & row == 3) || (col == 3 & row == 1)) {
edgeR = edgeR + r; // aggregate the edge color values
edgeG = edgeG + g;
edgeB = edgeB + b;
}
else {
middleR = middleR + r; // aggregate the center color values
middleG = middleG + g;
middleB = middleB + b;
// here some magic will be applied if there would be no ArrayIndexOutOfBoundsException: 1745840 error
}
}
}
}
}
}
當我運行代碼的輸出窗口凍結,我得到一個ArrayIndexOutOfBoundsException:1752120錯誤/如果我把調試就這還要不停地說:調試忙。
我敢肯定祿位置不正確,但我沒有一個知道如何解決公式。此外,嵌套for循環也可能是問題。
非常感謝您的幫助,非常感謝。
一切順利,
添
四重嵌套循環...有什麼可能出錯! :)嚴肅地說,註釋掉除最外層循環以外的所有內容,並且放入一些調試打印語句來測試你期望的循環邊界。然後每次添加一個循環來診斷問題的真實位置。 – Jeremy
謝謝Jeremy,但我的診斷是在第31行,我嘗試給r賦值,根據位置loc,因爲loc是計算loc的公式不正確,它會得到一個worong值並導致錯誤。或者你的意思是說這個診斷是不正確的? –
要與下面的答案對話...從較小的圖像開始。比如5 x 5或10 x 10 ...可調試的東西。使用紙或excel來計算您的期望值的上限,然後驗證您的公式是否給您預期的結果。 – Jeremy