how to vectorize this code?

2 visualizaciones (últimos 30 días)
Siddhesh Karbhari
Siddhesh Karbhari el 13 de En. de 2018
Comentada: Stephen23 el 13 de En. de 2018
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

Respuestas (2)

Roy Kadesh
Roy Kadesh el 13 de En. de 2018
Use meshgrid and logical indexing.

Jan
Jan el 13 de En. de 2018
Editada: Jan el 13 de En. de 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 comentario
Stephen23
Stephen23 el 13 de En. de 2018
+1 clearly explained and good advice.

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by