![]() |
|
[Tut] Matplotlib Imshow — A Helpful Illustrated Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Matplotlib Imshow — A Helpful Illustrated Guide (/thread-93845.html) |
[Tut] Matplotlib Imshow — A Helpful Illustrated Guide - xSicKxBot - 03-03-2020 Matplotlib Imshow — A Helpful Illustrated Guide I always struggled with the Code: plt.imshow()As you study the resource, you can play my explainer video that leads you through the code in this article: To show an image in matplotlib, first read it in using Code: plt.imread()Code: plt.imshow()Code: import matplotlib.pyplot as plt cat_img = plt.imread('Figures/cat.jpeg')
plt.imshow(cat_img)![]() To turn the (annoying) axis ticks off, call Code: plt.axis('off')Code: cat_img = plt.imread('Figures/cat.jpeg')
plt.axis('off')
plt.imshow(cat_img)![]() Much better! But there is a lot more you can do than just show images. Let’s look at how this works in more detail. Matplotlib Imshow Example When you display an in image in matplotlib, there are 2 steps you need to take: first you read the image and then you show it. You read in the image using Code: plt.imread()Code: Figures/Code: cat.jpegCode: Figures/I store the output of Code: plt.imread()Code: plt.imshow()Code: cat_img = plt.imread('Figures/cat.jpeg')Images are made up of pixels and each pixel is a dot of color. The cat image is 1200×800 pixels. When an image is loaded into a computer, it is saved as an array of numbers. Each pixel in a color image is made up of a Red, Green and Blue (RGB) part. It can take any value between 0 and 255 with 0 being the darkest and 255 being the brightest. In a grayscale image, each pixel is represented by just a single number between 0 and 1. If a pixel is 0, it is completely black, if it is 1 it is completely white. Everything in between is a shade of gray. So, if the cat image was black and white, it would be a 2D numpy array with shape Code: (800, 1200)Code: (800, 1200, 3)Note that Numpy writes image sizes is the opposite way to matplotlib and the ‘real world’. Numpy is from the world of mathematics and matrices where you always write the number of rows (height) first followed by the columns (width). If you need a quick NumPy refresher, check out my in-depth NumPy tutorial on this blog. Matplotlib bases its image functions on the ‘real world’ and so displays the width first followed by the height. Let’s look at the type and size of Code: cat_imgCode: cat_img = plt.imread('Figures/cat.jpeg') print(type(cat_img))
# <class 'numpy.ndarray'> print(cat_img.shape)
# (800, 1200, 3) <class 'numpy.ndarray'>
(800, 1200, 3)Once you’ve read your image into a numpy array, it’s time to display it using Code: plt.imshow()Code: plt.show()Code: plt.show()Code: plt.imshow(cat_img)![]() I’m not sure why but, by default, all images are shown with axis ticks and labels. This can be quite annoying, so call Code: plt.axis('off')However, ticks and labels can be helpful if you only want to select part of the image. By using them as guides, I’ll slice Code: cat_imgCode: # Slicing found by using axis ticks and lables on image above
cat_head = cat_img[150:450, 275:675, :]
plt.imshow(cat_head)![]() The above image is a jpeg but you can also display other types of image files such as pngs. Code: # A png image
snow_img = plt.imread('Figures/snowboarder.png')
plt.axis('off')
plt.imshow(snow_img)![]() You can display gifs but it is slightly more complicated to do so and so is outside the scope of this article. If you read in and show a gif using the above steps, matplotlib will just show one of its frames. Code: janice = plt.imread('Figures/janice.gif')
plt.axis('off')
plt.imshow(janice)![]() Matplotlib Imshow Grayscale You can turn any color image into a grayscale image in matplotlib. Since grayscale images are 2D numpy arrays, use slicing to turn your 3D array into a 2D one. Code: cat_img = plt.imread('Figures/cat.jpeg') # Turn 3D array into 2D by selecting just one of the three dimensions
grayscale_cat = cat_img[:, :, 0]If you write Code: cat_img[:, :, 1]Code: cat_img[:, :, 2]Let’s plot it and see what happens. Code: plt.axis('off')
plt.imshow(grayscale_cat)![]() Wait, what? Don’t worry, you haven’t done anything wrong! You created a grayscale image but matplotlib applied a colormap to it automatically. This happens even if you pick the second or third dimension in your Code: grayscale_catTo make it grayscale, set the Code: cmapCode: 'gray'Code: plt.imshow()Code: plt.axis('off')
plt.imshow(grayscale_cat, cmap='gray')![]() Perfect! Now you can easily turn any color image into a grayscale one in matplotlib. But there are many more colors you can choose from. Let’s look at all the colormaps in detail. Matplotlib Imshow Colormap There are many different colormaps you can apply to your images. Simply pass the name to the Code: cmapCode: plt.imshow()The default colormap is viridis. Let’s explicitly apply it to our cat image. Code: # Turn cat_img into a 2D numpy array colored_cat = cat_img[:, :, 0]
plt.axis('off')
plt.imshow(colored_cat, cmap='viridis')![]() I could write a whole article on colormaps – in fact, the creator of Seaborn did. It’s a fascinating topic. Choosing the right one can make your plot incredible and choosing a bad one can ruin it. For beginners, matplotlib recommends the Code: Perceptually Uniform SequentialCode: percp_uniform_seq_cmaps = ['viridis', 'plasma', 'inferno', 'magma', 'cividis']You’ve already seen Code: viridisCode: fig, axes = plt.subplots(nrows=2, ncols=2)
cmaps = ['plasma', 'inferno', 'magma', 'cividis'] for ax, cmap in zip(axes.flat, cmaps): ax.imshow(colored_cat, cmap=cmap) ax.set(title=cmap) ax.axis('off')
plt.show()![]() The colormaps are quite similar and easy to look at. They don’t distort the image and the highs and lows can still be seen. Here are some other colormaps I’ve randomly chosen. Note how odd some of them are, especially Code: flagCode: fig, axes = plt.subplots(nrows=2, ncols=3, figsize=plt.figaspect(1/2))
cmaps = ['jet', 'binary', 'RdYlGn', 'twilight', 'Pastel1', 'flag'] for ax, cmap in zip(axes.flat, cmaps): ax.imshow(colored_cat, cmap=cmap, label=cmap) ax.set(title=cmap) ax.axis('off')
plt.show()![]() Matplotlib Imshow Colorbar If your image has a colormap applied to it, you may want to tell the reader what each color means by providing a colorbar. Use Code: plt.colorbar()Code: plt.imshow(colored_cat, cmap='hot')
plt.axis('off')
plt.colorbar()![]() Remember that every value in an array representing a colored image is a number between 0 and 255 and so the colorbar reflects this. Note that I called Code: plt.imshow()Code: plt.show()Code: plt.imshow()Matplotlib Imshow Size As with every Code: FigureCode: FigureCode: plt.figure()Code: figsize
Note: the default figsize can be found by calling Code: plt.rcParams['figure.figsize']Code: (6.4, 4.8)Let’s see what happens when we modify the Code: FigureCode: # 1 inch wide x 1 inch tall...?
plt.figure(figsize=(1, 1)) cat_img = plt.imread('Figures/cat.jpeg')
plt.axis('off')
plt.imshow(cat_img)![]() This is certainly smaller than the original. But it doesn’t look like it is 1×1 inches – it’s clearly wider that it is tall. But it looks like one of the sides is correct which is better than nothing. Let’s try to make it 1 inch wide and 3 inches tall. Code: # 1 inch wide x 3 inches tall...?
plt.figure(figsize=(1, 3)) cat_img = plt.imread('Figures/cat.jpeg')
plt.axis('off')
plt.imshow(cat_img)![]() Now the image hasn’t changed at all. What’s going on? When you resize images in most programs like Microsoft Word or Google Sheets, they maintain their original height/width ratios. This is called preserving the aspect ratio of the image and is usually a very good thing. It ensures that pixels in the image are not distorted when you resize them. This is also the default behavior in matplotlib. If you actually want to distort the image and to fill up the entire space available in the Code: FigureCode: aspectCode: plt.imshow()There are only two possible values for Code: aspect
Let’s look at the same examples as above but set Code: aspect='auto'Code: # 1 inch wide x 1 inch tall (definitely)
plt.figure(figsize=(1, 1)) cat_img = plt.imread('Figures/cat.jpeg')
plt.axis('off')
plt.imshow(cat_img, aspect='auto')![]() Great! Now, the image is clearly 1×1 inches but it has come at the expense of slight image distortion. Let’s distort it even further. Code: # 1 inch wide x 3 inches tall (definitely)
plt.figure(figsize=(1, 3)) cat_img = plt.imread('Figures/cat.jpeg')
plt.axis('off')
plt.imshow(cat_img, aspect='auto')![]() Perfect! Clearly the image is distorted but now you know how to do it. Note the default aspect value can be changed for all images by setting Code: plt.rcParams['image.aspect'] = 'auto'Summary Now you know the basics of displaying images with matplotlib. You understand why you need to first read images in from a file and store them as a numpy array (NumPy tutorial here) before displaying them with Code: plt.imshow()If you want to set a specific colormap, you use the Code: cmapThere are some more advanced topics to learn about such as interpolation, adding legends and using log scales for your axes but I’ll leave them for another article. Where To Go From Here? Do you wish you could be a programmer full-time but don’t know how to start? Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back! https://tinyurl.com/become-a-python-freelancer It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar. These are proven, no-BS methods that get you results fast. This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed. https://tinyurl.com/become-a-python-freelancer WordPress conversion from imshow.ipynb by nb2wp v0.3.1 |