9

I try to display images inside a Jupyter notebook. To do that, I use a code like the following one:

import numpy as np
import matplotlib.pyplot as plt
for N in [20, 100, 300]:
  x, y = np.meshgrid(np.linspace(1,N,N), np.linspace(1,N,N))
  img = (x+y) % 2
  plt.figure()
  plt.imshow(img,cmap='gray')
  plt.title("Image shape: " + str(img.shape));

I obtain the images below:

big squares meddium squares small squares

As you can see, the images are not properly displayed because they are resized so as to have the same size on the screen. Therefore, the images are interpolated (to the nearest neighbors), creating unwanted aliasing. This is too bad for image processing...

I tried to define figsize and dpi in figure, but that not works.

Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
Vinz
  • 191
  • 1
  • 3
  • If you are using Jupyter lab double click on the plot cell to view it with given figure size. – Space Impact Aug 28 '18 at 15:09
  • It does not work. In addition, I would have them to be automatically well displayed. – Vinz Aug 28 '18 at 15:10
  • What exactly does not work when using `figsize` and `dpi` in `figure`? – ImportanceOfBeingErnest Aug 28 '18 at 15:10
  • For example, if I set `figsize` to the image size in pixels (obtained with `img.shape`) divided by the DPI value (obtained with `fig.dpi` where `fig = plt.figure()`), then, I obtain an image with approximately the good size, but not exactly... see https://nbviewer.jupyter.org/url/miv.u-strasbg.fr/mazet/test4.ipynb – Vinz Aug 28 '18 at 15:19
  • Correct. This is due to the spacings around the axes. You may set them to 0 via `fig.subplots_adjust(0,0,1,1)` (this works well in a jupyter notebook), or you can account for them and make the figure larger by the amount of spacing you want. – ImportanceOfBeingErnest Aug 28 '18 at 16:04
  • This still does not work: the images have not the correct size, this can easily be seen because of the aliasing effect... – Vinz Aug 29 '18 at 10:16
  • Feel free to provide a [mcve] of the attempted solution. (and use the @username notation to ping people in the comments) – ImportanceOfBeingErnest Aug 31 '18 at 11:27
  • @Vinz Did you end up solving this – Gulzar Jun 06 '20 at 13:35
  • Not at all! I did not find any solution to this. With Matlab however, it is easy to display an image at its actual size (ie one pixel in the matrix *is* one pixel on screen). – Vinz Jun 07 '20 at 18:23

1 Answers1

2

I used this & it worked:

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (width,height)

(Here width & height are in inches)

For more detail, you can have a look at this question

Abdur Rahman
  • 1,067
  • 4
  • 10