Esempio n. 1
0
def noise_removal_cheat(source_image, npy=True, show=False):
    if npy:
        source_image = np.load(source_image)
    Fp = 650
    Fc = 750
    Fe = 1600

    order, Wn = signal.buttord(2 * Fp / Fe, 2 * Fc / Fe, gpass=0.5, gstop=40)
    print(order)
    #order = 2
    b, a, *_ = signal.butter(order, Wn)

    if show:
        plt.figure()
        x, y = signal.freqz(b, a)
        plt.plot(x, 20 * np.log10(abs(y)))
        plt.title("Gain de la réponse en fréquence")
        plt.xlabel("Multiple fréquence gauchie (pi)")
        plt.ylabel("Gain (dB)")
        plt.show()

        print(a)
        print(b)
        zplane.zplane(b, a)
    output = signal.lfilter(b, a, source_image)

    if show:
        plt.figure()
        plt.title('Image débruitée - méthode butterworth')
        plt.imshow(output, cmap='gray')
        plt.show()
    return output
Esempio n. 2
0
def noise_removal_bilinear(source_image, npy=True, show=False):
    if npy:
        source_image = np.load(source_image)
    Fc = 650
    Fe = 1600
    T = 1 / Fe

    wc = Fe * np.tan(np.pi * Fc / Fe)

    b = [T**2 * wc**2, 2 * T**2 * wc**2, T**2 * wc**2]
    a = [(4 + 2 * np.sqrt(2) * T * wc + T**2 * wc**2), (-8 + T**2 * wc**2),
         (4 - np.sqrt(2) * 2 * T * wc + T**2 * wc**2)]
    a = np.asarray(a)
    b = np.asarray(b)
    if show:
        plt.figure()
        x, y = signal.freqz(b, a)
        plt.plot(x, 20 * np.log10(abs(y)))
        plt.title("Gain de la réponse en fréquence")
        plt.xlabel("Multiple fréquence gauchie (pi)")
        plt.ylabel("Gain (dB)")
        plt.show()

        print(a)
        print(b)
        zplane.zplane(b, a)

    output = signal.lfilter(b, a, source_image)

    if show:
        plt.figure()
        plt.title('Image débruitée - méthode bilinéaire')
        plt.imshow(output, cmap='gray')
        plt.show()
    return output
Esempio n. 3
0
def prob3a():
    Fe = 48000
    wp = 2500 / (Fe / 2)
    ws = 3500 / (Fe / 2)
    gpass = 0.2
    gstop = 40

    print(wp, ws)

    order, wn = signal.buttord(wp, ws, gpass, gstop, False, Fe)
    num, denum = signal.butter(order, wn, 'lowpass', False, output='ba')

    print(order)

    w, Hw = signal.freqz(num, denum)

    plt.figure()
    plt.plot(w * Fe / (2 * pi), dB(np.abs(Hw)))  # En frequences
    plt.title('Butter')

    num, denum, k = signal.butter(order, wn, 'lowpass', False)

    plt.figure()
    zplane(num, denum)
    print(k)
Esempio n. 4
0
def remove_aberrations(poles, zeros, source_image, npy=False, show=False):
    if npy:
        source_image = np.load(source_image)
    b, a = transfer_from_poles_zeros(poles, zeros)
    output = signal.lfilter(a, b, source_image)
    if show:
        plt.figure()
        plt.title('Image sans aberrations')
        plt.imshow(output, cmap='gray')
        plt.show()
        zplane.zplane(b, a)
    return output
Esempio n. 5
0
def H_inv(data, verbose=True, in_dB=True):
    # Given TF
    zeroes = [
        h.exp_img(0.9, pi / 2),
        h.exp_img(0.9, -pi / 2),
        h.exp_img(0.95, pi / 8),
        h.exp_img(0.95, -pi / 8)
    ]

    poles = [0, -0.99, -0.99, 0.9]  # 2x   -0.99??
    num = np.poly(zeroes)
    denum = np.poly(poles)

    # Inverse TF
    # Inverse poles/zeroes and num/denum to have inverse TF
    zeroes_inv = poles
    poles_inv = zeroes
    num_inv = denum
    denum_inv = num

    if verbose:
        # Verify for pole stability
        pole_stable = True
        for pole in poles_inv:
            if np.abs(pole) > 1:
                pole_stable = False
                break
        if pole_stable:
            print("Filter Stable")
        else:
            print("Filter Unstable")

        # Print zplane for TF and inverse TF
        # zplane(num, denum, t="H(z) zplane")
        zplane(num_inv, denum_inv, t="H(z)-1 zplane")

        # h.plot_filter(num, denum, t="H(z) (original) transfer function", in_dB=in_dB)
        # h.plot_filter(num_inv, denum_inv, t="H(z)-1 (inverse) transfer function", in_dB=in_dB)

    data_filtered = signal.lfilter(num_inv, denum_inv, data)
    h.imshow(data_filtered, t="After H(z)-1 filter")

    return data_filtered
# Escreve no arquivo
with open("saida_sweep_mm_4.pcm", "wb") as output:
    for x in output_data:
        output.write(x)
output.close()

#Zero = wcz + wc
#Polo = Flz + wcz + wc - Fl
zero = np.array([0, wc, wc])
polo = np.array([0, (Fl + wc), (wc - Fl)])

z = np.roots(zero)
p = np.roots(polo)
print(z, p)
zplane(zero, polo)

# Nome e tamanho da janela a ser aberta
matp.figure(u"Gráfico da transformada Z", figsize=(15, 8))

# Plota os gráficos
matp.subplot(311)
matp.title(u"Gráfico input")
matp.xlabel("amostra")
matp.ylabel("Amplitude")
matp.grid(1)
matp.plot(data)

matp.subplot(312)
matp.title(u"Gráfico output")
matp.xlabel("amostra")
Esempio n. 7
0
import matplotlib.pyplot as plt
from freqz import freqz
import numpy as np

A = [1, -0.9]
B = [1]
w = freqz(B,A)
print len(w)

from zplane import zplane 
zplane(B,A)
import numpy as np
import matplotlib.pyplot as plt
from zplane import zplane

#Zero = Z^2 + 1.5Z + 2
#Polo = Z^2
if __name__ == "__main__":
    num = np.array([1, 1.5, 2])
    dem = np.array([1, 0, 0])

    z = np.roots(num)
    p = np.roots(dem)

    print("Zeros: ", z)
    print("Polos: ", p)

    zplane(num, dem)

Esempio n. 9
0
def scatter_poles_zeros(poles, zeros):
    b = np.poly(zeros)
    a = np.poly(poles)
    zplane.zplane(b, a)
Esempio n. 10
0
def prob1a():
    zplane(num, denum)
Esempio n. 11
0
import numpy as np
from zplane import zplane
"""
        Z^2 + 1.5Z + 2
D(Z) =  --------------
             Z^2
"""

num = np.array([1, 1.5, 2])
den = np.array([1, 0, 0])

num_roots = np.roots(num)
den_roots = np.roots(den)

print(num_roots)
print(den_roots)

zplane(num, den)
Esempio n. 12
0
import matplotlib, sys

matplotlib.use('TkAgg')
from scipy import signal
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plot
import math
import zplane as zp

w0ideal = 13e3
Qideal = 4

w1ideal = w0ideal * (math.sqrt(1 + (1 / 2 / Qideal)**2) - 1 / 2 / Qideal)
f1ideal = w1ideal / 2 / math.pi
w2ideal = (w0ideal**2) / w1ideal
f2ideal = w2ideal / 2 / math.pi
f0ideal = w0ideal / 2 / math.pi

Rideal = 2.2e3
R6ideal = 8.8e-100
Cideal = 1 / w0ideal / Rideal
Lideal = (Rideal**2) * Cideal
z, p, k = signal.tf2zpk([2 * Lideal / R6ideal, 0],
                        [Lideal * Cideal, Lideal / R6ideal, 1])

zp.zplane(z, p)
Esempio n. 13
0
for i in range(size):
    sig.append(np.sin(i * np.pi / 16) + np.sin(i * np.pi / 32))

plt.figure()
output = signal.lfilter(b, a, sig)
plt.plot(sig)
plt.plot(output)
plt.show()

# Num 3

order, Wn = signal.buttord(2.5 / 24, 3.5 / 24, gpass=0.2, gstop=40)
print(order)
b, a, *_ = signal.butter(order, Wn)

zplane.zplane(b, a)

plt.figure()
x, y = signal.freqz(b, a)
plt.plot(x, 20 * np.log10(abs(y)))
plt.show()

# Num 4

T = np.matrix([[2, 0], [0, 0.5]])

a = np.matrix([[3, 1], [4, 7]])

res = a * T
print(res)
a=0.5;
B=[1/a.conjugate()]; #the numerator polynomial of H_AP
A=[a]; #the denominator polynomial

from zplane import zplane
zplane(B,A,[-1.1, 2.1, -1.1, 1.1]); #plot the pole/zero diagram with axis limits

import numpy as np
def warpingphase(w, a):
    #produces (outputs) phase wy for an allpass filter
    #w: input vector of normlized frequencies (0..pi)
    #a: allpass coefficient
    #phase of allpass zero/pole :
    theta = np.angle(a);
    #magnitude of allpass zero/pole :
    r = np.abs(a);
    wy = -w-2*np.arctan((r*np.sin(w-theta))/(1-r*np.cos(w-theta)))
    return wy
	
import matplotlib.pyplot as plt
#from warpingphase import *
#frequency range:
w = np.arange(0,np.pi, 0.01)
a = 0.5 * (1+1j)
wyy = (warpingphase(warpingphase(w,a),-a.conjugate()))
plt.plot(w,wyy)
plt.xlabel('Normalized Frequency')
plt.ylabel('Phase Angle')
plt.show()
a=0.5;
B=[-a.conjugate(), 1]
Esempio n. 15
0
def denoise(data, trans_bi=False, by_hand=False, verbose=True, show_plot=True):
    fd_pass = 500
    fd_stop = 750
    fe = 1600

    w = 1 / fe

    wd_pass = fd_pass
    wd_stop = fd_stop

    g_pass = 0.5
    g_stop = 40

    if trans_bi:
        if not by_hand:
            # "Gauchissement"
            wa_pass = h.gauchissement(fd_pass, fe)
            if verbose: print(wa_pass)

            # Write H(s) -> H(z) function
            z = sp.Symbol('z')
            s = 2 * fe * (z - 1) / (z + 1)
            H = 1 / ((s / wa_pass)**2 + np.sqrt(2) * (s / wa_pass) + 1)
            H = sp.simplify(H)
            if verbose: print(H)

            # Seperate num and denum into fractions
            num, denum = sp.fraction(H)

            # Put them in polynomial form
            num = sp.poly(num)
            denum = sp.poly(denum)

            # Extract all coefficients and write it in np.array form
            k = 1 / 2.3914
            num = np.float64(np.array(num.all_coeffs())) * k
            denum = np.float64(np.array(denum.all_coeffs())) * k
            if verbose:
                print("Num and Denum: " + str(num) + ", " + str(denum))

            # Extract zeros and poles by finding roots of num and den
            zeros = np.roots(num)
            poles = np.roots(denum)
            if verbose:
                print("Zeros and poles: " + str(zeros) + ", " + str(poles))

            if verbose:
                zplane(num,
                       denum,
                       t="zPlane 2nd order butterworth bilinéaire filter")
                h.plot_filter(num,
                              denum,
                              t="2nd order butterworth bilinéaire filter",
                              in_dB=True,
                              in_freq=True,
                              fe=fe)

        else:
            # Done by hand
            zeros = [-1, -1]
            poles = [np.complex(-0.2314, 0.3951), np.complex(-0.2314, -0.3951)]
            k = 1 / 2.39

            num = np.poly(zeros) * k
            num = k * np.poly(zeros)
            denum = np.poly(poles)

            if verbose:
                print("Num and Denum: " + str(num, ) + ", " + str(denum))
                zplane(num,
                       denum,
                       t="Butterworth order 2 (trans. bilinéaire) zplane")
                h.plot_filter(num,
                              denum,
                              t="Butterworth order 2 (trans. bilinéaire)",
                              in_dB=True,
                              in_freq=True,
                              fe=fe)

        data_denoised = signal.lfilter(num, denum, data)

        if show_plot:
            h.imshow(data_denoised,
                     t="After Butterworth order 2 trans. bilinéaire filter")

    else:

        order = np.zeros(4)
        wn = np.zeros(4)

        # Butterworth
        order[0], wn[0] = signal.buttord(wd_pass, wd_stop, g_pass, g_stop,
                                         False, fe)

        # Chebyshev type 1
        order[1], wn[1] = signal.cheb1ord(wd_pass, wd_stop, g_pass, g_stop,
                                          False, fe)

        # Chebyshev type 2
        order[2], wn[2] = signal.cheb2ord(wd_pass, wd_stop, g_pass, g_stop,
                                          False, fe)

        # Elliptic
        order[3], wn[3] = signal.ellipord(wd_pass, wd_stop, g_pass, g_stop,
                                          False, fe)

        lowest_order_index = np.argmin(order)
        if verbose:
            print(order)
            print(lowest_order_index)
            print(wn)

        if (lowest_order_index == 0):
            filter_name = "Butterworth filter order {order}".format(
                order=order[0])
            num, denum = signal.butter(order[0], wn[0], 'lowpass', False, 'ba',
                                       fe)
        elif (lowest_order_index == 1):
            filter_name = "Cheby1 filter order {order}".format(order=order[1])
            num, denum = signal.cheby1(order[1], g_pass, wn[1], 'lowpass',
                                       False, 'ba', fe)
        elif (lowest_order_index == 2):
            filter_name = "Cheby2 filter order {order}".format(order=order[2])
            num, denum = signal.cheby2(order[2], g_stop, wn[2], 'lowpass',
                                       False, 'ba', fe)
            filter_name = "Cheby2 " + str(order[2]) + " order"
        else:
            filter_name = "Ellip filter order {order}".format(order=order[3])
            num, denum = signal.ellip(order[3], g_pass, g_stop, wn[3],
                                      'lowpass', False, 'ba', fe)

        if verbose:
            print(filter_name)
            filter_response_str = "Filter response " + filter_name
            zplane_str = "zPlane " + filter_name
            h.plot_filter(num,
                          denum,
                          t=filter_response_str,
                          in_dB=True,
                          in_freq=True,
                          fe=fe)
            zplane(num, denum, t=zplane_str)

        data_denoised = signal.lfilter(num, denum, data)

        if show_plot:
            h.imshow(data_denoised, "After python function noise filter")

    return data_denoised
Esempio n. 16
0
1) Impulse response
2) I/O difference equation
3) Determine H(z) and sketch its pole-zero plot.
4) Plot |H(e^jw)| and ^D Phase of H(e^jw).
5) Determine the impulse response h(n)

'''
import numpy as np
import matplotlib.pyplot as plt

from scipy import signal
from zplane import zplane

zero = np.array([-0.4])
pole = np.array([0.8])
zplane(zero, pole)

# Find N = 100 Point complex frequency response of digital
# filter with b numerator coefficients and a denominator coefficients
# W is the vector in radians/sample between 0 and pi

# Now the 101st element of the array H will correspond to w = pi
# A similar result can be obtained using the third form of the
# freqz function.

N = np.linspace(0.0, 1.0, 100)
W = N * (np.pi / 100)  # these are the frequencies we want

zero = np.array([5, 2])
pole = np.array([1, -0.8])
w, h = signal.freqz(zero, pole, W)