glenn-jocher commited on
Commit
de44376
1 Parent(s): 7b35971

Create `Annotator()` class (#4591)

Browse files

* Add Annotator() class

* Download Arial

* 2x for loop

* Cleanup

* tuple 2 list

* max_size=1920

* bold logging results to

* tolist()

* im = annotator.im

* PIL save in detect.py

* Smart asarray in detect.py

* revert to cv2.imwrite

* Cleanup

* Return result asarray

* Add `Profile()` profiler

* CamelCase Timeout

* Resize after mosaic

* pillow>=8.0.0

* daemon imwrite

* Add cv2 support

* Remove plot_wh_methods and plot_one_box

* pil=False for hubconf.py annotations

* im.shape bug fix

* colorstr common.py

* join daemons

* Update t.daemon

* Removed daemon saving

Files changed (6) hide show
  1. detect.py +4 -2
  2. models/common.py +7 -4
  3. requirements.txt +1 -1
  4. train.py +1 -1
  5. utils/general.py +3 -2
  6. utils/plots.py +90 -99
detect.py CHANGED
@@ -23,7 +23,7 @@ from models.experimental import attempt_load
23
  from utils.datasets import LoadStreams, LoadImages
24
  from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \
25
  apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
26
- from utils.plots import colors, plot_one_box
27
  from utils.torch_utils import select_device, load_classifier, time_sync
28
 
29
 
@@ -181,6 +181,7 @@ def run(weights='yolov5s.pt', # model.pt path(s)
181
  s += '%gx%g ' % img.shape[2:] # print string
182
  gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
183
  imc = im0.copy() if save_crop else im0 # for save_crop
 
184
  if len(det):
185
  # Rescale boxes from img_size to im0 size
186
  det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
@@ -201,7 +202,7 @@ def run(weights='yolov5s.pt', # model.pt path(s)
201
  if save_img or save_crop or view_img: # Add bbox to image
202
  c = int(cls) # integer class
203
  label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
204
- im0 = plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_width=line_thickness)
205
  if save_crop:
206
  save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
207
 
@@ -209,6 +210,7 @@ def run(weights='yolov5s.pt', # model.pt path(s)
209
  print(f'{s}Done. ({t2 - t1:.3f}s)')
210
 
211
  # Stream results
 
212
  if view_img:
213
  cv2.imshow(str(p), im0)
214
  cv2.waitKey(1) # 1 millisecond
 
23
  from utils.datasets import LoadStreams, LoadImages
24
  from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \
25
  apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
26
+ from utils.plots import colors, Annotator
27
  from utils.torch_utils import select_device, load_classifier, time_sync
28
 
29
 
 
181
  s += '%gx%g ' % img.shape[2:] # print string
182
  gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
183
  imc = im0.copy() if save_crop else im0 # for save_crop
184
+ annotator = Annotator(im0, line_width=line_thickness, pil=False)
185
  if len(det):
186
  # Rescale boxes from img_size to im0 size
187
  det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
 
202
  if save_img or save_crop or view_img: # Add bbox to image
203
  c = int(cls) # integer class
204
  label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
205
+ annotator.box_label(xyxy, label, color=colors(c, True))
206
  if save_crop:
207
  save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
208
 
 
210
  print(f'{s}Done. ({t2 - t1:.3f}s)')
211
 
212
  # Stream results
213
+ im0 = annotator.result()
214
  if view_img:
215
  cv2.imshow(str(p), im0)
216
  cv2.waitKey(1) # 1 millisecond
models/common.py CHANGED
@@ -18,8 +18,9 @@ from PIL import Image
18
  from torch.cuda import amp
19
 
20
  from utils.datasets import exif_transpose, letterbox
21
- from utils.general import non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh, save_one_box
22
- from utils.plots import colors, plot_one_box
 
23
  from utils.torch_utils import time_sync
24
 
25
  LOGGER = logging.getLogger(__name__)
@@ -370,12 +371,14 @@ class Detections:
370
  n = (pred[:, -1] == c).sum() # detections per class
371
  str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
372
  if show or save or render or crop:
 
373
  for *box, conf, cls in reversed(pred): # xyxy, confidence, class
374
  label = f'{self.names[int(cls)]} {conf:.2f}'
375
  if crop:
376
  save_one_box(box, im, file=save_dir / 'crops' / self.names[int(cls)] / self.files[i])
377
  else: # all others
378
- im = plot_one_box(box, im, label=label, color=colors(cls))
 
379
  else:
380
  str += '(no detections)'
381
 
@@ -388,7 +391,7 @@ class Detections:
388
  f = self.files[i]
389
  im.save(save_dir / f) # save
390
  if i == self.n - 1:
391
- LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to '{save_dir}'")
392
  if render:
393
  self.imgs[i] = np.asarray(im)
394
 
 
18
  from torch.cuda import amp
19
 
20
  from utils.datasets import exif_transpose, letterbox
21
+ from utils.general import colorstr, non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh, \
22
+ save_one_box
23
+ from utils.plots import colors, Annotator
24
  from utils.torch_utils import time_sync
25
 
26
  LOGGER = logging.getLogger(__name__)
 
371
  n = (pred[:, -1] == c).sum() # detections per class
372
  str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
373
  if show or save or render or crop:
374
+ annotator = Annotator(im, pil=False)
375
  for *box, conf, cls in reversed(pred): # xyxy, confidence, class
376
  label = f'{self.names[int(cls)]} {conf:.2f}'
377
  if crop:
378
  save_one_box(box, im, file=save_dir / 'crops' / self.names[int(cls)] / self.files[i])
379
  else: # all others
380
+ annotator.box_label(box, label, color=colors(cls))
381
+ im = annotator.im
382
  else:
383
  str += '(no detections)'
384
 
 
391
  f = self.files[i]
392
  im.save(save_dir / f) # save
393
  if i == self.n - 1:
394
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
395
  if render:
396
  self.imgs[i] = np.asarray(im)
397
 
requirements.txt CHANGED
@@ -4,7 +4,7 @@
4
  matplotlib>=3.2.2
5
  numpy>=1.18.5
6
  opencv-python>=4.1.2
7
- Pillow
8
  PyYAML>=5.3.1
9
  scipy>=1.4.1
10
  torch>=1.7.0
 
4
  matplotlib>=3.2.2
5
  numpy>=1.18.5
6
  opencv-python>=4.1.2
7
+ Pillow>=8.0.0
8
  PyYAML>=5.3.1
9
  scipy>=1.4.1
10
  torch>=1.7.0
train.py CHANGED
@@ -260,7 +260,7 @@ def train(hyp, # path/to/hyp.yaml or hyp dictionary
260
  compute_loss = ComputeLoss(model) # init loss class
261
  LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
262
  f'Using {train_loader.num_workers} dataloader workers\n'
263
- f'Logging results to {save_dir}\n'
264
  f'Starting training for {epochs} epochs...')
265
  for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
266
  model.train()
 
260
  compute_loss = ComputeLoss(model) # init loss class
261
  LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
262
  f'Using {train_loader.num_workers} dataloader workers\n'
263
+ f"Logging results to {colorstr('bold', save_dir)}\n"
264
  f'Starting training for {epochs} epochs...')
265
  for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
266
  model.train()
utils/general.py CHANGED
@@ -122,9 +122,10 @@ def is_pip():
122
  return 'site-packages' in Path(__file__).absolute().parts
123
 
124
 
125
- def is_ascii(str=''):
126
  # Is string composed of all ASCII (no UTF) characters?
127
- return len(str.encode().decode('ascii', 'ignore')) == len(str)
 
128
 
129
 
130
  def emojis(str=''):
 
122
  return 'site-packages' in Path(__file__).absolute().parts
123
 
124
 
125
+ def is_ascii(s=''):
126
  # Is string composed of all ASCII (no UTF) characters?
127
+ s = str(s) # convert to str() in case of None, etc.
128
+ return len(s.encode().decode('ascii', 'ignore')) == len(s)
129
 
130
 
131
  def emojis(str=''):
utils/plots.py CHANGED
@@ -67,51 +67,59 @@ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
67
  return filtfilt(b, a, data) # forward-backward filter
68
 
69
 
70
- def plot_one_box(box, im, color=(128, 128, 128), txt_color=(255, 255, 255), label=None, line_width=3, use_pil=False):
71
- # Plots one xyxy box on image im with label
72
- assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
73
- lw = line_width or max(int(min(im.size) / 200), 2) # line width
74
-
75
- if use_pil or (label is not None and not is_ascii(label)): # use PIL
76
- im = Image.fromarray(im)
77
- draw = ImageDraw.Draw(im)
78
- draw.rectangle(box, width=lw + 1, outline=color) # plot
79
- if label:
80
- font = ImageFont.truetype("Arial.ttf", size=max(round(max(im.size) / 40), 12))
81
- txt_width, txt_height = font.getsize(label)
82
- draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=color)
83
- draw.text((box[0], box[1] - txt_height + 1), label, fill=txt_color, font=font)
84
- return np.asarray(im)
85
- else: # use OpenCV
86
- c1, c2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
87
- cv2.rectangle(im, c1, c2, color, thickness=lw, lineType=cv2.LINE_AA)
88
- if label:
89
- tf = max(lw - 1, 1) # font thickness
90
- txt_width, txt_height = cv2.getTextSize(label, 0, fontScale=lw / 3, thickness=tf)[0]
91
- c2 = c1[0] + txt_width, c1[1] - txt_height - 3
92
- cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
93
- cv2.putText(im, label, (c1[0], c1[1] - 2), 0, lw / 3, txt_color, thickness=tf, lineType=cv2.LINE_AA)
94
- return im
95
-
96
-
97
- def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
98
- # Compares the two methods for width-height anchor multiplication
99
- # https://github.com/ultralytics/yolov3/issues/168
100
- x = np.arange(-4.0, 4.0, .1)
101
- ya = np.exp(x)
102
- yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
103
-
104
- fig = plt.figure(figsize=(6, 3), tight_layout=True)
105
- plt.plot(x, ya, '.-', label='YOLOv3')
106
- plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
107
- plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
108
- plt.xlim(left=-4, right=4)
109
- plt.ylim(bottom=0, top=6)
110
- plt.xlabel('input')
111
- plt.ylabel('output')
112
- plt.grid()
113
- plt.legend()
114
- fig.savefig('comparison.png', dpi=200)
 
 
 
 
 
 
 
 
115
 
116
 
117
  def output_to_target(output):
@@ -123,82 +131,65 @@ def output_to_target(output):
123
  return np.array(targets)
124
 
125
 
126
- def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
127
  # Plot image grid with labels
128
-
129
  if isinstance(images, torch.Tensor):
130
  images = images.cpu().float().numpy()
131
  if isinstance(targets, torch.Tensor):
132
  targets = targets.cpu().numpy()
133
-
134
- # un-normalise
135
  if np.max(images[0]) <= 1:
136
- images *= 255
137
-
138
- tl = 3 # line thickness
139
- tf = max(tl - 1, 1) # font thickness
140
  bs, _, h, w = images.shape # batch size, _, height, width
141
  bs = min(bs, max_subplots) # limit plot images
142
  ns = np.ceil(bs ** 0.5) # number of subplots (square)
143
 
144
- # Check if we should resize
145
- scale_factor = max_size / max(h, w)
146
- if scale_factor < 1:
147
- h = math.ceil(scale_factor * h)
148
- w = math.ceil(scale_factor * w)
149
-
150
  mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
151
- for i, img in enumerate(images):
152
  if i == max_subplots: # if last batch has fewer images than we expect
153
  break
154
-
155
- block_x = int(w * (i // ns))
156
- block_y = int(h * (i % ns))
157
-
158
- img = img.transpose(1, 2, 0)
159
- if scale_factor < 1:
160
- img = cv2.resize(img, (w, h))
161
-
162
- mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
 
 
 
 
 
 
 
 
 
 
163
  if len(targets) > 0:
164
- image_targets = targets[targets[:, 0] == i]
165
- boxes = xywh2xyxy(image_targets[:, 2:6]).T
166
- classes = image_targets[:, 1].astype('int')
167
- labels = image_targets.shape[1] == 6 # labels if no conf column
168
- conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
169
 
170
  if boxes.shape[1]:
171
  if boxes.max() <= 1.01: # if normalized with tolerance 0.01
172
  boxes[[0, 2]] *= w # scale to pixels
173
  boxes[[1, 3]] *= h
174
- elif scale_factor < 1: # absolute coords need scale if image scales
175
- boxes *= scale_factor
176
- boxes[[0, 2]] += block_x
177
- boxes[[1, 3]] += block_y
178
- for j, box in enumerate(boxes.T):
179
- cls = int(classes[j])
180
  color = colors(cls)
181
  cls = names[cls] if names else cls
182
  if labels or conf[j] > 0.25: # 0.25 conf thresh
183
- label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
184
- mosaic = plot_one_box(box, mosaic, label=label, color=color, line_width=tl)
185
-
186
- # Draw image filename labels
187
- if paths:
188
- label = Path(paths[i]).name[:40] # trim to 40 char
189
- t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
190
- cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
191
- lineType=cv2.LINE_AA)
192
-
193
- # Image border
194
- cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
195
-
196
- if fname:
197
- r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
198
- mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
199
- # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
200
- Image.fromarray(mosaic).save(fname) # PIL save
201
- return mosaic
202
 
203
 
204
  def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
 
67
  return filtfilt(b, a, data) # forward-backward filter
68
 
69
 
70
+ class Annotator:
71
+ # YOLOv5 PIL Annotator class
72
+ def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=True):
73
+ assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
74
+ self.pil = pil
75
+ if self.pil: # use PIL
76
+ self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
77
+ self.draw = ImageDraw.Draw(self.im)
78
+ s = sum(self.im.size) / 2 # mean shape
79
+ f = font_size or max(round(s * 0.035), 12)
80
+ try:
81
+ self.font = ImageFont.truetype(font, size=f)
82
+ except: # download TTF
83
+ url = "https://github.com/ultralytics/yolov5/releases/download/v1.0/" + font
84
+ torch.hub.download_url_to_file(url, font)
85
+ self.font = ImageFont.truetype(font, size=f)
86
+ self.fh = self.font.getsize('a')[1] - 3 # font height
87
+ else: # use cv2
88
+ self.im = im
89
+ s = sum(im.shape) / 2 # mean shape
90
+ self.lw = line_width or max(round(s * 0.003), 2) # line width
91
+
92
+ def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
93
+ # Add one xyxy box to image with label
94
+ if self.pil or not is_ascii(label):
95
+ self.draw.rectangle(box, width=self.lw, outline=color) # box
96
+ if label:
97
+ w = self.font.getsize(label)[0] # text width
98
+ self.draw.rectangle([box[0], box[1] - self.fh, box[0] + w + 1, box[1] + 1], fill=color)
99
+ self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')
100
+ else: # cv2
101
+ c1, c2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
102
+ cv2.rectangle(self.im, c1, c2, color, thickness=self.lw, lineType=cv2.LINE_AA)
103
+ if label:
104
+ tf = max(self.lw - 1, 1) # font thickness
105
+ w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0]
106
+ c2 = c1[0] + w, c1[1] - h - 3
107
+ cv2.rectangle(self.im, c1, c2, color, -1, cv2.LINE_AA) # filled
108
+ cv2.putText(self.im, label, (c1[0], c1[1] - 2), 0, self.lw / 3, txt_color, thickness=tf,
109
+ lineType=cv2.LINE_AA)
110
+
111
+ def rectangle(self, xy, fill=None, outline=None, width=1):
112
+ # Add rectangle to image (PIL-only)
113
+ self.draw.rectangle(xy, fill, outline, width)
114
+
115
+ def text(self, xy, text, txt_color=(255, 255, 255)):
116
+ # Add text to image (PIL-only)
117
+ w, h = self.font.getsize(text) # text width, height
118
+ self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font)
119
+
120
+ def result(self):
121
+ # Return annotated image as array
122
+ return np.asarray(self.im)
123
 
124
 
125
  def output_to_target(output):
 
131
  return np.array(targets)
132
 
133
 
134
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):
135
  # Plot image grid with labels
 
136
  if isinstance(images, torch.Tensor):
137
  images = images.cpu().float().numpy()
138
  if isinstance(targets, torch.Tensor):
139
  targets = targets.cpu().numpy()
 
 
140
  if np.max(images[0]) <= 1:
141
+ images *= 255.0 # de-normalise (optional)
 
 
 
142
  bs, _, h, w = images.shape # batch size, _, height, width
143
  bs = min(bs, max_subplots) # limit plot images
144
  ns = np.ceil(bs ** 0.5) # number of subplots (square)
145
 
146
+ # Build Image
 
 
 
 
 
147
  mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
148
+ for i, im in enumerate(images):
149
  if i == max_subplots: # if last batch has fewer images than we expect
150
  break
151
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
152
+ im = im.transpose(1, 2, 0)
153
+ mosaic[y:y + h, x:x + w, :] = im
154
+
155
+ # Resize (optional)
156
+ scale = max_size / ns / max(h, w)
157
+ if scale < 1:
158
+ h = math.ceil(scale * h)
159
+ w = math.ceil(scale * w)
160
+ mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
161
+
162
+ # Annotate
163
+ fs = int(h * ns * 0.02) # font size
164
+ annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs)
165
+ for i in range(i + 1):
166
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
167
+ annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
168
+ if paths:
169
+ annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
170
  if len(targets) > 0:
171
+ ti = targets[targets[:, 0] == i] # image targets
172
+ boxes = xywh2xyxy(ti[:, 2:6]).T
173
+ classes = ti[:, 1].astype('int')
174
+ labels = ti.shape[1] == 6 # labels if no conf column
175
+ conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
176
 
177
  if boxes.shape[1]:
178
  if boxes.max() <= 1.01: # if normalized with tolerance 0.01
179
  boxes[[0, 2]] *= w # scale to pixels
180
  boxes[[1, 3]] *= h
181
+ elif scale < 1: # absolute coords need scale if image scales
182
+ boxes *= scale
183
+ boxes[[0, 2]] += x
184
+ boxes[[1, 3]] += y
185
+ for j, box in enumerate(boxes.T.tolist()):
186
+ cls = classes[j]
187
  color = colors(cls)
188
  cls = names[cls] if names else cls
189
  if labels or conf[j] > 0.25: # 0.25 conf thresh
190
+ label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'
191
+ annotator.box_label(box, label, color=color)
192
+ annotator.im.save(fname) # save
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
 
195
  def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):