计算两个数组之间偏移的简单方法? Python

Easy way to calculate the shift between two arrays? Python

我有两张 dicom 图像,可以使用下面的代码计算图像的均方误差。但是,与另一幅图像相比,一幅图像可能存在固有的偏移(如果我的成像仪略微未对齐)。有没有一种简单的方法来计算两个 numpy 数组的移位?

我试过将数组在每个方向上移动几个像素并计算最小 MSQ。然而,这还不够健壮。非常感谢任何帮助或建议!

import numpy as np
import dicom

#first image
ds = dicom.read_file("U:\temp\1.dcm")
array1 = ds.pixel_array
#second image
ds1 = dicom.read_file("U:\temp\5.dcm")
array2 = ds1.pixel_array

#shifting image by a number of pixels in any direction
arr1 = np.roll(array2, 100,  axis=1)
imshow(arr1)

def mse(imageA, imageB):
    # the 'Mean Squared Error' between the two images is the
    # sum of the squared difference between the two images;
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
    err /= float(imageA.shape[0] * imageA.shape[1])

    # return the MSE, the lower the error, the more "similar"
    # the two images are
    return err

first_try = mse(array1, array2)
second_try = mse(arr1, array2)

不看图片很难说,对一张图片有用的东西可能对下一张图片不起作用。但是一般尝试:

  • 多尺度估计 - 对数组进行下采样,计算粗略尺度的偏移,并在下一个尺度用这个偏移(对缩放进行补偿)进行初始化。
  • 像绝对差之和这样的可靠错误分数。

如果您确定图像除此偏移外完全相同,认为最佳解决方案是 scipy.signal.correlate2d:

import numpy as np
from scipy.signal import correlate2d

a = np.random.random((200, 200))
b = np.roll(np.roll(a, 15, axis=0),-33, axis=1)

corr = correlate2d(a, b)

shift = np.where(corr==corr.max())
shift = (shift[0]%a.shape[0], shift[1]%a.shape[1])

这给出了正确的值:

(array([184]), array([32]))