Esempio n. 1
0
import numpy as np
import sys, os
get_ipython().magic('matplotlib inline')
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
ia898path = os.path.abspath('/home/lotufo')
if ia898path not in sys.path:
    sys.path.append(ia898path)
import ia898.src as ia

# ## Atenção, ler com a função ia.nbread

# In[4]:

dt = ia.nbread('/home/lotufo/ia898/data/digits_train.png')
ia.adshow(dt, 'digits_train.png')

# In[5]:

print(dt.shape)
print(dt.dtype)
print(dt[:3, :20])

# ## Visualizando o dataset

# O dataset é composto de 80 amostras. Cada amostra está organizado como: primeira coluna é o rótulo do dígito, de 0 a 9 e seguida 160 atributos (16 linhas e 10 colunas). O típo é uint8.

# In[6]:

nb = ia.nbshow(10)
        sys.path.append(ia898path)
    import ia898.src as ia


# ## Showing a numerical example

# In[2]:


if testing:
    F = ia.circle([5,7], 2, [2,3])
    print (F.astype(np.uint8))


# ## Printing the generated image

# In[4]:


if testing:
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    get_ipython().run_line_magic('matplotlib', 'inline')
    f = ia.circle([200,300], 90, [100,150])
    ia.adshow(f,'circle')


# ## Contributions
# 
# Luis Antonio Prado, 1st semester 2017
    f = np.arange(24).reshape(2, 3, 4)  # original image with generic axis
    F = ia.dft(f)  # proposed dft
    F1 = np.fft.fftn(f)  # numpy dft

    print('ia.dft:', '\n', F.round(2), '\n')
    print('fft.fftn:', '\n', F1.round(2), '\n')
    print('Equal Results? (max error)', abs(F1 - F).max())

# ### Image example: 2d circle

# In[5]:

if testing:
    f = ia.circle([256, 256], 10, [129, 129])
    ia.adshow(f)
    F = ia.dft(f)
    Fv = ia.dftview(F)
    ia.adshow(Fv)

# ### Image example: 3d square

# In[6]:

if False:  #testing:

    f = np.zeros((25, 30, 40))
    f[10:15, 20:26, 21:27] = 1
    F = ia.dft(f)
    ia.adshow(ia.normalize(ia.mosaic(f, 5)), 'Original Image')
    ia.adshow(ia.mosaic(ia.dftview(F), 5), 'Fourier Transformation')
    ia898path = os.path.abspath('../../')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia


# ## Examples
# 
# ### Example 1

# In[2]:


if testing:
    A = ia.hadamardmatrix(128)
    ia.adshow(ia.normalize(A, [0, 255]))


# ### Example 2

# In[4]:


if testing:
    A = ia.hadamardmatrix(4)
    print(A)
    print(np.dot(A, np.transpose(A)))


# ## Measuring time:
# In[3]:

if testing:
    np.set_printoptions(suppress=True, precision=4)
    A = ia.dctmatrix(4)
    print('Visualiza matriz DCT 4x4:\n', A)
    B = np.dot(A, np.transpose(A))

    print("\nVisualiza propriedade A*A'= I:\n", B)

# ### Example 2

# In[4]:

if testing:
    get_ipython().run_line_magic('matplotlib', 'inline')
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import sys, os
    ia898path = os.path.abspath('/home/lotufo')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia
    A = ia.dctmatrix(128)
    ia.adshow(ia.normalize(A, [0, 255]), 'DCT 128x128')

# In[ ]:

# In[ ]:
    import matplotlib.image as mpimg
    ia898path = os.path.abspath('../../')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia

# ### Example 1

# In[6]:

if testing:

    f = ia.circle([120, 150], 6, [60, 75])
    F = ia.dft(f)
    Fs = ia.dftshift(F)
    ia.adshow(ia.dftview(F))
    ia.adshow(ia.dftview(Fs))

# In[7]:

if testing:

    F = np.array([[10 + 6j, 20 + 5j, 30 + 4j], [40 + 3j, 50 + 2j, 60 + 1j]])
    Fs = ia.dftshift(F)
    print('Fs=\n', Fs)

# ## Equation
#
# $$ \begin{matrix}
#     HS &=& H_{xo,yo} \\xo     &=& \lfloor W/2 \rfloor \\yo     &=& \lfloor H/2 \rfloor
# \end{matrix} $$
    print(np.round(g.real))

# In[4]:

if False:  #testing:
    import matplotlib.image as mpimg

    f = mpimg.imread('../data/cameraman.tif')
    F = ia.dft(f)
    print(F.shape)
    H = ia.circle(F.shape, 50, [F.shape[0] / 2, F.shape[1] / 2])
    H = ia.normalize(H, [0, 1])
    FH = F * ia.idftshift(H)
    print(ia.isdftsym(FH))
    g = ia.idft(FH)
    ia.adshow(f)
    ia.adshow(ia.dftview(F))
    ia.adshow(ia.normalize(H, [0, 255]))
    ia.adshow(ia.dftview(FH))
    ia.adshow(ia.normalize(abs(g)))

# ## Equation
#
# $$ \begin{matrix}
#     f(x) &=& \frac{1}{N}\sum_{u=0}^{N-1}F(u)\exp(j2\pi\frac{ux}{N}) \\ & & 0 \leq x < N, 0 \leq u < N \\ \mathbf{f}          &=& \frac{1}{\sqrt{N}}(A_N)^* \mathbf{F}
# \end{matrix} $$

# $$ \begin{matrix}
# f(x,y) &=& \frac{1}{NM}\sum_{u=0}^{N-1}\sum_{v=0}^{M-1}F(u,v)\exp(j2\pi(\frac{ux}{N} + \frac{vy}{M})) \\ & & (0,0) \leq (x,y) < (N,M), (0,0) \leq (u,v) < (N,M) \\
#     \mathbf{f} &=& \frac{1}{\sqrt{NM}} (A_N)^* \mathbf{F} (A_M)^*
# \end{matrix} $$
Esempio n. 8
0
if testing:
    g = ia.ellipse([16, 16], [2, 4], [8, 8], np.pi * 0.25)
    print('g:\n', g.astype(int))

# ## Measuring time:

# In[4]:

if testing:
    from time import time
    t = time()
    g = ia.ellipse([300, 300], [90, 140], [150, 150], np.pi * 0.25)
    tend = time()
    print('Computational time (10k, 10k) is {0:.2f} seconds.'.format(tend - t))
    ia.adshow(g, "Ellipse")

# In[6]:

if testing:
    print('Computational time (10k, 10k) is:')
    get_ipython().run_line_magic(
        'timeit', 'ia.ellipse([300,300], [90,140], [150,150], np.pi * 0.25)')

# ## Equation
#
# $$
#     \begin{matrix}
#         \frac{((x-center_x)\cos(\theta) - (y-center_y)\sin(\theta))^2}{r_x^2}
#             +
#         \frac{((x-center_x)\sin(\theta) - (y-center_y)\cos(\theta))^2}{r_y^2} <= 1
Esempio n. 9
0
if testing:
    F = ia.ramp([5, 7], 3, [4, 10])
    print(F)
    F = ia.ramp((1, 5, 7), (0, 3, 0), [0, 0, 4, 10, 0, 0])
    print(F)
    F = ia.ramp([1, 5, 7], [3, 0, 0], [4, 10, 0, 0, 0, 0])
    print(F)

# - **Image example**

# In[4]:

if testing:
    F = ia.ramp([1, 200, 300], [0, 10, 0], [0, 0, 0, 255, 0, 128])
    ia.adshow(ia.normalize(F.reshape(200, 300)))

# In[6]:

if testing:
    F = ia.ramp([200, 300], 10, [0, 255])
    ia.adshow(ia.normalize(F))

# In[7]:

if testing:
    F = ia.ramp([1, 200, 300], [10, 0, 0], [0, 255, 0, 0, 0, 0])
    ia.adshow(ia.normalize(F.reshape(200, 300)))

# ### Image example - 3D
# In[9]:

if testing:
    get_ipython().run_line_magic('matplotlib', 'inline')
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import sys, os
    ia898path = os.path.abspath('/home/lotufo')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia

    r, c = np.indices((256, 256))

    f = ((r - 129)**2 + (c - 129)**2 < 10**2) * 255
    ia.adshow(ia.normalize(f), 'Imagem original')

    F = ia.dct(f)

    ia.adshow(ia.normalize(np.log(abs(F) + 1)), 'DCT')

# ### Example 3
# Compare with dft

# In[10]:

if testing:
    f = mpimg.imread('../data/cameraman.tif')

    nb = ia.nbshow(3)
    nb.nbshow(f, 'Imagem original')
Esempio n. 11
0
    # 2D example
    f1 = mpimg.imread("../data/cameraman.tif")
    noise = np.random.rand(f1.shape[0], f1.shape[1])
    f2 = ia.normalize(ia.ptrans(f1, (-1, 50)) + 300 * noise)
    g1 = ia.phasecorr(f1, f2)
    i = np.argmax(g1)
    row, col = np.unravel_index(i, g1.shape)
    v = g1[row, col]
    print(np.array(f1.shape) - np.array((row, col)))

# In[ ]:

if testing:
    print('max at:(%d, %d)' % (row, col))

    ia.adshow(ia.normalize(f1), "input image")
    ia.adshow(ia.normalize(f2), "input image")
    ia.adshow(ia.normalize(g1),
              "Correlation peak at (%d,%d) with %d" % (row, col, v))

# ### Exemplo 3

# Show how to perform Template Matching using phase correlation.

# In[ ]:

if testing:
    # 2D example
    w1 = f1[27:69, 83:147]

    h3 = np.zeros_like(f1)
    get_ipython().system(' jupyter nbconvert --to python dftmatrix.ipynb')
    import numpy as np
    import sys, os
    import matplotlib.image as mpimg
    ia898path = os.path.abspath('../../')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia

# ### Example 1

# In[2]:

if testing:
    A = ia.dftmatrix(128)
    ia.adshow(ia.normalize(A.real), 'A.real')
    ia.adshow(ia.normalize(A.imag), 'A.imag')

# Example 2
# ---------

# In[3]:

if testing:
    A = ia.dftmatrix(4)
    print('A=\n', A.round(1))
    print('A-A.T=\n', A - A.T)
    print((np.abs(np.linalg.inv(A) - np.conjugate(A))).max() < 10E-15)

# ### Example 3
#
g = f[::4, ::4]
nb.nbshow(f, '%s' % (f.shape, ))
nb.nbshow(g, '%s' % (g.shape, ))
nb.nbshow()

# ## Função comb
#
# Será necessário a função `comb` para poder fazer esta demonstração.
#
# Será necessário também ver outras propriedades da convolução e do teorema da convolução para poder fazer esta demonstração. Recomendo ler livros ou textos sobre esta explicação da interpretação no domínio da frequência da redução via interpolação.

# In[15]:

c = ia.comb((f.shape), (4, 4), (0, 0))
ia.adshow(ia.normalize(c))

# In[16]:

C = np.fft.fft2(c)
F = np.fft.fft2(f)
G2 = ia.pconv(F, C)
nb = ia.nbshow(3)
nb.nbshow(ia.dftview(F), 'Espectro da imagem original')
nb.nbshow(ia.dftview(C), 'Espectro do trêm de impulsos')
nb.nbshow(ia.dftview(G2), 'Espectro resultante da convolução')
nb.nbshow()

# In[17]:

g2 = np.fft.ifft2(G2)
Esempio n. 14
0
    print(a)

# ### Example 4

# In[5]:

if testing:
    get_ipython().run_line_magic('matplotlib', 'inline')
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg

    f = mpimg.imread('../data/cameraman.tif')
    h = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
    g = ia.conv(f, h)
    gn = ia.normalize(g, [0, 255])
    ia.adshow(f, title='input')
    ia.adshow(gn, title='filtered')

# ## Limitations
#
# Both image and kernel are internally converted to double.

# ## Equation
#
# $$ \begin{matrix}
#     (f \ast h)(r,c) &=&  \sum_{i=0}^{H-1} \sum_{j=0}^{W-1} f_{e}(i,j) h_{e}(r-i, c-j) \\
#     f_{e}(r,c) &=& \left\{ \begin{array}{llcl} f(r,c), & 0 \leq r \leq H_{f}-1 & and & 0 \leq r \leq W_f-1  \\
#                                                          0, & H_f \leq r \leq H-1 & or & W_f \leq c \leq W-1 \end{array}\right.\\
#     h_{e}(r,c) &=& \left\{ \begin{array}{llcl} f(r,c), & 0 \leq r \leq H_{h}-1 & and & 0 \leq r \leq W_h-1  \\
#                                                          0, & H_h \leq r \leq H-1 & or & W_h \leq c \leq W-1 \end{array}\right.\\
#     H & \geq & H_f + H_h - 1 \\
    print('spread factor =', sigma)
    print('Laplacian of Gaussian image : \n', F.round(2))


# #### Generating a image 2D 128x128, centered at 64x64 and sigma 4:

# In[5]:


if testing:
    s, mu, sigma = [128, 128], [64, 64], 4
    F = ia.log(s, mu, sigma)
    print('image dimensions = ', s)
    print('center of function = ', mu)
    print('spread factor =', sigma)
    ia.adshow(ia.normalize(F), 'Laplacian of Gaussian')


# #### Generating a image 2D 256x256, centered at 128x128 and sigma 20

# In[6]:


if testing:
    s, mu, sigma = [256, 256], [128, 128], 20
    F = ia.log(s, mu, sigma)
    print('image dimensions = ', s)
    print('center of function = ', mu)
    print('spread factor =', sigma)
    ia.adshow(ia.normalize(F), 'Laplacian of Gaussian')
    import sys,os
    ia898path = os.path.abspath('../../')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia


# ### Example 1

# In[2]:


if testing:

    H2_10 = ia.bwlp([100,100],2,2) # cutoff period: 2 pixels, order: 10
    ia.adshow(ia.dftview(H2_10))


# In[3]:


if testing:
    H4_1 = ia.bwlp([100,100],4,1) # cutoff period: 4, order: 1
    ia.adshow(ia.dftview(H4_1))


# In[4]:


if testing:
    H8_100 = ia.bwlp([100,100],8,100) # cutoff period: 8, order: 100
    print(ia.isccsym(np.fft.fft2(np.random.rand(100,100)))) # dimension variation
    print(ia.isccsym(np.fft.fft2(np.random.rand(101,100))))
    print(ia.isccsym(np.fft.fft2(np.random.rand(101,101))))


# ### Image Example: circular filter

# In[14]:


if testing:
    img = mpimg.imread('../data/cameraman.tif')
    F = ia.dft(img)
    imgc = 1 * ia.circle(img.shape, 50, [img.shape[0]/2, img.shape[1]/2])  
    imgct = ia.ptrans(imgc, np.array(imgc.shape)//2)
    ia.adshow(ia.normalize(imgct),'circular filter')
    res = F * imgct
    ia.adshow(ia.dftview(res))
    print('Is this filter symmetric?', ia.isccsym(res))


# ### Image Example 2: retangular filter

# In[17]:


if False: # testing:
    mquadra = ia.rectangle(img.shape, [50,50], [img.shape[0]/2, img.shape[1]/2])
    ia.adshow(mquadra,'RETANGULO')
    mquadra = ia.ptrans(mquadra, array(mquadra.shape)/2)
    ia.adshow(ia.normalize(mquadra),'retangular filter')
    np.set_printoptions(suppress=True, precision=4)
    A = ia.haarmatrix(4)
    print('Visualiza matriz haar 4x4:\n',A)
    B = np.dot(A,np.transpose(A))
    print("\nVisualiza propriedade A*A'= I:\n", B)


# ### Example 2

# In[3]:


if testing:
    
    A = ia.haarmatrix(128)
    ia.adshow(ia.normalize(A),'Haar matrix 128x128')


# ### Example 3

# In[4]:


if testing:
    f = mpimg.imread('../data/cameraman.tif')
    
    A = ia.haarmatrix(f.shape[0])
    B = ia.haarmatrix(f.shape[1])
    F = np.dot(np.dot(A, f), np.transpose(B))
    
    nb = ia.nbshow(2)
    itn = 5 - it  # negation
    print('itn=', itn)
    gn = ia.applylut(f, itn)
    print('gn=\n', gn)

# ### Example 2
#
# This example shows the negation operation applying the intensity transform through a negation grayscale table: it = 255 - i.

# In[3]:

if testing:
    f = mpimg.imread('../data/cameraman.tif')
    it = (255 - np.arange(256)).astype('uint8')
    g = ia.applylut(f, it)
    ia.adshow(f, 'f')
    ia.adshow(g, 'g')

# ### Example 3
#
# In this example, the colortable has 3 columns and the application of the colortable to an scalar image results in an image with 3 bands.

# In[4]:

if testing:
    f = np.array([[0, 1, 2], [2, 0, 1]])
    ct = np.array([[100, 101, 102], [110, 111, 112], [120, 121, 122]])
    #print iaimginfo(ct)
    g = ia.applylut(f, ct)
    print(g)
# In[2]:


if testing:
    F = ia.rectangle([7,9], [3,2], [3,4])
    print(F)


# - **Example 2**

# In[3]:


if testing:
    F = ia.rectangle([200,300], [90,120], [70,120])
    ia.adshow(ia.normalize(F))


# ## Equation
# 
# \begin{equation}
#   g(x,y)=\begin{cases}
#     1, & \text{if } x_\text{min} \leq x < x_\text{max} \text{ and } y_\text{min} \leq y < y_\text{max}.\\
#     0, & \text{otherwise}.
#   \end{cases}
# \end{equation}

# ## Contributions
# 
# Lucas de Vasconcellos Teixeira, 1st semester 2017
    ia898path = os.path.abspath('../../')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia


# ### Example 1

# In[2]:


if testing:
    import matplotlib.image as mpimg
    import numpy.fft as FFT
    f = mpimg.imread('../data/cameraman.tif')
    ia.adshow(f, "Original 2D image - Cameraman")
    F = FFT.fft2(f)
    Fv = ia.dftview(F)
    ia.adshow(Fv, "Cameraman DFT optical spectrum")


# ## Equation
# 
# 
# $$ \begin{matrix}
#     Gaux &=& \log(|F_{xc,yc}| + 1)\\xc     &=& \lfloor W/2 \rfloor \\yc     &=& \lfloor H/2 \rfloor\\ G &=& Gaux|_0^{255}
# \end{matrix} $$

# In[3]:

if testing:
    f = ia.gaussian( (100,), 50, [[10*10]]) 
    g = ia.normalize(f, [0,1])
    plt.plot(g)
    plt.show()


# ### Example 3 - two-dimensional image

# In[4]:


if testing:
    f = ia.gaussian((150,250), np.transpose([[75,100]]), [[40*40,0],[0,30*30]])
    g = ia.normalize(f, [0,255]).astype(np.uint8)
    ia.adshow(g)


# ## Example 4 - Numeric 3-dimensional

# In[6]:


if testing:
    f = ia.gaussian((3,4,5), np.transpose([[1,2,3]]), [[1,0,0],[0,4,0],[0,0,9]])
    print('f=\n', np.array2string(f, precision=4, suppress_small=1))
    g = ia.normalize(f, [0,255]).astype(np.uint8)
    print('g=\n', g)


# ## Equation
Esempio n. 23
0
#
# $$    f(r,c) = r \ c $$
# $$    \text{para} \ r  \in  [-75,75] $$
# $$                  c  \in  [-100,100]$$
#
#
# No exemplo a seguir é utilizado a função `arange` para gerar os vetores de coordenadas. Para melhorar
# a visualização foi utilizada a função `ia636:iaisolines iaisolines` que permite visualizar os
# pixels de mesmo valores (isolinhas) da imagem gerada com uma cor destacada.

# In[4]:

r, c = np.meshgrid(np.arange(-75, 75), np.arange(-100, 100), indexing='ij')
f = r * c
fn = ia.normalize(f)
ia.adshow(fn, 'Ponto de sela')
#ia.adshow(ia.iaisolines(fn,9), 'Ponto de sela com isolinhas')

# ## Outras images criadas com matrizes de índices
#
# Implemente alguma das seguintes funções da toolbox `ia636:MainPage` que também foram feitas desta forma:
#
# - [ia636:iacos](http://adessowiki.fee.unicamp.br/adesso-1/wiki/ia636/iacos/view/) - Cossenóide
# - [ia636:iacircle](http://adessowiki.fee.unicamp.br/adesso-1/wiki/ia636/iacircle/view/) - Círculo
# - [ia636:iarectangle](http://adessowiki.fee.unicamp.br/adesso-1/wiki/ia636/iarectangle/view/) - Retângulo
# - [ia636:ialog](http://adessowiki.fee.unicamp.br/adesso-1/wiki/ia636/ialog/view/) - Laplaciano da gaussiana

# ## Atividades
#
# - Faça a seguir um programa qualquer de geração de imagem a partir de uma equação:
                  [[17, 18, 19], [20, 21, 22], [23, 24, 25]]])

    print("\n Image Kernel (H): ")
    print(h)

    result = ia.pconv(f, h)
    print("\n Image Output - (G): ")
    print(result)

# ## Example with Image 2D

# In[6]:

if testing:
    f = mpimg.imread('../data/cameraman.tif')
    ia.adshow(f, title='a) - Original Image')
    h = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])
    g = ia.pconv(f, h)
    print("\nPrewitt´s Mask")
    print(h)

    gn = ia.normalize(g, [0, 255])
    ia.adshow(gn, title='b) Prewitt´s Mask filtering')

    ia.adshow(ia.normalize(abs(g)),
              title='c) absolute of Prewitt´s Mask filtering')

# ## Equation
#
# $$ f(i) = f(i + kN), h(i)=h(i+kN)$$
#
Esempio n. 25
0
    import numpy as np
    import sys,os
    ia898path = os.path.abspath('../..')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia
    dir(ia)
    print('file:',ia.__file__)
    print(ia.__version__)


# In[3]:

if testing:
    A = (np.arange(256*256) % 256).reshape(256,256).astype('uint8')
    ia.adshow(A,'teste')
    ia.show(A)


# In[6]:

if testing:
    R = (np.arange(256*256) % 256).reshape(256,256).astype('uint8')
    G = 255-R
    B = R[:,::-1]
    rgb = np.array((R,G,B))
    print(rgb.shape)
    ia.adshow(rgb)
    ia.show(rgb)
    ff = rgb.transpose((1,2,0))
    print(ff.shape)
        sys.path.append(ia898path)
    import ia898.src as ia
    get_ipython().run_line_magic('matplotlib', 'inline')
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg


# ### Example 1

# In[3]:


if testing:
    tables = [ 'gray', 'hsv', 'hot', 'cool', 'copper','pink','bone']
    r,f = np.indices((10,256), 'uint8')
    ia.adshow(f, 'gray scale')

    for table in tables:
        cm = ia.colormap(table)
        g = ia.applylut(f, cm)
        g = g.astype('uint8')
        if len(g.shape)==3:
            g = g.transpose(1,2,0)
        ia.adshow(g, table)
        


# ### Example 2
# 
# Plotting the colormap table