-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathprep_train.py
executable file
·2060 lines (1784 loc) · 83.8 KB
/
prep_train.py
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 2020
@author: avanetten
"""
import os
import sys
import math
import shutil
import rasterio
import rasterio.mask
import pandas as pd
import numpy as np
import skimage
import multiprocessing
import skimage.io
import skimage.transform
from rasterio.windows import Window
import fiona
import random
import cv2
# import solaris.vector
import shapely
import matplotlib
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
from shapely.wkt import loads
from affine import Affine
import rasterio
from rasterio.warp import transform_bounds
from rasterio.crs import CRS
# from ..utils.geo import list_to_affine, _reduce_geom_precision
# from ..utils.core import _check_gdf_load, _check_crs, _check_rasterio_im_load
#from ..raster.image import get_geo_transform
from shapely.geometry import box, Polygon
import pandas as pd
import geopandas as gpd
from rtree.core import RTreeError
import shutil
from shapely.geometry import MultiLineString, MultiPolygon, mapping, box, shape
# yolt funcs
import tile_ims_labels
import utils
###############################################################################
###############################################################################
# https://github.com/CosmiQ/solaris/blob/master/solaris/utils/geo.py
###############################################################################
def _reduce_geom_precision(geom, precision=2):
geojson = mapping(geom)
geojson['coordinates'] = np.round(np.array(geojson['coordinates']),
precision)
return shape(geojson)
# https://github.com/CosmiQ/solaris/blob/master/solaris/raster/image.py
###############################################################################
def get_geo_transform(raster_src):
"""Get the geotransform for a raster image source.
Arguments
---------
raster_src : str, :class:`rasterio.DatasetReader`, or `osgeo.gdal.Dataset`
Path to a raster image with georeferencing data to apply to `geom`.
Alternatively, an opened :class:`rasterio.Band` object or
:class:`osgeo.gdal.Dataset` object can be provided. Required if not
using `affine_obj`.
Returns
-------
transform : :class:`affine.Affine`
An affine transformation object to the image's location in its CRS.
"""
if isinstance(raster_src, str):
affine_obj = rasterio.open(raster_src).transform
elif isinstance(raster_src, rasterio.DatasetReader):
affine_obj = raster_src.transform
elif isinstance(raster_src, gdal.Dataset):
affine_obj = Affine.from_gdal(*raster_src.GetGeoTransform())
return affine_obj
# https://github.com/CosmiQ/solaris/blob/master/solaris/vector/polygon.py
###############################################################################
def convert_poly_coords(geom, raster_src=None, affine_obj=None, inverse=False,
precision=None):
"""Georegister geometry objects currently in pixel coords or vice versa.
Arguments
---------
geom : :class:`shapely.geometry.shape` or str
A :class:`shapely.geometry.shape`, or WKT string-formatted geometry
object currently in pixel coordinates.
raster_src : str, optional
Path to a raster image with georeferencing data to apply to `geom`.
Alternatively, an opened :class:`rasterio.Band` object or
:class:`osgeo.gdal.Dataset` object can be provided. Required if not
using `affine_obj`.
affine_obj: list or :class:`affine.Affine`
An affine transformation to apply to `geom` in the form of an
``[a, b, d, e, xoff, yoff]`` list or an :class:`affine.Affine` object.
Required if not using `raster_src`.
inverse : bool, optional
If true, will perform the inverse affine transformation, going from
geospatial coordinates to pixel coordinates.
precision : int, optional
Decimal precision for the polygon output. If not provided, rounding
is skipped.
Returns
-------
out_geom
A geometry in the same format as the input with its coordinate system
transformed to match the destination object.
"""
if not raster_src and not affine_obj:
raise ValueError("Either raster_src or affine_obj must be provided.")
if raster_src is not None:
affine_xform = get_geo_transform(raster_src)
else:
if isinstance(affine_obj, Affine):
affine_xform = affine_obj
else:
# assume it's a list in either gdal or "standard" order
# (list_to_affine checks which it is)
if len(affine_obj) == 9: # if it's straight from rasterio
affine_obj = affine_obj[0:6]
affine_xform = list_to_affine(affine_obj)
if inverse: # geo->px transform
affine_xform = ~affine_xform
if isinstance(geom, str):
# get the polygon out of the wkt string
g = shapely.wkt.loads(geom)
elif isinstance(geom, shapely.geometry.base.BaseGeometry):
g = geom
else:
raise TypeError('The provided geometry is not an accepted format. '
'This function can only accept WKT strings and '
'shapely geometries.')
xformed_g = shapely.affinity.affine_transform(g, [affine_xform.a,
affine_xform.b,
affine_xform.d,
affine_xform.e,
affine_xform.xoff,
affine_xform.yoff])
if isinstance(geom, str):
# restore to wkt string format
xformed_g = shapely.wkt.dumps(xformed_g)
if precision is not None:
xformed_g = _reduce_geom_precision(xformed_g, precision=precision)
return xformed_g
###############################################################################
#http://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python
def rotate(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy
###############################################################################
def create_mask(im_path, label_path, out_path_mask, burnValue=255):
with fiona.open(label_path, "r") as annotation_collection:
annotations = [feature["geometry"] for feature in annotation_collection]
with rasterio.open(im_path) as src:
out_image, out_transform = rasterio.mask.mask(src, annotations,
all_touched=False, invert=False, crop=False)
out_meta = src.meta
# clip
out_image = burnValue * np.clip(out_image, 0, 1)
htmp, wtmp = out_image.shape[1], out_image.shape[2]
out_meta.update({"driver": "GTiff",
"height": htmp,
"width": wtmp,
"transform": out_transform})
with rasterio.open(out_path_mask, "w", **out_meta) as dest:
dest.write(out_image)
###############################################################################
def prep_one(pan_path, mul_path, label_path, ps_rgb_path,
subdir, suff,
out_dir_image, out_dir_label, out_dir_mask,
out_path_image, out_path_label, out_path_mask,
sliceHeight=416, sliceWidth=416, mask_burnValue=255,
cls_id=0,
verbose=True):
##################
# Pan-sharpen
##################
# https://gdal.org/programs/gdal_pansharpen.html
# http://blog.cleverelephant.ca/2015/02/geotiff-compression-for-dummies.html
if 2 > 1: #not os.path.exists(ps_rgb_path):
if suff == 'yuge':
cmd = 'gdal_pansharpen.py ' + pan_path + ' ' \
+ mul_path + ' ' + ps_rgb_path + ' ' \
+ '-b 5 -b 3 -b 2 ' + '-spat_adjust none' \
+ ' -co COMPRESS=JPEG -co JPEG_QUALITY=40 -co PHOTOMETRIC=YCBCR -co TILED=YES'
else:
cmd = 'gdal_pansharpen.py ' + pan_path + ' ' \
+ mul_path + ' ' + ps_rgb_path + ' ' \
+ '-b 5 -b 3 -b 2 ' + '-spat_adjust none' \
+ ' -co COMPRESS=LZW'
print("Pan-sharpening cmd:", cmd)
os.system(cmd)
# ##################
# # Image
# ##################
im_tmp = skimage.io.imread(ps_rgb_path)
h, w = im_tmp.shape[:2]
aspect_ratio = 1.0 * h / w
dx = np.abs(h - w)
max_dx = 3
##################
# Labels
##################
if label_path:
with fiona.open(label_path, "r") as annotation_collection:
annotations = [feature["geometry"] for feature in annotation_collection]
# get pixel coords of bounding boxes
boxes, dhs = [], []
for a in annotations:
geom = shapely.geometry.Polygon(a['coordinates'][0])
pixel_geom = convert_poly_coords(geom, raster_src=ps_rgb_path,
affine_obj=None, inverse=True,
precision=2)
# Get bounding box. object.bounds: Returns a (minx, miny, maxx, maxy) tuple.
minx, miny, maxx, maxy = pixel_geom.bounds
boxes.append([minx, miny, maxx, maxy])
dhs.append([maxy-miny])
# set classes
classes = len(boxes) * [cls_id]
else:
classes, boxes = [], []
##################
# Process data
##################
# create masks
if out_path_mask and (not os.path.exists(out_path_mask)):
create_mask(ps_rgb_path, label_path, out_path_mask,
burnValue=mask_burnValue)
# tile data, if needed
if suff == '_tile':
# tile image, labels, and mask
out_name = subdir + '_PS-RGB'
# tile (also creates labels)
# for training, skip highly overlapped edge tiles
skip_highly_overlapped_tiles=True
tile_ims_labels.slice_im_plus_boxes(
ps_rgb_path, out_name, out_dir_image,
boxes=boxes, yolo_classes=classes, out_dir_labels=out_dir_label,
mask_path=out_path_mask, out_dir_masks=out_dir_mask,
sliceHeight=sliceHeight, sliceWidth=sliceWidth,
overlap=0.1, slice_sep='|',
skip_highly_overlapped_tiles=skip_highly_overlapped_tiles,
out_ext='.png', verbose=False)
else:
# no tiling
# first let's process images, then later we'll make labels
# simply copy to dest folder if object is yuge
if suff == '_yuge':
shutil.copyfile(ps_rgb_path, out_path_image)
hfinal, wfinal = h, w
# simply copy to dest folder if aspect ratio is reasonable
elif (0.9 < aspect_ratio < 1.1):
shutil.copyfile(ps_rgb_path, out_path_image)
hfinal, wfinal = h, w
# else let's add a border on right or bottom,
# (which doesn't affect pixel coords of labels).
else:
topBorderWidth, bottomBorderWidth, leftBorderWidth, rightBorderWidth = 0, 0, 0, 0
if h / w > 1.1:
rightBorderWidth = np.abs(h - w)
if h / w < 0.9:
bottomBorderWidth = np.abs(h - w)
# add border to image
# im_tmp = cv2.imread(out_path_image, 1) # make everything 3-channel?
outputImage = cv2.copyMakeBorder(
im_tmp,
topBorderWidth,
bottomBorderWidth,
leftBorderWidth,
rightBorderWidth,
cv2.BORDER_CONSTANT,
value=0)
skimage.io.imsave(out_path_image, outputImage)
# cv2.imwrite(out_path_image, outputImage)
hfinal, wfinal = outputImage.shape[:2]
if out_path_mask:
# add border to mask
im_tmp2 = skimage.io.imread(out_path_mask)
#im2 = cv2.imread(out_path_mask, 0)
outputImage2 = cv2.copyMakeBorder(
im_tmp2,
topBorderWidth,
bottomBorderWidth,
leftBorderWidth,
rightBorderWidth,
cv2.BORDER_CONSTANT,
value=0)
skimage.io.imsave(out_path_mask, outputImage2)
# cv2.imwrite(out_path_mask, outputImage2)
# make yolo labels
if out_path_label:
txt_outfile = open(out_path_label, "w")
# create yolo style labels
for class_tmp,box_tmp in zip(classes, boxes):
minx, miny, maxx, maxy = box_tmp
bb = utils.convert((wfinal, hfinal), [minx, maxx, miny, maxy])
# (xb,yb,wb,hb) = bb
if (np.min(bb) < 0) or (np.max(bb) > 1):
print(" yolo coords:", bb)
raise ValueError(" coords outside bounds, breaking!")
outstring = str(class_tmp) + " " + " ".join([str(a) for a in bb]) + '\n'
if verbose:
print(" outstring:", outstring.strip())
txt_outfile.write(outstring)
txt_outfile.close()
###############################################################################
def win_jitter(window_size, jitter_frac=0.1):
'''get x and y jitter'''
val = np.rint(jitter_frac * window_size)
dx = np.random.randint(-val, val)
dy = np.random.randint(-val, val)
return dx, dy
###############################################################################
def get_window_geoms(df, window_size=416, jitter_frac=0.2, image_w=0, image_h=0,
geometry_col='geometry_poly_pixel', category_col='Category',
aug_count_dict=None,
verbose=False):
'''Iterate through dataframe and get square window cutouts centered on each
object, modulu some jitter,
set category_col to None if none exists
aug_count_dict is a dictionary detailing the number of augmentations to make,
set to None to not augment'''
geom_windows, geom_windows_aug = [], []
len_df = len(df)
i = 0
for index, row in df.iterrows():
cat = row[category_col]
if verbose and category_col:
print ("\n", i+1, "/", len_df, "category:", cat)
# print ("\n", index, row['Category'])
# get coords
geom_pix = row[geometry_col]
if type(geom_pix) == str:
geom_pix = loads(geom_pix)
# print(" geom_pix:", geom_pix)
#pix_coords = list(geom_pix.coords)
bounds = geom_pix.bounds
area = geom_pix.area
(minx, miny, maxx, maxy) = bounds
dx, dy = maxx-minx, maxy-miny
if verbose:
print (" bounds:", bounds )
print (" dx, dy:", dx, dy )
print (" area:", area )
# get centroid
centroid = geom_pix.centroid
#print "centroid:", centroid
cx_tmp, cy_tmp = list(centroid.coords)[0]
cx, cy = np.rint(cx_tmp), np.rint(cy_tmp)
# get window coords, jitter, and shapely geometry for window
# do this multiple times if augmentations are desired
if aug_count_dict == None:
n_wins = 1
else:
n_wins = 1 + aug_count_dict[cat]
if verbose and category_col:
print(" n_wins:", n_wins)
for k in range(n_wins):
jx, jy = win_jitter(window_size, jitter_frac=jitter_frac)
x0 = cx - window_size/2 + jx
y0 = cy - window_size/2 + jy
# ensure window does not extend outside larger image
x0 = max(x0, 0)
x0 = int(min(x0, image_w - window_size))
y0 = max(y0, 0)
y0 = int(min(y0, image_h - window_size))
# set other side of square
x1 = x0 + window_size
y1 = y0 + window_size
win_p1 = shapely.geometry.Point(x0, y0)
win_p2 = shapely.geometry.Point(x1, y0)
win_p3 = shapely.geometry.Point(x1, y1)
win_p4 = shapely.geometry.Point(x0, y1)
pointList = [win_p1, win_p2, win_p3, win_p4, win_p1]
geom_window = shapely.geometry.Polygon([[p.x, p.y] for p in pointList])
if verbose:
print (" geom_window.bounds", geom_window.bounds )
# only append first to geom_window, others should be in windows_aug
if k == 0:
geom_windows.append(geom_window)
else:
geom_windows_aug.append(geom_window)
i += 1
return geom_windows, geom_windows_aug
###############################################################################
def tile_window_geoms(image_w, image_h, window_size=416, overlap_frac=0.2,
verbose=False):
'''Create tiled square window cutouts for given image size
Return a list of geometries for the windows
'''
sliceHeight = window_size
sliceWidth = window_size
dx = int((1. - overlap_frac) * sliceWidth)
dy = int((1. - overlap_frac) * sliceHeight)
n_ims = 0
geom_windows = []
for y0 in range(0, image_h, dy):#sliceHeight):
for x0 in range(0, image_w, dx):#sliceWidth):
n_ims += 1
# ensure window does not extend outside larger image
x0 = max(x0, 0)
x0 = max(0, int(min(x0, image_w - sliceWidth)))
y0 = max(y0, 0)
y0 = max(0, int(min(y0, image_h - sliceHeight)))
# set other side of square
x1 = x0 + sliceWidth
y1 = y0 + sliceHeight
win_p1 = shapely.geometry.Point(x0, y0)
win_p2 = shapely.geometry.Point(x1, y0)
win_p3 = shapely.geometry.Point(x1, y1)
win_p4 = shapely.geometry.Point(x0, y1)
pointList = [win_p1, win_p2, win_p3, win_p4, win_p1]
geom_window = shapely.geometry.Polygon([[p.x, p.y] for p in pointList])
if verbose:
print (" geom_window.bounds", geom_window.bounds )
# append
geom_windows.append(geom_window)
return geom_windows
###############################################################################
def get_objs_in_window(df_, geom_window, min_obj_frac=0.7,
geometry_col='geometry_poly_pixel', category_col='Category',
use_box_geom=True, verbose=False):
'''Find all objects in the window
if use_box_geom, turn the shapefile object geom into a bounding box
return: [index_nest, cat_nest, x0_obj, y0_obj, x1_obj, y1_obj]'''
(minx_win, miny_win, maxx_win, maxy_win) = geom_window.bounds
if verbose:
print ("geom_window.bounds:", geom_window.bounds)
obj_list = []
for index_nest, row_nest in df_.iterrows():
cat_nest = row_nest[category_col]
geom_pix_nest_tmp = row_nest[geometry_col]
if type(geom_pix_nest_tmp) == str:
geom_pix_nest_tmp = loads(geom_pix_nest_tmp)
# if use_box_geom, turn the shapefile object geom into a bounding box
if use_box_geom:
(x0, y0, x1, y1) = geom_pix_nest_tmp.bounds
geom_pix_nest = shapely.geometry.box(x0, y0, x1, y1, ccw=True)
else:
geom_pix_nest = geom_pix_nest_tmp
#pix_coords = list(geom_pix.coords)
#bounds_nest = geom_pix_nest.bounds
area_nest = geom_pix_nest.area
# skip zero or negative areas
if area_nest <= 0:
continue
# sometimes we get an invalid geometry, not sure why
try:
intersect_geom = geom_pix_nest.intersection(geom_window)
except:
# create a buffer around the exterior
geom_pix_nest = geom_pix_nest.buffer(0)
intersect_geom = geom_pix_nest.intersection(geom_window)
print ("Had to update geom_pix_nest:", geom_pix_nest.bounds )
intersect_bounds = intersect_geom.bounds
intersect_area = intersect_geom.area
intersect_frac = intersect_area / area_nest
# skip if object not in window, else add to window
if intersect_frac < min_obj_frac:
continue
else:
# get window coords
(minx_nest, miny_nest, maxx_nest, maxy_nest) = intersect_bounds
dx_nest, dy_nest = maxx_nest - minx_nest, maxy_nest - miny_nest
x0_obj, y0_obj = minx_nest - minx_win, miny_nest - miny_win
x1_obj, y1_obj = x0_obj + dx_nest, y0_obj + dy_nest
x0_obj, y0_obj, x1_obj, y1_obj = np.rint(x0_obj), np.rint(y0_obj),\
np.rint(x1_obj), np.rint(y1_obj)
obj_list.append([index_nest, cat_nest, x0_obj, y0_obj, x1_obj,
y1_obj])
if verbose:
print (" ", index_nest, "geom_obj.bounds:", geom_pix_nest.bounds )
print (" intesect area:", intersect_area )
print (" obj area:", area_nest )
print (" intersect_frac:", intersect_frac )
print (" intersect_bounds:", intersect_bounds )
print (" category:", cat_nest )
return obj_list
###############################################################################
def get_image_window(im, window_geom):
'''Get sub-window in image'''
bounds_int = [int(itmp) for itmp in window_geom.bounds]
(minx_win, miny_win, maxx_win, maxy_win) = bounds_int
window = im[miny_win:maxy_win, minx_win:maxx_win]
return window
###############################################################################
def plot_obj_list(window, obj_list, color_dic, thickness=2,
show_plot=False, outfile=''):
'''Plot the cutout, and the object bounds'''
print ("window.shape:", window.shape )
for row in obj_list:
[index_nest, cat_nest, x0_obj, y0_obj, x1_obj, y1_obj] = row
color = color_dic[cat_nest]
cv2.rectangle(window, (int(x0_obj), int(y0_obj)),
(int(x1_obj), int(y1_obj)),
(color), thickness)
if show_plot:
cv2.imshow(str(index_nest), window)
cv2.waitKey(0)
if outfile:
cv2.imwrite(outfile, window)
###############################################################################
def plot_training_bboxes(label_folder, image_folder, ignore_augment=True,
figsize=(10, 10), color=(0, 0, 255), thickness=2,
max_plots=100, sample_label_vis_dir=None, ext='.png',
show_plot=False, specific_labels=[],
label_dic=[], output_width=60000, shuffle=True,
verbose=False):
'''Plot bounding boxes for yolt
specific_labels allows user to pass in labels of interest'''
out_suff = '' # '_vis'
if sample_label_vis_dir and not os.path.exists(sample_label_vis_dir):
os.mkdir(sample_label_vis_dir)
# boats, boats_harbor, airplanes, airports (blue, green, red, orange)
# remember opencv uses bgr, not rgb
colors = 40*[(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 140, 255),
(0, 255, 125), (125, 125, 125), (140, 200, 0), (50, 200, 255),
(0, 102, 0), (255, 0, 127), (51, 0, 105), (153, 0, 0),
(0, 128, 250), (255, 255, 100), (127, 0, 255), (153, 76, 0)]
#colorsmap = plt.cm.gist_rainbow
#colors = [colormap(i) for i in np.linspace(0, 0.9, len(archs))]
if verbose:
print("colors:", colors)
try:
cv2.destroyAllWindows()
except:
pass
i = 0
if len(specific_labels) == 0:
label_list = os.listdir(label_folder)
# shuffle?
if shuffle:
random.shuffle(label_list)
else:
label_list = specific_labels
for label_file in label_list:
if ignore_augment:
if (label_file == '.DS_Store') or (label_file.endswith(('_lr.txt', '_ud.txt', '_lrud.txt'))):
continue
# else:
# if (label_file == '.DS_Store'):
# continue
if i >= max_plots:
# print "i, max_plots:", i, max_plots
return
else:
i += 1
if verbose:
print(i, "/", max_plots)
print(" label_file:", label_file)
# get image
# root = label_file.split('.')[0]
root = label_file[:-4]
im_loc = os.path.join(image_folder, root + ext)
label_loc = os.path.join(label_folder, label_file)
if verbose:
print(" root:", root)
print(" label loc:", label_loc)
print(" image loc:", im_loc)
image0 = cv2.imread(im_loc, 1)
height, width = image0.shape[:2]
# resize output file
if output_width < width:
height_mult = 1.*height / width
output_height = int(height_mult * output_width)
outshape = (output_width, output_height)
image = cv2.resize(image0, outshape)
else:
image = image0
height, width = image.shape[:2]
shape = (width, height)
if verbose:
print("im.shape:", image.shape)
# start plot (mpl)
#fig, ax = plt.subplots(figsize=figsize)
#img_mpl = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# ax.imshow(img_mpl)
# just opencv
img_mpl = image
# get and plot labels
# z = pd.read_csv(label_folder + label_file, sep = ' ', names=['cat', 'x', 'y', 'w', 'h'])
z = pd.read_csv(label_loc, sep=' ', names=['cat', 'x', 'y', 'w', 'h'])
# print "z", z.values
for yolt_box in z.values:
cat_int = int(yolt_box[0])
color = colors[cat_int]
yb = yolt_box[1:]
box0 = utils.convert_reverse(shape, yb)
# convert to int
box1 = [int(round(b, 2)) for b in box0]
[xmin, xmax, ymin, ymax] = box1
# plot
cv2.rectangle(img_mpl, (xmin, ymin),
(xmax, ymax), (color), thickness)
# add border
if label_dic:
# https://codeyarns.files.wordpress.com/2015/03/20150311_opencv_fonts.png
font = cv2.FONT_HERSHEY_TRIPLEX # FONT_HERSHEY_SIMPLEX #_SIMPLEX _TRIPLEX
font_size = 0.25
label_font_width = 1
#text_offset = [3, 10]
if len(label_dic.items()) <= 10:
ydiff = 35
else:
ydiff = 22
# add border
# http://docs.opencv.org/3.1.0/d3/df2/tutorial_py_basic_ops.html
# top, bottom, left, right - border width in number of pixels in corresponding directions
border = (0, 0, 0, 200)
border_color = (255, 255, 255)
label_font_width = 1
img_mpl = cv2.copyMakeBorder(img_mpl, border[0], border[1], border[2], border[3],
cv2.BORDER_CONSTANT, value=border_color)
# add legend
xpos = img_mpl.shape[1] - border[3] + 15
# for itmp, k in enumerate(sorted(label_dic.keys())):
# for itmp, (k, value) in enumerate(sorted(label_dic.items(), key=operator.itemgetter(1))):
for itmp, (k, value) in enumerate(sorted(label_dic.items(), key=lambda item: item[1])):
labelt = label_dic[k]
colort = colors[k]
#labelt, colort = label_dic[k]
text = '- ' + labelt # str(k) + ': ' + labelt
ypos = ydiff + (itmp) * ydiff
# cv2.putText(img_mpl, text, (int(xpos), int(ypos)), font, 1.5*font_size, colort, label_font_width, cv2.CV_AA)#, cv2.LINE_AA)
cv2.putText(img_mpl, text, (int(xpos), int(ypos)), font, 1.5 *
# font_size, colort, label_font_width, cv2.CV_AA) # cv2.LINE_AA)
font_size, colort, label_font_width, cv2.LINE_AA)
# legend box
cv2.rectangle(img_mpl, (xpos-5, 2*border[0]), (img_mpl.shape[1]-10, ypos+int(
0.75*ydiff)), (0, 0, 0), label_font_width)
# title
# title = figname.split('/')[-1].split('_')[0] + ': Plot Threshold = ' + str(plot_thresh) # + ': thresh=' + str(plot_thresh)
#title_pos = (border[0], int(border[0]*0.66))
# cv2.putText(img_mpl, title, title_pos, font, 1.7*font_size, (0,0,0), label_font_width, cv2.CV_AA)#, cv2.LINE_AA)
# cv2.putText(img_mpl, title, title_pos, font, 1.7*font_size, (0,0,0), label_font_width, cv2.CV_AA)#cv2.LINE_AA)
if show_plot:
cv2.imshow(root, img_mpl)
cv2.waitKey(0)
if sample_label_vis_dir:
fout = os.path.join(sample_label_vis_dir, root + out_suff + ext)
cv2.imwrite(fout, img_mpl)
return
###############################################################################
def augment_training_data(label_folder, image_folder,
label_folder_out='', image_folder_out='',
hsv_range=[0.5, 1.5],
skip_hsv_transform=True, ext='.jpg'):
'''
From yolt_data_prep_funcs.py
Rotate data to augment training sizeo
darknet c functions already to HSV transform, and left-right swap, so
skip those transforms
Image augmentation occurs in data.c load_data_detection()'''
if len(label_folder_out) == 0:
label_folder_out = label_folder
if len(image_folder_out) == 0:
image_folder_out = image_folder
hsv_diff = hsv_range[1] - hsv_range[0]
im_l_out = []
for label_file in os.listdir(label_folder):
# don't augment the already agumented data
if (label_file == '.DS_Store') or \
(label_file.endswith(('_lr.txt', '_ud.txt', '_lrud.txt', '_rot90.txt', '_rot180.txt', '_rot270.txt'))):
continue
# get image
print("image loc:", label_file)
root = label_file.split('.')[0]
im_loc = os.path.join(image_folder, root + ext)
#image = skimage.io.imread(f, as_grey=True)
image = cv2.imread(im_loc, 1)
# randoly scale in hsv space, create a list of images
if skip_hsv_transform:
img_hsv = image
else:
try:
img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
except:
continue
img_out_l = []
np.random.seed(42)
# three mirrorings
if skip_hsv_transform:
img_out_l = 6*[image]
else:
for i in range(6):
im_tmp = img_hsv.copy()
# alter values for each of 2 bands (hue and saturation)
# for j in range(2):
# rand = hsv_range[0] + hsv_diff*np.random.random() # between 0,5 and 1.5
# z0 = (im_tmp[:,:,j]*rand).astype(int)
# im_tmp[:,:,j] = z0
# alter values for each of 3 bands (hue and saturation, value
for j in range(3):
# set 'value' range somewhat smaller
if j == 2:
rand = 0.7 + 0.6*np.random.random()
else:
rand = hsv_range[0] + hsv_diff * \
np.random.random() # between 0,5 and 1.5
z0 = (im_tmp[:, :, j]*rand).astype(int)
z0[z0 > 255] = 255
im_tmp[:, :, j] = z0
# convert back to bgr and add to list of ims
img_out_l.append(cv2.cvtColor(im_tmp, cv2.COLOR_HSV2BGR))
# print "image.shape", image.shape
# reflect or flip image left to right (skip since yolo.c does this?)
image_lr = np.fliplr(img_out_l[0]) # (image)
image_ud = np.flipud(img_out_l[1]) # (image)
image_lrud = np.fliplr(np.flipud(img_out_l[2])) # (image_ud)
#cv2.imshow("in", image)
#cv2.imshow("lr", image_lr)
#cv2.imshow("ud", image_ud)
#cv2.imshow("udlr", image_udlr)
image_rot90 = np.rot90(img_out_l[3])
image_rot180 = np.rot90(np.rot90(img_out_l[4]))
image_rot270 = np.rot90(np.rot90(np.rot90(img_out_l[5])))
# flip coords of bounding boxes too...
# boxes have format: (x,y,w,h)
z = pd.read_csv(os.path.join(label_folder, label_file),
sep=' ', names=['x', 'y', 'w', 'h'])
# left right flip
lr_out = z.copy()
lr_out['x'] = 1. - z['x']
# left right flip
ud_out = z.copy()
ud_out['y'] = 1. - z['y']
# left right, up down, flip
lrud_out = z.copy()
lrud_out['x'] = 1. - z['x']
lrud_out['y'] = 1. - z['y']
##################
# rotate bounding boxes X degrees
origin = [0.5, 0.5]
point = [z['x'], z['y']]
# 90 degrees
angle = -1*np.pi/2
xn, yn = rotate(origin, point, angle)
rot_out90 = z.copy()
rot_out90['x'] = xn
rot_out90['y'] = yn
rot_out90['h'] = z['w']
rot_out90['w'] = z['h']
# 180 degrees (same as lrud)
angle = -1*np.pi
xn, yn = rotate(origin, point, angle)
rot_out180 = z.copy()
rot_out180['x'] = xn
rot_out180['y'] = yn
# 270 degrees
angle = -3*np.pi/2
xn, yn = rotate(origin, point, angle)
rot_out270 = z.copy()
rot_out270['x'] = xn
rot_out270['y'] = yn
rot_out270['h'] = z['w']
rot_out270['w'] = z['h']
##################
# print to files, add to list
im_l_out.append(im_loc)
# # reflect or flip image left to right (skip since yolo.c does this?)
# imout_lr = image_folder + root + '_lr.jpg'
# labout_lr = label_folder + root + '_lr.txt'
# cv2.imwrite(imout_lr, image_lr)
# lr_out.to_csv(labout_lr, sep=' ', header=False)
# #im_l_out.append(imout_lr)
# flip vertically or rotate 180 randomly
if bool(random.getrandbits(1)):
# flip vertically
imout_ud = os.path.join(image_folder_out, root + '_ud' + ext)
labout_ud = os.path.join(label_folder_out, root + '_ud.txt')
cv2.imwrite(imout_ud, image_ud)
ud_out.to_csv(labout_ud, sep=' ', header=False)
im_l_out.append(imout_ud)
else:
im180_path = os.path.join(image_folder_out, root + '_rot180' + ext)
cv2.imwrite(os.path.join(im180_path), image_rot180)
rot_out180.to_csv(os.path.join(label_folder_out,
root + '_rot180.txt'), sep=' ', header=False)
im_l_out.append(im180_path)
# # lrud flip, same as rot180
# # skip lrud flip because yolo does this sometimes
# imout_lrud = image_folder + root + '_lrud.jpg'
# labout_lrud = label_folder + root + '_lrud.txt'
# cv2.imwrite(imout_lrud, image_lrud)
# lrud_out.to_csv(labout_lrud, sep=' ', header=False)
# #im_l_out.append(imout_lrud)
# same as _lrud
#im180 = image_folder + root + '_rot180.jpg'
#cv2.imwrite(image_folder + root + '_rot180.jpg', image_rot180)
#rot_out180.to_csv(label_folder + root + '_rot180.txt', sep=' ', header=False)
# im_l_out.append(im180)
# rotate 90 degrees or 270 randomly
if bool(random.getrandbits(1)):
im90_path = os.path.join(image_folder_out, root + '_rot90' + ext)
#lab90 = label_folder + root + '_rot90.txt'
cv2.imwrite(im90_path, image_rot90)
rot_out90.to_csv(os.path.join(label_folder_out,
root + '_rot90.txt'), sep=' ', header=False)
im_l_out.append(im90_path)
else:
# rotate 270 degrees ()
im270_path = os.path.join(image_folder_out, root + '_rot270' + ext)
cv2.imwrite(im270_path, image_rot270)
rot_out270.to_csv(os.path.join(label_folder_out,
root + '_rot270.txt'), sep=' ', header=False)
im_l_out.append(im270_path)
return im_l_out
###############################################################################
def rm_augment_training_data(label_folder, image_folder, tmp_dir):
'''Remove previusly created augmented data since it's done in yolt.c and
need not be doubly augmented'''
# mv augmented labels
for label_file in os.listdir(label_folder):
if (label_file.endswith(('_lr.txt', '_ud.txt', '_lrud.txt', '_rot90.txt', '_rot180.txt', '_rot270.txt'))):
try:
os.mkdir(tmp_dir)
except:
print("")
# mv files to tmp_dir
print("label_file", label_file)
#shutil.move(label_file, tmp_dir)
# overwrite:
shutil.move(os.path.join(label_folder, label_file),
os.path.join(tmp_dir, label_file))
# just run images separately below to make sure we get errthing
# get image
# print "image loc:", label_file
#root = label_file.split('.')[0]
#im_loc = image_folder + root + '.jpg'
# mv files to tmp_dir
#shutil.move(im_loc, tmp_dir)
# mv augmented images
for image_file in os.listdir(image_folder):
if (image_file.endswith(('_lr.jpg', '_ud.jpg', '_lrud.jpg', '_rot90.jpg', '_rot180.jpg', '_rot270.jpg'))):
try:
os.mkdir(tmp_dir)
except:
print("")
# mv files to tmp_dir
#shutil.move(image_file, tmp_dir)
# overwrite
shutil.move(os.path.join(image_folder, image_file),
os.path.join(tmp_dir, image_file))
return
###############################################################################
def yolt_from_df(im_path, df_polys,
window_size=512,
jitter_frac=0.1,
min_obj_frac=0.7,