python opencv convolution

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

showing results for - "python opencv convolution"
Aarón
09 Jun 2016
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
23from scipy import ndimage as nd
24
25
26def processImage(image):
27    # image = cv2.imread(image)
28    # plt.imshow(image)
29    image = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2GRAY)
30    return image
31
32
33def convolve(image, kernel, bias, strides, padding):
34    result = nd.convolve(image, kernel, mode='reflect', cval=1.0)
35    print(image.shape)
36    return result
37
38
39# image = processImage('images.jpg')
40# print(image.shape)
41# plt.imshow(image)
42# plt.show()
43# kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
44# image_conv = convolve(image, kernel, 1, 1)
45
46
47if __name__ == '__main__':
48
49    kernel = np.array([[1, 1, 1],
50                       [1, 1, 1],
51                       [1, 1, 1]])
52
53    video = cv2.VideoCapture(r'video.avi')
54    try:
55        if not os.path.exists('pet'):
56            os.makedirs('pet')
57    except OSError:
58        print('Error')
59    currentframe = 0
60    while True:
61        ret, frame = video.read()
62
63        if ret:
64            cv2.imshow("original", frame)
65            image = processImage(frame)
66
67            output = convolve(image, kernel, 0, 1, 0)
68            cv2.imshow("convert", output)
69            if cv2.waitKey(27) & 0xFF == ord('q'):
70                break
71
72        else:
73            break
74    video.release()
75    cv2.destroyAllWindows()
76
77    # Grayscale Image
78    # image = processImage('images.jpg')
79
80    # Edge Detection Kernel
81
82    # Convolve and Save Output
83    # output = convolve(image, kernel, 0, 1, 15)
84    # plt.imshow(output)
85    # plt.show()
86    # cv2.imwrite('2DConvolved.jpg', output)
87