Filter löschen
Filter löschen

Error using == Arrays have incompatible sizes for this operation. How solve this error??

6 Ansichten (letzte 30 Tage)
clc;
clear all;
close all;
% Define the main directories
mainDirectories = {'Training', 'Testing'};
% Define the classes
classes = {'Glioma Tumor', 'Meningiloma Tumor','No Tumor', 'Pituitary Tumor'};
for mainIndex = 1:numel(mainDirectories)
mainDir = mainDirectories{mainIndex};
% Set the directory containing subdirectories for each class
datasetDirectory = fullfile('C:\Users\sukla\OneDrive\Desktop\Dataset', mainDir);
% List only directories in the specified directory
subDirectories = dir(datasetDirectory);
subDirectoryNames = {subDirectories([subDirectories.isdir]).name};
subDirectoryNames = subDirectoryNames(~ismember(subDirectoryNames, {'.', '..'}));
% Display the names of subdirectories
disp(subDirectoryNames);
df = [];
GroupTrain = cell(0, 1);
max_area = [];
% Loop through subdirectories (each corresponds to a class)
for classIndex = 1:numel(subDirectoryNames)
classDir = subDirectoryNames{classIndex};
%Skip entries for the current directory (.) and parent directory (..)
if strcmp(classDir, '.') || strcmp(classDir, '..')
continue;
end
classPath = fullfile(datasetDirectory, classDir);
% Display the current class directory
disp(['Class Directory: ' classDir]);
% Load images for the current class
imageFiles = dir(fullfile(classPath, '*.jpg'));
for i = 1:numel(imageFiles)
% Load the image
x = imread(fullfile(classPath, imageFiles(i).name));
%%%%%%%texture features%%%%%%%%
y=rgb2gray(x);
% Define the standard deviation (sigma) and filter size
sigma = 1.5;
filter_size = 5; % Choose an appropriate filter size based on sigma
% Create a 2D Gaussian filter
gaussian_filter = fspecial('gaussian', [filter_size, filter_size], sigma);
% Apply the Gaussian filter to the image
smoothed_image = imfilter(y, gaussian_filter, 'conv', 'replicate');
% %% Global Thresholding
global_threshold = 160; % Adjust threshold value
binaryImage = smoothed_image > global_threshold;
%% Define a structuring element (disk-shaped in this case)
se = strel('disk', 5);
%% Perform dilation
dilatedImage = imdilate(binaryImage, se);
%% Morphological Operation
label = bwlabel(dilatedImage);
stats = regionprops(logical(dilatedImage), 'Solidity', 'Area', 'BoundingBox');
density = [stats.Solidity];
area = [stats.Area];
high_dense_area = density > 0.6;
max_area = max(area(high_dense_area));
disp(max_area);
disp(area);
tumor_label = find(area == max_area);
tumor = ismember(label, tumor_label);
if max_area > 200
figure;
imshow(tumor)
title('Tumor alone', 'FontSize', 20);
else
h = msgbox('No Tumor!!', 'status');
return;
end
%% Bounding box
box = stats(tumor_label);
wantedBox = box.BoundingBox;
% figure
% imshow(x);
% title('Bounding Box', 'FontSize', 20);
% hold on;
% rectangle('Position', wantedBox, 'EdgeColor', 'y');
% hold off;
% Debug output
disp(['Size of label: ' num2str(size(label))]);
disp(['Size of stats: ' num2str(size(stats))]);
disp(['Size of area: ' num2str(size(area))]);
disp(['Size of max_area: ' num2str(size(max_area))]);
disp(['Size of tumor_label: ' num2str(size(tumor_label))]);
%% Getting Tumor Outline - image filling, eroding, subtracting
% erosion the walls by a few pixels
dilationAmount = 5;
rad = floor(dilationAmount);
[r,c] = size(tumor);
filledImage = imfill(tumor, 'holes');
for i=1:r
for j=1:c
x1=i-rad;
x2=i+rad;
y1=j-rad;
y2=j+rad;
if x1<1
x1=1;
end
if x2>r
x2=r;
end
if y1<1
y1=1;
end
if y2>c
y2=c;
end
erodedImage(i,j) = min(min(filledImage(x1:x2,y1:y2)));
end
end
%% subtracting eroded image from original BW image
% Resize erodedImage to match the dimensions of tumorOutline
tumorOutline=tumor;
erodedImage = imresize(erodedImage, size(tumorOutline));
% Subtract erodedImage from tumorOutline
tumorOutline = tumorOutline & ~erodedImage;
tumorOutline(erodedImage)=0;
lbpB1 = extractLBPFeatures(erodedImage,'Upright',false);
lb1=sum(lbpB1);
glcm=graycomatrix(y,'Offset',[2,0;0,2]); %Gray-Level Co-Occurrence Matrix
st1=graycoprops(glcm,{'contrast','homogeneity'});
st2=graycoprops(glcm,{'correlation','energy'});
f1=st1.Contrast;
f2=st1.Homogeneity;
f3=st2.Correlation;
f4=st2.Energy;
Fr=horzcat([lb1,f1,f2,f3,f4]);
df=[df;Fr];
%% Inserting the outline in the filtered image in green color
rgb = cat(3, y, y, y);
red = rgb(:,:,1);
green = rgb(:,:,2);
blue = rgb(:,:,3);
red(tumorOutline) = 255;
green(tumorOutline) = 0;
blue(tumorOutline) = 0;
tumorOutlineInserted = cat(3, red, green, blue);
% Store the class label for this image
GroupTrain = [GroupTrain; classDir];
end
end
end
% Define the classes
classes = {'No Tumor', 'Glioma Tumor', 'Meningiloma Tumor', 'Pituitary Tumor'}; % Replace with your class labels
% Initialize an empty cell array to store trained SVM models
SVMModels = cell(numel(classes), 1);
% Train an SVM model for each class
for j = 1:numel(classes)
% Extract features and labels for the current class
idx = strcmp(GroupTrain, classes{j});
SVMModels{j} = fitcsvm(df, idx, 'ClassNames', [false true], 'Standardize', true, 'KernelFunction', 'rbf', 'BoxConstraint', 1);
end
Error using ClassificationSVM.prepareData
No class names are found in input labels.

Error in classreg.learning.FitTemplate/fit (line 247)
this.PrepareData(X,Y,this.BaseFitObjectArgs{:});

Error in ClassificationSVM.fit (line 261)
this = fit(temp,X,Y);

Error in fitcsvm (line 342)
obj = ClassificationSVM.fit(X,Y,RemainingArgs{:});
% Test your image and classify it
% Load and process your test image
%cd ..
%%%%%%%%%%%%get test image %%%%%%%%%%
[f,p]=uigetfile('*.*');
test=imread(strcat(p,f));
%%%%%%%texture features test image%%%%%%%%
y=rgb2gray(test);
% Define the standard deviation (sigma) and filter size
sigma = 1.5;
filter_size = 5; % Choose an appropriate filter size based on sigma
% Create a 2D Gaussian filter
gaussian_filter = fspecial('gaussian', [filter_size, filter_size], sigma);
% Apply the Gaussian filter to the image
smoothed_image = imfilter(y, gaussian_filter, 'conv', 'replicate');
%% Global Thresholding
global_threshold = 160; % Adjust threshold value
binaryImage = smoothed_image > global_threshold;
figure
imshow(binaryImage);
%% Define a structuring element (disk-shaped in this case)
se = strel('disk', 5);
%% Perform dilation
dilatedImage = imdilate(binaryImage, se);
%% Morphological Operation
label = bwlabel(dilatedImage);
stats = regionprops(logical(dilatedImage), 'Solidity', 'Area', 'BoundingBox');
density = [stats.Solidity];
area = [stats.Area];
high_dense_area = density > 0.6;
max_area = max(area(high_dense_area));
tumor_label = find(area == max_area);
tumor = ismember(label, tumor_label);
if max_area > 200
figure;
imshow(tumor)
title('Tumor alone', 'FontSize', 20);
else
h = msgbox('No Tumor!!', 'status');
return;
end
%% Bounding box
box = stats(tumor_label);
wantedBox = box.BoundingBox;
figure
imshow(y);
title('Bounding Box', 'FontSize', 20);
hold on;
rectangle('Position', wantedBox, 'EdgeColor', 'y');
hold off;
%% Getting Tumor Outline - image filling, eroding, subtracting
% erosion the walls by a few pixels
dilationAmount = 5;
rad = floor(dilationAmount);
[r,c] = size(tumor);
filledImage = imfill(tumor, 'holes');
for i=1:r
for j=1:c
x1=i-rad;
x2=i+rad;
y1=j-rad;
y2=j+rad;
if x1<1
x1=1;
end
if x2>r
x2=r;
end
if y1<1
y1=1;
end
if y2>c
y2=c;
end
erodedImage(i,j) = min(min(filledImage(x1:x2,y1:y2)));
end
end
figure
imshow(erodedImage);
title('Eroded Image','FontSize',20);
%
% %% subtracting eroded image from original BW image
% tumorOutline=tumor;
% tumorOutline(erodedImage)=0;
%% subtracting eroded image from original BW image
% Resize erodedImage to match the dimensions of tumorOutline
tumorOutline=tumor;
erodedImage = imresize(erodedImage, size(tumorOutline));
% Subtract erodedImage from tumorOutline
tumorOutline = tumorOutline & ~erodedImage;
tumorOutline(erodedImage)=0;
figure;
imshow(tumorOutline);
title('Tumor Outline','FontSize',20);
lbpB1 = extractLBPFeatures(erodedImage,'Upright',false);
lb1=sum(lbpB1);
glcm=graycomatrix(y,'Offset',[2,0;0,2]); %Gray-Level Co-Occurrence Matrix
st1=graycoprops(glcm,{'contrast','homogeneity'});
st2=graycoprops(glcm,{'correlation','energy'});
f1=st1.Contrast;
f2=st1.Homogeneity;
f3=st2.Correlation;
f4=st2.Energy;
Testftr=horzcat([lb1,f1,f2,f3,f4]);
%% Inserting the outline in the filtered image in green color
rgb = cat(3, y, y, y);
red = rgb(:,:,1);
green = rgb(:,:,2);
blue = rgb(:,:,3);
red(tumorOutline) = 255;
green(tumorOutline) = 0;
blue(tumorOutline) = 0;
tumorOutlineInserted = cat(3, red, green, blue);
figure
imshow(tumorOutlineInserted);
title('Detected Tumer','FontSize',20);
% Loop through the trained models for all classes to classify your test image
Scores = zeros(size(Testftr, 1), numel(classes)); % Assuming 'Testftr' contains features of the test image
for j = 1:numel(classes)
[~, score] = predict(SVMModels{j}, Testftr); % Use 'Testftr' for the test image
Scores(:, j) = score(:, 2);
end
% Determine the predicted class with the highest score
[~, maxScore] = max(Scores, [], 2);
predictedClass = classes(maxScore);
% Display the result message (as you have done in your code)
if strcmp(predictedClass, 'Glioma Tumor')
msgbox('Glioma Tumor');
elseif strcmp(predictedClass, 'Meningiloma Tumor')
msgbox('Meningiloma Tumor');
elseif strcmp(predictedClass, 'No Tumor')
msgbox('No Tumor');
elseif strcmp(predictedClass, 'Pituitary Tumor')
msgbox('Pituitary Tumor');
else
msgbox('None');
end
{'glioma_tumor'} {'meningioma_tumor'} {'no_tumor'} {'pituitary_tumor'}
Class Directory: glioma_tumor
1316
Columns 1 through 8
158 92 390 1316 1255 187 402 78
Column 9
69
Size of label: 512 512
Size of stats: 9 1
Size of area: 1 9
Size of max_area: 1 1
Size of tumor_label: 1 1
1316
4938 5721
Error using ==
Arrays have incompatible sizes for this operation.
Error in imtest (line 93)
tumor_label = find(area == max_area);

Antworten (1)

Jon
Jon am 16 Okt. 2023
The error is telling you that the dimensions of your variable named, area are not equal to the dimensions of the variable called max_area. To use "==" both variables must have the same dimensions, or one of them must be a scalar (only one element).
Check the dimensions of the two variables just before the statement that throws the error. If they are not what you think then work backwards to see where you assigned them, and get them to be compatible.
  2 Kommentare
Dyuman Joshi
Dyuman Joshi am 16 Okt. 2023
"To use "==" both variables must have the same dimensions, or one of them must be a scalar (only one element)."
x=(1:10);
x==x'
ans = 10×10 logical array
1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1
Jon
Jon am 16 Okt. 2023
Bearbeitet: Jon am 16 Okt. 2023
So apparently you can also get some valid results due to MATLAB applying implicit expansion. While if I think it through, I can understand how MATLAB computes x == y with x a row and y a column with the same number of elements as y, the results are not obvious.
Implicit expansion can provide a powerful shorthand for expressing certain operations. It can also easily lead to surprising behavior, and obscure errors when the user unintentionally operates on two vectors with the same number of elements, but where one is a row and the other is a column.

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