我编写了一个简单的脚本,使用PIL将几个矩阵格式化为.png 比方说,我有一个大小的张量(n,c,h,w),其中:
现在,我想输出((8 +填充)* 28,(8 +填充)* 28)数组并从中创建一个png。 这是我的代码:
# x = np.random.uniform(0,1,(64,1,28,28))
x = np.zeros((64,1,28,28))
x[0,:,:,:] = 1. # Just to check
def make_grid(x, n_row = 8, n_col = 8, padding = 2):
bw = np.zeros((n_row*x.shape[2], (n_col)*x.shape[3]))
current_row, current_col = 0,0
counter = 0
for i in range(n_row):
for j in range(n_col):
print('[{} {}] --> [{}:{} {}:{}] = {}'.format(i,j,i*x.shape[2],(i+1)*x.shape[2],j*x.shape[3],(j+1)*x.shape[3], np.max(x[counter,0,:,:])))
bw[i*x.shape[2]:(i+1)*x.shape[2],j*x.shape[3]:(j+1)*x.shape[3]] = x[counter,0,:,:]
counter += 1
return bw
def save_image(x, path):
grid = make_grid(x)
grid = np.clip(grid,0,1.)
im = Image.fromarray(grid , mode = 'L')
im.save(path)
这是我在网格上使用matplotlib获得的内容:
我使用PIL获得了什么:
有人可以帮我解决这个问题吗?
谢谢!