user1218247
user1218247

Reputation:

Can i improve the efficiency of this Matlab function?

I have written a matlab function that performs some cpu intensive operations on images. I would like to improve the speed of this function, but cannot think of anymore ways to optimize it. Does anyone know how to further optimise the function below?

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

Any suggestions would be greatly appreciated!

Upvotes: 2

Views: 270

Answers (2)

anon
anon

Reputation:

You are calling

imread([resizeFolder fname])

twice in your first for-loop. Call it once as

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

This should result in some improvement.

Upvotes: 0

zenpoy
zenpoy

Reputation: 20126

I would suggest that you use the built-in profiler of MATLAB in order to have a better idea on what are the most time consuming operations and then try to optimize there.

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

Upvotes: 4

Related Questions