cloudFPGA (cF) API  1.0
The documentation of the source code of cloudFPGA (cF)
test_harris_standalone.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # *****************************************************************************
4 # * cloudFPGA
5 # * Copyright 2016 -- 2022 IBM Corporation
6 # * Licensed under the Apache License, Version 2.0 (the "License");
7 # * you may not use this file except in compliance with the License.
8 # * You may obtain a copy of the License at
9 # *
10 # * http://www.apache.org/licenses/LICENSE-2.0
11 # *
12 # * Unless required by applicable law or agreed to in writing, software
13 # * distributed under the License is distributed on an "AS IS" BASIS,
14 # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # * See the License for the specific language governing permissions and
16 # * limitations under the License.
17 # *----------------------------------------------------------------------------
18 
19 
23 
24 '''
25 Usage:
26  test_harris_standalone.py <imagefile name>
27 
28  Run harris in opencv
29 
30 '''
31 
32 import sys
33 import os
34 import numpy as np
35 import cv2 as cv
36 import logging
37 import time
38 import pandas as pd
39 import seaborn as sns
40 import matplotlib.pyplot as plt
41 #from pandasgui import show
42 import math
43 from scipy.interpolate import griddata
44 
45 
46 
47 debug_level = logging.DEBUG
48 logging.basicConfig(stream=sys.stdout, level=debug_level)
49 
50 REPEATS = 5
51 kernels = ["MedianFilter", "HarrisDetector", "Histogram", "CannyEdgeDetector", "HoughLineTransform",
52  "Demosaicing", "GammaCorrection", "Sobel", "GaussianBlur", "Laplacian", "Remap", "PyrUp",
53  "PyrDown", "Rotate", "WarpAffine", "HOGDescriptor"]
54 
55 frame = cv.imread(cv.samples.findFile("CARLA.jpg"))
56 if frame is None:
57  sys.exit("Could not read the image.")
58 else:
59  orig_frame = cv.cvtColor(frame, cv.COLOR_RGB2GRAY)
60 
61 
62 
63 def gammaCorrection(src, gamma):
64  invGamma = 1 / gamma
65 
66  table = [((i / 255) ** invGamma) * 255 for i in range(256)]
67  table = np.array(table, np.uint8)
68 
69  return cv.LUT(src, table)
70 
71 
72 
73 
74 
75 # When everything done, release the video capture object
76 toc_capture = time.perf_counter()
77 
78 #elapsed_times = np.zeros(shape=(REPEATS,len(kernels)), dtype=float)
79 
80 elapsed_times = [[0 for j in range(REPEATS)] for i in range(len(kernels))]
81 results = [[0 for j in range(REPEATS)] for i in range(len(kernels))]
82 
83 print(results)
84 for i in range(len(kernels)):
85  frame = orig_frame.copy()
86  for j in range(REPEATS):
87  start_time = time.time()
88  print(i,j)
89  # Opencv function call
90  if (i == 0):
91  results[i][j] = cv.medianBlur(frame, 9)
92  #time.sleep(1)
93  elif (i == 1):
94  blockSize = 2
95  ksize = 3
96  freeParameter = 0.04
97  results[i][j] = cv.cornerHarris(frame, blockSize, ksize , freeParameter)
98  #result is dilated for marking the corners, not important
99  results[i][j] = cv.dilate(results[i][j],None)
100  # Threshold for an optimal value, it may vary depending on the image.
101  tmp = frame
102  tmp[results[i][j]>0.01*results[i][j].max()]=[255]
103  results[i][j] = tmp
104  elif (i == 2):
105  # find frequency of pixels in range 0-255
106  channels = [0]
107  mask = None
108  histSize = [256]
109  ranges = [0,256]
110  tmp = [frame]
111  hist = cv.calcHist(tmp, channels, mask, histSize, ranges)
112  results[i][j] = hist
113  elif (i == 3):
114  # Setting parameter values
115  t_lower = 50 # Lower Threshold
116  t_upper = 150 # Upper threshold
117  # Applying the Canny Edge filter
118  canny = cv.Canny(frame, t_lower, t_upper)
119  results[i][j] = canny
120  elif (i == 4):
121  lines = cv.HoughLines(canny, 1, np.pi / 180, 150, None, 0, 0)
122  elif (i == 5):
123  results[i][j] = cv.demosaicing(frame, cv.COLOR_BayerRG2BGR_VNG);
124  elif (i == 6):
125  results[i][j] = gammaCorrection(frame, 2.2)
126  elif (i == 7):
127  x = cv.Sobel(frame, cv.CV_64F, 1, 0, ksize=5)
128  y = cv.Sobel(frame, cv.CV_64F, 0, 1, ksize=5)
129  absx= cv.convertScaleAbs(x)
130  absy = cv.convertScaleAbs(y)
131  results[i][j] = cv.addWeighted(absx, 0.5, absy, 0.5,0)
132  elif (i == 8):
133  results[i][j] = cv.GaussianBlur(frame,(35,35),cv.BORDER_DEFAULT)
134  elif (i == 9):
135  ddepth = cv.CV_16S
136  kernel_size = 5
137  results[i][j] = cv.Laplacian(frame, ddepth, ksize=kernel_size)
138  elif (i == 10):
139  source = np.array([
140  [315, 15],
141  [962, 18],
142  [526, 213],
143  [754, 215],
144  [516, 434],
145  [761, 433],
146  [225, 701],
147  [1036, 694],
148  ], dtype=int)
149  destination = np.array([
150  [14, 14],
151  [770, 14],
152  [238, 238],
153  [546, 238],
154  [238, 546],
155  [546, 546],
156  [14, 770],
157  [770, 770]
158  ], dtype=int)
159  grid_x, grid_y = np.mgrid[0:783:784j, 0:783:784j]
160  grid_z = griddata(destination, source, (grid_x, grid_y), method='cubic')
161  map_x = np.append([], [ar[:,1] for ar in grid_z]).reshape(784,784)
162  map_y = np.append([], [ar[:,0] for ar in grid_z]).reshape(784,784)
163  map_x_32 = map_x.astype('float32')
164  map_y_32 = map_y.astype('float32')
165  results[i][j] = cv.remap(frame, map_x_32, map_y_32, cv.INTER_CUBIC)
166  elif (i == 11):
167  rows, cols = map(int, frame.shape)
168  results[i][j] = cv.pyrUp(frame, ( cols*2, rows*2 ))
169  elif (i == 12):
170  rows, cols = map(int, frame.shape)
171  results[i][j] = cv.pyrDown(frame, ( cols/2, rows/2 ))
172  elif (i == 13):
173  results[i][j] = cv.rotate(frame, cv.ROTATE_90_CLOCKWISE)
174  elif (i == 14):
175  rows, cols = frame.shape[:2]
176  # Define the 3 pairs of corresponding points
177  input_pts = np.float32([[0,0], [cols-1,0], [0,rows-1]])
178  output_pts = np.float32([[cols-1,0], [0,0], [cols-1,rows-1]])
179  input_pts = np.float32([[50, 50],
180  [200, 50],
181  [50, 200]])
182  output_pts = np.float32([[10, 100],
183  [200, 50],
184  [100, 250]])
185  # Calculate the transformation matrix using cv2.getAffineTransform()
186  M = cv.getAffineTransform(input_pts , output_pts)
187  # Apply the affine transformation using cv2.warpAffine()
188  results[i][j] = cv.warpAffine(frame, M, (cols,rows))
189  elif (i == 14):
190  hog = cv.HOGDescriptor()
191  h = hog.compute(frame)
192  results[i][j] = h
193 
194  end_time = time.time()
195  elapsed_times[i][j] = (end_time - start_time)
196 
197 for i in range(len(kernels)):
198  image_name = "CARLA_out_kernel_" + kernels[i] + ".jpg"
199  cv.imwrite(image_name, results[i][0])
200  logging.info("First saved image of " + kernels[i] + ": " + image_name)
201 
202 elapsed_times = np.sort(elapsed_times)
203 average_elapsed_time = sum(elapsed_times) / REPEATS
204 print(elapsed_times)
205 print("Time required to submit a trivial function call:")
206 print(" Average: {}".format(average_elapsed_time))
207 #print(" 90th percentile: {}".format(elapsed_times[round((90/100) * REPEATS)-1]))
208 #print(" 99th percentile: {}".format(elapsed_times[round((99/100) * REPEATS)-1]))
209 #print(" best: {}".format(elapsed_times[0]))
210 #print(" worst: {}".format(elapsed_times[round((99.9/100) * REPEATS)-1]))
211 
212 elapsed_times = np.transpose(elapsed_times)
213 df = pd.DataFrame(elapsed_times)
214 
215 ax = sns.boxplot(data=df)
216 ax.set_xticklabels(kernels)
217 ax.legend(loc='best')
218 ax.tick_params(axis='x', labelrotation=30)
219 
220 ax.set_xlabel("Computer Vision Kernel", fontsize = 20)
221 ax.set_ylabel("Exec. Time (s)", fontsize = 20)
222 #gui = show(df)
223 
224 # to show histogram
225 #plt.plot(hist)
226 
227 # to show hughlines
228 lines = cv.HoughLinesP(canny, 1, np.pi/180.0, 120, minLineLength=10, maxLineGap=250)
229 for line in lines:
230  x1, y1, x2, y2 = line[0]
231  # cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 3)
232  cv.line(frame,(x1,y1),(x2,y2),(0,0,255),2)
233 cv.imwrite('file.png', frame)
234 
235 
236 
237 plt.show()