Generating a HSV Histogram without For-loops

3 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 6 Feb 2014
No loop needed.
h = hsvVid(:,:,1,frame);
idxH = max(1, ceil(h*12));
H = histc(idxH(:), 1:12);
  1 Comment
Gareth
Gareth on 6 Feb 2014
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

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!