how to vectorize this code?

조회 수: 1 (최근 30일)
Siddhesh Karbhari
Siddhesh Karbhari 2018년 1월 13일
댓글: Stephen23 2018년 1월 13일
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

답변 (2개)

Roy Kadesh
Roy Kadesh 2018년 1월 13일
Use meshgrid and logical indexing.

Jan
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.
  댓글 수: 1
Stephen23
Stephen23 2018년 1월 13일
+1 clearly explained and good advice.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by