MATLAB: How to calculate the probability of each element in string

.

i am having a rgb image i have converted to string as
rgb_image = imread('lena1.jpg');
% Display the original image
figure(1)
imshow(rgb_image)
title('Original Image');
%convert to string
out=num2str(rgb_image)
now i need to calculate the probability of each pixel value that is now converted to string can anyone help please

Best Answer

Although Huffman encode works on "strings", you can apply it to numbers also, of course. histcounts will be usual for your purpose.
The code can be simplified. E.g.:
flag=ismember(symbol,string(i)); %symbols
if sum(flag)==0
can be written as:
if ~any(string(i) == symbol)
This is at least confusing:
for i=1:1:size((count)');
Note that size replies a vector and 1:size(x) need not be, what you expect. Transposing the array only to get the wanted dimension as first output of size is a waste of time. Better:
for i = 1:size(count, 2)
or because count is a vector:
for i = 1:numel(count)
But this loop is not required at all:
prob = count / total;
ent = -sum(prob .* log2(prob));
This is very inefficient also:
for i = 1:length(deco)
str = strcat(str, deco(i));
end
The iterative growing of an array is a very bad programming pattern, because the costs grow exponentially. Better without a loop:
str = char(deco);
Finally: num2str(rgb_image) is a very bad idea. Imagine the first pixel has the red channel value 0.2543. Now you convert this by num2str to '0.2543'. Then the Huffman encoding will consider the probability of digits, but you want to encode the probability of colors. This is something completely different.
So start from scratch. 1. improve the code for the Huffman encoding. 2. modify it such, that it accepts numbers from 0 to 255 as inputs. 3. Convert your RGB image to the uint8 format. Afterwards you can apply the Huffman encoding to your image.
Related Question