gpt4 book ai didi

python - numpy/scipy,遍历子数组

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:56 25 4
gpt4 key购买 nike

最近我一直在对 8x8 图像数据 block 进行大量处理。标准方法是使用嵌套的 for 循环来提取 block ,例如

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]))

脚注:

  1. 实际申请:https://github.com/figgis/dctdemo

最佳答案

在 Scikit Image 中有一个函数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)

关于python - numpy/scipy,遍历子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23527825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com