In [ ]:
# import numpy as np
# import cv2

# from matplotlib import pyplot as plt
# from IPython import __version__

In [ ]:
# %reload_ext version_information
# %version_information numpy, cv2, matplotlib
# %load_ext version_information
# %reload_ext version_information
# %version_information numpy, matplotlib
# __version__
# %config InlineBackend.figure_format='retina'

In [ ]:
# from IPython.display import HTML
# video = open("walkingeye.mp4", "rb").read()
# video_encoded = video.encode("base64")
# video_tag = '<video width=300 controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
# HTML(video_tag)

In [ ]:
# def showVideo(filename):
#     from IPython.display import HTML
#     video = open(filename, "rb").read()
#     video_encoded = video.encode("base64")
#     video_tag = '<video width=300 controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
#     return HTML(video_tag)
    

# showVideo("walkingeye.mp4")

In [30]:
# %load ./test.py
%matplotlib inline
from __future__ import print_function
from __future__ import division
import cv2
import numpy as np
from matplotlib import pyplot as plt

print('OpenCV version {}'.format(cv2.__version__))

# pip install version_information
%version_information
%config InlineBackend.figure_format='retina'


OpenCV version 3.1.0-dev

In [ ]:
from IPython.display import IFrame
IFrame('http://www.macrumors.com/', width=800, height=500)

In [ ]:
from IPython.display import IFrame
IFrame('https://en.wikipedia.org', width=700, height=500)

In [ ]:
IFrame('http://www.apple.com/', width=800, height=500)

In [ ]:
HTML(html)

In [ ]:
%lsmagic

In [ ]:
# %load ./test.py
from __future__ import print_function
from __future__ import division
import cv2
import numpy as np
%version_information

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:
%who
%time
%system
%pwd
%colors nocolor
%alias
%connect_info
%env

In [ ]:


In [ ]:


In [27]:
import test2

In [28]:
test2.showVideo2("walkingeye.mp4", width=400)


Out[28]:

In [ ]:
# %load_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py

In [ ]:
# """
# An IPython extension that provides a magic command that displays
# a table with information about versions of installed modules.

# This makes it much easier to determine which versions of modules
# were installed in the source IPython interpreter's environment.

# Produces output in:

# * Plaintext (IPython [qt]console)
# * HTML (IPython notebook, ``nbconvert --to html``, ``--to slides``)
# * JSON (IPython notebook ``.ipynb`` files)
# * LaTeX (e.g. ``ipython nbconvert example.ipynb --to LaTeX --post PDF``)

# Usage
# ======

# .. sourcecode:: ipython

#    In [1]: %load_ext version_information

#    In [2]: %version_information
#    Out[2]:
#    Software versions
#    Python 2.7.3 (default, Sep 26 2013, 20:08:41) [GCC 4.6.3]
#    IPython 2.0.0-dev
#    OS posix [linux2]

#    Mon Dec 09 10:21:40 2013 CST

#    In [3]: %version_information sphinx, jinja2
#    Out[3]:
#    Software versions
#    Python 2.7.3 (default, Sep 26 2013, 20:08:41) [GCC 4.6.3]
#    IPython 2.0.0-dev
#    OS posix [linux2]
#    sphinx 1.2b3
#    jinja2 2.7.1

#    Mon Dec 09 10:21:52 2013 CST

# .. note:: ``%version_information`` expects to find the module version in
#    ``<module>.__version__``.

#    If ``<module>.__version__`` is not set, it attempts to get a version
#    string with ``pkg_resources.require('<module>')[0].version``
#    (the ``version`` field from ``setup.py``).

# """
# import cgi
# import json
# import sys
# import time
# import locale
# import IPython
# import platform
# from IPython.core.magic import magics_class, line_magic, Magics

# try:
#     import pkg_resources
# except ImportError:
#     pkg_resources = None

# timefmt = '%a %b %d %H:%M:%S %Y %Z'


# def _date_format_encoding():
#     return locale.getlocale(locale.LC_TIME)[1] or locale.getpreferredencoding()


# @magics_class
# class VersionInformation(Magics):

#     @line_magic
#     def version_information(self, line=''):
#         """Show information about versions of modules.

#         Usage:

#             %version_information [optional comma-separated list of modules]

#         """
#         self.packages = [
#             ("Python", "{version} {arch} [{compiler}]".format(
#                 version=platform.python_version(),
#                 arch=platform.architecture()[0],
#                 compiler=platform.python_compiler())),
#             ("IPython", IPython.__version__),
#             ("OS", platform.platform().replace('-', ' '))
#             ]

#         modules = line.replace(' ', '').split(",")

#         for module in modules:
#             if len(module) > 0:
#                 try:
#                     code = ("import %s; version=str(%s.__version__)" %
#                             (module, module))
#                     ns_g = ns_l = {}
#                     exec(compile(code, "<string>", "exec"), ns_g, ns_l)
#                     self.packages.append((module, ns_l["version"]))
#                 except Exception as e:
#                     try:
#                         if pkg_resources is None:
#                             raise
#                         version = pkg_resources.require(module)[0].version
#                         self.packages.append((module, version))
#                     except Exception as e:
#                         self.packages.append((module, str(e)))

#         return self

#     def _repr_json_(self):
#         obj = {
#             'Software versions': [
#                 {'module': name, 'version': version} for
#                 (name, version) in self.packages]}
#         if IPython.version_info[0] >= 3:
#             return obj
#         else:
#             return json.dumps(obj)

#     def _repr_html_(self):

#         html = "<table>"
#         html += "<tr><th>Software mmm</th><th>Version</th></tr>"
#         for name, version in self.packages:
#             _version = cgi.escape(version)
#             html += "<tr><td>%s</td><td>%s</td></tr>" % (name, _version)

#         try:
#             html += "<tr><td colspan='2'>%s</td></tr>" % time.strftime(timefmt)
#         except:
#             html += "<tr><td colspan='2'>%s</td></tr>" % \
#                 time.strftime(timefmt).decode(_date_format_encoding())
#         html += "</table>"

#         return html

#     @staticmethod
#     def _latex_escape(str_):
#         CHARS = {
#             '&':  r'\&',
#             '%':  r'\%',
#             '$':  r'\$',
#             '#':  r'\#',
#             '_':  r'\_',
#             '{':  r'\letteropenbrace{}',
#             '}':  r'\letterclosebrace{}',
#             '~':  r'\lettertilde{}',
#             '^':  r'\letterhat{}',
#             '\\': r'\letterbackslash{}',
#             '>':  r'\textgreater',
#             '<':  r'\textless',
#         }
#         return u"".join([CHARS.get(c, c) for c in str_])

#     def _repr_latex_(self):

#         latex = r"\begin{tabular}{|l|l|}\hline" + "\n"
#         latex += r"{\bf Software} & {\bf Version} \\ \hline\hline" + "\n"
#         for name, version in self.packages:
#             _version = self._latex_escape(version)
#             latex += r"%s & %s \\ \hline" % (name, _version) + "\n"

#         try:
#             latex += r"\hline \multicolumn{2}{|l|}{%s} \\ \hline" % \
#                 time.strftime(timefmt) + "\n"
#         except:
#             latex += r"\hline \multicolumn{2}{|l|}{%s} \\ \hline" % \
#                 time.strftime(timefmt).decode(_date_format_encoding()) + "\n"

#         latex += r"\end{tabular}" + "\n"

#         return latex

#     def _repr_pretty_(self, pp, cycle):

#         text = "Software versions\n"
#         for name, version in self.packages:
#             text += "%s %s\n" % (name, version)

#         try:
#             text += "%s" % time.strftime(timefmt)
#         except:
#             text += "%s" % \
#                 time.strftime(timefmt).decode(_date_format_encoding())

#         pp.text(text)


# def load_ipython_extension(ipython):
#     ipython.register_magics(VersionInformation)

In [26]:
%reload_ext version_information
%version_information numpy, matplotlib, cv2


Out[26]:
SoftwareVersion
Python2.7.12 64bit [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)]
IPython5.1.0
OSDarwin 16.3.0 x86_64 i386 64bit
numpy1.11.2
matplotlib1.5.3
cv23.1.0-dev
Fri Dec 23 09:04:47 2016 MST

In [ ]:

Commands

Git

You can actually issues git commands from the notebook.

!git add <file>
!git commit -m "message"
!git push

In [18]:
!git status


On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   face_detection.ipynb
	modified:   histogram_tracking-Copy2.ipynb

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	hello.c
	hello.o
	hello.py
	libhello.so
	misc.ipynb
	simplehtml.ipynb
	test.py
	test2.py
	walkingeye.mp4

no changes added to commit (use "git add" and/or "git commit -a")

Command Line


In [19]:
!ls


DH.ipynb                       histogram_tracking-Copy1.ipynb
Gait.ipynb                     histogram_tracking-Copy2.ipynb
Gait_Code_Check.ipynb          histogram_tracking.ipynb
OpenCV_test.ipynb              libhello.so
README.md                      misc.ipynb
cm.ipynb                       simplehtml.ipynb
face_detection.ipynb           stitch_pics
face_pics                      stitcher.ipynb
hello.c                        test.py
hello.o                        test2.py
hello.py                       test2.pyc
hello.pyc                      video_odometry.ipynb
hist_pics                      walkingeye.mp4

In [21]:
!df -h


Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1     233Gi   63Gi  169Gi    28% 1033140 4293934139    0%   /
devfs          186Ki  186Ki    0Bi   100%     642          0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%       0          0  100%   /home

C and Python



In [3]:
%%file hello.c

#include <stdio.h>
#include <math.h>

int hello(int j);

int hello(int j){
    int i;
    int sum = 0;
    for(i=0; i<j; ++i){
        sum += 10;
        // printf("hello world: %d\n", sum);
    }
    
    return sum;
}


Overwriting hello.c

In [4]:
!gcc -c -O2 -fPIC -o hello.o hello.c
!gcc -o libhello.so -shared hello.o

In [5]:
!file libhello.so


libhello.so: Mach-O 64-bit dynamically linked shared library x86_64

In [6]:
%%file hello.py

import numpy
import ctypes

_libhello = numpy.ctypeslib.load_library('libhello', '.')

_libhello.hello.argtypes = [ctypes.c_int]
_libhello.hello.restype  =  ctypes.c_int

def hello(n):
    return _libhello.hello(int(n))


Overwriting hello.py

In [7]:
import hello

Note, the printf will go to standard out, which is the termial where you launched jupyter notebook and not to this cell.


In [8]:
hello.hello(1000)


Out[8]:
10000

In [9]:
!ls


DH.ipynb                       histogram_tracking-Copy1.ipynb
Gait.ipynb                     histogram_tracking-Copy2.ipynb
Gait_Code_Check.ipynb          histogram_tracking.ipynb
OpenCV_test.ipynb              libhello.so
README.md                      misc.ipynb
cm.ipynb                       simplehtml.ipynb
face_detection.ipynb           stitch_pics
face_pics                      stitcher.ipynb
hello.c                        test.py
hello.o                        test2.py
hello.py                       test2.pyc
hello.pyc                      video_odometry.ipynb
hist_pics                      walkingeye.mp4

In [16]:
timeit hello.hello(1000)


The slowest run took 49.46 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 716 ns per loop

In [23]:
# Let's make a pure python example for comparison
def hellotest(n):
    sum = 0
    for i in range(n):
        sum += 10
    return sum

In [24]:
hellotest(1000)


Out[24]:
10000

In [25]:
timeit hellotest(1000)


The slowest run took 5.51 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 41.4 µs per loop

In [37]:
fig1 = plt.figure(figsize = (8,8)) # create a figure with the default size 

im1 = np.random.rand(5,5)
ax1 = fig1.add_subplot(1,2,1) 
ax1.imshow(im1, interpolation='none')
ax1.set_title('5 X 5')

im2 = np.random.rand(100,100)
ax2 = fig1.add_subplot(1,2,2)
ax2.imshow(im2, interpolation='none')
ax2.set_title('100 X 100');



In [38]:
# change the figure size
fig2 = plt.figure(figsize = (1,1)) # create a 5 x 5 figure 
ax3 = fig2.add_subplot(111)
ax3.imshow(im1, interpolation='none')
ax3.set_title('larger figure');



In [128]:
# from math import ceil
# def imshow(images, bgr=True, width=4, titles=None):
#     for i, im in enumerate(images):
#         num = len(images)
#         if num > width:
#             col = width
#         else:
#             col = num
#         row = int(ceil(num/col))
#         plt.subplot(row, col, i+1)

#         # plot RGB images
#         if len(im.shape) > 2:
#             if bgr:
#                 im = opencv2matplotlib(im)
#             plt.imshow(im)
#         # plot grayscale images
#         else:
#             plt.imshow(im, cmap='gray')

#         f = plt.gca()
#         f.axes.get_xaxis().set_visible(False)
#         f.axes.get_yaxis().set_visible(False)
#         if titles:
#             plt.title(titles[i])

In [129]:
# from math import ceil
# def imshow(images, bgr=True, width=4, titles=None, figsize=None, showaxes=True):
#     # edit the size of the figures
#     if figsize:
#         fs = figsize
#         fig = plt.figure(figsize=fs)
#     else:
#         fig = plt.figure()
    
#     # figure out the number of subplots
#     num = len(images)
#     if num > width:
#         col = width
#     else:
#         col = num
#     row = int(ceil(num/col))
    
# #     print('row', row)
# #     print('col', col)
    
#     # draw the plots
#     for i, im in enumerate(images):
#         f = fig.add_subplot(row, col, i+1)

#         # plot RGB images
#         if len(im.shape) > 2:
#             if bgr:
#                 im = opencv2matplotlib(im)
#             f.imshow(im)
#         # plot grayscale images
#         else:
#             f.imshow(im, cmap='gray')

#         # do we want axes?
#         if showaxes:
#             pass
#         else:
#             ff = plt.gca()
#             ff.axes.get_xaxis().set_visible(False)
#             ff.axes.get_yaxis().set_visible(False)
        
#         # do we want titles?
#         if titles:
#             f.title(titles[i])
        
#     # clean up and make pretty
#     plt.tight_layout()

In [130]:
# from math import ceil
# import opencvutils as cvu
# def imshow(images, bgr=True, width=4, titles=None, figsize=None, showaxes=False):
#     """
#     Make an array of plots.
    
#     exmaple:
#         imshow([im1,im2], bgr=True, width=1, titles=['one', 'two'], figsize=(4,2), showaxes=True)
    
#     params:
#         images - array of images
#         bgr - if a color image, assume it is opencv and switch it rgb format
#         width - how many images wide
#         figsize - a tuple (width,height) of how wide the figure should be in inches (this is depended on your dpi setting)
#         titles - an array of titles for each subplot
#         showaxes - True/False to show axes
#     """
#     # edit the size of the figures
#     if figsize:
#         fs = figsize
#         plt.figure(figsize=fs)
#     else:
#         plt.figure()
    
#     # figure out the number of subplots
#     num = len(images)
#     if num > width:
#         col = width
#     else:
#         col = num
#     row = int(ceil(num/col))
    
#     # draw the plots
#     for i, im in enumerate(images):
#         plt.subplot(row, col, i+1)

#         # plot RGB images
#         if len(im.shape) > 2:
#             if bgr:
#                 im = cvu.opencv2matplotlib(im)
#             plt.imshow(im)
#         # plot grayscale images
#         else:
#             plt.imshow(im, cmap='gray')

#         # do we want axes?
#         if showaxes:
#             pass
#         else:
#             plt.xticks(())
#             plt.yticks(())
        
#         # do we want titles?
#         if titles:
#             plt.title(titles[i])
        
#     # clean up and make pretty
#     plt.tight_layout()

In [127]:
# imshow([im1,im1,im1,im1,im1,im1,im1,im1], width=5, figsize=(8,4), showaxes=False)

In [126]:
# imshow([im1,im1,im1], width=2, figsize=(8,8))

In [123]:
# import opencvutils as cvu
pic = cvu.url_to_image('https://s-media-cache-ak0.pinimg.com/564x/76/c7/7c/76c77c6fa937a0df3be1df8873006af0.jpg')
# pic = cvu.opencv2matplotlib(pic)
pic.shape


Out[123]:
(752, 564, 3)

In [124]:
plt.figure(figsize=(2,2))
plt.imshow(cvu.opencv2matplotlib(pic));



In [125]:
imshow([pic,pic,pic], width=1, figsize=(1,3))



In [ ]: