How to Read Image in MATLAB: Syntax and Example
In MATLAB, you can read an image using the
imread function by passing the image file name as a string, like img = imread('filename.jpg'). This loads the image into a matrix variable for further processing.Syntax
The basic syntax to read an image in MATLAB is:
img = imread(filename): Reads the image file specified byfilenameand stores it in the variableimg.filenameis a string with the image file name and extension, e.g.,'photo.png'.- The output
imgis a matrix representing the image pixels.
matlab
img = imread('example.jpg');Example
This example reads an image file named peppers.png (a sample image included with MATLAB) and displays it using imshow.
matlab
img = imread('peppers.png');
imshow(img);Output
A window opens displaying the colorful peppers image.
Common Pitfalls
- Make sure the image file is in the current folder or provide the full path.
- Use correct file extension and spelling in the filename string.
- Trying to read unsupported or corrupted files will cause errors.
- Remember that
imreadreturns different data types depending on the image format.
matlab
% Wrong: missing quotes around filename
img = imread(peppers.png);
% Right:
img = imread('peppers.png');Quick Reference
Summary tips for reading images in MATLAB:
- Use
imread('filename.ext')to load images. - Supported formats include PNG, JPG, BMP, GIF, TIFF.
- Check current folder or specify full path.
- Use
imshow(img)to display the image.
Key Takeaways
Use imread('filename') to load an image file into MATLAB as a matrix.
Ensure the image file is accessible in the current folder or provide full path.
Use imshow(imageMatrix) to display the loaded image.
Always include quotes around the filename string in imread.
Supported image formats include PNG, JPG, BMP, GIF, and TIFF.