import numpy as np
"""
please implement convolution on an image
arguments:
image: input color image, numpy array of shape (in_height, in_width, in_channel)
kernel: weigths, numpy array of shape (kernel_size, kernel_size, in_channel, out_channel)
bias: biases, numpy array of shape (1,1,1,out_channel)
stride: stride, scalar
padding: the number of zero padding along image boundary, scalar
returns:
result: results of convolution, numpy array of shape (out_height, out_width, out_channel)
"""
import matplotlib.pyplot as plt
import cv2
import os
def processImage(image):
plt.imshow(image)
image = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2GRAY)
return image
def convolve(image, kernel, bias, strides, padding):
kernel = np.flipud(np.fliplr(kernel))
xKernShape = kernel.shape[0]
yKernShape = kernel.shape[1]
xImgShape = image.shape[0]
yImgShape = image.shape[1]
xOutput = int(((xImgShape - xKernShape + padding) / strides) + 1)
yOutput = int(((yImgShape - yKernShape + padding) / strides) + 1)
result = np.zeros((xOutput, yOutput))
if padding != 0:
imagePadded = np.zeros((image.shape[0] + padding * 2, image.shape[1] + padding * 2))
imagePadded[int(padding):int(-1 * padding), int(padding):int(-1 * padding)] = image
print(imagePadded)
else:
imagePadded = image
for y in range(image.shape[1]):
if y > image.shape[1] - yKernShape:
break
if y % strides == 0:
for x in range(image.shape[0]):
if x > image.shape[0] - xKernShape:
break
try:
if x % strides == 0:
result[x, y] = (kernel * imagePadded[x: x + xKernShape, y: y + yKernShape]).sum()
except:
break
return result
if __name__ == '__main__':
kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
video = cv2.VideoCapture(r'video.avi')
try:
if not os.path.exists('pet'):
os.makedirs('pet')
except OSError:
print('Error')
currentframe = 0
while (True):
ret, frame = video.read()
if ret:
image = processImage(frame)
cv2.imshow("original", frame)
output = convolve(image, kernel, 0, 1, 0)
cv2.imshow("convert", output)
if cv2.waitKey(27) & 0xFF == ord('q'):
break
else:
break
video.release()
cv2.destroyAllWindows()
image = processImage('images.jpg')