0
我有具有2的向下采样率也就是说,我的金字塔的底部是一个形状(256, 256)
,其中一个新的水平是(128, 128)
的图像等图像金字塔如何指定numpy矩阵的子集来放置较小的矩阵?
我的目标是显示该金字塔合并为一个图像。第一张图片放在左边。第二个放在右上角。每个后续图像必须放置在先前的下方并楔入角落。
这里是我当前的功能:
def pyramid2img(pmd):
'''
Given a pre-constructed pyramid, this is a helper
function to display the pyramid in a single image.
'''
# orignal shape (pyramid goes from biggest to smallest)
org_img_shp = pmd[0].shape
# the output will have to have 1.5 times the width
out_shp = tuple(int(x*y) \
for (x,y) in zip(org_img_shp, (1, 1.5)))
new_img = np.zeros(out_shp, dtype=np.int8)
# i keep track of the top left corner of where I want to
# place the current image matrix
origin = [0, 0]
for lvl, img_mtx in enumerate(pmd):
# trying to specify the subset to place the next img_mtx in
sub = new_img[origin[0]:origin[0]+pmd[lvl].shape[0],
origin[1]:origin[1]+pmd[lvl].shape[1]]# = img_mtx
# some prints to see exactly whats being called above^
print 'level {}, sub {}, mtx {}'.format(
lvl, sub.shape, img_mtx.shape)
print 'sub = new_img[{}:{}, {}:{}]'.format(
origin[0], origin[0]+pmd[lvl].shape[0],
origin[1], origin[1]+pmd[lvl].shape[1])
# first shift moves the origin to the right
if lvl == 0:
origin[0] += pmd[lvl].shape[0]
# the rest move the origin downward
else:
origin[1] += pmd[lvl].shape[1]
return new_img
输出打印语句:
level 0, sub (256, 256), mtx (256, 256)
sub = new_img[0:256, 0:256]
level 1, sub (0, 128), mtx (128, 128)
sub = new_img[256:384, 0:128]
level 2, sub (0, 64), mtx (64, 64)
sub = new_img[256:320, 128:192]
level 3, sub (0, 32), mtx (32, 32)
sub = new_img[256:288, 192:224]
level 4, sub (0, 16), mtx (16, 16)
sub = new_img[256:272, 224:240]
level 5, sub (0, 8), mtx (8, 8)
sub = new_img[256:264, 240:248]
level 6, sub (0, 4), mtx (4, 4)
sub = new_img[256:260, 248:252]
如果你查看输出,你可以看到,我想引用一个2D片的输出图像,以便我可以将金字塔的下一层放置在其中。
问题是,我正在执行的切片没有给出我期望的形状的2D数组。它认为我试图将(n,n)矩阵放入(0,n)矩阵中。
为什么当我指定像new_img[256:320, 128:192]
片,它返回一个对象,具有形状(0, 64)
,不(64, 64)
?
有没有更简单的方法来做我想做的事情?
哗一下这是一个聪明的方法!非常感谢你:) 我开始阅读关于numpy切片/大踏步前进http://stackoverflow.com/questions/4257394/slicing-of-a-numpy-2d-array-or-how-do-i-extract -an-mxm-submatrix-from-an-nxn-ar 这似乎是一场噩梦。您的解决方案非常直观。谢谢。 – spanishgum