Generating a HSV Histogram without For-loops

조회 수: 2 (최근 30일)
Gareth
Gareth 2014년 2월 6일
댓글: Gareth 2014년 2월 6일
Hi,
I'm creating a video processing tool in MatLab, which works, but my code is extremely slow, which I believe is due to my use of for-loops.
One example of this is in creating a HSV Histogram for a video. The code I have is as follows:
function [hsvHist] = generateHSVHist(hsvVid, numRows, numColumns, numFrames)
H = zeros(12,1);
S = zeros(4,1);
V = zeros(4,1);
for frame = 1 : numFrames
for row = 1 : numRows
for column = 1 : numColumns
h = hsvVid(row,column,1,frame);
s = hsvVid(row,column,2,frame);
v = hsvVid(row,column,3,frame);
idxH = ceil(h*12);
idxS = ceil(s*4);
idxV = ceil(v*4);
%ensure no zero indices
if idxH == 0
idxH = 1;
end
if idxS == 0
idxS = 1;
end
if idxV == 0
idxV = 1;
end
H(idxH) = H(idxH)+1;
S(idxS) = S(idxS)+1;
V(idxV) = V(idxV)+1;
end
end
end
%Normalise the histograms
totalPixels = numFrames * numRows * numColumns;
H = H/totalPixels;
S = S/totalPixels;
V = V/totalPixels;
%Concatenate the histograms
hsvHist = [H;S;V];
end
Do you guys have any tips or advice on how I can approach this problem without using for-loops? Any help is greatly appreciated.
Thanks,
Gareth

채택된 답변

Walter Roberson
Walter Roberson 2014년 2월 6일
No loop needed.
h = hsvVid(:,:,1,frame);
idxH = max(1, ceil(h*12));
H = histc(idxH(:), 1:12);
  댓글 수: 1
Gareth
Gareth 2014년 2월 6일
Thanks, this worked perfectly. The function is now roughly 10x faster.
Here's the final code for anyone wondering:
function [hsvHist] = generateHSVHist(hsvVid, numRows, numColumns, numFrames)
H = zeros(12,1);
S = zeros(4,1);
V = zeros(4,1);
%Histogram for Hue
h = hsvVid(:,:,1,:);
idxH = max(1, ceil(h*12));
H = H + histc(idxH(:), 1:12);
%Histogram for Saturation
s = hsvVid(:,:,2,:);
idxS = max(1, ceil(s*4));
S = S + histc(idxS(:), 1:4);
%Histogram for Value
v = hsvVid(:,:,3,:);
idxV = max(1, ceil(v*4));
V = V + histc(idxV(:), 1:4);
%Normalise the histograms
totalPixels = numFrames * numRows * numColumns;
H = H/totalPixels;
S = S/totalPixels;
V = V/totalPixels;
%Concatenate the histograms
hsvHist = [H;S;V];
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Histograms에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by