Learn how to import an image file into MATLAB and work with some simple image functions.
- [Instructor] We can not only use Matlab to generate plots but we can also import images and display those as well. Let's go ahead and create a new file. We'll call this one image time. Close up plot time here and... open up our image time. I've included an image that we can work with in the exercise files. Let's go ahead and copy it into our current folder. In the root of the exercise files, we have cake.jpg. Let's go ahead and copy that.
And paste it here in our working folder. If we highlight it, we can see our nice image down here. Looks like a Victoria sponge, one of my favorites. So let's go ahead and read this image into our workspace. I'll call it myIm for my image. We're going to use the function imread to read this in much in the same way that we did with our CSV file earlier. We're going to pass this a string, that's the name of our file. Again, you want to make sure that this is in your current folder that's in the path.
If your file is located somewhere else that's outside the Matlab path, this will throw an error and you will have to add it in. Now that we have myIm read in, let's go ahead and create a new figure. Looks like this is figure two. We can use the function image to plot the image data right to a figure window. We'll do myIm. Let's go ahead and run this and see how it looks. So here's our cake image. You notice that the aspect ratio is out of whack.
That's because our image wasn't originally originally square and Matlab is attempting to scale the axis in such a way that this is square. But this does put the image on a set of axis just like it would a plot. We could do other things like turn hold on and plot other data on top of this. We can use another function though to show the image at the correct aspect ratio, mostly just for display. We open up another figure window here. We can use the imshow function.
Pass it my image. And if we run this one, we see in our new figure window here, number three, that the image is shown with the correct aspect ratio. Notice here there's no labels on the axis or anything like that though. Again, Matlab has a ton of functionality to process pixel data or change the images to different formats such as from rgb to greyscale. That's a little bit beyond the scope of this course, but I do encourage you to check out the help for imshow and image to get yourself started.
A lot of the more advanced image processing functionality is not included in the base Matlab package. You would need to purchase the image processing toolbox to get those.
- Creating MATLAB variables
- Working with matrix and scalar operations
- Using if statements and loops
- Creating functions
- Importing data
- Building basic plots and 3D plots
- Working with images
- Creating Simulink models