I understand that you are trying to implement a live spectrometer in MATLAB, but you are facing the mentioned issue with it. This issue actually occurs in the “previewCallback” function because you are comparing the dimensions of the incoming video frame (“event.Data”) and the preview image data (“app.ImagePreview.CData”) using the “~=” operator. MATLAB interprets this as an element-wise comparison, which fails if the two arrays have different numbers of dimensions.
To resolve this, you should use “isequal” instead of “~=” when comparing sizes. Kindly refer to the corrected code snippet below:
function previewCallback(app,obj,event,hImage)
try
% Get the latest frame
Emission_Reading_Img = event.Data;
% Ensure preview has the same size
if ~isequal(size(Emission_Reading_Img), size(app.ImagePreview.CData))
set(app.ImagePreview, 'CData', zeros(size(Emission_Reading_Img), 'like', Emission_Reading_Img));
end
% Convert to grayscale if needed
if size(Emission_Reading_Img, 3) == 3
Emission_Reading_Img = rgb2gray(Emission_Reading_Img);
end
% Update live preview image
set(app.ImagePreview, 'CData', Emission_Reading_Img);
% Process spectrum
height = size(Emission_Reading_Img, 1);
central_row = app.ROI_Middle_Pixel;
window_size = round(height * app.ROI_Percentage_Decimal);
valid_rows = max(1, central_row - window_size) : min(height, central_row + window_size);
% Compute spectrum sum and subtract background
spectrum_sum = sum(Emission_Reading_Img(valid_rows, :), 1);
background_Img = sum(app.background_img(valid_rows, :), 1);
% Resize background if needed
if ~isequal(size(spectrum_sum), size(background_Img))
background_Img = background_Img(1:min(end, numel(spectrum_sum)));
end
spectrum_sum = spectrum_sum - background_Img;
% Update spectrum plot
if isempty(app.PlotHandle) || ~isvalid(app.PlotHandle)
app.PlotHandle = plot(app.SpectrumAxes, app.wvlength, spectrum_sum, 'b');
xlabel(app.SpectrumAxes, 'Wavelength (nm)');
ylabel(app.SpectrumAxes, 'Arb. Counts');
else
set(app.PlotHandle, 'YData', spectrum_sum);
end
drawnow limitrate;
catch ME
warning('Acquisition Error: %s', ME.message);
end
end
In this, the main change is:
if ~isequal(size(Emission_Reading_Img), size(app.ImagePreview.CData))
This will ensures that MATLAB checks the dimensions safely, avoiding the incompatible size warning you are getting in your code.
For further reference, kindly refer to the following official documentation:
Cheers & Happy Coding!