我正在嘗試僅使用 NumPy 來實現圖像卷積代碼,類似于cv2.filter2D(...)的做法。import numpy as npimport time# kernalH = np.array([[0,1,0],[1,-4,1],[0,1,0]])# imageSEED = 23img = np.random.RandomState(SEED).randint(10, size=(4, 4))# shapesHi, Wi = img.shapeHk, Wk = H.shapehk = Hk//2wk = Wk//2# paddingnew_img = np.pad(img, (hk, wk), 'constant', constant_values=0)pHi, pWi = new_img.shapeprint('img: ')print(new_img)print('kernal: ')print(H)print('\n')# image convolution################################################### Method 1st = time.time()out = np.zeros((Hi, Wi))for i in range(hk, pHi-hk): for j in range(wk, pWi-wk): batch = new_img[i-hk:i+hk+1, j-wk:j+wk+1] out[i-hk][j-wk] = np.sum(batch*H)print('out: ')print(out)print("[*] process time : %f" % (time.time()- st))print('\n')################################################### Method 2st = time.time()Hi, Wi = img.shapeout = np.zeros((Hi, Wi))H_1d = H.ravel()hl = len(H_1d)for i in range(Wi): img_slice = new_img[:, i:Hk+i] for j in range(Hi): out[j][i] = np.sum(img_slice[j:j+Hk,:]*H) il = len(img_slice) h1 = 0 h2 = hl while h2 <= il: index = h1//Hk # print(index) out[index][i] = np.sum(img_slice[h1:h2]*H_1d) h1 = h1 + Hk h2 = h2 + Hkprint('out: ')print(out)print("[*] process time : %f" % (time.time()- st))print('\n')##################################################它有效,但我需要更快、更有效的實施。為了使算法更快,我嘗試在此處查看圖像的卷積過程中找到模式,但仍然無法弄清楚應該做什么。有人可以幫助我改進當前的代碼,使其更快,僅使用 NumPy 嗎?
1 回答

交互式愛情
TA貢獻1712條經驗 獲得超3個贊
這是使用 strides 的更快方法(請注意,view_as_windows在底層使用 numpy strides。如果您必須嚴格使用 numpy,只需使用 numpy 包中的 strides 即可。了解 numpy 中的等效實現view_as_windows):
from skimage.util import view_as_windows
out = view_as_windows(new_img, (Hk,Wk))
out = np.einsum('ijkl,kl->ij',out,H)
輸出:
out:?
[[? 0? -5 -10 -19]
?[-10? -7? -2 -18]
?[? 5? -7? 11? ?7]
?[-12? -9? 11 -18]]
輸入的時間:
#Method 1
[*] process time : 0.000615
#Method 2
[*] process time : 0.000475
#proposed method in this answer
[*] process time : 0.000348
較大陣列的計時使用benchit:
(方法2對于較大的數組有錯誤)
方法 3 比方法 1 快幾個數量級。
添加回答
舉報
0/150
提交
取消