所以我有以下問題:我有一個方法將一個大矩陣分成相同大小的較小塊。在我對塊進行了一些操作之後,我想按照正確的順序重構這個大矩陣,但是我會以某種方式出錯。整個矩陣塊的列表 - java
以下代碼正確地重建了一個4x4矩陣,該矩陣可以分解爲2x2,但對於任何其他維度而言,它無法正常工作。
public long[][] blocksToMatrix(List<long[][]> blocks, int blockDimension, int width, int height){
long[][] yuvMatrix = new long[height][width];
int heightPos = 0;
int widthPos = 0;
for (int i = 0; i < blocks.size(); i++) {
long[][] yuvBlock = blocks.get(i);
int heightPosTemp = heightPos;
for (int j = 0; j < blockDimension * blockDimension; j++) {
yuvMatrix[heightPos][widthPos] = yuvBlock[j/blockDimension][j % blockDimension];
widthPos++;
if (widthPos >= width){
widthPos = (i * blockDimension) % width;
heightPos++;
}
if (widthPos == ((i + 1) * blockDimension) % width){
widthPos = (i * blockDimension) % width;
heightPos++;
}
}
if (heightPos == height){
heightPos = heightPosTemp;
}
else {
heightPos = (i * blockDimension) % height;
}
widthPos = ((i + 1) * blockDimension) % width;
}
return yuvMatrix;
}
我用來打破的矩陣的方法:
public static void testareMatBlo(int height, int width, int blockdim){
long[][] test = new long[height][width];
int val = 1;
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
test[i][j] = val;
val++;
}
}
List<long[][]> blocks = matrixToBlocks(test, blockdim, width, height);
long[][] matrix = blocksToMatrix(blocks, blockdim, width, height);
if (Arrays.deepEquals(test, matrix)){
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
這工作:
testareMatBlo(4, 4, 2);
但什麼都沒有按
public List<long[][]> matrixToBlocks(long[][] yuvMatrix, int blockDimension, int width, int height){
int blocksSize = width/blockDimension * (height/blockDimension);
List<long[][]> blocks = new ArrayList<long[][]>();
for (int i = 0; i < blocksSize; i++) {
long[][] subBlock = new long[blockDimension][blockDimension];
int heightPos = (blockDimension * (i/blockDimension)) % height;
int widthPos = (blockDimension * i) % width;
if (widthPos + blockDimension > width) {
widthPos = 0;
}
for (int row = 0; row < blockDimension; row++) {
for (int col = 0; col < blockDimension; col++) {
subBlock[row][col] = yuvMatrix[heightPos + row][col + widthPos];
}
}
blocks.add(subBlock);
}
return blocks;
}
我測試了它的方式「T。任何人都可以解釋我做錯了什麼?
上'matrixToBlocks幾側音符(長[] [] yuvMatrix,整數blockDimension,INT寬度,高度INT)'(和'blocksToMatrix(...)'):假定'width'和'高度意思是你可能不需要它們的矩陣的維數,因爲你已經可以像'yuvMatrix.length'和'yuvMatrix [0] .length'那樣得到它們(假設你可以相信第二維總是具有相同的尺寸)。另外,你應該確保'blockDimension'是矩陣維數的一個因素,否則你可能在分解成塊的時候遇到困難(例如,將5×5矩陣分解成2×2塊)。 – Thomas
是的,我已經知道所有這些,但是謝謝你提醒我。在我讓他們工作之後,我正在清理這些方法,現在他們有點混亂。 – Pred
You'r'blocksToMatrix(...)'缺少一些代碼:'long [] [] yuvBlock = blocks.get(i);' - 'i'沒有在您發佈的代碼中定義。 – Thomas