JeVoisBase  1.18
JeVois Smart Embedded Machine Vision Toolkit Base Modules
Share this page:
demo.py
Go to the documentation of this file.
1 # This file is part of OpenCV Zoo project.
2 # It is subject to the license terms in the LICENSE file found in the same directory.
3 #
4 # Copyright (C) 2021, Shenzhen Institute of Artificial Intelligence and Robotics for Society, all rights reserved.
5 # Third party copyrights are property of their respective owners.
6 
7 import argparse
8 
9 import numpy as np
10 import cv2 as cv
11 
12 from db import DB
13 
14 def str2bool(v):
15  if v.lower() in ['on', 'yes', 'true', 'y', 't']:
16  return True
17  elif v.lower() in ['off', 'no', 'false', 'n', 'f']:
18  return False
19  else:
20  raise NotImplementedError
21 
22 backends = [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_BACKEND_CUDA]
23 targets = [cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16]
24 help_msg_backends = "Choose one of the computation backends: {:d}: OpenCV implementation (default); {:d}: CUDA"
25 help_msg_targets = "Chose one of the target computation devices: {:d}: CPU (default); {:d}: CUDA; {:d}: CUDA fp16"
26 try:
27  backends += [cv.dnn.DNN_BACKEND_TIMVX]
28  targets += [cv.dnn.DNN_TARGET_NPU]
29  help_msg_backends += "; {:d}: TIMVX"
30  help_msg_targets += "; {:d}: NPU"
31 except:
32  print('This version of OpenCV does not support TIM-VX and NPU. Visit https://gist.github.com/fengyuentau/5a7a5ba36328f2b763aea026c43fa45f for more information.')
33 
34 parser = argparse.ArgumentParser(description='Real-time Scene Text Detection with Differentiable Binarization (https://arxiv.org/abs/1911.08947).')
35 parser.add_argument('--input', '-i', type=str, help='Path to the input image. Omit for using default camera.')
36 parser.add_argument('--model', '-m', type=str, default='text_detection_DB_TD500_resnet18_2021sep.onnx', help='Path to the model.')
37 parser.add_argument('--backend', '-b', type=int, default=backends[0], help=help_msg_backends.format(*backends))
38 parser.add_argument('--target', '-t', type=int, default=targets[0], help=help_msg_targets.format(*targets))
39 parser.add_argument('--width', type=int, default=736,
40  help='Preprocess input image by resizing to a specific width. It should be multiple by 32.')
41 parser.add_argument('--height', type=int, default=736,
42  help='Preprocess input image by resizing to a specific height. It should be multiple by 32.')
43 parser.add_argument('--binary_threshold', type=float, default=0.3, help='Threshold of the binary map.')
44 parser.add_argument('--polygon_threshold', type=float, default=0.5, help='Threshold of polygons.')
45 parser.add_argument('--max_candidates', type=int, default=200, help='Max candidates of polygons.')
46 parser.add_argument('--unclip_ratio', type=np.float64, default=2.0, help=' The unclip ratio of the detected text region, which determines the output size.')
47 parser.add_argument('--save', '-s', type=str, default=False, help='Set true to save results. This flag is invalid when using camera.')
48 parser.add_argument('--vis', '-v', type=str2bool, default=True, help='Set true to open a window for result visualization. This flag is invalid when using camera.')
49 args = parser.parse_args()
50 
51 def visualize(image, results, box_color=(0, 255, 0), text_color=(0, 0, 255), isClosed=True, thickness=2, fps=None):
52  output = image.copy()
53 
54  if fps is not None:
55  cv.putText(output, 'FPS: {:.2f}'.format(fps), (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, text_color)
56 
57  pts = np.array(results[0])
58  output = cv.polylines(output, pts, isClosed, box_color, thickness)
59 
60  return output
61 
62 if __name__ == '__main__':
63  # Instantiate DB
64  model = DB(modelPath=args.model,
65  inputSize=[args.width, args.height],
66  binaryThreshold=args.binary_threshold,
67  polygonThreshold=args.polygon_threshold,
68  maxCandidates=args.max_candidates,
69  unclipRatio=args.unclip_ratio,
70  backendId=args.backend,
71  targetId=args.target
72  )
73 
74  # If input is an image
75  if args.input is not None:
76  image = cv.imread(args.input)
77  image = cv.resize(image, [args.width, args.height])
78 
79  # Inference
80  results = model.infer(image)
81 
82  # Print results
83  print('{} texts detected.'.format(len(results[0])))
84  for idx, (bbox, score) in enumerate(zip(results[0], results[1])):
85  print('{}: {} {} {} {}, {:.2f}'.format(idx, bbox[0], bbox[1], bbox[2], bbox[3], score))
86 
87  # Draw results on the input image
88  image = visualize(image, results)
89 
90  # Save results if save is true
91  if args.save:
92  print('Resutls saved to result.jpg\n')
93  cv.imwrite('result.jpg', image)
94 
95  # Visualize results in a new window
96  if args.vis:
97  cv.namedWindow(args.input, cv.WINDOW_AUTOSIZE)
98  cv.imshow(args.input, image)
99  cv.waitKey(0)
100  else: # Omit input to call default camera
101  deviceId = 0
102  cap = cv.VideoCapture(deviceId)
103 
104  tm = cv.TickMeter()
105  while cv.waitKey(1) < 0:
106  hasFrame, frame = cap.read()
107  if not hasFrame:
108  print('No frames grabbed!')
109  break
110 
111  frame = cv.resize(frame, [args.width, args.height])
112  # Inference
113  tm.start()
114  results = model.infer(frame) # results is a tuple
115  tm.stop()
116 
117  # Draw results on the input image
118  frame = visualize(frame, results, fps=tm.getFPS())
119 
120  # Visualize results in a new Window
121  cv.imshow('{} Demo'.format(model.name), frame)
122 
123  tm.reset()
124 
demo.str2bool
str2bool
Definition: demo.py:43
demo.visualize
def visualize(image, results, box_color=(0, 255, 0), text_color=(0, 0, 255), fps=None)
Definition: demo.py:46
db.DB
Definition: db.py:10