Calculate the displacement distance of two images

Calculation principle

First, for each pixel (i, j), calculate the sum of the difference between image 1 and image 2 in the 2H 2W rectangular area centered on (i, j), and calculate the area (400) and the image The boundary has made a certain limit judgment, and then the minimum value of the sum of the difference and the mean value is used as the best matching position. Finally, the function calculates the translation (dx, dy) and distance (distance) of image 2 relative to image 1 based on the best matching position.

Code

void CalPos(unsigned char* img1, unsigned char* img2, int h, int w, int *dx, int *dy, int *distance)
{
	int H, W;
	int i, j, ii, jj;
	int p1i, p1j;

	double minval = 9999;
	int mini = 0;
	int minj = 0;
	double val, sum, cnt, mincnt = 0;
	
    //取中心50*50的区域计算减少计算量加速
	H = 50;//h;
	W = 50;//w;

	unsigned char* img1_temp = malloc(H*W);
	unsigned char* img2_temp = malloc(H*W);
	

	for(i=0;i<H;i++)
	{
		for(j=0;j<W;j++)
		{
			img1_temp[i*W+j]=img1[((h-H)/2+i)*w+((w-W)/2)+j];
			img2_temp[i*W+j]=img2[((h-H)/2+i)*w+((w-W)/2)+j];
		}
	}

	for (i = 0; i < 2 * H; i++)
	{
		for (j = 0; j < 2 * W; j++)
		{
			cnt = 0;
			sum = 0;
			for (ii = 0; ii < H; ii++)
			{
				for (jj = 0; jj < W; jj++)
				{
					p1i = i + ii - H; p1j = j + jj - W;
					if ((p1i < H - 1 && p1i > 2 && p1j < W - 1 && p1j > 0) &&
						(ii < H - 1 && ii > 2 && jj < W - 1 && j > 0))
					{
						val = img1_temp[p1i*W + p1j] - img2_temp[ii*W + jj];
						if (val<0)
							val = -val;
						sum = sum + val;
						cnt = cnt + 1;
					}
				}
			}
			if (cnt>400)
				val = sum / cnt;
			else
				val = 255;
			if (val == 0)
				val = 1;
			if (val < minval)
			{
				minval = val;
				mini = i;
				minj = j;
				mincnt = cnt;
			}
		}
	}
	if (mincnt>0)
	{
		*dx = W - minj;
		*dy = mini - H;
		//*dif = minval;
		*distance = sqrt((*dx)*(*dx)+(*dy)*(*dy));
	}
	printf("minval %d\n",(int)(minval*100));
	if(img1_temp)
		free(img1_temp);
	if(img2_temp)
		free(img2_temp);
	return;
}

operation result:

The displacement distance calculated by the two unmoved images is 0

 

Guess you like

Origin blog.csdn.net/L888666Q/article/details/131002317