Python 以扁平1D格式存储的图像的干净平铺numpy阵列
我正在用Numpy从.csv文件加载一组16x16图像。每一行是存储在CMO中的256个灰度值的列表(因此形状是(n,256),其中n是图像的数量)。这意味着我可以使用pyplot将任何单个图像显示为:Python 以扁平1D格式存储的图像的干净平铺numpy阵列,python,numpy,matplotlib,Python,Numpy,Matplotlib,我正在用Numpy从.csv文件加载一组16x16图像。每一行是存储在CMO中的256个灰度值的列表(因此形状是(n,256),其中n是图像的数量)。这意味着我可以使用pyplot将任何单个图像显示为: plot.imshow(np.reshape(images[index], (16,16), order='F'), cmap=cm.Greys_r) 我想用每行一定数量的图像平铺这些图像。我有一个可行的解决方案: def TileImage(imgs, picturesPerRow=16):
plot.imshow(np.reshape(images[index], (16,16), order='F'), cmap=cm.Greys_r)
我想用每行一定数量的图像平铺这些图像。我有一个可行的解决方案:
def TileImage(imgs, picturesPerRow=16):
# Convert to a true list of 16x16 images
tmp = np.reshape(imgs, (-1, 16, 16), order='F')
img = ""
for i in range(0, tmp.shape[0], picturesPerRow):
# On the last iteration, we may not have exactly picturesPerRow
# images left so we need to pad
if tmp.shape[0] - i >= picturesPerRow:
mid = np.concatenate(tmp[i:i+picturesPerRow], axis=1)
else:
padding = np.zeros((picturesPerRow - (tmp.shape[0] -i), 16, 16))
mid = np.concatenate(np.concatenate((tmp[i:tmp.shape[0]], padding), axis=0), axis=1)
if img == "":
img = mid
else:
img = np.concatenate((img, mid), axis=0)
return img
这样做很好,但感觉应该有更干净的方法来做这类事情。我是Numpy的新手,我想知道是否有一种更干净的方法来平铺平坦的数据,而不需要所有的手动填充和条件连接
通常,这些简单的数组整形操作可以用Numpy在几行中完成,所以我觉得我遗漏了一些东西。(另外,将“”用作标志(就好像它是空指针一样)似乎有点混乱)这里是您的实现的简化版本 想不出更简单的方法
def TileImage(imgs, picturesPerRow=16):
""" Convert to a true list of 16x16 images
"""
# Calculate how many columns
picturesPerColumn = imgs.shape[0]/picturesPerRow + 1*((imgs.shape[0]%picturesPerRow)!=0)
# Padding
rowPadding = picturesPerRow - imgs.shape[0]%picturesPerRow
imgs = vstack([imgs,zeros([rowPadding,imgs.shape[1]])])
# Reshaping all images
imgs = imgs.reshape(imgs.shape[0],16,16)
# Tiling Loop (The conditionals are not necessary anymore)
tiled = []
for i in range(0,picturesPerColumn*picturesPerRow,picturesPerRow):
tiled.append(hstack(imgs[i:i+picturesPerRow,:,:]))
return vstack(tiled)
希望有帮助。这里是您的实现的简化版本 想不出更简单的方法
def TileImage(imgs, picturesPerRow=16):
""" Convert to a true list of 16x16 images
"""
# Calculate how many columns
picturesPerColumn = imgs.shape[0]/picturesPerRow + 1*((imgs.shape[0]%picturesPerRow)!=0)
# Padding
rowPadding = picturesPerRow - imgs.shape[0]%picturesPerRow
imgs = vstack([imgs,zeros([rowPadding,imgs.shape[1]])])
# Reshaping all images
imgs = imgs.reshape(imgs.shape[0],16,16)
# Tiling Loop (The conditionals are not necessary anymore)
tiled = []
for i in range(0,picturesPerColumn*picturesPerRow,picturesPerRow):
tiled.append(hstack(imgs[i:i+picturesPerRow,:,:]))
return vstack(tiled)
希望能有帮助