Matlab与Python二维卷积性能比较

2024-09-30 18:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢在Matlab中创建算法原型,但是我需要将它们放在运行大量Python代码的服务器上。因此,我很快将代码转换为Python并将两者进行了比较。Matlab实现的运行速度快1000倍(来自定时函数调用-无需评测)。有人马上知道为什么Python的性能这么慢吗?在

Matlab语言

% init random data
w = 800;
h = 1200;
hmap = zeros(w,h);

npts = 250;
for i=1:npts
    hmap(randi(w),randi(h)) = hmap(randi(w),randi(h))+1;
end

% Params
disksize = 251;
nBreaks = 25;
saturation = .9;
floorthresh =.05;

fh = fspecial('gaussian', disksize, disksize/7);
hmap = conv2(hmap, fh, 'same');

% Scaling, paritioning etc
hmap = hmap/(max(max(hmap)));
hmap(hmap<floorthresh) = 0;
hmap = round(nBreaks * hmap)/nBreaks;
hmap = hmap * (1/saturation);

% Show the image
imshow(hmap, [0,1])
colormap('jet')

Python

^{pr2}$

Tags: 代码服务器算法原型速度maxmatlabsaturation
1条回答
网友
1楼 · 发布于 2024-09-30 18:30:44

好吧,多亏了@Yves Daust的建议,问题为我解决了

滤波器scipy.ndimage.filters.gaussian_filter利用了内核的可分性,并将运行时间减少到matlab实现的一个数量级之内。在

import numpy as np
from scipy.ndimage.filters import gaussian_filter as gaussian


# Test data parameters
w = 800
h = 1200
npts = 250

# generate data
xvals = np.random.randint(w, size=npts)
yvals = np.random.randint(h, size=npts)

# Heatmap parameters
gaussianSize = 250
nbreaks = 25

# Preliminary function definitions
def populateMat(w, h, xvals, yvals):
    container = np.zeros((w,h))

    for idx in range(0,xvals.size):
        x = xvals[idx]
        y = yvals[idx]
        container[x,y] += 1

    return container


# Create the data matrix
dmat = populateMat(w,h,xvals,yvals)

# Convolve
dmat2 = gaussian(dmat, gaussianSize/7)

# Scaling etc
dmat2 = dmat2 / dmat2.max()
dmat2 = np.round(nbreaks*dmat2)/nbreaks

# Show
imshow(dmat2)

相关问题 更多 >