python convolution

Solutions on MaxInterview for python convolution by the best coders in the world

showing results for - "python convolution"
Lilli
02 Aug 2020
1# please use python 3.x
2import numpy as np
3
4# def convolve(image, kernel, bias, stride, padding):
5
6"""
7please implement convolution on an image
8arguments:
9    image: input color image,  numpy array of shape (in_height, in_width, in_channel)
10    kernel: weigths, numpy array of shape (kernel_size, kernel_size, in_channel, out_channel)
11    bias: biases, numpy array of shape (1,1,1,out_channel)
12    stride: stride, scalar
13    padding: the number of zero padding along image boundary, scalar
14returns:
15    result: results of convolution, numpy array of shape (out_height, out_width, out_channel)
16"""
17
18# return result
19
20import matplotlib.pyplot as plt
21import cv2
22import os
23
24
25def processImage(image):
26    # image = cv2.imread(image)
27    plt.imshow(image)
28    image = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2GRAY)
29    return image
30
31
32def convolve(image, kernel, bias, strides, padding):
33    # Cross Correlation
34    kernel = np.flipud(np.fliplr(kernel))
35
36    # Gather Shapes of Kernel + Image + Padding
37    xKernShape = kernel.shape[0]
38    yKernShape = kernel.shape[1]
39    xImgShape = image.shape[0]
40    yImgShape = image.shape[1]
41
42    # Shape of Output Convolution
43    xOutput = int(((xImgShape - xKernShape + padding) / strides) + 1)
44    yOutput = int(((yImgShape - yKernShape + padding) / strides) + 1)
45    result = np.zeros((xOutput, yOutput))
46
47    # Apply Equal Padding to All Sides
48    if padding != 0:
49        imagePadded = np.zeros((image.shape[0] + padding * 2, image.shape[1] + padding * 2))
50        imagePadded[int(padding):int(-1 * padding), int(padding):int(-1 * padding)] = image
51        print(imagePadded)
52    else:
53        imagePadded = image
54
55    # Iterate through image
56    for y in range(image.shape[1]):
57        # Exit Convolution
58        if y > image.shape[1] - yKernShape:
59            break
60        # Only Convolve if y has gone down by the specified Strides
61        if y % strides == 0:
62            for x in range(image.shape[0]):
63                # Go to next row once kernel is out of bounds
64                if x > image.shape[0] - xKernShape:
65                    break
66                try:
67                    # Only Convolve if x has moved by the specified Strides
68                    if x % strides == 0:
69                        result[x, y] = (kernel * imagePadded[x: x + xKernShape, y: y + yKernShape]).sum()
70                except:
71                    break
72
73    return result
74
75
76# image = processImage('images.jpg')
77# print(image.shape)
78# plt.imshow(image)
79# plt.show()
80# kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
81# image_conv = convolve(image, kernel, 1, 1)
82
83
84if __name__ == '__main__':
85
86    kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
87
88    video = cv2.VideoCapture(r'video.avi')
89    try:
90        if not os.path.exists('pet'):
91            os.makedirs('pet')
92    except OSError:
93        print('Error')
94    currentframe = 0
95    while (True):
96        ret, frame = video.read()
97
98        if ret:
99            image = processImage(frame)
100            # name = './pet/frame' + str(currentframe) + '.jpg'
101            # print('Captured...' + name)
102            # cv2.imwrite(name, frame)
103            cv2.imshow("original", frame)
104            output = convolve(image, kernel, 0, 1, 0)
105            cv2.imshow("convert", output)
106            if cv2.waitKey(27) & 0xFF == ord('q'):
107                break
108
109        else:
110            break
111    video.release()
112    cv2.destroyAllWindows()
113
114    # Grayscale Image
115    image = processImage('images.jpg')
116
117    # Edge Detection Kernel
118
119    # Convolve and Save Output
120    # output = convolve(image, kernel, 0, 1, 15)
121    # plt.imshow(output)
122    # plt.show()
123    # cv2.imwrite('2DConvolved.jpg', output)
124