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!