使用skimage view_as_windows制作图像补丁和重建补丁

Using skimage view_as_windows to make image patches and reconstruct patches

我想从 512x512 彩色图像中提取彩色图像块,并将它们作为单独的图像块保存在文件夹中。我如何从这些图像块中重建我的原始图像? 我已经阅读并查看了一些类似的问题,但它们并没有解决我的问题。

我读了一些书,决定使用 SKimage 的 view_as_windows 函数来执行我的图像修补。我还设法将我的补丁保存到 png 文件中。

目前使用 SKimage view_as_window 从大小为 512x512 patch_img = view_as_windows(input_img, (128, 128, 3), step=64) 的彩色图像中提取色块,当显示输出数组的细节时,我注意到 patch_img 的形状为 (7 , 7, 1, 128, 128, 3) 和 unint8 的 dtype。要将每个补丁保存为单独的图像,我使用以下代码。

    for i in range(0, len(patch_img)):    #range should be 0 to 6
        for x in range(0, len(patch_img)):
            fname= 'IMG_test_{}_{}.png'.format(i, x)
            #cv2.imwrite(fname, crop_img[i,x,0,:,:,:])

当使用 CV2 加载包含已保存图像的整个文件夹时,我无法取回与 patch_img 相同的形状和数据类型,相反,我得到了一个形状 (49, 128, 128, 3) .我该如何解决这个问题。

编辑:使用 savedimg = savedimg.reshape(7,7,128 128, 3)

修复了形状

另外,如何使用保存的图像块重建原始图像?

让我们假设我们首先在做一些更简单的事情。假设我们想要拆分一个二维数字数组,而不是二维 RGB 数组,如下所示:

>>> image_arr = np.array(list(range(1, 26))).reshape((5,5))
>>> image_arr
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.],
       [11., 12., 13., 14., 15.],
       [16., 17., 18., 19., 20.],
       [21., 22., 23., 24., 25.]])

现在,假设我们要将其拆分为 2x2 windows:

>>> patch_arr = view_as_windows(image_arr, (2,2))

我们来比较一下两个数组的形状:

>>> image_arr.shape
(5, 5)
>>> patch_arr.shape
(4, 4, 2, 2)

现在,(如果我理解正确的话)你问我们如何使用 patch_arr?

重建 image_arr

我们将采用的方法是创建一个空的 np.array,然后我们将获取每个 'patches' 并将它们粘贴到图像上。由于它们重叠,这意味着我们将多次向大多数单元格写入相同的值,但这当然不是问题。

您也可以尝试优化这种方法,使每个单元格只写入一次,但我不确定在这种情况下是否值得。

  1. 让我们创建空数组
>>> reconstructed_arr = np.zeros(shape=(5,5))
>>> reconstructed_arr
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
  1. 我们现在将遍历补丁并将它们粘贴到 reconstructed_arr:
for x in range(patch_arr.shape[0]):
    for y in range(patch_arr.shape[1]):
        reconstructed_arr[x:x + 2, y:y + 2] = patch_arr[x,y]
  1. 就是这样
>>> reconstructed_arr
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.],
       [11., 12., 13., 14., 15.],
       [16., 17., 18., 19., 20.],
       [21., 22., 23., 24., 25.]])

需要对您的数据应用类似的方法(这次使用另一个轴表示 RGB 值):

  1. 生成随机 input_img 数组
input_img = np.random.rand(512, 512, 3)
  1. 让我们像您一样创建补丁:
patch_img = view_as_windows(input_img, (128, 128, 3), step=64)
  1. 重构空数组:
>>> reconstructed_arr = np.zeros((512, 512, 3))
  1. 用一些小的调整重建 for 循环,因为你使用了 step=64
>>> step = 64
>>> for x in range(patch_img.shape[0]):
        for y in range(patch_img.shape[1]):
            x_pos, y_pos = x * step, y * step
            reconstructed_arr[x_pos:x_pos + 128, y_pos:y_pos + 128] = patch_img[x, y, 0, ...]
>>> (input_img == reconstructed_arr).all()
True