5
5
import numpy as np
6
6
import cv2
7
7
from matplotlib import pyplot as plt
8
+ import time
8
9
9
10
10
11
def np_img_to_tensor (img ):
@@ -21,8 +22,7 @@ def tensor_to_np_img(img_tensor):
21
22
return img [0 , ...] # get the first element since it's batch form
22
23
23
24
24
- def sobel_torch_version (img_np ):
25
- torch_sobel = Sobel ()
25
+ def sobel_torch_version (img_np , torch_sobel ):
26
26
img_tensor = np_img_to_tensor (np .float32 (img_np ))
27
27
img_edged = tensor_to_np_img (torch_sobel (img_tensor ))
28
28
img_edged = np .squeeze (img_edged )
@@ -32,13 +32,29 @@ def sobel_torch_version(img_np):
32
32
def main ():
33
33
img_dir = "sample-imgs/*"
34
34
imgs = sorted (glob (img_dir ))
35
-
35
+ torch_sobel = Sobel ()
36
36
for img in imgs :
37
37
rgb_orig = cv2 .imread (img , cv2 .IMREAD_GRAYSCALE )
38
38
rgb_orig = cv2 .resize (rgb_orig , (224 , 224 ))
39
- rgb_edged = sobel_torch_version (rgb_orig )
39
+ tik = time .time ()
40
+ rgb_edged = sobel_torch_version (rgb_orig , torch_sobel = torch_sobel )
41
+ tok = time .time ()
42
+
43
+ torch_time = tok - tik
44
+
45
+ tik = time .time ()
46
+ rgb_edged_cv2_x = cv2 .Sobel (rgb_orig , cv2 .CV_64F , 1 , 0 , ksize = 3 )
47
+ rgb_edged_cv2_y = cv2 .Sobel (rgb_orig , cv2 .CV_64F , 0 , 1 , ksize = 3 )
48
+ tok = time .time ()
49
+ rgb_edged_cv2 = np .sqrt (np .square (rgb_edged_cv2_x ), np .square (rgb_edged_cv2_y ))
50
+ cv2_time = tok - tik
51
+
52
+ print (f"torch time: { torch_time } s, cv2 time: { cv2_time } s" )
53
+
40
54
rgb_orig = cv2 .resize (rgb_orig , (222 , 222 ))
41
- rgb_both = np .concatenate ([rgb_orig / 255 , rgb_edged / np .max (rgb_edged )], axis = 1 )
55
+ rgb_edged_cv2 = cv2 .resize (rgb_edged_cv2 , (222 , 222 ))
56
+ rgb_both = np .concatenate (
57
+ [rgb_orig / 255 , rgb_edged / np .max (rgb_edged ), rgb_edged_cv2 / np .max (rgb_edged_cv2 )], axis = 1 )
42
58
43
59
plt .imshow (rgb_both , cmap = "gray" )
44
60
plt .show ()
0 commit comments