[英]Cleanly tile numpy array of images stored in a flattened 1D format
我正在使用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):
# 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)
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.