how to vectorize this code?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Jan
2018-1-13
编辑:Jan
2018-1-13
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!