-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm_with_inputs.py
More file actions
71 lines (55 loc) · 2.42 KB
/
algorithm_with_inputs.py
File metadata and controls
71 lines (55 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import sys
import cv2
import numpy as np
# Grayscale Image
def processImage(image):
image = cv2.imread(image)
image = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2GRAY)
return image
def convolve2D(image, kernel, padding=0, strides=1):
# Cross Correlation
kernel = np.flipud(np.fliplr(kernel))
# Gather Shapes of Kernel + Image + Padding
xKernShape = kernel.shape[0]
yKernShape = kernel.shape[1]
xImgShape = image.shape[0]
yImgShape = image.shape[0]
# Shape of Output Convolution
xOutput = int(((xImgShape - xKernShape + 2 * padding) / strides) + 1)
yOutput = int(((yImgShape - yKernShape + 2 * padding) / strides) + 1)
output = np.zeros((xOutput, yOutput))
# Apply Equal Padding to All Sides
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
else:
imagePadded = image
# Iterate through image
for y in range(image.shape[1]):
# Exit Convolution
if y > image.shape[1] - yKernShape:
break
# Only Convolve if y has gone down by the specified Strides
if y % strides == 0:
for x in range(image.shape[0]):
# Go to next row once kernel is out of bounds
if x > image.shape[0] - xKernShape:
break
try:
# Only Convolve if x has moved by the specified Strides
if x % strides == 0:
output[x, y] = (kernel * imagePadded[x: x + xKernShape, y: y + yKernShape]).sum()
except:
break
return output
if __name__ == '__main__':
print("Welcome! This is an algorithm that will detect edges in an image. It makes really cool line art out of any square image.")
pathToImage = input("Please type the path to your SQUARE image with forward slashes. For example, \"C:/users/name/downloads/image.jpg\"")
pathToOutput = input("Please type the path to your output in the same format as the input. You can name the output image whatever you like!")
# Grayscale Image
image = processImage(pathToImage)
# Edge Detection Kernel
kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
# Convolve and Save Output
output = convolve2D(image, kernel, padding=2)
cv2.imwrite(pathToOutput, output)