コード例 #1
0
def line_detection(image, verbose=False):
    # Líneas Horizontales
    print('\n')
    print("LÍNEAS HORIZONTALES")
    # Definimos el filtro para la detección de líneas horizontal
    kernel = np.array([[-1, -1, -1], [2, 2, 2], [-1, -1, -1]])

    # Realizamos la convolución con la imagen y el kernel anterior
    image_lines_x = convolution(image, kernel, False)

    # Se muestra la imagen con la detección de líneas horizontales.
    if verbose:
        plt.imshow(image_lines_x, cmap='gray')
        plt.title("Horizontal Lines")
        plt.show()

    # Líneas verticales
    print('\n')
    print("LÍNEAS VERTICALES")
    kernel = (kernel.T)
    image_lines_y = convolution(image, kernel, False)

    if verbose:
        plt.imshow(image_lines_y, cmap='gray')
        plt.title("Vertical Lines")
        plt.show()

    # Líneas a 45°
    print('\n')
    print("LÍNEAS 45°")
    kernel = np.array([[-1, -1, 2], [-1, 2, -1], [2, -1, -1]])
    image_lines_45_dgrs = convolution(image, kernel, False)

    if verbose:
        plt.imshow(image_lines_45_dgrs, cmap='gray')
        plt.title("45 Degree Lines")
        plt.show()

    # Líneas 135°
    print('\n')
    print("LÍNEAS 135°")
    kernel = np.fliplr(kernel)
    image_lines_135_dgrs = convolution(image, kernel, False)

    if verbose:
        plt.imshow(image_lines_135_dgrs, cmap='gray')
        plt.title("135 Degree Lines")
        plt.show()

    # Obtenemos las líneas juntando las imágenes anteriores.
    print('\n')
    print("LINE DETECTION")
    image = image_lines_x + image_lines_y + image_lines_45_dgrs + image_lines_135_dgrs

    if verbose:
        plt.imshow(image, cmap='gray')
        plt.title("Line Detection")
        plt.show()

    return image
コード例 #2
0
ファイル: sobel.py プロジェクト: Nisanchhetri/blog
def sobel_edge_detection(image,
                         filter,
                         convert_to_degree=False,
                         verbose=False):
    new_image_x = convolution(image, filter, verbose)

    if verbose:
        plt.imshow(new_image_x, cmap='gray')
        plt.title("Horizontal Edge")
        plt.show()

    new_image_y = convolution(image, np.flip(filter.T, axis=0), verbose)

    if verbose:
        plt.imshow(new_image_y, cmap='gray')
        plt.title("Vertical Edge")
        plt.show()

    gradient_magnitude = np.sqrt(
        np.square(new_image_x) + np.square(new_image_y))

    gradient_magnitude *= 255.0 / gradient_magnitude.max()

    if verbose:
        plt.imshow(gradient_magnitude, cmap='gray')
        plt.title("Gradient Magnitude")
        plt.show()

    gradient_direction = np.arctan2(new_image_y, new_image_x)

    if convert_to_degree:
        gradient_direction = np.rad2deg(gradient_direction)
        gradient_direction += 180

    return new_image_x, new_image_y, gradient_magnitude, gradient_direction
コード例 #3
0
ファイル: ej4.py プロジェクト: gciruelos/imagenes-practicas
    def border_detection(img, kernelx, kernely):
        imx = convolution.convolution(img, kernelx)
        imx = imx.astype(np.float)
        imy = convolution.convolution(img, kernely)
        imy = imy.astype(np.float)

        r = np.power(np.power(imx, 2)+np.power(imy, 2), 0.5) / np.sqrt(2.0)
        t = np.arctan(imy / (imx + 0.00001))
        return r, t  
コード例 #4
0
def border_detection(img, kernelx, kernely):
    imx = convolution.convolution(img, kernelx)
    imx = imx.astype(np.float)
    imy = convolution.convolution(img, kernely)
    imy = imy.astype(np.float)

    imx = np.power(imx, 2)
    imy = np.power(imy, 2)
    r = convolution.scale(np.power(imx + imy, 0.5)) / np.sqrt(2)
    convolution.apply_threshold(r, 150)
    return r
コード例 #5
0
def mean_filter(image, kernel_size, iterations, verbose=False):
    kernel = mean_kernel(kernel_size)
    output = np.zeros(image.shape)

    for k in range(0, iterations):
        if k == 0:
            output = convolution(image, kernel, verbose=verbose)
        else:
            image = output
            output = convolution(image, kernel, verbose=verbose)

    return output
コード例 #6
0
ファイル: prewitt.py プロジェクト: Dadajon/coursework
def prewitt_edge_detection(image):
    vertical_filter = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
    horizontal_filter = np.flip(
        vertical_filter.T,
        axis=0)  # array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])

    prewitt_x = convolution(image, vertical_filter, verbose=False)
    prewitt_y = convolution(image, horizontal_filter, verbose=False)

    # calculate gradient magnitude
    prewitt = np.hypot(prewitt_x, prewitt_y)
    prewitt *= 255.0 / prewitt.max()

    return prewitt_x, prewitt_y, prewitt
コード例 #7
0
def sobel_edge_detection(image, filter):
    new_image_x = convolution(image, filter)

    new_image_y = convolution(image, np.flip(filter.T, axis=0))

    gradient_magnitude = np.sqrt(
        np.square(new_image_x) + np.square(new_image_y))

    gradient_magnitude *= 255.0 / gradient_magnitude.max()

    gradient_direction = np.arctan2(new_image_y, new_image_x)

    gradient_direction = np.rad2deg(gradient_direction)
    gradient_direction += 180

    return gradient_magnitude, gradient_direction
コード例 #8
0
    def down(image, expected_shape=None):
        # Desce um nivel na piramide
        # Duplica linhas e colunas
        image_down = np.repeat(image, 2, axis=0)
        image_down = np.repeat(image_down, 2, axis=1)

        #Interpolation with a 3x3 box blur kernel.
        msk = np.full((3, 3), 1 / (3 * 3))
        image_down = conv.convolution(image_down, msk)

        # Fix the shape in case the lower image was odd
        if expected_shape is not None:
            if image_down.shape[0] > expected_shape[0]:
                image_down = np.delete(image_down,
                                       image_down.shape[0] - 1,
                                       axis=0)
                if image_down.shape[0] != expected_shape[0]:
                    print("Wrong shape in the axis=0.")
                    return None
            if image_down.shape[1] > expected_shape[1]:
                image_down = np.delete(image_down,
                                       image_down.shape[1] - 1,
                                       axis=1)
                if image_down.shape[1] != expected_shape[1]:
                    print("Wrong shape in the axis=1.")
                    return None

        return image_down
コード例 #9
0
def ej_c(im1):
    gaussian = np.ones((5, 5), dtype=np.float)
    gaussian[:, :] = [[1, 4, 7, 4, 1], [4, 16, 26, 16, 4], [7, 26, 41, 26, 7],
                      [4, 16, 26, 16, 4], [1, 4, 7, 4, 1]]
    gaussian[:, :] *= 1. / 273
    im2 = convolution.convolution(im1, gaussian)
    return ej_a(im2)
コード例 #10
0
    def gaussiano(im):
        gaussian = np.ones((5, 5), dtype=np.float)
        gaussian[:, :] = [[1, 4, 7, 4, 1], [4, 16, 26, 16, 4],
                          [7, 26, 41, 26, 7], [4, 16, 26, 16, 4],
                          [1, 4, 7, 4, 1]]
        gaussian[:, :] *= 1. / 273

        return convolution.convolution(im, gaussian)
コード例 #11
0
def gaussian_blur(image, kernel_size, iterations, verbose=False):
    kernel = gaussian_kernel(kernel_size, sigma=math.sqrt(kernel_size))
    output = np.zeros(image.shape)

    for k in range(0, iterations):
        if k == 0:
            output, plt = convolution(image,
                                      kernel,
                                      average=True,
                                      verbose=verbose)
        else:
            image = output
            output, plt = convolution(image,
                                      kernel,
                                      average=True,
                                      verbose=verbose)

    return output, plt
コード例 #12
0
 def up(image):
     msk = np.array([[1, 4, 6, 4, 1], [4, 16, 24, 16,
                                       4], [6, 24, 36, 24, 6],
                     [4, 16, 24, 16, 4], [1, 4, 6, 4, 1]])
     msk = msk / np.sum(msk)
     # Blur
     image_up = conv.convolution(image, msk)
     # Remove linhas e colunas pares
     image_up = image_up[::2, ::2]
     return image_up
コード例 #13
0
def sobel_edge_detection(image, convert_to_degree=False):
    vertical_filter = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    horizontal_filter = vertical_filter.T  # array([[-1, -2, -1],[ 0,  0,  0],[ 1,  2,  1]])

    sobel_x = convolution(image, vertical_filter, verbose=False)
    sobel_y = convolution(image, horizontal_filter, verbose=False)

    # calculate gradient magnitude
    G = np.hypot(
        sobel_x,
        sobel_y)  # np.hypot() = sqrt(img_x**2 + img_2**2) -> hypotenuse
    G *= 255.0 / G.max()

    # calculate gradient direction
    G_theta = np.arctan2(sobel_x, sobel_y)

    if convert_to_degree:
        G_theta = np.rad2deg(G_theta)
        G_theta += 180

    return sobel_x, sobel_y, G, G_theta
コード例 #14
0
def myEdgeFilter(img0, sigma):

    # smooth out the image
    hsize = 2 * math.ceil(3 * sigma) + 1
    kernal = cv2.getGaussianKernel(hsize, sigma)
    smoothImg = convolution(img0, kernal)

    # calculate x direction sobel
    kernal = numpy.array(([-1, 0, 1], [-2, 0, 2], [-1, 0, 1]))
    xSobel = convolution(smoothImg, kernal)
    cv2.imwrite("xSobel.png", xSobel)

    # calculate y direction sobel
    kernal = numpy.array(([-1, -2, -1], [0, 0, 0], [1, 2, 1]))
    ySobel = convolution(smoothImg, kernal)
    cv2.imwrite("ySobel.png", ySobel)

    # add x and y sobel
    # G(i,j) = sqrt(I^2(i,j) + I^2(i,j))
    sobel = numpy.sqrt(numpy.square(xSobel) + numpy.square(ySobel))
    cv2.imwrite("gradient magnitude.png", sobel)

    suppression = compare(xSobel, ySobel, sobel)
    cv2.imwrite("Non-Maximum Suppression.png", suppression)
コード例 #15
0
def laplacian(image, verbose=False):
    #se define el kernel usado para este filtro
    kernel = np.array([[0, 0, -1, 0, 0], [0, -1, -2, -1, 0],
                       [-1, -2, -16, -2, -1], [0, -1, -2, -1, 0],
                       [0, 0, -1, 0, 0]])

    #se hace la convolucion usando el kernel declarado
    image_lap = convolution(image, kernel, False)

    #se muestra la imagen
    if verbose:
        plt.imshow(image_lap, cmap='gray')
        plt.title('laplacian')
        plt.show()

    return image
コード例 #16
0
ファイル: LPoly.py プロジェクト: Agzs/BulletProof-repos
    def fft_mul(self, other):
        dnew = self.ldegree + other.ldegree
        sizenew = len(self) + len(other)

        c = LPoly(convolution(self, other))
        #print c[0][0]
        #print "c=",c
        c.setbot(dnew)
        m = self.modulus
        if m:
            c.setmodulus(m)
            for i in xrange(len(c)):
                #print sum(c[i])
                c[i] = sum(c[i]) % m

        else:
            for i in xrange(len(c)):
                c[i] = sum(c[i])
        return c
コード例 #17
0
ファイル: LPoly.py プロジェクト: Agzs/BulletProof-repos
 def fft_mul_slice(self, other):
     SLICES = 222
     vsize = len(self[0])
     for i in xrange(1 + (vsize - 1) / SLICES):
         if SLICES == 1:
             if (i % 50) == 0: print i, " of ", 1 + (vsize - 1) / SLICES
             otherslice = [si[i] for si in other]
             selfslice = [si[i] for si in self]
         else:
             if (i % 10) == 0: print i, " of ", 1 + (vsize - 1) / SLICES
             otherslice = [
                 Ve(si[i * SLICES:(i + 1) * SLICES]) for si in other
             ]
             selfslice = [
                 Ve(si[i * SLICES:(i + 1) * SLICES]) for si in self
             ]
         #selfslice.ldegree=self.ldegree
         #if self.modulus: selfslice.modulus=self.modulus
         #otherslice.ldegree=self.ldegree
         #if other.modulus: otherslice.modulus=self.modulus
         if SLICES == 1:
             ct = LPoly(convolution_scalar(selfslice, otherslice))
             ct.setmodulus(self.modulus)
         else:
             ct = LPoly(convolution(selfslice, otherslice))
         if i == 0:
             c = ct
             #c.setmodulus(self.modulus)
         else:
             c = c + ct % self.modulus
     dnew = self.ldegree + other.ldegree
     c.setbot(dnew)
     m = self.modulus
     if SLICES != 1:
         c.setmodulus(m)
         for i in xrange(len(c)):
             #if SLICES==1:
             #    c[i]=c[i]%m
             #else:
             c[i] = sum(c[i]) % self.modulus
     return c
コード例 #18
0
def ej_a(im1):
    K1, K2 = im1.shape
    im2 = convolution.convolution(im1, laplaciano)
    r = np.zeros(im1.shape, dtype=np.float)
    maximum = 0.0
    minimum = 0.0
    median = mediana_difs(im2) * 2.0
    for k1 in range(1, K1 - 1):
        for k2 in range(1, K2 - 1):
            indices = [((k1 - 1, k2 - 1), (k1 + 1, k2 + 1)),
                       ((k1, k2 - 1), (k1, k2 + 1)),
                       ((k1 - 1, k2), (k1 + 1, k2)),
                       ((k1 + 1, k2 - 1), (k1 - 1, k2 + 1))]
            found = False
            for i1, i2 in indices:
                p1 = im2[i1[0], i1[1]]
                p2 = im2[i2[0], i2[1]]
                if p1 * p2 < 0 and abs(p1 - p2) > median:
                    found = True
                    break
            r[k1, k2] = 255 if found else 0
    return r
コード例 #19
0
def ej_b(im1):
    K1, K2 = im1.shape
    im2 = convolution.convolution(im1, laplaciano)
    r = np.zeros(im1.shape, dtype=np.float)
    maximum = 0.0
    minimum = 0.0
    mediana = mediana_difs(im2) * 2.0
    for k1 in range(1, K1 - 1):
        for k2 in range(1, K2 - 1):
            indices = [((k1 - 1, k2 - 1), (k1 + 1, k2 + 1)),
                       ((k1, k2 - 1), (k1, k2 + 1)),
                       ((k1 - 1, k2), (k1 + 1, k2)),
                       ((k1 + 1, k2 - 1), (k1 - 1, k2 + 1))]
            found = False
            varianza = varianza_local(im2, 2, k1, k2)
            if varianza < VARIANZA_THRESHOLD: continue
            for i1, i2 in indices:
                p1 = im2[i1[0], i1[1]]
                p2 = im2[i2[0], i2[1]]
                if p1 * p2 < 0 and abs(p1 - p2) >= mediana:
                    found = True
                    break
            r[k1, k2] = 255 if found else 0
    return r
コード例 #20
0
# Call Option Pricing with Circular Convolution (General)

import numpy as np
from convolution import revnp, convolution
from parameters import *

# Parameter Adjustments
M = 3  #numberoftimesteps
dt, df, u, d, q = get_binomial_parameters(M)

# Array Generation for Stock Prices
mu = np.arange(M + 1)
mu = np.resize(mu, (M + 1, M + 1))
md = np.transpose(mu)
mu = u**(mu - md)
md = d**md
S = S0 * mu * md

# Valuation
V = np.maximum(S - K, 0)
qv = np.zeros((M + 1), dtype=np.float)

qv[0] = q
qv[1] = 1 - q
for t in range(M - 1, -1, -1):
    V[:, t] = convolution(V[:, t + 1], revnp(qv)) * df

print("Value of the Call Option %8.3f" % V[0, 0])
コード例 #21
0
def conv(image, label, params, conv_s, pool_f, pool_s):
    '''
    Combine the forward and backward propogation to build a method that takes the input parameters and hyperparamets as inputs and outputs gradient and loss
    '''

    [f1, f2, w3, w4, b1, b2, b3, b4] = params  #filters, weights and biases

    #############################################
    ###########Forward operation#################
    #############################################

    conv1 = convolution(image, f1, b1, conv_s)
    conv1[conv1 <= 0] = 0  #apply ReLU non-linearity

    cov2 = convolution(conv1, f2, b2, conv_s)
    conv2[conv2 <= 0] = 0

    pooled = maxpool(conv2, pool_f, pool_s)  #maxpooling

    (nf2, dim2, _) = pooled.shape
    fc = pooled.reshape((nf2 * dim2 * dim2, 1))  #flatten pooled layer

    z = w3.dot(
        fc) + b3  #pass flattened pool through first fully connected layer
    z[z <= 0] = 0  #pass through ReLU function

    out = w4.dot(z) + b4  #pass through second layer

    probs = softmax(
        out
    )  #apply softmax activation function to find prodicted probabilities

    #############################################
    ############# Loss ##########################
    #############################################
    loss = categoricalCrossEntropy(probs, label)

    ##############################################
    ############ Backward operation ##############
    ##############################################

    d_out = probs - label  #derivate of loss w.r.t final dense layer

    dw4 = d_out.dot(z.T)  #loss gradient weights
    db4 = np.sum(d_out, axis=1).reshape(b4.shape)  #loss gradient of biases

    dz = w4.T.dot(d_out)  #loss gradient of first dense layer outputs
    dz[z <= 0] = 0  #ReLU
    dw3 = dz.dot(fc.T)  #loss function os weights
    db3 = np.sum(dz, axis=1).reshape(b3.shape)

    dfc = w3.T.dot(dz)  #loss gradient of fully connested pooling layer
    dpool = dfc.reshape(
        pooled.shape)  #reshape into into dimension of pooling layer

    dconv2 = maxoolBackward(dpool, conv2, pool_f, pool_s)
    dconv2[conv2 <= 0] = 0

    dconv1, df2, db2 = convolutionBackward(dconv2, conv1, f2, conv_s)
    dconv1[conv1 <= 0] = 0

    dimage, df1, db1 = convolutionBackward(dconv1, image, f1, convs)

    grads = [df1, df2, dw3, dw4, db1, db2, db3, db4]

    return grads, loss
コード例 #22
0
ファイル: ej1.py プロジェクト: gciruelos/imagenes-practicas
low_pass_5 = np.ones((5, 5), dtype=np.float)
low_pass_5[:, :] = 1. / 25
high_pass_3 = np.ones((3, 3), dtype=np.float)
high_pass_3[:, :] /= -9.0
high_pass_3[1, 1] = 8. / 9
high_pass_5 = np.ones((5, 5), dtype=np.float)
high_pass_5[:, :] /= -25.0
high_pass_5[2, 2] = 24. / 25

kernels = {
    "low": {
        "3": low_pass_3,
        "5": low_pass_5
    },
    "high": {
        "3": high_pass_3,
        "5": high_pass_5
    }
}

im1 = np.asarray(Image.open(argv[1]).convert('L'))
im2 = convolution.convolution(im1, kernels[argv[2]][argv[3]])

print(im1)
print(im2)

side_by_side.sbys(
    [im1, im2],
    ["Original", argv[2] + "-pass filter de " + argv[3] + "x" + argv[3]],
    argv=None if len(argv) <= 4 else argv[4])
コード例 #23
0
ファイル: mapper.py プロジェクト: ELVIS-Project/Cantorinus
from ast import literal_eval
from PIL import Image
import csv
import sys
import convolution

image = Image.open("mandrill.png")
pixels = image.load()
size = image.size

reader = csv.reader(sys.stdin, delimiter=';')
gaussian_blur = convolution.generate_centered_gaussian_convolution_matrix(5, 16, 16)

for line in reader:
    index = literal_eval(line[0])
    x = index[0]
    y = index[1]

    new_pixel = convolution.convolution(convolution.unsharp_kernel, pixels, x, y, size[0], size[1])

    print("{0}\t{1}\t{2}\t{3}\t{4}".format(x, y, int(new_pixel[0]), int(new_pixel[1]), int(new_pixel[2])))

コード例 #24
0
def gaussian_blur(image, kernel_size, sigma, verbose=False):
    kernel = gaussian_kernel(kernel_size, sigma, verbose=verbose)
    return convolution(image, kernel, average=True, verbose=verbose)
コード例 #25
0
ファイル: dft.py プロジェクト: bozhu/DFT-Attack
def dft(sequence, reference=None):
    if None == reference:
        N = len(sequence)
        seq_a = list(sequence)
    else:
        N = len(reference)
        seq_a = list(reference)
        seq_a_target = list(sequence)

    fun_p = bma(seq_a * 2)  # turn sequence as periodic
    L = fun_p.degree()

    # assert 2 * L <= len(seq_a)

    # selection of parameters
    # fine smallest n, s.t. N | (2^n - 1)
    n = 1
    while 0 != (2 ** n - 1) % N:  # this means N cannot be even number
        n += 1
    # print n

    # define the extension field
    TheExtensionField = GF(2 ** n, "beta")
    beta = TheExtensionField.gen()
    fun_f = TheExtensionField.polynomial()
    TheExtensionPolynomialRing = TheExtensionField["Y"]
    # print fun_f

    # construct a new m-seq {b_t}
    seq_b_iv = []
    for i in range(n):
        seq_b_iv.append((beta ** i).trace())
    seq_b_generator = lfsr(seq_b_iv, fun_f)
    seq_b = []
    for i in range(2 ** len(seq_b_iv) - 1):
        seq_b.append(seq_b_generator.next())
    # print seq_b_iv
    # print seq_b

    # let alpha be an element in GF(2^n) with order N
    alpha = beta ** ((2 ** n - 1) / N)
    # print alpha, alpha ** N

    # procedure
    # step 1. compute coset
    I = coset(N)
    # print I

    # step 2.
    fun_p_extended = TheExtensionPolynomialRing(fun_p)
    # print fun_p_extended

    spectra_A = [None] * N
    spectra_A_target = [None] * N
    for k in I:
        if fun_p_extended(alpha ** k) != 0:
            spectra_A[k] = 0
            if reference:
                spectra_A_target[k] = 0
            continue

        # print 'k', k, fun_p_extended(alpha ** k)

        # sub-routine for computing A_k
        # 1. get coset size
        m = I[k]
        # print k, m, n

        # 2. k-decimation sequence
        seq_c = []
        if m == n:
            for t in range(2 * m):
                seq_c.append(seq_b[(t * k) % (2 ** n - 1)])
        elif m < n:
            for t in range(2 * m):
                seq_c.append(trace(alpha ** (k * t), m))
        else:
            import sys

            sys.stderr.write("should never happen?\n")
            sys.exit(-1)

        # print seq_b
        # print seq_c

        fun_p_k = bma(seq_c)
        # print fun_p
        # print fun_p_k
        # print fun_p / fun_p_k

        matrix_M_ele = []
        for i in range(m):
            for ele in range(i, m + i):
                matrix_M_ele.append(seq_c[ele])
        matrix_M = matrix(GF(2), m, m, matrix_M_ele)
        # print 'matrix_M'
        # print matrix_M

        # 3. contruct a filter
        fun_q = fun_p.parent()(fun_p / fun_p_k)
        # print fun_q
        # print type(fun_q)

        # 4. compute the time convolution
        seq_v_generator = convolution(seq_a, fun_q)
        seq_v = []
        for i in range(m):
            seq_v.append(seq_v_generator.next())

        if reference:
            seq_v_target_generator = convolution(seq_a_target, fun_q)
            seq_v_target = []
            for i in range(m):
                seq_v_target.append(seq_v_target_generator.next())

        # 4.5 solve linear equations to get x_i
        matrix_x = matrix_M.inverse() * matrix(GF(2), m, 1, seq_v)
        # print 'matrix_x'
        # print matrix_x
        if reference:
            matrix_x_target = matrix_M.inverse() * matrix(GF(2), m, 1, seq_v_target)
            # print 'matrix_x_target'
            # print matrix_x_target

        # 5. compute A_k = V * T
        V = 0
        for i in range(m):
            if 1 == matrix_x[i][0]:
                V += alpha ** (i * k)
        if reference:
            V_target = 0
            for i in range(m):
                if 1 == matrix_x_target[i][0]:
                    V_target += alpha ** (i * k)

        fun_q_extended = TheExtensionPolynomialRing(fun_q)

        # print fun_q_extended
        T = fun_q_extended(alpha ** k) ** (-1)
        # print T
        # print type(T)

        A_k = V * T
        # print A_k
        spectra_A[k] = A_k

        if reference:
            A_k_target = V_target * T
            spectra_A_target[k] = A_k_target

    # print spectra_A
    # print spectra_A_target
    # to compute the A_k where k is not coset leader
    for i in I:
        for j in range(1, I[i]):
            spectra_A[(i * (2 ** j)) % N] = spectra_A[i] ** (2 ** j)
            if reference:
                spectra_A_target[(i * (2 ** j)) % N] = spectra_A_target[i] ** (2 ** j)
    # print alpha ** 6

    if None == reference:
        return spectra_A
    else:
        return spectra_A, spectra_A_target
コード例 #26
0
# 06_fou/call_convolution_general.py
#
# (c) Dr. Yves J. Hilpisch
# Derivatives Analytics with Python
#
import numpy as np
from convolution import revnp, convolution
from parameters import *

# Parmeter Adjustments
M = 3  # number of time steps
dt, df, u, d, q = get_binomial_parameters(M)

# Array Generation for Stock Prices
mu = np.arange(M + 1)
mu = np.resize(mu, (M + 1, M + 1))
md = np.transpose(mu)
mu = u ** (mu - md)
md = d ** md
S = S0 * mu * md

# Valuation
V = np.maximum(S - K, 0)
qv = np.zeros((M + 1), dtype=np.float)
qv[0] = q
qv[1] = 1 - q
for t in range(M - 1, -1, -1):
    V[:, t] = convolution(V[:, t + 1], revnp(qv)) * df

print("Value of the Call Option %8.3f" % V[0, 0])
コード例 #27
0
1.- Edge detection
2.- Sobel
3.- Line detection horizontal
4.- Cambiar de imagen
5.- Salir                 
            """

    pop = True  #Breack del ciclo while.
    while pop == True:  #Ciclo while para imprimir filtros, cambiar imagen o salir.
        print(filtros)
        print("Elige una opcion:")
        op = input()

        if op == "1":
            edgeDetection = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
            imageEdge = convolution(
                image, edgeDetection)  # Función de convolución con padding
            # Mostrar el plot del resultado con filtro.
            plt.imshow(imageEdge, cmap='twilight_shifted')
            edge_row, edge_col = imageEdge.shape
            plt.title("Output Edge detection of {}X{}".format(
                edge_row, edge_col))
            plt.show()
        elif op == "2":
            sobel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
            imageSobel = convolution(
                image, sobel)  # Función de convolución con padding
            # Mostrar el plot del resultado con filtro.
            plt.imshow(imageSobel, cmap='twilight_shifted')
            sobel_row, sobel_col = imageSobel.shape
            plt.title("Output Sobel of {}X{}".format(sobel_row, sobel_col))
            plt.show()
コード例 #28
0
def gaussian_blur(image, kernel_size, steps=False):
    kernel = gaussian_kernel(kernel_size,
                             sigma=math.sqrt(kernel_size),
                             steps=steps)
    return convolution(image, kernel, average=True, steps=steps)
コード例 #29
0
#
# Call Option Pricing with Circular Convolution (Simple)
# 06_fou/call_convolution.py
#
# (c) Dr. Yves J. Hilpisch
# Derivatives Analytics with Python
#
import math
import numpy as np
from convolution import revnp, convolution

# Parameter Definitions
M = 4  # number of time steps
dt = 1.0 / M  # length of time interval
r = 0.05  # constant short rate
C = [49.18246976, 22.14027582, 0, 0, 0]  # call payoff at maturity
q = 0.537808372  # martingale probability
qv = np.array([q, 1 - q, 0, 0, 0])  # probabilitiy vector filled with zeros

# Calculation
V = np.zeros((M + 1, M + 1), dtype=np.float)
V[M] = C

for t in range(M - 1, -1, -1):
    V[t] = convolution(V[t + 1], revnp(qv)) * math.exp(-r * dt)

print "Value of the Call Option %8.3f" % V[0, 0]

コード例 #30
0
def update_parameters(filt, gradient_val, bias, biasgradient_value):
    alpha=0.001
    filt= filt - (alpha * gradient_val)
    bias=bias-(alpha * biasgradient_value)
    return filt, bias


def l2loss(param1, param2):
    loss=((param1 - param2) ** 2).mean(axis=None)
    gradient = param2 - param1
    return loss,gradient

Blurred_Img=[]
Sharp_Img=[]
level1=convolution(3, 64)
f_1=level1.filter
bias1=level1.bias

print(f_1, bias1)

level2=convolution(64, 64)
f_2=level2.filter
bias2=level2.bias



level3=convolution(64, 64)
f_3=level3.filter
bias3=level3.bias
コード例 #31
0
ファイル: ej3.py プロジェクト: gciruelos/imagenes-practicas
def op_kirsch(im):
    r = np.zeros(im.shape, dtype=float)
    for i in range(8):
        r = np.maximum(r, convolution.convolution(im, kirschs[i]))
    return r
コード例 #32
0
import convolution as conv
import numpy as np
import cv2
import time
import sys
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
img = cv2.imread(dir_path + '/../input/input-p1-2-1-0.png', 1)
if img is None:
    print("Image not found.")
    sys.exit()
#Kernel 3x3 edge detection
msk = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
start_time = time.time()
img_conv = conv.convolution(img, msk)
print("A 3x3 mask took %s seconds in our convolution function" %
      round(time.time() - start_time, 4))
cv2.imwrite(dir_path + '/../output/output-p1-2-1-0.png', img_conv)
start_time = time.time()
img_conv_opencv = cv2.filter2D(img, -1, msk)
print("A 3x3 mask took %s seconds in OpenCV filter" %
      round(time.time() - start_time, 4))

#Kernel 7x7 box blur
msk = np.full((7, 7), 1 / (7 * 7))
start_time = time.time()
img_conv = conv.convolution(img, msk)
print("A 7x7 mask took %s seconds in our convolution function" %
      round(time.time() - start_time, 4))
cv2.imwrite(dir_path + '/../output/output-p1-2-1-1.png', img_conv)
コード例 #33
0
    # Metodos para imprimir los tatos
    def output(self, text):
        self.scrolledtext1.insert("1.0", text)
        print(text)
        return 0


if __name__ == "__main__":
    #Se manda a llamar la interfaz para buscar la imagen
    image = Procesar_imagen()
    #Se guarda el atributo "image_name" de la clase "Principal" en la variable "image_name"
    image_name = image.image_name
    # se saca la matriz de la imagen
    img = cv2.imread(image_name)

    # Hacer kernel gausiano
    kernel_gauss = gaussian_blur(9)

    # Hacer convolusion
    img = convolution(img, kernel_gauss, True)
    output = Output("Gaussian Blur\n" + "Shape:" + str(img.shape[0]) + " X " +
                    str(img.shape[1]))
    # Aplicar Line Detection
    img = line_detection(img, verbose=True)
    output = Output("Line Detection\n" + "Shape:" + str(img.shape[0]) + " X " +
                    str(img.shape[1]))
    # Aplicar laplacian
    img = laplacian(img, verbose=True)
    output = Output("Laplacian\n" + "Shape:" + str(img.shape[0]) + " X " +
                    str(img.shape[1]))