Advertisement
PNiewiarowska

AI_Niewiarowska_lab8_zad1

Jan 13th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. from keras.datasets import mnist
  2.  
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5.  
  6.  
  7. def convolution2d(image, kernel):
  8.     m, n = kernel.shape
  9.     if (m == n):
  10.         y, x = image.shape
  11.         y = y - m + 1
  12.         x = x - m + 1
  13.         new_image = np.zeros((y, x))
  14.         for i in range(y):
  15.             for j in range(x):
  16.                 new_image[i][j] = np.sum(image[i:i+m, j:j+m]*kernel)
  17.     return new_image
  18.  
  19.  
  20. def maxpooling(image):
  21.     m, n = kernel.shape
  22.     if (m == n):
  23.         y, x = image.shape
  24.         x //= 2
  25.         y //= 2
  26.         new_image = np.zeros((y, x))
  27.         for i in range(y):
  28.             for j in range(x):
  29.                 ox = j * 2
  30.                 oy = i * 2
  31.                 new_image[i][j] = np.max(image[oy:oy+2, ox:ox+2])
  32.     return new_image
  33.  
  34.  
  35. (X_train, y_train), (X_test, y_test) = mnist.load_data()
  36.  
  37.  
  38. kernel = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
  39. print(kernel)
  40.  
  41. image1 = X_train[0]
  42. image2 = convolution2d(image1, kernel)
  43. image3 = maxpooling(image2)
  44.  
  45. plt.subplot(1, 3, 1)
  46. plt.imshow(image1, cmap=plt.get_cmap('gray'))
  47. plt.subplot(1, 3, 2)
  48. plt.imshow(image2, cmap=plt.get_cmap('gray'))
  49. plt.subplot(1, 3, 3)
  50. plt.imshow(image3, cmap=plt.get_cmap('gray'))
  51. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement