-
Notifications
You must be signed in to change notification settings - Fork 0
/
sobel.py
65 lines (50 loc) · 2.19 KB
/
sobel.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
import tkinter as tk
import tkinter.filedialog as fd
import cv2
import numpy as np
from scipy.signal import convolve2d
import time
def convolve(image, kernel):
convolved_matrix = convolve2d(image, kernel, mode='same', boundary='symm')
return np.array(convolved_matrix, dtype=np.float64)
def sobel_algorithm(img):
# Apply Sobel Gx kernel
x_gradient_matrix = convolve(img, gx_kernel)
# Apply Sobel Gy kernel
y_gradient_matrix = convolve(img, gy_kernel)
# Combine the gradient matrices to get the gradient magnitude
gradient_magnitude = np.sqrt(x_gradient_matrix**2 + y_gradient_matrix**2)
return gradient_magnitude / np.max(gradient_magnitude) * 255
def on_tr_trackbar(val):
global gradient_image, threshold_tracker, img
threshold_tracker = int(cv2.getTrackbarPos('Threshold', 'Trackbars'))
start_time = time.time()
gradient_magnitude = sobel_algorithm(img)
gradient_image = np.zeros(gradient_magnitude.shape, dtype=np.uint8)
gradient_image[gradient_magnitude > threshold_tracker] = 255
print(time.time() - start_time)
gradient_image = cv2.putText(gradient_image, f'T: {threshold_tracker}', (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
gradient_image = cv2.putText(gradient_image, f'T: {threshold_tracker}', (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
# Show results
cv2.imshow('Gray Scale', img)
cv2.imshow('Sobel Operator', gradient_image)
IMAGE_FILE = '../../test-images/simple-shapes.png'
IMAGE_NAME = IMAGE_FILE.split('/')[-1]
img = cv2.imread(IMAGE_FILE, 0)
threshold_tracker = 0
gradient_image = None
gx_kernel = np.array([[1, 0, -1],
[2, 0, -2],
[1, 0, -1]])
gy_kernel = np.array([[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]])
#Creating trackbar window
cv2.namedWindow('Trackbars')
cv2.resizeWindow('Trackbars', 640, 240)
cv2.createTrackbar("Threshold", "Trackbars", 0, 255, on_tr_trackbar)
on_tr_trackbar(50)
cv2.waitKey(0)
cv2.destroyAllWindows()
gradient_image = cv2.putText(gradient_image, f'T: {threshold_tracker}', (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
cv2.imwrite('results/' + IMAGE_NAME, gradient_image)