我可以提高这个Matlab函数的效率吗?

时间:2012-03-04 15:41:12

标签: matlab optimization

我编写了一个matlab函数,可以对图像执行一些cpu密集型操作。我想提高这个功能的速度,但想不出再优化它的方法了。有谁知道如何进一步优化下面的功能?

function imageMedoid(imageList, resizeFolder, outputFolder, x, y)

    % local variables
    medoidImage = zeros([1, y*x, 3]);
    alphaImage = zeros([y x]);
    medoidContainer = zeros([y*x, length(imageList), 3]);

    % loop through all images in the resizeFolder
    for i=1:length(imageList)

        % get filename and load image
        fname = imageList(i).name;
        container = im2double(imread([resizeFolder fname]));

        % load alpha channel, convert to zeros and ones, add to alphaImage
        [~,~,alpha] = imread([resizeFolder fname]);
        alpha = double(alpha) / 255;
        alphaImage = alphaImage + alpha;

        % add (r,g,b) values to medoidContainer and reshape to single line
        medoidContainer(:, i, :) = reshape(container, [y*x 3]);

    end

    % loop through every pixel in medoidContainer
    for i=1:length(medoidContainer)

        % calculate distances between all values for current pixel
        distances = pdist(squeeze(medoidContainer(i,:,1:3)));

        % convert found distances to matrix of distances
        distanceMatrix = squareform(distances);

        % find index of image with the medoid value
        [~, j] = min(mean(distanceMatrix,2));

        % write found medoid value to medoidImage
        medoidImage(1, i, 1:3) = medoidContainer(i, j, 1:3);

    end

    % replace values larger than one in alpha channel
    alphaImage(alphaImage > 1) = 1;

    % reshape image to original proportions
    medoidImage = reshape(medoidImage, y, x, 3);

    % save medoid image
    imwrite(medoidImage, [outputFolder 'medoid.png'], 'Alpha', alphaImage);

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:4)

我建议您使用MATLAB的内置分析器,以便更好地了解最耗时的操作,然后尝试优化。

Tools -> Open Profiler -> imageMedoid(...)

答案 1 :(得分:0)

您正在致电

imread([resizeFolder fname])
在你的第一个for循环中

两次。将其称为

[A,~,alpha] = imread([resizeFolder fname]);

这应该会带来一些改善。