How to fix the" reshape "error to convert a mat dataset file to an input image dataset file for convolutional neural network training?

1 view (last 30 days)
My dataset includes data with 2816 x 2500 doubles, label pose with 2816 x 1, label person with 2816 x 1, label dataset with 2816 x 1, and POSE with 7 x 1 cells. i want to use this dataset in image format for training the CNN.so i should convert it into an image dataset for using in input . i said that to chat gpt and it gives me this code:
% Load the .mat file
data = load('file1.mat');
% Extract the components from the loaded file
data_matrix = data.data; % 2816 x 2500 matrix
pose_labels = data.label_pose; % 2816 x 1 vector
person_labels = data.label_person; % 2816 x 1 vector
dataset_labels = data.label_dataset; % 2816 x 1 vector
POSE = data.POSE; % 7 x 1 cell array
% Define the desired image size
imageSize = [229, 229]; % Set your desired image size
% Reshape the data matrix into images
numImages = size(data_matrix, 1);
images = cell(numImages, 1);
for i = 1:numImages
image = reshape(data_matrix(i, :), imageSize);
images{i} = mat2gray(image); % Normalize pixel values to range [0, 1]
end
% Save the images as PNG files
outputFolder = 'output_images'; % Set your desired output folder
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
for i = 1:numImages
imwrite(images{i}, fullfile(outputFolder, ['image_' num2str(i) '.png']));
end
now i have this error:Error using reshape
Number of elements must not change. Use [] as one of the size inputs to automatically calculate the appropriate size for that dimension.
how can i fix it ?

Answers (1)

Neha
Neha on 8 May 2024
Hi Ghazaleh,
I understand you are facing an error while pre-processing the dataset for your CNN model.
The error you are encountering is due to the mismatch between the number of elements in your original data matrix for each sample (2500 elements) and the number of elements required by the desired image size (229x229 = 52441 elements). To resolve this issue, you need to ensure that the number of elements in the reshaped image matches the number of elements in your original data row.
You can adjust the "imageSize" to a dimension that matches the number of elements in your data. For a 2500 element vector, a 50x50 image would work since 50*50 = 2500.
Hope this helps!

Community Treasure Hunt

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

Start Hunting!