Reputation: 469
I'm doing an exercise where I have to plot the histogram of an image by reading each pixel's value. Then my idea is to loop through each color layers (r, g, b) and for each pixel store the value in a matrix. The following code runs but there it doesn't look right and I'm not totally sure why. First issue is that the graph is not a histogram with vertical bars and stacked values (How can I achieve that) and the second issue is that the graph is weird as it looks like the same values are applied for r, g and b, which is not possible given the images I'm using. Help? Thanks!
clc;
clear;
%% init values
% loading initial image
init_img = imread('face-1.jpg');
% rgb matrixes
r = zeros(256, 1);
g = zeros(256, 1);
b = zeros(256, 1);
%% main loop
% for each colour (r-g-b)
for a = 1:size(init_img, 3)
% loop through eache layer of the image
for i = 1:size(init_img, 1)
for j = 1:size(init_img, 2)
if(a == 1)
for n = 1:size(r,1)
if(n == init_img(i, j, 1))
% get value (x) from n(th) row, column 1
x = r(n, 1);
r(n, 1) = x+1;
end
end
elseif(a == 2)
for n = 1:size(g,1)
if(init_img(i, j, 1) == n-1)
% get value (x) from n(th) row, column 1
x = g(n, 1);
g(n, 1) = x+1;
end
end
elseif (a == 3)
for n = 1:size(b,1)
if(init_img(i, j, 1) == n-1)
% get value (x) from n(th) row, column 1
x = b(n, 1);
b(n, 1) = x+1;
end
end
end
end
end
end
%% plot
plot(r, 'Red');
hold('on');
plot(g, 'Green');
hold('on');
plot(b, 'Blue');
Upvotes: 0
Views: 2298
Reputation: 1305
Perhaps something like this helps:
I changed your code a little bit and came up with the following.
I retrieve the pixel value by iterating through the image and store it in the corresponding bin. Instead of plot
I'm using bar
(see here)
% loading initial image
init_img = imread('test.jpg');
% rgb matrixes
r = zeros(256, 1);
g = zeros(256, 1);
b = zeros(256, 1);
%% main loop
for i = 1:size(init_img, 1)
for j = 1:size(init_img,2)
pix = init_img(i,j,1:3);
r(pix(1)+1) = r(pix(1)+1) + 1;
g(pix(2)+1) = g(pix(2)+1) + 1;
b(pix(3)+1) = b(pix(3)+1) + 1;
end
end
%% plot
subplot(2,1,1);
title('histogram using for loops');
hold('on');
bar(r);
bar(g);
bar(b);
%% compare data
subplot(2,1,2);
title('imhist');
hold('on');
imhist(init_img(:,:,1));
imhist(init_img(:,:,2));
imhist(init_img(:,:,3));
I added a compare section in the end which uses imhist
(see here for documentation).
If this doesn't suite your requirements take a look at histogram
(here).
The script will print the following (note that the color in the plots does not match the corresponding color of the pixels):
Upvotes: 1
Reputation: 60474
You're reading the first plane of init_img
three times! You should read init_img(i,j,a)
instead.
Other than that:
- Why the loop over a if you are doing something different for each a? Might as well remove the loop and the conditionals.
- Dont loop over n. You can directly set n=init_img(i,j,a)
.
Upvotes: 0