convolve.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # @Author : lightXu
  2. # @File : convolve.py
  3. # @Time : 2019/7/8 0008 下午 16:13
  4. from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
  5. from numpy import array, zeros, ravel, pad, dot, uint8
  6. def im2col(image, block_size):
  7. rows, cols = image.shape
  8. dst_height = cols - block_size[1] + 1
  9. dst_width = rows - block_size[0] + 1
  10. image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
  11. row = 0
  12. for i in range(0, dst_height):
  13. for j in range(0, dst_width):
  14. window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
  15. image_array[row, :] = window
  16. row += 1
  17. return image_array
  18. def img_convolve(image, filter_kernel):
  19. height, width = image.shape[0], image.shape[1]
  20. k_size = filter_kernel.shape[0]
  21. pad_size = k_size // 2
  22. # Pads image with the edge values of array.
  23. image_tmp = pad(image, pad_size, mode="edge")
  24. # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
  25. image_array = im2col(image_tmp, (k_size, k_size))
  26. # turn the kernel into shape(k*k, 1)
  27. kernel_array = ravel(filter_kernel)
  28. # reshape and get the dst image
  29. dst = dot(image_array, kernel_array).reshape(height, width)
  30. return dst
  31. if __name__ == "__main__":
  32. # read original image
  33. img = imread(r"../image_data/lena.jpg")
  34. # turn image in gray scale value
  35. gray = cvtColor(img, COLOR_BGR2GRAY)
  36. # Laplace operator
  37. Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
  38. out = img_convolve(gray, Laplace_kernel).astype(uint8)
  39. imshow("Laplacian", out)
  40. waitKey(0)