我想从 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 的数据类型。要将每个补丁保存为单个图像,我使用以下代码。
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)
修复形状另外,我怎样才能使用保存的图像补丁来重建原始图像?
最佳答案
让我们假设我们首先在做一些更简单的事情。假设我们想要分割一个二维数字数组,而不是一个 2D 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
个窗口:>>> patch_arr = view_as_windows(image_arr, (2,2))
让我们比较两个数组的形状:
>>> image_arr.shape
(5, 5)
>>> patch_arr.shape
(4, 4, 2, 2)
现在,(如果我理解正确的话)您问我们如何使用
image_arr
重建 patch_arr
?我们将要处理它的方式是,我们将创建一个空的 np.array,然后我们将获取每个“补丁”并将它们粘贴到图像上。由于它们是重叠的,这意味着我们将多次向大多数单元格写入相同的值,但这当然不是问题。
您也可以尝试优化这种方法,只对每个单元格写入一次,但我不确定在这种情况下是否值得。
>>> 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.]])
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]
>>> 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 值):
input_img = np.random.rand(512, 512, 3)
patch_img = view_as_windows(input_img, (128, 128, 3), step=64)
>>> reconstructed_arr = np.zeros((512, 512, 3))
step=64
,因此使用了一些小的调整来重建 for 循环。 >>> 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
关于python - 使用 skimage view_as_windows 制作图像补丁和重建补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831987/