Gal Shai
Gal Shai

Reputation: 11

A way to reduce run-time

I have a 2048x2048 image and I want to re-set the pixels values according to certain condition. The problem is that it takes houres (if not days) for the code to end. Is there a way to shorten the run-time? This is the function:

function ProcImage = ProcessImage(X,length,width)
 for i=1:length
    for j=1:width
        if X(j,i)<=0.025*(max(max(X(:,:))))
            X(j,i)=0;
        else
            if X(j,i)>=0.95*(max(max(X(:,:))))
                X(j,i)=(max(max(X(:,:))));
            end
        end
    end
end
ProcImage=X(1:end,1:end);

thanks in advance.

Upvotes: 1

Views: 58

Answers (2)

rahnema1
rahnema1

Reputation: 15837

If your image is a gray scale image that its values are in the range 0 to 255 here is a possible solution:

m = max(X(:));
tbl = 0:255;
tbl(tbl<=0.025*m)=0;
tbl(tbl>=0.95*m)=m;
X = tbl(int16(X)+1);

Upvotes: 2

gnovice
gnovice

Reputation: 125864

Vectorize it. You don't need to compute the maximum value of X on every iteration, since it will be the same throughout. Compute it once, store that value, then use it later. You can also do away with the loops by using element-wise logical operations and matrix indexing. Here's a simplified version that should be much faster:

maxX = max(X(:));
X(X <= 0.025.*maxX) = 0;
X(X >= 0.95.*maxX) = maxX;

Upvotes: 4

Related Questions