how to vectorize this code?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Program to perform contrast stretching on an Image
clc;
close all;
clear all;
%%Input section
I= imread('pout.tif');
%%Calculation section
[r,c]=size(I);
P=I;
a=85;
b=170;
v=65;
w=195;
for i=1:r
for j=1:c
k=I(i,j);
if(k<a)
l=(v/a);
I(i,j)=l*k;
elseif(a<k<b)
m=(w-v)/(b-a);
I(i,j)=m*k;
else
n=(r-w)/(c-b);
I(i,j)=n*k;
end
end
end
subplot(1,2,1)
gpuArray(imshow(P))
subplot(1,2,2)
imshow(I)
%%End of contrast.m
0 Kommentare
Antworten (2)
Jan
am 13 Jan. 2018
Bearbeitet: Jan
am 13 Jan. 2018
Note that "elseif(a<k<b)" will not do what you expect. The condition is evaluated from left to right: At first "a<k", which replies either false (which is 0) or true (which is 1). Afterwards you get "0<b" or "1<b" respectively. You need this instead:
elseif a<k && k<b
Before caring about a vectorization, create correctly working code.
You can replace the loops by logical indexing:
m = I < a;
I(m) = I(m) * (v / a);
m = (a < I) & (I < b);
I(m) = I(m) * (w-v) / (b-a);
m = I >= b;
I(m) = I(m) * (r-w) / (c-b);
imshow replies the graphics handle. Then
gpuArray(imshow(P))
converts the value of the handle to a gpuarray, but you do not store the result. This does not seems to be meaningful.
I cannot reconsider, why so many beginners like the brute clearing header "clc; close all; clear all;". Better use functions to keep your workspace clean. Especially "clear all" removes all functions from the memory and reloading them from the slow hard disk wastes a lot of time.
1 Kommentar
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!