簡體   English   中英

循環遍歷 java 中的兩個矩陣

[英]Looping through two matrices in java

我是 java 和一般編程的新手,我有一個從 Android 的圖像中識別文本的項目。 我在 Android Studio 工作,目前我有兩個矩陣——一個是從設備庫中獲取的源圖像的值,一個是模板圖像的值。 矩陣中的值基本上是像素的colors,灰度工作,分為6個區間:255-214的顏色值等於0,172-213的顏色值等於0.2,129-171的顏色值等於0.4等。

我需要在兩個矩陣中逐行 go 並對它們進行一些計數 - 在源矩陣的第一行中取第一個值,在模板矩陣的第一行中取第一個值,並在公式中使用它:

nIntensity = 1 - abs(template_value - source_value)

並對一行中的所有值執行此操作,然后將這些值和 go 相加到第二行並執行相同操作(導致 x 矩陣行的 x nIntensity 值數組)。 我一開始嘗試的是使用嵌套循環,但我對它們有點過度了:

for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
    for(int sColumn = 0; sColumn < 1; sColumn++) {
        for(int pRow = 0; pRow < patternMatrix.length; pRow++) {
            for(int pColumn = 0; pColumn < 1; pColumn++) {
                nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));}}}}

這導致 nIntensity 變量的值太高 - 對於 sourceMatrix 和 patternMatrix 有 56 個值等於 1.0 我應該得到數字 56 的結果,而不是我得到 3192,這意味着它在所有循環中運行了太多次。 使用sColumn < 1pColumn < 1我試圖從一開始就變得簡單,只取兩個矩陣的第一行,然后再深入研究它並使用多行。

在做了一些研究之后,我試着用代碼讓它變得非常簡單:

for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
    for (int sColumn = 0; sColumn < 1; sColumn++) {
         nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
         System.out.println("Result: " + nIntensity);}}

當我在每個循環實際到達結果 56 后打印結果時,它會崩潰,但出現異常

引起:java.lang.ArrayIndexOutOfBoundsException: length=56; 指數=56

您以錯誤的方式嵌套了循環。

代替

for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
    for(int sColumn = 0; sColumn < 1; sColumn++) {
        for(int pRow = 0; pRow < patternMatrix.length; pRow++) {
            for(int pColumn = 0; pColumn < 1; pColumn++) {
                nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));}}}}

for(int sRow = 0, pRow=0; sRow < sourceMatrix.length && pRow < patternMatrix.length; sRow++, pRow++) {
    for(int sColumn = 0; sColumn < 1; sColumn++) {
        nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));
    }
}

此外,在以下代碼塊中,您沒有檢查patternMatrix的邊界。 替換此代碼塊

for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
    for (int sColumn = 0; sColumn < 1; sColumn++) {
         nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
         System.out.println("Result: " + nIntensity);}}

for(int sRow = 0; sRow < sourceMatrix.length && sRow < patternMatrix.length; sRow++) {
    for (int sColumn = 0; sColumn < 1; sColumn++) {
         nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
         System.out.println("Result: " + nIntensity);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM