Clear Filters
Clear Filters

how to read a grey scale image in call back function and display it as matrix?

4 views (last 30 days)
% Callback function for the "Load Image" button
function loadImageCallback(hObject, eventdata, handles)
% Open a file dialog to select an image
[fileName, filePath] = uigetfile({'*.jpg;*.png;*.bmp;*.tif', 'All Image Files'; '*.*', 'All Files'}, 'Select an Image');
% Check if a file was selected
if isequal(fileName, 0)
return; % User canceled the operation
end
% Read the selected image
img = imread(fullfile(filePath, fileName));
% Check if the image was read successfully
if isempty(img)
errordlg('Failed to read the image', 'Error');
return;
end
% Store the image data in the handles structure
handles.img = img;
% Update the handles structure
guidata(hObject, handles);
% Optionally, display a message to indicate successful loading
msgbox('Image loaded successfully', 'Success');
end

Answers (1)

Adam Danz
Adam Danz on 29 May 2024
Edited: Adam Danz on 30 May 2024
If you need to convert the image to grayscale use rgb2gray or im2gray (thanks DGM).
I'm not sure what you mean to display an image as a matrix. The grayscale image should already be a matrix. You could use imagesc or pcolor to plot the matrix (or imshow, image, or others). Set the colormap to gray.
  2 Comments
DGM
DGM on 30 May 2024
Edited: DGM on 30 May 2024
Just to get ahead of any complications, I'm of the opinion that any users of versions R2020b or newer should not be using rgb2gray() unless they're catering to older versions with the appropriate care. The only difference between rgb2gray() and im2gray() is that im2gray() will pass single-channel inputs as if gray, whereas rgb2gray() will throw an error.
Otherwise, all blind usage of rgb2gray() necessarily must come wrapped in a check for the size of dim3 to prevent errors. I don't know why this basic improvement was implemented as a mostly redundant function instead of improving the existing rgb2gray() (maybe the implications of the function name itself), but it is what it is.

Sign in to comment.

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!