python – numpy / scipy,遍历子数组

最近我一直在对8×8图像数据块进行大量处理.

标准方法是使用嵌套的for循环来提取块,例如

for y in xrange(0,height,8):
    for x in xrange(0,width,8):
        d = image_data[y:y+8,x:x+8]
        # further processing on the 8x8-block

我不禁想知道是否有办法使用我可以使用的numpy / scipy来操作此操作或其他方法?某种迭代器?

一个MWE1:

#!/usr/bin/env python

import sys
import numpy as np
from scipy.fftpack import dct, idct
import scipy.misc
import matplotlib.pyplot as plt

def dctdemo(coeffs=1):
    unzig = np.array([
         0,  1,  8, 16,  9,  2,  3, 10,
        17, 24, 32, 25, 18, 11,  4, 5,
        12, 19, 26, 33, 40, 48, 41, 34,
        27, 20, 13,  6,  7, 14, 21, 28,
        35, 42, 49, 56, 57, 50, 43, 36,
        29, 22, 15, 23, 30, 37, 44, 51,
        58, 59, 52, 45, 38, 31, 39, 46,
        53, 60, 61, 54, 47, 55, 62, 63])

    lena = scipy.misc.lena()
    width, height = lena.shape

    # reconstructed
    rec = np.zeros(lena.shape, dtype=np.int64)

    # Can this part be vectorized?
    for y in xrange(0,height,8):
        for x in xrange(0,width,8):
            d = lena[y:y+8,x:x+8].astype(np.float)
            D = dct(dct(d.T, norm='ortho').T, norm='ortho').reshape(64)
            Q = np.zeros(64, dtype=np.float)
            Q[unzig[:coeffs]] = D[unzig[:coeffs]]
            Q = Q.reshape([8,8])
            q = np.round(idct(idct(Q.T, norm='ortho').T, norm='ortho'))
            rec[y:y+8,x:x+8] = q.astype(np.int64)

    plt.imshow(rec, cmap='gray')
    plt.show()

if __name__ == '__main__':
    try:
        c = int(sys.argv[1])
    except ValueError:
        sys.exit()
    else:
        if 1 <= int(sys.argv[1]) <= 64:
            dctdemo(int(sys.argv[1]))

脚注:

>实际应用:https://github.com/figgis/dctdemo

最佳答案 在Scikit Image中有一个函数view_as_windows

> http://scikit-image.org/docs/dev/api/skimage.util.html#view-as-windows

不幸的是,我将不得不再次完成这个答案,但你可以以一种形式抓住窗户,你可以传递给dct:

from skimage.util import view_as_windows
# your code...
d = view_as_windows(lena.astype(np.float), (8, 8)).reshape(-1, 8, 8)
dct(d, axis=0)
点赞