In [2]:
from scipy import misc
import matplotlib.pyplot as plt

In [3]:
plt.imshow(misc.face())


Out[3]:
<matplotlib.image.AxesImage at 0x8b2d6a0>

In [4]:
plt.show()



In [5]:
plt.imsave('face.png', misc.face())

In [6]:
img = misc.imread('face.png')

In [7]:
import numpy

In [8]:
type(img)


Out[8]:
numpy.ndarray

In [9]:
img.shape


Out[9]:
(768, 1024, 4)

In [10]:
img


Out[10]:
array([[[121, 112, 131, 255],
        [138, 129, 148, 255],
        [153, 144, 165, 255],
        ..., 
        [119, 126,  74, 255],
        [131, 136,  82, 255],
        [139, 144,  90, 255]],

       [[ 89,  82, 100, 255],
        [110, 103, 121, 255],
        [130, 122, 143, 255],
        ..., 
        [118, 125,  71, 255],
        [134, 141,  87, 255],
        [146, 153,  99, 255]],

       [[ 73,  66,  84, 255],
        [ 94,  87, 105, 255],
        [115, 108, 126, 255],
        ..., 
        [117, 126,  71, 255],
        [133, 142,  87, 255],
        [144, 153,  98, 255]],

       ..., 
       [[ 87, 106,  76, 255],
        [ 94, 110,  81, 255],
        [107, 124,  92, 255],
        ..., 
        [120, 158,  97, 255],
        [119, 157,  96, 255],
        [119, 158,  95, 255]],

       [[ 85, 101,  72, 255],
        [ 95, 111,  82, 255],
        [112, 127,  96, 255],
        ..., 
        [121, 157,  96, 255],
        [120, 156,  94, 255],
        [120, 156,  94, 255]],

       [[ 85, 101,  74, 255],
        [ 97, 113,  84, 255],
        [111, 126,  97, 255],
        ..., 
        [120, 156,  95, 255],
        [119, 155,  93, 255],
        [118, 154,  92, 255]]], dtype=uint8)

In [11]:
img[img < 128] = 0
img[img >= 128] = 255

In [12]:
plt.imshow(img)


Out[12]:
<matplotlib.image.AxesImage at 0x8a1d160>

In [13]:
plt.show()



In [14]:
img


Out[14]:
array([[[  0,   0, 255, 255],
        [255, 255, 255, 255],
        [255, 255, 255, 255],
        ..., 
        [  0,   0,   0, 255],
        [255, 255,   0, 255],
        [255, 255,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [255,   0, 255, 255],
        ..., 
        [  0,   0,   0, 255],
        [255, 255,   0, 255],
        [255, 255,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        ..., 
        [  0,   0,   0, 255],
        [255, 255,   0, 255],
        [255, 255,   0, 255]],

       ..., 
       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        ..., 
        [  0, 255,   0, 255],
        [  0, 255,   0, 255],
        [  0, 255,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        ..., 
        [  0, 255,   0, 255],
        [  0, 255,   0, 255],
        [  0, 255,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        ..., 
        [  0, 255,   0, 255],
        [  0, 255,   0, 255],
        [  0, 255,   0, 255]]], dtype=uint8)

In [15]:
imgL = misc.imread('face.png', mode='L')

In [16]:
imgL.shape


Out[16]:
(768, 1024)

In [17]:
imgL[0]


Out[17]:
array([116, 133, 149, ..., 117, 128, 136], dtype=uint8)

In [18]:
misc.imsave('faceL.png', imgL)

In [19]:
imgL[imgL < 128] = 0
imgL[imgL >= 128] = 255

misc.imsave('faceL_bw.png', imgL)

In [21]:
fl = misc.imread('faceL_bw.png')
plt.imshow(fl)
plt.show()



In [22]:
del fl

In [23]:
fl


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-51ac5d3f32be> in <module>()
----> 1 fl

NameError: name 'fl' is not defined

In [24]:
import to_bw

In [25]:
to_bw.to_bw


Out[25]:
<function to_bw.to_bw>

In [30]:
hanabi = misc.imread('hanabi_bw.png', mode='L')

In [31]:
plt.imshow(hanabi)
plt.show()



In [32]:
hanabi.shape


Out[32]:
(752, 1199)

In [33]:
hanabi


Out[33]:
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ..., 
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)

In [36]:
hanabi == hanabi


Out[36]:
array([[ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       ..., 
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True]], dtype=bool)

In [40]:
hanabi[0][hanabi[0] == 255]


Out[40]:
array([255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
       255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
       255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
       255, 255], dtype=uint8)

In [44]:
numpy.nonzero(hanabi)


Out[44]:
(array([  0,   0,   0, ..., 751, 751, 751], dtype=int64),
 array([209, 210, 232, ..., 727, 728, 730], dtype=int64))

In [46]:
# this is equivalent to the data plot!
X, y = numpy.nonzero(hanabi)

In [47]:
X


Out[47]:
array([  0,   0,   0, ..., 751, 751, 751], dtype=int64)

In [48]:
y


Out[48]:
array([209, 210, 232, ..., 727, 728, 730], dtype=int64)

In [49]:
data = numpy.transpose(numpy.nonzero(hanabi))

In [50]:
from sklearn.mixture import GaussianMixture

In [51]:
est = GaussianMixture(n_components=20, covariance_type='full')

In [52]:
est.fit(data)


Out[52]:
GaussianMixture(covariance_type='full', init_params='kmeans', max_iter=100,
        means_init=None, n_components=20, n_init=1, precisions_init=None,
        random_state=None, reg_covar=1e-06, tol=0.001, verbose=0,
        verbose_interval=10, warm_start=False, weights_init=None)

In [53]:
def make_ellipses(gmm, ax):
    for n, color in enumerate(colors):
        if gmm.covariance_type == 'full':
            covariances = gmm.covariances_[n][:2, :2]
        elif gmm.covariance_type == 'tied':
            covariances = gmm.covariances_[:2, :2]
        elif gmm.covariance_type == 'diag':
            covariances = np.diag(gmm.covariances_[n][:2])
        elif gmm.covariance_type == 'spherical':
            covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[n]
        v, w = np.linalg.eigh(covariances)
        u = w[0] / np.linalg.norm(w[0])
        angle = np.arctan2(u[1], u[0])
        angle = 180 * angle / np.pi  # convert to degrees
        v = 2. * np.sqrt(2.) * np.sqrt(v)
        ell = mpl.patches.Ellipse(gmm.means_[n, :2], v[0], v[1],
                                  180 + angle, color=color)
        ell.set_clip_box(ax.bbox)
        ell.set_alpha(0.5)
        ax.add_artist(ell)

In [56]:
from matplotlib import cm
colors=iter(cm.rainbow(numpy.linspace(0,1,20)))

In [59]:
data.shape


Out[59]:
(170359, 2)

In [68]:
plt.scatter(data[:,0], data[:,1], s=0.001)
plt.show()



In [71]:
import numpy as np
import matplotlib as mpl
make_ellipses(est, plt.plot())


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-71-eceec7b798e3> in <module>()
      1 import numpy as np
      2 import matplotlib as mpl
----> 3 make_ellipses(est, plt.plot())

<ipython-input-53-38cc3cf31af5> in make_ellipses(gmm, ax)
     17         ell = mpl.patches.Ellipse(gmm.means_[n, :2], v[0], v[1],
     18                                   180 + angle, color=color)
---> 19         ell.set_clip_box(ax.bbox)
     20         ell.set_alpha(0.5)
     21         ax.add_artist(ell)

AttributeError: 'list' object has no attribute 'bbox'

In [72]:
est.covariances_


Out[72]:
array([[[ 1251.49836011,   111.00584494],
        [  111.00584494,  1555.58323133]],

       [[ 2572.10827833,    47.65989465],
        [   47.65989465,  2623.61288397]],

       [[ 3462.09883697,  -235.5696768 ],
        [ -235.5696768 ,   916.33592397]],

       [[ 1275.91244651,   104.11090696],
        [  104.11090696,  2954.87316822]],

       [[ 5159.90735999, -1372.48726701],
        [-1372.48726701,  5843.06404057]],

       [[ 1806.99714738,   792.42042358],
        [  792.42042358,  2991.21085893]],

       [[  814.82191626,   126.04172262],
        [  126.04172262,   852.92943513]],

       [[ 2874.44297463,  -180.29466835],
        [ -180.29466835,  4043.16591993]],

       [[ 3497.37978616,  1010.9549114 ],
        [ 1010.9549114 ,  2927.3903949 ]],

       [[ 3199.60290226,   278.00893959],
        [  278.00893959,  2711.75636593]],

       [[ 1556.24956188,   511.11178794],
        [  511.11178794,  2796.56477287]],

       [[ 1594.5824368 ,  -498.07807304],
        [ -498.07807304,  1318.62696313]],

       [[ 2772.61620968,   786.11593909],
        [  786.11593909,  2442.18245905]],

       [[ 1716.70593717,   220.08688653],
        [  220.08688653,  2096.35577274]],

       [[ 1534.95328579,   533.20616295],
        [  533.20616295,  1909.94387344]],

       [[ 4175.57918372, -1112.77281039],
        [-1112.77281039,  2926.80452536]],

       [[ 3311.06472543,   402.2307756 ],
        [  402.2307756 ,  2589.69974343]],

       [[ 4298.93011085,  -831.81773051],
        [ -831.81773051,  2428.6565931 ]],

       [[ 2958.84005939,   566.55702299],
        [  566.55702299,  1495.55037513]],

       [[ 3135.43876939,    59.00898979],
        [   59.00898979,  1701.03010475]]])

In [74]:
covariances = est.covariances_

In [76]:
from matplotlib.patches import Ellipse

def plot_point_cov(points, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma ellipse based on the mean and covariance of a point
    "cloud" (points, an Nx2 array).

    Parameters
    ----------
        points : An Nx2 array of the data points.
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the 
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    pos = points.mean(axis=0)
    cov = np.cov(points, rowvar=False)
    return plot_cov_ellipse(cov, pos, nstd, ax, **kwargs)

def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma error ellipse based on the specified covariance
    matrix (`cov`). Additional keyword arguments are passed on to the 
    ellipse patch artist.

    Parameters
    ----------
        cov : The 2x2 covariance matrix to base the ellipse on
        pos : The location of the center of the ellipse. Expects a 2-element
            sequence of [x0, y0].
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the 
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]

    if ax is None:
        ax = plt.gca()

    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))

    # Width and height are "full" widths, not radius
    width, height = 2 * nstd * np.sqrt(vals)
    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)

    ax.add_artist(ellip)
    return ellip

In [ ]: