Error using vertcat Dimensions of arrays being concatenated are not consistent.

2 Ansichten (letzte 30 Tage)
My problem is I am trying to compress and decompress an image file using Huffman Coding,
here is the code where I get the error "Error using vertcat Dimensions of arrays being concatenated are not consistent." I undelined the part where the code is not running
% Compress function
function compressed_data = compress_image(image)
% Convert the image to a 1D array
image = image(:);
% Calculate the frequency of each pixel value
freq = histcounts(image, unique(image));
% Create a cell array to store the pixel values and their corresponding frequencies
pixel_freq = num2cell(freq);
pixel_val = num2cell(unique(image));
pixel_data = [pixel_val; pixel_freq];
% Sort the pixel data based on frequency
[~, sort_index] = sort(freq, 'descend');
sorted_pixel_data = pixel_data(:, sort_index);
% Generate the Huffman code dictionary
huffman_dict = generate_huffman_dict(sorted_pixel_data);
% Encode the image using Huffman coding
encoded_data = encode_image(image, huffman_dict);
% Pack the compressed data as a struct
compressed_data = struct('image_size', size(image), 'huffman_dict', huffman_dict, 'encoded_data', encoded_data);
end

Antworten (2)

Image Analyst
Image Analyst am 23 Mai 2023
pixel_val and pixel_freq have different number of columns -- check it for yourself -- so you cannot stitch them together vertically, one atop the other.
Also, "image" is a built-in function so you must not destroy it by using it as a variable name.

Walter Roberson
Walter Roberson am 23 Mai 2023
histcounts() returns row vectors whereas unique() of a non-row returns a column vector. (Unique of a row vector returns a row vector.)
You used
image = image(:);
so image is not a row vector, so unique() is going to return a column vector.
With histcounts returning a row vector and unique returning a column vector, vertcat of the two cannot work.
  3 Kommentare
Image Analyst
Image Analyst am 23 Mai 2023
There is no reason for you to do that in the first place. It is simply not needed.
Sandra
Sandra am 23 Mai 2023
Can you please explain why is not needed? I need to convert the image into 1D array and I also need the values of the pixels and their frequecies in order to calculate the probability and sort based on Huffman algorithm. Would appreciate if you could explain your answer :)

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by