-
Notifications
You must be signed in to change notification settings - Fork 0
/
edge.py
76 lines (61 loc) · 1.85 KB
/
edge.py
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
72
73
74
75
76
''' Image Processing
sharpening of greyscale images
- sobel kernels
- edge detection
- sharpening
by simon | github.com/mightbesimon
[!] * * * PLEASE NOTE * * * [!]
In this code, sobel and mean kernel operations may look weird.
They are optimised for speed.
For example, instead of [1 0 -1] * [a b c] = [1*a, 0*b, -1*c],
it is simply a - c in my representation
adapted for numpy ndarrays
'''
import numpy as np
# custom decorator for timing functions
from time_this import time_this
####################### edge detection #######################
''' [ 1 2 1] [ 1]
[ 0 0 0] = [1 2 1] x [ 0] x (1/4)
[-1 0 -2] [-1]
^ ^
9 calculations 3 calculations
'''
@time_this
def sobel_horizontal(image):
# * [1 0 -1]^T operation
copy = image[:-2, :] - image[2:, :]
# * [1 2 1] operation
copy = copy[:, :-2] + 2*copy[:, 1:-1] + copy[:, 2:]
# * (1/4) and padded
return np.pad(copy/4, 1)
''' [1 0 -1] [1]
[2 0 -2] = [1 0 -1] x [2] x (1/4)
[1 0 -1] [1]
^ ^
9 calculations 3 calculations
'''
@time_this
def sobel_vertical(image):
# [1 0 -1] operation
copy = image[:, :-2] - image[:, 2:]
# * [1 2 1]^T operation
copy = copy[:-2, :] + 2*copy[1:-1, :] + copy[2:, :]
# * (1/4) and padded
return np.pad(copy/4, 1)
@time_this
def combine(image1, image2):
# formula gm = sqrt( gx(x,y)^2 + gx(x,y)^2 )
return (image1**2 + image2**2) ** 0.5
@time_this
def combine_fast(image1, image2):
# using the appromimate formula gm = |gx(x,y)| + |gy(x,y)|
return abs(image1) + abs(image2)
def edge_image(image):
edges_h = sobel_horizontal(image)
edges_v = sobel_vertical (image)
return combine(edges_h, edges_v)
########################## sharpen ###########################
def sharpen(image):
edges = edge_image(image)
return combine(image, edges)