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