import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)  # if you do not have latex installed simply uncomment this line + line 75


def load_data():
    """ loads the data for this task
    :return:
    """
    fpath = 'images/ball.png'
    radius = 70
    Im = cv2.imread(fpath, 0).astype('float32')/255  # 0 .. 1

    # we resize the image to speed-up the level set method
    Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)

    height, width = Im.shape

    centre = (width // 2, height // 2)
    Y, X = np.ogrid[:height, :width]
    phi = radius - np.sqrt((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)

    return Im, phi


def get_contour(phi):
    """ get all points on the contour
    :param phi:
    :return: [(x, y), (x, y), ....]  points on contour
    """
    eps = 1
    A = (phi > -eps) * 1
    B = (phi < eps) * 1
    D = (A - B).astype(np.int32)
    D = (D == 0) * 1
    Y, X = np.nonzero(D)
    return np.array([X, Y]).transpose()

# ===========================================
# RUNNING
# ===========================================

# FUNCTIONS
# ------------------------
# your implementation here

# ------------------------
    
def div(x,y):
    # print (x.shape)
    #print (y.shape)
    
    nx = np.shape(x)[0]
    n = 1        
    phix = (x[np.hstack((np.arange(1,nx),[nx-1])),:] - x[np.hstack(([0],np.arange(0,nx-1))),:])/2.
    phix[0,:] = + x[1,:]/2. + x[0,:]           
    phix[1,:] = + x[1,:]/2. - x[0,:]
    phix[nx-1,:] = - x[nx-1,:]-x[nx-2,:]/2.
    phix[nx-2,:] = + x[nx-1,:]-x[nx-3,:]/2.
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[ny-1]))] - y[:,np.hstack(([0],np.arange(0,ny-1)))])/2.
    phiy[:,0] = + y[:,1]/2. + y[:,0]
    phiy[:,1] = + y[:,2]/2. - y[:,0]
    phiy[:,ny-1] = - y[:,ny-1]-y[:,ny-2]/2.
    phiy[:,ny-2] = + y[:,ny-1]-y[:,ny-3]/2.
    '''
    nx = np.shape(x)[0]
    phix = (x[np.hstack((np.arange(1,nx),[0])),:]) - (x[np.hstack(([nx-1],np.arange(0,nx-1))),:])
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[0]))]) - (y[:,np.hstack(([ny-1],np.arange(0,ny-1)))])
    '''
    return (phix+phiy)
    


if __name__ == '__main__':

    n_steps = 200
    plot_every_n_step = 100

    Im, phi = load_data()

    fig = plt.figure(figsize=(16, 8))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    # ------------------------
    # your implementation here

    # ------------------------    
   # print(phi)
    gradient = np.gradient(Im, 2)
    #print(gradient)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    eps = np.finfo(float).eps
    weight = 1./(distance+1)    
   # print(weight)
    n = 200
    
   # plt.figure(figsize=(10,5))
   # ax2.imshow(w)
   # ax2.set_title(r'$\phi$', fontsize=22)
   # plt.show()\
   
    gWeight = np.gradient(weight, 2)
    #print (gWeight.shape)
    '''
    grad = np.gradient(phi, 2)
    #print (grad)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    #print (distance.shape)
    g = grad/np.repeat(distance[:,:,np.newaxis], 1, 2)
    g = np.array(g)
    print(g.shape)
    K = distance*div(g[:,:,0], g[:,:,1])
    phi = phi + plot_every_n_step*K
    '''
    for t in range(n_steps):
        # ------------------------
        # your implementation here

        # ------------------------        
        grad = np.gradient(phi, 2)
        grad = np.array(grad)
        #print (grad)
        distance = np.sqrt(np.sum(grad**2, 2))
        distance = np.array(distance)
        #print (distance.shape)
        g = grad/np.repeat(distance[:,:,np.newaxis], 1, 2)
        g = np.array(g)        
        #print(g.shape)
        deltaPhi = distance*div(g[:,:,0], g[:,:,1])
        phi =  plot_every_n_step* deltaPhi
        if t % plot_every_n_step == 0:
            ax1.clear()
            ax1.imshow(Im, cmap='gray')
            ax1.set_title('frame ' + str(t))

            contour = get_contour(phi)
            if len(contour) > 0:
                ax1.scatter(contour[:, 0], contour[:, 1], color='red', s=1)

            ax2.clear()
            ax2.imshow(phi)
            ax2.set_title(r'$\phi$', fontsize=22)
           # plt.pause(0.01)

    plt.show()

a0e705b28f6c83e9bad50fb994c5c53cf8000636
<mask token>


def load_data():
    """ loads the data for this task
    :return:
    """
    fpath = 'images/ball.png'
    radius = 70
    Im = cv2.imread(fpath, 0).astype('float32') / 255
    Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)
    height, width = Im.shape
    centre = width // 2, height // 2
    Y, X = np.ogrid[:height, :width]
    phi = radius - np.sqrt((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)
    return Im, phi


<mask token>

<mask token>


def load_data():
    """ loads the data for this task
    :return:
    """
    fpath = 'images/ball.png'
    radius = 70
    Im = cv2.imread(fpath, 0).astype('float32') / 255
    Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)
    height, width = Im.shape
    centre = width // 2, height // 2
    Y, X = np.ogrid[:height, :width]
    phi = radius - np.sqrt((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)
    return Im, phi


def get_contour(phi):
    """ get all points on the contour
    :param phi:
    :return: [(x, y), (x, y), ....]  points on contour
    """
    eps = 1
    A = (phi > -eps) * 1
    B = (phi < eps) * 1
    D = (A - B).astype(np.int32)
    D = (D == 0) * 1
    Y, X = np.nonzero(D)
    return np.array([X, Y]).transpose()


def div(x, y):
    nx = np.shape(x)[0]
    n = 1
    phix = (x[np.hstack((np.arange(1, nx), [nx - 1])), :] - x[np.hstack(([0
        ], np.arange(0, nx - 1))), :]) / 2.0
    phix[0, :] = +x[1, :] / 2.0 + x[0, :]
    phix[1, :] = +x[1, :] / 2.0 - x[0, :]
    phix[nx - 1, :] = -x[nx - 1, :] - x[nx - 2, :] / 2.0
    phix[nx - 2, :] = +x[nx - 1, :] - x[nx - 3, :] / 2.0
    ny = np.shape(y)[1]
    phiy = (y[:, np.hstack((np.arange(1, ny), [ny - 1]))] - y[:, np.hstack(
        ([0], np.arange(0, ny - 1)))]) / 2.0
    phiy[:, 0] = +y[:, 1] / 2.0 + y[:, 0]
    phiy[:, 1] = +y[:, 2] / 2.0 - y[:, 0]
    phiy[:, ny - 1] = -y[:, ny - 1] - y[:, ny - 2] / 2.0
    phiy[:, ny - 2] = +y[:, ny - 1] - y[:, ny - 3] / 2.0
    """
    nx = np.shape(x)[0]
    phix = (x[np.hstack((np.arange(1,nx),[0])),:]) - (x[np.hstack(([nx-1],np.arange(0,nx-1))),:])
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[0]))]) - (y[:,np.hstack(([ny-1],np.arange(0,ny-1)))])
    """
    return phix + phiy


<mask token>

<mask token>
rc('text', usetex=True)


def load_data():
    """ loads the data for this task
    :return:
    """
    fpath = 'images/ball.png'
    radius = 70
    Im = cv2.imread(fpath, 0).astype('float32') / 255
    Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)
    height, width = Im.shape
    centre = width // 2, height // 2
    Y, X = np.ogrid[:height, :width]
    phi = radius - np.sqrt((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)
    return Im, phi


def get_contour(phi):
    """ get all points on the contour
    :param phi:
    :return: [(x, y), (x, y), ....]  points on contour
    """
    eps = 1
    A = (phi > -eps) * 1
    B = (phi < eps) * 1
    D = (A - B).astype(np.int32)
    D = (D == 0) * 1
    Y, X = np.nonzero(D)
    return np.array([X, Y]).transpose()


def div(x, y):
    nx = np.shape(x)[0]
    n = 1
    phix = (x[np.hstack((np.arange(1, nx), [nx - 1])), :] - x[np.hstack(([0
        ], np.arange(0, nx - 1))), :]) / 2.0
    phix[0, :] = +x[1, :] / 2.0 + x[0, :]
    phix[1, :] = +x[1, :] / 2.0 - x[0, :]
    phix[nx - 1, :] = -x[nx - 1, :] - x[nx - 2, :] / 2.0
    phix[nx - 2, :] = +x[nx - 1, :] - x[nx - 3, :] / 2.0
    ny = np.shape(y)[1]
    phiy = (y[:, np.hstack((np.arange(1, ny), [ny - 1]))] - y[:, np.hstack(
        ([0], np.arange(0, ny - 1)))]) / 2.0
    phiy[:, 0] = +y[:, 1] / 2.0 + y[:, 0]
    phiy[:, 1] = +y[:, 2] / 2.0 - y[:, 0]
    phiy[:, ny - 1] = -y[:, ny - 1] - y[:, ny - 2] / 2.0
    phiy[:, ny - 2] = +y[:, ny - 1] - y[:, ny - 3] / 2.0
    """
    nx = np.shape(x)[0]
    phix = (x[np.hstack((np.arange(1,nx),[0])),:]) - (x[np.hstack(([nx-1],np.arange(0,nx-1))),:])
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[0]))]) - (y[:,np.hstack(([ny-1],np.arange(0,ny-1)))])
    """
    return phix + phiy


if __name__ == '__main__':
    n_steps = 200
    plot_every_n_step = 100
    Im, phi = load_data()
    fig = plt.figure(figsize=(16, 8))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    gradient = np.gradient(Im, 2)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    eps = np.finfo(float).eps
    weight = 1.0 / (distance + 1)
    n = 200
    gWeight = np.gradient(weight, 2)
    """
    grad = np.gradient(phi, 2)
    #print (grad)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    #print (distance.shape)
    g = grad/np.repeat(distance[:,:,np.newaxis], 1, 2)
    g = np.array(g)
    print(g.shape)
    K = distance*div(g[:,:,0], g[:,:,1])
    phi = phi + plot_every_n_step*K
    """
    for t in range(n_steps):
        grad = np.gradient(phi, 2)
        grad = np.array(grad)
        distance = np.sqrt(np.sum(grad ** 2, 2))
        distance = np.array(distance)
        g = grad / np.repeat(distance[:, :, np.newaxis], 1, 2)
        g = np.array(g)
        deltaPhi = distance * div(g[:, :, 0], g[:, :, 1])
        phi = plot_every_n_step * deltaPhi
        if t % plot_every_n_step == 0:
            ax1.clear()
            ax1.imshow(Im, cmap='gray')
            ax1.set_title('frame ' + str(t))
            contour = get_contour(phi)
            if len(contour) > 0:
                ax1.scatter(contour[:, 0], contour[:, 1], color='red', s=1)
            ax2.clear()
            ax2.imshow(phi)
            ax2.set_title('$\\phi$', fontsize=22)
    plt.show()

import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)


def load_data():
    """ loads the data for this task
    :return:
    """
    fpath = 'images/ball.png'
    radius = 70
    Im = cv2.imread(fpath, 0).astype('float32') / 255
    Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)
    height, width = Im.shape
    centre = width // 2, height // 2
    Y, X = np.ogrid[:height, :width]
    phi = radius - np.sqrt((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)
    return Im, phi


def get_contour(phi):
    """ get all points on the contour
    :param phi:
    :return: [(x, y), (x, y), ....]  points on contour
    """
    eps = 1
    A = (phi > -eps) * 1
    B = (phi < eps) * 1
    D = (A - B).astype(np.int32)
    D = (D == 0) * 1
    Y, X = np.nonzero(D)
    return np.array([X, Y]).transpose()


def div(x, y):
    nx = np.shape(x)[0]
    n = 1
    phix = (x[np.hstack((np.arange(1, nx), [nx - 1])), :] - x[np.hstack(([0
        ], np.arange(0, nx - 1))), :]) / 2.0
    phix[0, :] = +x[1, :] / 2.0 + x[0, :]
    phix[1, :] = +x[1, :] / 2.0 - x[0, :]
    phix[nx - 1, :] = -x[nx - 1, :] - x[nx - 2, :] / 2.0
    phix[nx - 2, :] = +x[nx - 1, :] - x[nx - 3, :] / 2.0
    ny = np.shape(y)[1]
    phiy = (y[:, np.hstack((np.arange(1, ny), [ny - 1]))] - y[:, np.hstack(
        ([0], np.arange(0, ny - 1)))]) / 2.0
    phiy[:, 0] = +y[:, 1] / 2.0 + y[:, 0]
    phiy[:, 1] = +y[:, 2] / 2.0 - y[:, 0]
    phiy[:, ny - 1] = -y[:, ny - 1] - y[:, ny - 2] / 2.0
    phiy[:, ny - 2] = +y[:, ny - 1] - y[:, ny - 3] / 2.0
    """
    nx = np.shape(x)[0]
    phix = (x[np.hstack((np.arange(1,nx),[0])),:]) - (x[np.hstack(([nx-1],np.arange(0,nx-1))),:])
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[0]))]) - (y[:,np.hstack(([ny-1],np.arange(0,ny-1)))])
    """
    return phix + phiy


if __name__ == '__main__':
    n_steps = 200
    plot_every_n_step = 100
    Im, phi = load_data()
    fig = plt.figure(figsize=(16, 8))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    gradient = np.gradient(Im, 2)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    eps = np.finfo(float).eps
    weight = 1.0 / (distance + 1)
    n = 200
    gWeight = np.gradient(weight, 2)
    """
    grad = np.gradient(phi, 2)
    #print (grad)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    #print (distance.shape)
    g = grad/np.repeat(distance[:,:,np.newaxis], 1, 2)
    g = np.array(g)
    print(g.shape)
    K = distance*div(g[:,:,0], g[:,:,1])
    phi = phi + plot_every_n_step*K
    """
    for t in range(n_steps):
        grad = np.gradient(phi, 2)
        grad = np.array(grad)
        distance = np.sqrt(np.sum(grad ** 2, 2))
        distance = np.array(distance)
        g = grad / np.repeat(distance[:, :, np.newaxis], 1, 2)
        g = np.array(g)
        deltaPhi = distance * div(g[:, :, 0], g[:, :, 1])
        phi = plot_every_n_step * deltaPhi
        if t % plot_every_n_step == 0:
            ax1.clear()
            ax1.imshow(Im, cmap='gray')
            ax1.set_title('frame ' + str(t))
            contour = get_contour(phi)
            if len(contour) > 0:
                ax1.scatter(contour[:, 0], contour[:, 1], color='red', s=1)
            ax2.clear()
            ax2.imshow(phi)
            ax2.set_title('$\\phi$', fontsize=22)
    plt.show()

import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)  # if you do not have latex installed simply uncomment this line + line 75


def load_data():
    """ loads the data for this task
    :return:
    """
    fpath = 'images/ball.png'
    radius = 70
    Im = cv2.imread(fpath, 0).astype('float32')/255  # 0 .. 1

    # we resize the image to speed-up the level set method
    Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)

    height, width = Im.shape

    centre = (width // 2, height // 2)
    Y, X = np.ogrid[:height, :width]
    phi = radius - np.sqrt((X - centre[0]) ** 2 + (Y - centre[1]) ** 2)

    return Im, phi


def get_contour(phi):
    """ get all points on the contour
    :param phi:
    :return: [(x, y), (x, y), ....]  points on contour
    """
    eps = 1
    A = (phi > -eps) * 1
    B = (phi < eps) * 1
    D = (A - B).astype(np.int32)
    D = (D == 0) * 1
    Y, X = np.nonzero(D)
    return np.array([X, Y]).transpose()

# ===========================================
# RUNNING
# ===========================================

# FUNCTIONS
# ------------------------
# your implementation here

# ------------------------
    
def div(x,y):
    # print (x.shape)
    #print (y.shape)
    
    nx = np.shape(x)[0]
    n = 1        
    phix = (x[np.hstack((np.arange(1,nx),[nx-1])),:] - x[np.hstack(([0],np.arange(0,nx-1))),:])/2.
    phix[0,:] = + x[1,:]/2. + x[0,:]           
    phix[1,:] = + x[1,:]/2. - x[0,:]
    phix[nx-1,:] = - x[nx-1,:]-x[nx-2,:]/2.
    phix[nx-2,:] = + x[nx-1,:]-x[nx-3,:]/2.
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[ny-1]))] - y[:,np.hstack(([0],np.arange(0,ny-1)))])/2.
    phiy[:,0] = + y[:,1]/2. + y[:,0]
    phiy[:,1] = + y[:,2]/2. - y[:,0]
    phiy[:,ny-1] = - y[:,ny-1]-y[:,ny-2]/2.
    phiy[:,ny-2] = + y[:,ny-1]-y[:,ny-3]/2.
    '''
    nx = np.shape(x)[0]
    phix = (x[np.hstack((np.arange(1,nx),[0])),:]) - (x[np.hstack(([nx-1],np.arange(0,nx-1))),:])
    ny = np.shape(y)[1]
    phiy = (y[:,np.hstack((np.arange(1,ny),[0]))]) - (y[:,np.hstack(([ny-1],np.arange(0,ny-1)))])
    '''
    return (phix+phiy)
    


if __name__ == '__main__':

    n_steps = 200
    plot_every_n_step = 100

    Im, phi = load_data()

    fig = plt.figure(figsize=(16, 8))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    # ------------------------
    # your implementation here

    # ------------------------    
   # print(phi)
    gradient = np.gradient(Im, 2)
    #print(gradient)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    eps = np.finfo(float).eps
    weight = 1./(distance+1)    
   # print(weight)
    n = 200
    
   # plt.figure(figsize=(10,5))
   # ax2.imshow(w)
   # ax2.set_title(r'$\phi$', fontsize=22)
   # plt.show()\
   
    gWeight = np.gradient(weight, 2)
    #print (gWeight.shape)
    '''
    grad = np.gradient(phi, 2)
    #print (grad)
    distance = np.sqrt(np.sum(np.power(gradient, 2), 2))
    #print (distance.shape)
    g = grad/np.repeat(distance[:,:,np.newaxis], 1, 2)
    g = np.array(g)
    print(g.shape)
    K = distance*div(g[:,:,0], g[:,:,1])
    phi = phi + plot_every_n_step*K
    '''
    for t in range(n_steps):
        # ------------------------
        # your implementation here

        # ------------------------        
        grad = np.gradient(phi, 2)
        grad = np.array(grad)
        #print (grad)
        distance = np.sqrt(np.sum(grad**2, 2))
        distance = np.array(distance)
        #print (distance.shape)
        g = grad/np.repeat(distance[:,:,np.newaxis], 1, 2)
        g = np.array(g)        
        #print(g.shape)
        deltaPhi = distance*div(g[:,:,0], g[:,:,1])
        phi =  plot_every_n_step* deltaPhi
        if t % plot_every_n_step == 0:
            ax1.clear()
            ax1.imshow(Im, cmap='gray')
            ax1.set_title('frame ' + str(t))

            contour = get_contour(phi)
            if len(contour) > 0:
                ax1.scatter(contour[:, 0], contour[:, 1], color='red', s=1)

            ax2.clear()
            ax2.imshow(phi)
            ax2.set_title(r'$\phi$', fontsize=22)
           # plt.pause(0.01)

    plt.show()
