[英]How to compare two 2D arrays of different sizes in C++?
我正在嘗試實現二進制圖像匹配算法。 我需要生成下面給出的C矩陣。 給定較小的圖案圖像A,我需要將其與大圖像逐行和逐列匹配,以找到該圖案最匹配的位置。
給定M x M尺寸的圖案A:
0 0 1
0 1 1
1 1 1
和N x N大小的輸入圖像B:
0 0 0 0 0 1 0 0
0 0 0 0 1 1 0 0
0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0
1 1 1 0 0 0 1 0
0 0 0 0 0 0 1 0
0 0 0 1 1 1 1 0
0 0 0 0 0 0 0 0
N×N大小的輸出圖像C是A在B的每一行和每一列與B的相似度。因此C:
0 0 0 0 0 0 0 0
0 3 4 6 9 4 2 0
0 3 4 6 4 1 1 0
0 6 6 4 2 2 3 0
0 4 3 2 3 5 5 0
0 2 2 4 6 8 5 0
0 3 4 5 4 5 2 0
0 0 0 0 0 0 0 0
我處於需要比較矩陣A和B的問題上。我將它們制成2D數組。
這是我到目前為止所做的
for (int i = 0; i <3 ; i++)
{
for (int j = 0; j<3; j++)
{
for (int k = 0; k < 8; i++)
{
for (int s = 0; s < 8; j++)
{
if (A[i][j] == B[k][s])
{
count++;
}
}
}
}
您的代碼或算法是什么? 矩陣中有9個,所以
0 0 1
0 1 1
1 1 1
完全匹配。 您必須在尋找坐標對。
typedef int** matrix;
struct position
{
int x;
int y;
position(int _x,int _y){ x = _x ; y= _y; }
}
// M <= N
//checks all MxM submatrices in NxN matrix B
//and compares them with NxN matrix A
position f(matrix A, int M , matrix B , int N)
{
int best_match_first_row = -1;
int best_match_first_column = -1;
int best_match_counted = -1;
for(int i=0; i <= N-M ; ++i)// iterate through the first elements of every
for(int j=0; j <= N-M ; ++j)// MxM submatrix
{
int match_count = 0;
for(int k=0 ; k < M ; ++k)//iterate through the submatrix
for(int l=0 ; l < M ; ++l)//and compare elements with matrix A
if( A[k][l] == B[i+k][j+l] ) ++match_count; //count if it matches
if(match_count > best_match_counted) //if we have a better match than before
{
best_match_counted = match_count; //store the new count as best.
best_match_first_row = i; //store the position of the
best_match_first_column = j; //first element in the submatrix
}
}
//returns the position of the first element of the most matching submatrix
return position( best_match_first_row , best_match_first_column )
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.