Plt show img python

Display an image with Python

If you are using matplotlib and want to show the image in your interactive notebook, try the following:

%matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('your_image.png') imgplot = plt.imshow(img) plt.show() 

Thank you for your answer, it almost works 🙂 The image is displayed, but the gray levels are replaced using a fire lut. Any idea?

In my understanding, the last plt.show() command produces the display. Before that, you could add to the plot, e.g. by adding layers to the image. I recommend the matplotlib image tutorial as a reference: matplotlib.org/users/image_tutorial.html

Thanks for your answers, now it works perfectly! Just a little details for the potential readers, it «gray» instead of «grey».

If you use matplotlib , you need to show the image using plt.show() unless you are not in interactive mode. E.g.:

plt.figure() plt.imshow(sample_image) plt.show() # display it 

Reading an other answer, I just got that I have to add plt.show() after the code I already have, instead of replacing the imshow. Thanks for your help.

In a much simpler way, you can do the same using

from PIL import Image image = Image.open('image.jpg') image.show() 

Thank you for your help. I’ve installed PIL and now it works. Any idea why the two methods I tried didn’t work?

This solution does not necessarily close the file descriptor. Instead, use it with a context manager: with Image.open(‘image.jpg’) as im: im.show()

Your first suggestion works for me

from IPython.display import display, Image display(Image(filename='path/to/image.jpg')) 

not sure. I’m not an ipython expert. There are several ways to show an image as you can see from the answers here.

Image is not being displayed in ubuntu terminal, any other tab is not opened to display the image. Do you have any answer for this. But it’s working on colab

Using opencv-python is faster for more operation on image:

import cv2 import matplotlib.pyplot as plt im = cv2.imread('image.jpg') im_resized = cv2.resize(im, (224, 224), interpolation=cv2.INTER_LINEAR) plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB)) plt.show() 

It’s simple Use following pseudo code

from pylab import imread,subplot,imshow,show import matplotlib.pyplot as plt image = imread('. ') // choose image location plt.imshow(image) 

plt.show() // this will show you the image on console.

Using Jupyter Notebook, the code can be as simple as the following.

%matplotlib inline from IPython.display import Image Image('your_image.png') 

Sometimes you might would like to display a series of images in a for loop, in which case you might would like to combine display and Image to make it work.

%matplotlib inline from IPython.display import display, Image for your_image in your_images: display(Image('your_image')) 
import matplotlib.pyplot as plt import matplotlib.image as mpimg 
plt.imshow(mpimg.imread('MyImage.png')) File_name = mpimg.imread('FilePath') plt.imshow(FileName) plt.show() 

you’re missing a plt.show() unless you’re in Jupyter notebook, other IDE’s do not automatically display plots so you have to use plt.show() each time you want to display a plot or made a change to an existing plot in follow up code.

import IPython.display as display from PIL import Image image_path = 'my_image.jpg' display.display(Image.open(image_path)) 

Solution for Jupyter notebook PIL image visualization with arbitrary number of images:

def show(*imgs, **kwargs): '''Show in Jupyter notebook one or sequence of PIL images in a row. figsize - optional parameter, controlling size of the image. Examples: show(img) show(img1,img2,img3) show(img1,img2,figsize=[8,8]) ''' if 'figsize' not in kwargs: figsize = [9,9] else: figsize = kwargs['figsize'] fig, ax = plt.subplots(1,len(imgs),figsize=figsize) if len(imgs)==1: ax=[ax] for num,img in enumerate(imgs): ax[num].imshow(img) ax[num].axis('off') tight_layout() 

Источник

Image tutorial#

First, let’s start IPython. It is a most excellent enhancement to the standard Python prompt, and it ties in especially well with Matplotlib. Start IPython either directly at a shell, or with the Jupyter Notebook (where IPython as a running kernel).

With IPython started, we now need to connect to a GUI event loop. This tells IPython where (and how) to display plots. To connect to a GUI loop, execute the %matplotlib magic at your IPython prompt. There’s more detail on exactly what this does at IPython’s documentation on GUI event loops.

If you’re using Jupyter Notebook, the same commands are available, but people commonly use a specific argument to the %matplotlib magic:

This turns on inline plotting, where plot graphics will appear in your notebook. This has important implications for interactivity. For inline plotting, commands in cells below the cell that outputs a plot will not affect the plot. For example, changing the colormap is not possible from cells below the cell that creates a plot. However, for other backends, such as Qt, that open a separate window, cells below those that create the plot will change the plot — it is a live object in memory.

This tutorial will use Matplotlib’s implicit plotting interface, pyplot. This interface maintains global state, and is very useful for quickly and easily experimenting with various plot settings. The alternative is the explicit, which is more suitable for large application development. For an explanation of the tradeoffs between the implicit and explicit interfaces see Matplotlib Application Interfaces (APIs) and the Quick start guide to start using the explicit interface. For now, let’s get on with the implicit approach:

import matplotlib.pyplot as plt import numpy as np from PIL import Image 

Importing image data into Numpy arrays#

Matplotlib relies on the Pillow library to load image data.

Here’s the image we’re going to play with:

../../_images/stinkbug.png

It’s a 24-bit RGB PNG image (8 bits for each of R, G, B). Depending on where you get your data, the other kinds of image that you’ll most likely encounter are RGBA images, which allow for transparency, or single-channel grayscale (luminosity) images. Download stinkbug.png to your computer for the rest of this tutorial.

We use Pillow to open an image (with PIL.Image.open ), and immediately convert the PIL.Image.Image object into an 8-bit ( dtype=uint8 ) numpy array.

img = np.asarray(Image.open('../../doc/_static/stinkbug.png')) print(repr(img)) 
array([[[104, 104, 104], [104, 104, 104], [104, 104, 104], . [109, 109, 109], [109, 109, 109], [109, 109, 109]], [[105, 105, 105], [105, 105, 105], [105, 105, 105], . [109, 109, 109], [109, 109, 109], [109, 109, 109]], [[107, 107, 107], [106, 106, 106], [106, 106, 106], . [110, 110, 110], [110, 110, 110], [110, 110, 110]], . [[112, 112, 112], [111, 111, 111], [110, 110, 110], . [116, 116, 116], [115, 115, 115], [115, 115, 115]], [[113, 113, 113], [113, 113, 113], [112, 112, 112], . [115, 115, 115], [114, 114, 114], [114, 114, 114]], [[113, 113, 113], [115, 115, 115], [115, 115, 115], . [114, 114, 114], [114, 114, 114], [113, 113, 113]]], dtype=uint8)

Each inner list represents a pixel. Here, with an RGB image, there are 3 values. Since it’s a black and white image, R, G, and B are all similar. An RGBA (where A is alpha, or transparency) has 4 values per inner list, and a simple luminance image just has one value (and is thus only a 2-D array, not a 3-D array). For RGB and RGBA images, Matplotlib supports float32 and uint8 data types. For grayscale, Matplotlib supports only float32. If your array data does not meet one of these descriptions, you need to rescale it.

Plotting numpy arrays as images#

So, you have your data in a numpy array (either by importing it, or by generating it). Let’s render it. In Matplotlib, this is performed using the imshow() function. Here we’ll grab the plot object. This object gives you an easy way to manipulate the plot from the prompt.

images

You can also plot any numpy array.

Applying pseudocolor schemes to image plots#

Pseudocolor can be a useful tool for enhancing contrast and visualizing your data more easily. This is especially useful when making presentations of your data using projectors — their contrast is typically quite poor.

Pseudocolor is only relevant to single-channel, grayscale, luminosity images. We currently have an RGB image. Since R, G, and B are all similar (see for yourself above or in your data), we can just pick one channel of our data using array slicing (you can read more in the Numpy tutorial):

images

Now, with a luminosity (2D, no color) image, the default colormap (aka lookup table, LUT), is applied. The default is called viridis. There are plenty of others to choose from.

images

Note that you can also change colormaps on existing plot objects using the set_cmap() method:

imgplot = plt.imshow(lum_img) imgplot.set_cmap('nipy_spectral') 

images

However, remember that in the Jupyter Notebook with the inline backend, you can’t make changes to plots that have already been rendered. If you create imgplot here in one cell, you cannot call set_cmap() on it in a later cell and expect the earlier plot to change. Make sure that you enter these commands together in one cell. plt commands will not change plots from earlier cells.

There are many other colormap schemes available. See the list and images of the colormaps.

Color scale reference#

It’s helpful to have an idea of what value a color represents. We can do that by adding a color bar to your figure:

imgplot = plt.imshow(lum_img) plt.colorbar() 

images

Examining a specific data range#

Sometimes you want to enhance the contrast in your image, or expand the contrast in a particular region while sacrificing the detail in colors that don’t vary much, or don’t matter. A good tool to find interesting regions is the histogram. To create a histogram of our image data, we use the hist() function.

plt.hist(lum_img.ravel(), bins=range(256), fc='k', ec='k') 

images

Most often, the «interesting» part of the image is around the peak, and you can get extra contrast by clipping the regions above and/or below the peak. In our histogram, it looks like there’s not much useful information in the high end (not many white things in the image). Let’s adjust the upper limit, so that we effectively «zoom in on» part of the histogram. We do this by setting clim, the colormap limits.

This can be done by passing a clim keyword argument in the call to imshow .

images

This can also be done by calling the set_clim() method of the returned image plot object, but make sure that you do so in the same cell as your plot command when working with the Jupyter Notebook — it will not change plots from earlier cells.

imgplot = plt.imshow(lum_img) imgplot.set_clim(0, 175) 

images

Array Interpolation schemes#

Interpolation calculates what the color or value of a pixel «should» be, according to different mathematical schemes. One common place that this happens is when you resize an image. The number of pixels change, but you want the same information. Since pixels are discrete, there’s missing space. Interpolation is how you fill that space. This is why your images sometimes come out looking pixelated when you blow them up. The effect is more pronounced when the difference between the original image and the expanded image is greater. Let’s take our image and shrink it. We’re effectively discarding pixels, only keeping a select few. Now when we plot it, that data gets blown up to the size on your screen. The old pixels aren’t there anymore, and the computer has to draw in pixels to fill that space.

We’ll use the Pillow library that we used to load the image also to resize the image.

images

Here we use the default interpolation («nearest»), since we did not give imshow() any interpolation argument.

Let’s try some others. Here’s «bilinear»:

imgplot = plt.imshow(img, interpolation="bilinear") 

images

imgplot = plt.imshow(img, interpolation="bicubic") 

images

Bicubic interpolation is often used when blowing up photos — people tend to prefer blurry over pixelated.

Total running time of the script: ( 0 minutes 9.089 seconds)

Источник

Читайте также:  example-like- php mysql examples | w3resource
Оцените статью