Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust the display size of an image in a Jupyter notebook

I want to modify the following code so that the image is sufficiently magnified to see individual pixels (python 3x).

import numpy as np
from PIL import Image   
from IPython.display import display  
width = int(input('Enter width: '))
height = int(input('Enter height: '))
iMat = np.random.rand(width*height).reshape((width,height))
im=Image.fromarray(iMat, mode='L')
display(im)
like image 859
Dustin Soodak Avatar asked Oct 06 '19 19:10

Dustin Soodak


People also ask

How do you resize an image in Python?

To resize an image, you call the resize() method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.

How do I display an image in a Jupyter Notebook?

To display the image, the Ipython. display() method necessitates the use of a function. In the notebook, you can also specify the width and height of the image.


1 Answers

Once you have your image, you could resize it by some ratio large enough to see individual pixels.

Example:

width = 10
height = 5
# (side note: you had width and height the wrong way around)
iMat = np.random.rand(height * width).reshape((height, width))
im = Image.fromarray(iMat, mode='L')
display(im)

Out: minuscule

10x larger:

display(im.resize((40 * width, 40 * height), Image.NEAREST))

enter image description here

Note: it's important to use Image.NEAREST for the resampling filter; the default (Image.BICUBIC) will blur your image.


Also, if you plan to actually display numerical data (not some image read from a file or generated as an example), then I would recommend doing away with PIL or other image processing libraries, and instead use proper data plotting libraries. For example, Seaborn's heatmap (or Matplotlib's). Here is an example:

sns.heatmap(iMat, cmap='binary')

,---

like image 139
Pierre D Avatar answered Sep 17 '22 22:09

Pierre D