我有一个图像阵列,我需要在100x100的碎片上分解它,然后用它进行操作收集回原始图像。问题:我不能收回件,我有这样的东西,
但真实的图像是800x800
我的代码:
将图像作为数组,删除第三维
path_to_image = './la3.jpg'
image_array = plt.imread(path_to_image)
image_array = image_array[:, :, 0]
写入新的数组件100x100(工作正常):
main2_array = np.zeros(10000,)
for row in tqdm_notebook(range(0,8)):
for col in range(0,8):
main2_array = np.vstack((main2_array, image_array[0 + (100*row):100 + (100*row) ,0 + (100*col):100 + (100*col)].flatten()))
main2_array = np.delete(main2_array, main2_array[0] , axis=0 )
收回件(它不起作用)
main_array = np.zeros(100,)
for p in tqdm_notebook(range(0,100)):
for i in range(0,64):
main_array = np.vstack((main_array, main2_array[0 + (10000*i) + (100*p): 100 + (10000*i) + (100*p)]))
main_array = np.delete(main_array, main_array[0] , axis=0 )
收集完毕后,我得到了
假图像
x, y = 800,800
img_array = np.arange(x*y).reshape((x,y))
解构后,main2_array.shape
是(64,10000);每行是一个扁平的100x100补丁。在解构过程中,您从左到右,从上到下穿过图像,并在前一个补丁下方滑动每个补丁。
重建逆转过程:
main_array = np.zeros((x,y))
for n, patch in enumerate(main2_array):
patch = patch.reshape(100,100)
# eight patches per row
row, col = divmod(n, 8)
row_offset, col_offset = row*100, col*100
row_slice = slice(row_offset, 100 + row_offset)
col_slice = slice(col_offset, 100 + col_offset)
#print(np.all(patch == image_array[row_slice,col_slice]))
main_array[row_slice, col_slice] = patch
>>> np.all(main_array == img_array)
True
>>>
或者你可以重新塑造你原来的方式
>>> b = main2_array.reshape(8,8,100,100)
>>> b[0,1].shape # row zero column 1?
(100, 100)
>>> np.all(b[0,1] == a[0:100, 100:200])
True
>>>
>>> c = np.swapaxes(b, 1,2)
>>> c.shape
(8, 100, 8, 100)
>>> np.all(c[0,:,1,:] == a[0:100, 100:200]) # row zero column 1?
True
>>> d = c.reshape(800,800)
>>> np.all(d==img_array)
True
>>>
有点晚了,但我相信这个问题应该得到一个更加图解的答案。
你不需要慢循环,你可以用numpy
重塑和花式索引来完成所有这一切。
让我们从一个示例图像开始
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import skimage.transform
import skimage.data
img = skimage.data.chelsea()
# crop from (300, 451, 3) to (300, 300, 3)
img = img[:,80:380,:]
# resize to (800, 800)
img = skimage.transform.resize(img, (800,800))
plt.imshow(img)
在64
100*100
瓷砖中分解图像。新的形状是(8, 100, 8, 100, 3)
,你可以用img[i, :, j, :, ...]
解决单个图像。除了可能更容易阅读之外,无需将它们存储在新阵列中。
img = img.reshape(8, 100, 8, 100, 3)
gs = mpl.gridspec.GridSpec(8,8)
for i in range(8):
for j in range(8):
ax = plt.subplot(gs[i,j])
ax.imshow(img[i,:,j,:,...])
现在让我们对瓷砖进行一些操作。
清除一些随机的瓷砖
cells = np.random.randint(8, size=(20,2))
img[cells[:,0],:,cells[:,1],...] = 1
翻转并从左到右翻转
img = img[:,::-1,:,::-1,...]
添加黑色边框
img[:,:6,...] = 0
img[:,-6:,...] = 0
img[:,:,:,:6,...] = 0
img[:,:,:,-6:,...] = 0
并绘制它们
for i in range(8):
for j in range(8):
ax = plt.subplot(gs[i,j])
ax.imshow(img[i,:,j,:,...])
现在重建你可以重塑原始形状
img = img.reshape(800, 800, 3)
plt.imshow(img)