|
| 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 | + |
| 7 | + |
| 8 | +def im2col(image, block_size): |
| 9 | + rows, cols = image.shape |
| 10 | + dst_height = cols - block_size[1] + 1 |
| 11 | + dst_width = rows - block_size[0] + 1 |
| 12 | + image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) |
| 13 | + row = 0 |
| 14 | + for i in range(0, dst_height): |
| 15 | + for j in range(0, dst_width): |
| 16 | + window = ravel(image[i:i + block_size[0], j:j + block_size[1]]) |
| 17 | + image_array[row, :] = window |
| 18 | + row += 1 |
| 19 | + |
| 20 | + return image_array |
| 21 | + |
| 22 | + |
| 23 | +def img_convolve(image, filter_kernel): |
| 24 | + height, width = image.shape[0], image.shape[1] |
| 25 | + k_size = filter_kernel.shape[0] |
| 26 | + pad_size = k_size//2 |
| 27 | + # Pads image with the edge values of array. |
| 28 | + image_tmp = pad(image, pad_size, mode='edge') |
| 29 | + |
| 30 | + # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows |
| 31 | + image_array = im2col(image_tmp, (k_size, k_size)) |
| 32 | + |
| 33 | + # turn the kernel into shape(k*k, 1) |
| 34 | + kernel_array = ravel(filter_kernel) |
| 35 | + # reshape and get the dst image |
| 36 | + dst = dot(image_array, kernel_array).reshape(height, width) |
| 37 | + return dst |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == '__main__': |
| 41 | + # read original image |
| 42 | + img = imread(r'../image_data/lena.jpg') |
| 43 | + # turn image in gray scale value |
| 44 | + gray = cvtColor(img, COLOR_BGR2GRAY) |
| 45 | + # Laplace operator |
| 46 | + Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) |
| 47 | + out = img_convolve(gray, Laplace_kernel).astype(uint8) |
| 48 | + imshow('Laplacian', out) |
| 49 | + waitKey(0) |
0 commit comments