-
Notifications
You must be signed in to change notification settings - Fork 0
/
ir.go
582 lines (507 loc) · 15.7 KB
/
ir.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package lblconv
// The intermediate annotation metadata representation.
import (
"fmt"
"image"
"log"
"math"
"math/rand"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/disintegration/imaging"
)
// Keys for known annotation attributes.
const (
AncestorLabels = "Ancestors" // Ancestors in the label taxonomy. Type []string.
Confidence = "Confidence" // Type float64 in [0.0, 1.0].
CropCoords = "CropCoords" // Absolute coords (x1,y1)(x2,y2) in the source image. Type string.
DetectedText = "Text" // Text that is associated with the bounding box. Type string.
)
// Annotation is the intermediate representation of an object label.
type Annotation struct {
Attributes map[string]interface{} // Additional attributes of this annotation.
Coords [4]float64 // Absolute x1, y1, x2, y2 offsets from the top-left corner.
Label string
}
// Width is the object width from a.Coords.
func (a Annotation) Width() float64 {
return a.Coords[2] - a.Coords[0]
}
// Height is the object height from a.Coords.
func (a Annotation) Height() float64 {
return a.Coords[3] - a.Coords[1]
}
// AnnotatedFile is the intermediate representation of file metadata.
type AnnotatedFile struct {
Annotations []Annotation // The annotations.
FilePath string // The annotated file.
}
// scaleCoords scales all Annotations.Coords by the given scale factors.
func (f *AnnotatedFile) scaleCoords(width, height float64) {
for i := range f.Annotations {
for j := 0; j < 4; j++ {
if j&1 == 0 {
f.Annotations[i].Coords[j] *= width
} else {
f.Annotations[i].Coords[j] *= height
}
}
}
}
type subImager interface {
SubImage(r image.Rectangle) image.Image
}
// cropObjectsFromImage returns a crop of img for each annotation with a bounding box that is at
// least partially contained in img. The crops may share their data with the original image.
//
// In addition it returns an []AnnotatedFile, one for each cropped image. The file paths are
// derived from f.FilePath, with a "_xx" suffix appended before the file extension, where xx is the
// index in f.Annotations.
func (f *AnnotatedFile) cropObjectsFromImage(img image.Image) (
[]image.Image, []AnnotatedFile, error) {
img2, ok := img.(subImager)
if !ok {
return nil, nil,
fmt.Errorf("the image type of %q does not provide a SubImage method", f.FilePath)
}
crops := make([]image.Image, 0, len(f.Annotations))
annotatedFiles := make([]AnnotatedFile, 0, len(f.Annotations))
bounds := img.Bounds()
for i, a := range f.Annotations {
// Clip the bounding box to the image bounds.
r := image.Rect(int(math.Round(a.Coords[0])), int(math.Round(a.Coords[1])),
int(math.Round(a.Coords[2])), int(math.Round(a.Coords[3])))
r = r.Intersect(bounds)
if r.Empty() {
continue
}
// Make a shallow clone of the annotation's attributes and add the CropCoords.
attrs := make(map[string]interface{}, 1+len(a.Attributes))
for k, v := range a.Attributes {
attrs[k] = v
}
attrs[CropCoords] = fmt.Sprintf("(%d,%d)(%d,%d)", r.Min.X, r.Min.Y, r.Max.X, r.Max.Y)
// Construct the file path for the crop from the original path.
ext := filepath.Ext(f.FilePath)
path := fmt.Sprintf("%s_%02d%s", f.FilePath[0:len(f.FilePath)-len(ext)], i, ext)
// Create the annotation for the crop with a bounding box covering the entire area.
fileData := AnnotatedFile{
Annotations: []Annotation{
{
Attributes: attrs,
Coords: [4]float64{0, 0, float64(r.Dx()), float64(r.Dy())},
Label: a.Label,
},
},
FilePath: path,
}
crops = append(crops, img2.SubImage(r))
annotatedFiles = append(annotatedFiles, fileData)
}
return crops, annotatedFiles, nil
}
// AnnotatedFiles is the annotation metadata for a list of files.
type AnnotatedFiles []AnnotatedFile
// MapLabels replaces label (sub-)strings with substitution values, as specified in mappings.
//
// The format of mappings is old=new.
func (data *AnnotatedFiles) MapLabels(mappings []string) error {
if len(mappings) == 0 {
return nil
}
// Extract the individual old and new strings to map between.
replacements := make([]struct{ old, new string }, len(mappings))
for i, v := range mappings {
a := strings.Split(v, "=")
if len(a) != 2 {
return fmt.Errorf("invalid mapping: %v", v)
}
replacements[i].old = a[0]
replacements[i].new = a[1]
}
// Apply the replacements, in order, to all labels.
count := 0
for _, f := range *data {
for i, aLen := 0, len(f.Annotations); i < aLen; i++ {
a := &f.Annotations[i]
oldLabel := a.Label
for _, r := range replacements {
a.Label = strings.Replace(a.Label, r.old, r.new, -1)
}
if a.Label != oldLabel {
count++
}
}
}
log.Printf("The label mappings changed %d labels", count)
return nil
}
// TransformBboxes transforms bounding boxes.
//
// First bboxes are scaled by the horizontal and vertical scale factors scaleX and scaleY.
//
// Next, the bounding box is grown (never shrunk) to match the desired aspect ratio. An aspectRatio
// of zero disables this transformation.
func (data *AnnotatedFiles) TransformBboxes(scaleX, scaleY, aspectRatio float64) {
for _, f := range *data {
for i, aLen := 0, len(f.Annotations); i < aLen; i++ {
a := &f.Annotations[i]
// Scale.
if scaleX != 1 || scaleY != 1 {
w := a.Width()
h := a.Height()
dx := (w*scaleX - w) * 0.5
dy := (h*scaleY - h) * 0.5
a.Coords[0] -= dx
a.Coords[1] -= dy
a.Coords[2] += dx
a.Coords[3] += dy
}
// Grow to match desired aspect ratio.
if aspectRatio > 0 {
// Calculate the ratio so that the expansion works even if one of width or height is zero.
w := a.Width()
h := a.Height()
var ratio float64
if h != 0 {
ratio = w / h
} else {
ratio = math.MaxFloat64
}
if ratio < aspectRatio {
// Expand horizontally.
dx := (h*aspectRatio - w) * 0.5
a.Coords[0] -= dx
a.Coords[2] += dx
} else if ratio > aspectRatio {
// Expand vertically.
dy := (w/aspectRatio - h) * 0.5
a.Coords[1] -= dy
a.Coords[3] += dy
}
}
}
}
}
// Filter filters out annotations which do not match any of the given labelNames, have a confidence
// value less than minConfidence, a bounding box with less than minBboxWidth or minBboxHeight, or
// do not match the required aspect ratio.
//
// The aspect ratio of width/height must be in [minAspectRatio, maxAspectRatio], except that a
// min/max value of zero disables the respective filter.
//
// If attributes is non empty, only the listed attributes are kept. This only filters the list
// of attributes, not the annotations themselve.
//
// Similarly, requiredAttrs specifies attributes that must be present with a value that is not the
// Go zero value of their type. If this test fails for an annotation, that annotation is deleted.
func (data *AnnotatedFiles) Filter(labelNames, attributes, requiredAttrs []string,
minConfidence float64, requireLabel bool, minBboxWidth, minBboxHeight, minAspectRatio,
maxAspectRatio float64) {
// Deletes the annotation at index i.
deleteAnnotation := func(annotations []Annotation, i int) []Annotation {
l := len(annotations)
annotations[i] = annotations[l-1]
return annotations[:l-1]
}
// Look for string in list.
inList := func(v string, l []string) bool {
for _, val := range l {
if val == v {
return true
}
}
return false
}
numFiles := len(*data)
numLabelsBeforeFilter := 0
numLabelsAfterFilter := 0
// Apply filters.
for dataIdx, dataLen := 0, len(*data); dataIdx < dataLen; dataIdx++ {
d := &(*data)[dataIdx]
numLabelsBeforeFilter += len(d.Annotations)
// Annotation filters.
annotationLoop:
for i, aLen := 0, len(d.Annotations); i < aLen; i++ {
a := &d.Annotations[i]
// Filter by confidence. If the annotation has no confidence value then it passes the filter.
if c, ok := a.Attributes[Confidence].(float64); ok && c < minConfidence {
d.Annotations = deleteAnnotation(d.Annotations, i)
aLen--
i--
continue
}
// Filter by bbox size.
width := a.Width()
height := a.Height()
if minBboxWidth > width || minBboxHeight > height {
d.Annotations = deleteAnnotation(d.Annotations, i)
aLen--
i--
continue
}
// Filter by bbox aspect ratio.
if minAspectRatio != 0 || maxAspectRatio != 0 {
keep := height != 0
if keep {
ratio := width / height
keep = (minAspectRatio == 0 || ratio >= minAspectRatio) &&
(maxAspectRatio == 0 || ratio <= maxAspectRatio)
}
if !keep {
d.Annotations = deleteAnnotation(d.Annotations, i)
aLen--
i--
continue
}
}
// Filter by labels.
if len(labelNames) > 0 && !inList(a.Label, labelNames) {
d.Annotations = deleteAnnotation(d.Annotations, i)
aLen--
i--
continue
}
// Filter by required attributes with non zero value.
if len(requiredAttrs) > 0 {
for _, k := range requiredAttrs {
// Test against the zero value of the underlying type.
if v := a.Attributes[k]; v == nil || v == reflect.Zero(reflect.TypeOf(v)).Interface() {
d.Annotations = deleteAnnotation(d.Annotations, i)
aLen--
i--
continue annotationLoop
}
}
}
// Filter attributes.
if len(attributes) > 0 {
for k := range a.Attributes {
if !inList(k, attributes) {
delete(a.Attributes, k)
}
}
}
}
numLabelsAfterFilter += len(d.Annotations)
// Delete the file annotation if files with no labels are filtered out.
if requireLabel && len(d.Annotations) == 0 {
dataLen--
(*data)[dataIdx] = (*data)[dataLen]
*data = (*data)[0:dataLen]
dataIdx--
}
}
log.Printf("Filtered out %d labels and %d files",
numLabelsBeforeFilter-numLabelsAfterFilter, numFiles-len(*data))
}
// ProcessImages resizes all referenced images and writes them to imageOutDir using the specified
// encoding.
//
// If doCropObjects is true, individual objects as per the labels are cropped from the images. The
// crops are resized instead of the original images in this case. The data changes accordingly, with
// 0 or more cropped images replacing the original AnnotatedFile.
func (data *AnnotatedFiles) ProcessImages(imageOutDir string, longerSide, shorterSide int,
downsamplingFilter, upsamplingFilter, encoding string, jpegQuality int,
doCropObjects bool) error {
doResizeImages := longerSide > 0 || shorterSide > 0
if !doResizeImages && !doCropObjects {
return nil
}
log.Print("Processing images")
// Select the resampling algorithms.
downsample := imaging.Box
upsample := imaging.Linear
filters := []struct {
name string
filter *imaging.ResampleFilter
}{
{downsamplingFilter, &downsample},
{upsamplingFilter, &upsample},
}
for _, v := range filters {
switch v.name {
case "nearest":
*v.filter = imaging.NearestNeighbor
case "box":
*v.filter = imaging.Box
case "linear":
*v.filter = imaging.Linear
case "gaussian":
*v.filter = imaging.Gaussian
case "lanczos":
*v.filter = imaging.Lanczos
default:
return fmt.Errorf("unknown resampling filter %q", v.name)
}
}
// Select the output file extension based on the requested encoding.
var fileExt string
switch strings.ToLower(encoding) {
case "jpg", "jpeg":
fileExt = ".jpg"
case "png":
fileExt = ".png"
default:
return fmt.Errorf("unsupported output encoding %q", encoding)
}
// Prepare for concurrent processing. Limit the number of goroutines in flight, as they load
// potentially large images into memory.
numTasks := 2 * runtime.NumCPU()
if len(*data) < numTasks {
numTasks = len(*data)
}
workQueue := make(chan *AnnotatedFile, 2*numTasks)
var croppedData []AnnotatedFile
var croppedDataCh chan *AnnotatedFile
if doCropObjects {
croppedData = make([]AnnotatedFile, 0, len(*data))
croppedDataCh = make(chan *AnnotatedFile, 2*numTasks)
}
errors := make(chan error, 1)
var wg sync.WaitGroup
// Process images concurrently from a work queue.
wg.Add(numTasks)
for i := 0; i < numTasks; i++ {
go func() {
defer wg.Done()
for d := range workQueue {
processImage(d, imageOutDir, fileExt, longerSide, shorterSide, downsample,
upsample, jpegQuality, doCropObjects, doResizeImages, croppedDataCh, errors)
}
}()
}
// Append image metadata for cropped images.
var wgAppend sync.WaitGroup
if doCropObjects {
wgAppend.Add(1)
go func() {
defer wgAppend.Done()
for d := range croppedDataCh {
croppedData = append(croppedData, *d)
}
}()
}
// Feed the work queue.
for i := range *data {
workQueue <- &(*data)[i]
}
close(workQueue)
// Wait for image processing to finish.
wg.Wait()
if doCropObjects {
// Wait for all new metadata to be appended and then replace the old data.
close(croppedDataCh)
wgAppend.Wait()
*data = croppedData
}
close(errors)
if len(errors) > 0 {
return <-errors
}
return nil
}
// processImage processes the image described by data.
//
// If and only if doCropObjects is true, new metadata for the image crops is written to croppedData.
func processImage(data *AnnotatedFile, imageOutDir, fileExt string, longerSide, shorterSide int,
downsample, upsample imaging.ResampleFilter, jpegQuality int, doCropObjects, doResizeImage bool,
croppedData chan<- *AnnotatedFile, errors chan<- error) {
trySendError := func(err error) {
select {
case errors <- err:
default:
}
}
// Read the image.
img, _, err := loadImage(data.FilePath)
if err != nil {
trySendError(err)
return
}
// Crop labelled objects from the image if requested.
var images []image.Image
var imageData []*AnnotatedFile
if doCropObjects {
// The original image is not further processed in this case.
var tmpData []AnnotatedFile
images, tmpData, err = data.cropObjectsFromImage(img)
if err != nil {
trySendError(err)
return
}
imageData = make([]*AnnotatedFile, len(tmpData))
for i := range tmpData {
imageData[i] = &tmpData[i]
}
} else {
images = []image.Image{img}
imageData = []*AnnotatedFile{data}
}
// Process either the original image or the crops.
for i, img := range images {
data := imageData[i]
// Resize.
var scaleWidth, scaleHeight float64
if doResizeImage {
img, scaleWidth, scaleHeight, err =
resizeImage(img, longerSide, shorterSide, downsample, upsample)
if err != nil {
trySendError(err)
return
}
}
// Save the image.
inName := filepath.Base(data.FilePath)
inFileExt := filepath.Ext(inName)
outName := inName[0:len(inName)-len(inFileExt)] + fileExt
outPath := filepath.Join(imageOutDir, outName)
if err := saveImage(outPath, img, jpegQuality); err != nil {
trySendError(err)
return
}
// Update the image file path and rescale the coordinates.
data.FilePath = outPath
if doResizeImage {
data.scaleCoords(scaleWidth, scaleHeight)
}
// Return the metadata for the cropped image.
if doCropObjects {
croppedData <- data
}
}
}
// Split randomly splits the data into multiple datasets.
//
// The cumulativeSplits specify the cumulative distribution according to which the data is split
// into the returned datasets. Its values must add up to 100!
func (data *AnnotatedFiles) Split(cumulativeSplits []int) ([]AnnotatedFiles, error) {
datasets := make([]AnnotatedFiles, len(cumulativeSplits))
// Allocate slightly more than the expected size for each dataset.
var sum int
for i, s := range cumulativeSplits {
percent := s - sum
datasets[i] = make(AnnotatedFiles, 0, int(1.05*float64(percent)/100*float64(len(*data))))
sum = s
}
if sum != 100 {
return nil, fmt.Errorf("the split percentages do not add up to 100")
}
// Split the data.
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
outer:
for _, d := range *data {
r := rng.Intn(100)
for i, s := range cumulativeSplits {
if r < s {
datasets[i] = append(datasets[i], d)
continue outer
}
}
}
return datasets, nil
}