重磅干货,第一时间送达 同形转换 我们所常见的都是以这样的方式来处理图像:检测斑点,分割感兴趣的对象等。我们如何将它们从一种形式转换为另一种形式来处理这些图像呢?通过单应矩阵快速转换图像可以实现这个需求。 单应性,也被称为平面单应性,是两个平面之间发生的转换。换句话说,它是图像的两个平面投影之间的映射。它由同构坐标空间中的3x3转换矩阵表示。在数学上,同质矩阵表示为: 如图所示,图像中的元素在同一个坐标平面中投影到另一幅图像,保留了相同的信息,但具有变换的透视图。现在,让我们使用Python代码实现这一操作。与往常一样,在我们实际执行此操作之前。必须导入以下库: from skimage.io import imread, imshow from skimage import transform import matplotlib.pyplot as plt import numpy as np 我们将在本文中使用多个图像。通过单击标题中嵌入的链接来下载图像。考虑一下这个棋盘: chess = imread('chess.png') imshow(chess) 假设你们想改为看到木板及其零件的鸟瞰图。是否可以仅使用图像中的信息来做到这一点?在这种情况下,你们要做的就是找到木板的角并将其设置为原坐标。之后,在要进行单应性投影的同一图像中,选择要显示变换后的图像的目标坐标。该代码已实现: #source coordinates src = np.array([391, 100, 14, 271, 347, 624, 747, 298,]).reshape((4, 2)) #destination coordinates src = np.array([100, 100, 100, 650, 650, 650, 650, 100,]).reshape((4, 2)) #using skimage’s transform module where 'projective’ is our desired parameter tform = transform.estimate_transform('projective', src, dst) tf_img = transform.warp(chess, tform.inverse) #plotting the transformed image fig, ax = plt.subplots() ax.imshow(tf_img) _ = ax.set_title('projective transformation') 既然我们已经做到了,那么考虑到目标图像来自其他图像的情况,我们又如何处理另一个图像呢?让我们来看这个例子。考虑一下这张图像,一场篮球比赛。 still2 = imread('still2.png') imshow(still2) 假设我们有兴趣通过单应性法改变球场的一半。首先,从上面的图像(即半场的角)确定原坐标。然后,从另一幅与上述图像完全不同的图像中找到我们的目的地坐标。我们正在谈论的另一个图像如下所示: court = imread('court.png') plt.imshow(court) 让我们通过代码实际看到这一点: src_2 = np.array([440, 470, 10, 750, 1190, 490, 1195, 785,]).reshape((4, 2)) dst_2 = np.array([3, 7, 3, 506, 447, 7, 447, 506,]).reshape((4, 2)) fig, ax = plt.subplots(3, 1, figsize=(25, 15)) ax[0].imshow(still2, ) ax[0].scatter(src_2[:,0], src_2[:,1], c='red', s=30) ax[0].set_title('source coordinates') ax[1].imshow(court) ax[1].scatter(dst_2[:,0], dst_2[:,1], c='red', s=30) ax[1].set_title('destination coordinates') dst_2 = dst_2*2 #because image sizes are not the same. tform = transform.estimate_transform('projective', src_2, dst_2)tf_img = transform.warp(still2, tform.inverse) ax[2].imshow(tf_img) ax[2].scatter(dst_2[:,0], dst_2[:,1], c='red', s=10)
就这样利用单应矩阵来进行变换图像,现在,我们不仅可以从另一个角度来看待球场上的玩家,而且仍然保留了原始角度的相关信息。 |
|