image does not display in ipython - ipython

The image does not load if it is part of a while loop. For e.g. the following works as expected:
from IPython.display import Image
Image(filename='someimage.jpg')
But this does not work:
while True:
Image(filename='someimage.jpg')
break
update:
How do I display several images from a list?

This works fine here:
from IPython.display import display, Image
path1 = "/some/path/to/image1.png"
path2 = "/some/path/to/image2.png"
for path in path1, path2:
img = Image(path)
display(img)

Ok, I have exactly the same problem as apler details above. I am going thru a detailed example, where IPython is used to create an image. After several attempts, I have successfully displayed a .jpg image from a file, and confirmed Mac OSX Yosemite can use Python+PIL to display an image.
I had to uninstall PIL, and use Pillow instead, in order for the libjpeg library to be recognized correctly. The Python code creates an image - but it will not display the image.
I try to create the image with:
f = BytesIO()
PIL.Image.fromarray(a).save(f, 'jpeg')
clear_output(wait = True)
display(Image(data=f.getvalue()))
What I see when I run the little program in Python is:
<IPython.core.display.Image object>
In :
This In : looks to be an IPython prompt.
It appears that the code example I am working through is specifically designed to use IPython Notebook which is not the same as IPython, or interactive Python.
To use the code above, which is from the Google TensorFlow tutorial, one needs to configure an "IPython Notebook Server" and run something called "Jupyter". The documentation for Jupyter stuff is at:
http://jupyter-notebook.readthedocs.io/en/latest/
The point apler makes is good. We should just be able to use plain Python to create a .jpg file, and display it on a Mac running OSX. I've pulled some code togther to show how to do this. It creates a .jpg image, writes it out to a file, and then displays it using Pillow version of PIL. (Note: I had to use pip to uninstall original PIL, then pip install Pillow, and I picked up the "libjpeg" library as a .dmg file from the Ethan.Tira-Thompson.com/Mac_OS_X_Ports.html site). You also need numpy and scipy.misc modules.
#
# --- Make+Show immediately a simulated Moire pattern as a .jpg file
#
# --- start Python and import this file with: import MakeShowMoire
# --- or use: execfile ("MakeShowMoire.py")
#
# --- import modules we need
from PIL import Image, ImageDraw
import numpy as np
import scipy.misc
#
# --- Ok, lets go..
width = 1020
height = 710
channels = 3
#
img = np.zeros((height, width, channels), dtype=np.uint8)
xx, yy = np.mgrid[:height, :width]
circle = (xx - 100) ** 2 + (yy - 100) ** 2
for y in range(img.shape[0]):
for x in range(img.shape[1]):
r, g, b = circle[y][x], circle[y][x], circle[y][x]
img[y] [x] [0] = r
img[y] [x] [1] = g
img[y] [x] [2] = b
#
# --- now, we have made the image, lets save it
scipy.misc.imsave("testimg.jpg", img)
#
# --- Since we have saved it, we should be able to display it
image = Image.open("testimg.jpg")
image.show()
Save this file as MakeShowMoire.py. To run this, start a terminal session, and run Python. I am using Python 2.7.10 [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang 600.0.39)] on darwin, and Mac OSX is 10.10.5 Yosemite. When Python runs, just enter:
>>> execfile ("MakeShowMoire.py")
And the example should display on your Mac, in a window called "tmpblahblah.BMP", which will be pitched when you close the window, but your testimg.jpg is retained, of course.
I was using "import MakeShowMoire" at Python prompt to run the file, but the namespace does not map to the interactive Python session. If you use the execfile function, you can re-display the file contents with image.show() again. Hope this is useful.

When working in IPython notebooks, the interpreter will give a response when typed as a separate command.
So for example:
>>>>a = 5
>>>>a
5
But if we were to do the same thing in a function or loop, we would not get the response.
So if you want to display images from within a loop/function, you will have to use the display function (IPython.display.display)
from IPython.display import display, Image
for image_path in images: # images is a list of paths
display(Image(image_path))
So the Image function is returning an image. When in the interpreter, it will get displayed, but otherwise it will not.
To ensure that it is displayed, we use the display function.
This is similar to the print command. When in the interpreter, it is not necessary to use the print command to view variables, whereas while running a program it is.

I tried the chosen answer, and just about everything else under the sun, but no matter what I tried, it would only display the last photo. I was finally able to get it working with matplotlib.
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def display_photo(path):
print("File: {}".format(path))
img = mpimg.imread(path)
imgplot = plt.imshow(img)
plt.show()
for path in glob.iglob('my_photos/*'):
display_photo(path)

Note: The image displays in a different window - image viewer. If using QtConsole, one could set the display to inline using %matplotlib inline
Hope this helps.

Imports and that function can be rewritten as below. It perfectly opens windows photo viewer with the result fractal image
import tensorflow as tf
import numpy as np
from PIL import Image
from io import BytesIO
from IPython.display import display
def DisplayFractal(a, fmt='jpeg'):
a_cyclic = (6.28*a/20.0).reshape(list(a.shape)+[1])
img = np.concatenate([10+20*np.cos(a_cyclic),
30+50*np.sin(a_cyclic),
155-80*np.cos(a_cyclic)], 2)
img[a==a.max()] = 0
a = img
a = np.uint8(np.clip(a, 0, 255))
Image.fromarray(a).show()

Related

Jupyter Lab Max Number of Outputs Trimmed

How to change Jupyter Lab default behaviour trimming higher number of outputs.
The message in the middle of outputs says:
Output of this cell has been trimmed on the initial display.
Displaying the first 50 top and last bottom outputs.
Click on this message to get the complete output.
There is maxNumberOutputs parameter in Jupyter Lab source code, but I didn't found any method to change it.
You can change maxNumberOutputs in settings: click on Menu bar → Settings → Advanced Settings Editor → Notebook → set maxNumberOutputs in the User Preferences tab, like:
{
"maxNumberOutputs": 100
}
save, and reload.
Using jupyter lab path to find the "User settings" path, you can write from the notebook directly by executing this writefile magic from within a cell:
%%writefile <your-jupyter-lab-path>/user-settings/#jupyterlab/notebook-extension/tracker.jupyterlab-settings
{
"maxNumberOutputs":100
}
This path may be slightly different depending on your environment and Jupyterlab version, so probably best to manually change it using this answer and then finding the file that was modified. After that you can place this code before the %%writefile command to ensure that this works on your next Jupyter session without manually going to advanced settings in the menu bar:
!file="<your-jupyter-lab-path>/user-settings/#jupyterlab/notebook-extension/tracker.jupyterlab-settings" && mkdir -p "${file%/*}" && touch "$file"
Finally, to ensure that you have correctly changed the values,use this code to test your output:
from IPython.display import display
[display(i) for i in range(75)]
where 75 outputs should not be trimmed. If it is, then try refreshing the page to re-apply the settings.

How do I edit a jupyter notebook cell's tags in visual studio code?

I am editing a .ipynb file in Visual Studio Code, with the file open in VS code's Jupyter Notebook editor.
When I edit this notebook in the Jupyter Notebook App (i.e. if I were not using VS code, instead using the interface described here), I could add tags to cells by clicking View > Cell Toolbar > Tags, and then entering tags into the UI that comes up.
Is there an equivalent way to do this in VS Code?
I am aware I can reopen the file in a text editor view and edit the JSON directly. But I am looking for something a bit more user friendly than this.
Try installing this jupyter on vs code.
On my old windows 7 I used to use this. It has the same interface as when you open Jupiter in your browser but you don't need to load a bunch of stuff to open jupyter. You can open it in one single click like changing text file while writing code inside vc code.
Also you need to install one library to use it but unfortunately I can't remember the library as I don't use python or Jupiter anymore.
In the documentation is a python code cell which enables to change all the cell tags.
import nbformat as nbf
from glob import glob
# Collect a list of all notebooks in the content folder
notebooks = glob("**/*.ipynb", recursive=True)
notebooks_windows = []
for i in notebooks:
j = i.replace("\\", "/")
notebooks_windows.append(j)
notebooks_windows
# Text to look for in adding tags
text_search_dict = {
"# HIDDEN": "remove-cell", # Remove the whole cell
"# NO CODE": "remove-input", # Remove only the input
"# HIDE CODE": "hide-input" # Hide the input w/ a button to show
}
# Search through each notebook and look for the text, add a tag if necessary
for ipath in notebooks_windows:
ntbk = nbf.read(ipath, nbf.NO_CONVERT)
for cell in ntbk.cells:
cell_tags = cell.get('metadata', {}).get('tags', [])
for key, val in text_search_dict.items():
if key in cell['source']:
if val not in cell_tags:
cell_tags.append(val)
if len(cell_tags) > 0:
cell['metadata']['tags'] = cell_tags
Microsoft have finally released an extra extension to support this.
ms-toolsai.vscode-jupyter-cell-tags
See this long running github.com/microsoft/vscode-jupyter issue #1182 and comment recently closing the issue.
Be ware however, that while you can set tags, e.g. raises-exception, which is meant to make the runtime expect and ignore the exception and keep on running more cells, but the vscode-jupyter extension that runs the cells does not always honor tag features the same way that the standard Jupyter notebook runtime does, and so, disappointingly, it's still difficult to demo common mistakes or what not to do (exceptions).
Just copy everything in .py file with the unremovable tags, paste that into a plaintext file. The tags are now just editable text. Remove them, Save As or copy/paste back to the .py file.

Jupyter Notebook: command for hide the output of a cell?

In my notebook, I have a cell returning temp calculation results. It's a bit long, so after it is run, I want to hide it and when needed, to show it.
To do it manually, I can double click the left side of the output, to hide it
After double click
But is there any way I can do this by code? For example,
the last line of the cell, use a command like %%hide output, and the output would be hidden after finished running.
Additionally, can I get this feature in output HTML?
Add ; by the end of the cell to hide the output of that cell.
In the newer versions(5.0.0 at the time I'm writing this), pressing o in the command mode hides the output of the cell in focus. The same happens if you triple click in front of the output.
o is
the first letter in the word "output" or
lower case of 15th letter in the alphabet
You can add %%capture to the beginning of the cell.
Jupyter provides a magic cell command called %%capture that allows you to capture all of to outputs from that cell.
You can use it like this:
%%capture test
print('test')
test.stdout => 'test\n'
https://ipython.readthedocs.io/en/stable/interactive/magics.html
In newer versions of Jupiter Notebook, select the desired cell, make sure you're in command mode and then on the menubar press Cell > Current Outputs. You have then three options:
Toggle (press O in the command mode to apply the same effect)
Toggle Scrolling (the default output)
Clear (to clear the output all together)
Image to Menubar Options
Additionally, you can apply the same effect to all the cells in your document if you chose All Output instead of Current Output.
Not exactly what you are after, but the effect might be good enough for your purposes:
Look into the %%capture magic (https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb). It lets you assign that cell output to a variable. By calling that variable later you could see the output.
Based on this, I just came up with this for myself a few minutes ago:
%%javascript
$('#maintoolbar-container').children('#toggleButton').remove()
var toggle_button = ("<button id='toggleButton' type='button'>Show Code</button>");
$('#maintoolbar-container').append(toggle_button);
var code_shown = false;
function code_toggle()
{
if (code_shown)
{
console.log("code shown")
$('div.input').hide('500');
$('#toggleButton').text('Show Code');
}
else
{
console.log("code not shown")
$('div.input').show('500');
$('#toggleButton').text('Hide Code');
}
code_shown = !code_shown;
}
$(document).ready(function()
{
code_shown=false;
$('div.input').hide();
});
$('#toggleButton').on('click', code_toggle);
It does have a glitch: each time you run that cell (which I put at the top), it adds a button. So, that is something that needs to be fixed. Would need to check in the maintoolbar-container to see if the button already exists, and then not add it.
EDIT
I added the necessary piece of code:
$('#maintoolbar-container').children('#toggleButton').remove()
You can use the notebook utils from https://github.com/google/etils:
!pip install etils[ecolab]
from etils import ecolab
with etils.collapse():
print('This content will be hidden by default')
It will capture the stdout/stderr output and display it a some collapsible section.
Internally, this is more or less equivalent to:
import contextlib
import html
import io
import IPython.display
#contextlib.contextmanager
def collapse(name: str = ''):
f = io.StringIO()
with contextlib.redirect_stderr(f):
with contextlib.redirect_stdout(f):
yield
name = html.escape(name)
content = f.getvalue()
content = html.escape(content)
content = f'<pre><code>{content}</code></pre>'
content = IPython.display.HTML(
f'<details><summary>{name}</summary>{content}</details>')
IPython.display.display(content)
The section is collapsed by default, but I uncollapsed it for the screenshot.
To prepend a cell from getting rendered in the output, in the notebook, by voilo or voila gridstack, just put in the first line of each cell to hide the output:
%%capture --no-display
reference in ipypthon documentation
For Windows,
in Jupyter Notebook, click the cell whose output you want to hide.
Click Esc + o for toggling the output
So I totally understand. When you have like 100 different plot and when you do the "Restart & Run All" those ugly plots all show up again
what you can do is ctrl+A and press o it will all of a sudden hide all your cells!!! For you to collapse automatically, you may need to use JupyterLab (another level after JupyterNotebook) but still, by doing ctrl+A then o you will be able to collapse all the results!!!
ctrl+A --> select ALL (make sure to click outside of coding box before you do it!)
o --> toggle collapse
If you don't mind a little hacking, then you may write a simple script for inverting the "collapsed" attribute of each cell from false to true
in the notebook .ipynb file (which is a simple JSON file).
This is however may fail in the future if a the .ipynb format changes.

Can I create an iPython notebook using JavaScript as the language in the cells?

I love IPython to explain algorithms in python. But I want to do the same using javascript. Is it possible to write a notebook where I use javascript as the cell language?
You can use the %%javascript magic function for running javascript in IPython notebook. For example Paste the following code in a IPython cell and run it. You should see the output in your browser's javascript console.
%%javascript
console.log("Hello World!")
For global variables, you can add an attribute to the windows object for
example, in a cell run the following code:
%%javascript
window.myvar = 12;
In another cell, run the following code and check browser's javascript console. The variable's value should be printed.
%%javascript
console.log(myvar)
Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)

How to show (as output cell) the contents of a .py file with syntax highlighting?

I'm aware of the %load function (formerly %loadpy) which loads the contents of a file (or URL, ...) into a new input cell (which can be executed afterwards).
I'm also aware of %less, %more and %pycat, which show the contents of a file in a pager (which means in the notebook it's shown in the split-window at the bottom of the screen).
Is there a (magic) command to load a file and show its content (with syntax highlighting) in an output cell?
I.e. something like the following but with syntax highlighting of the result:
with open('my_file.py', 'r') as f:
print(f.read())
I want the file content to be stored with the .ipynb file but I don't want it to be executed when I do Cell -> Run All.
Is there a command similar to %psource which shows the source code in an output cell instead of a pager?
Example code based on answer by #Matt:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import IPython
with open('my_file.py') as f:
code = f.read()
formatter = HtmlFormatter()
IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, PythonLexer(), formatter)))
No there is not way to do that with current magics, but it is pretty easy using pygments and returning IPython.display.HTML(...).
10 years later, and there's now a much simpler solution:
https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.Code
from IPython.display import Code
Code(filename='my_file.py', language='python')