please help me run this code, as i am unable to solve an error.
1 view (last 30 days)
Show older comments
%clc, clear, close all
A = imread('image.jpg');
R = A(:, :, 1);
G = A(:, :, 2);
B = A(:, :, 3);
[m,n] = size(A);
total = m*n;
color = zeros(total,3);
freq = zeros(total);
index = 1;
for i = 1:172
for j = 1:276
X(1) = R(i,j);
X(2) = G(i,j);
X(3) = B(i,j);
if i==1 && j==1
color(index,1) = X(1);
color(index,2) = X(2);
color(index,3) = X(3);
freq(index) = 1;
else
k = index;
while k >= 1
if color(k,1)== X(1) && color(k,2)== X(2) && color(k,3)== X(3)
freq(k) = freq(k)+1;
break;
end
k = k-1;
end
if k < 0
index = index + 1;
color(index,1) = X(1);
color(index,2) = X(2);
color(index,3) = X(3);
freq(index) = 1;
end
end
end
end
C = sort(freq, 'descend');
fprintf('\n');
fprintf('\t Number \t Frequency\n');
for i = 1 : index
fprintf '('color(i,1)','color(i,2)','color(i,3)' = 'freq(i)'\n' ;
end
4 Comments
Image Analyst
on 13 Jul 2019
Again, you forgot to attach image.jpg. Is it proprietary/secret or something?
Accepted Answer
Guillaume
on 13 Jul 2019
There are a few issues with your code:
- you correctly query the size of your image and use that to preallocate your arrays, then you throw that out of the window and have hardcoded values for the loops of your bound. If the input image is not exactly 172x276 your code will either error (smaller image) or miss some pixels (larger image).
- you have a while loop that ends when k reaches 0. So the subsequent if k < 0 is guaranteed to never be true. As a result, you never increment i and never store new colours.
- Not sure why you're sorting the frequency. You never use C anyway. And you can't sort the frequency without rearraging your color array at the same time.
- Your fprintf statement is completely wrong.
fprintf('(%d, %d, %d) = %d\n', color(i, 1), color(i, 2), color(i, 3), freq(i)); %assuming color is uint8 or uint16
Of course, the whole code is very inefficient and it's probably going to be very slow. If you want to search an array for some values, use ismember rather than coding your while loop.
The whole thing could be coded very simply with:
img = imread('image.jpg');
pixels = reshape(img, [], 3); %reshape the image as a Mx3 array where M is the number of pixel and columns are R, G, B respectively
[colours, id] = unique(pixels, 'rows'); %get unique colour, and assign unique id to each
freq = accumarray(id, 1); %calculate histogram of ids
fprintf('(%03d, %03d, %03d) = %d\n', [colours, freq]');
2 Comments
Guillaume
on 14 Jul 2019
If you sort the frequency, you also need to keep track of which order you sort them in, so, as walter said in a comment, you have to use the two output version of sort:
[sortedfreq, order] = sort(freq);
color = color(order, :);
More Answers (0)
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!