/
PlantPypeline.py
1675 lines (1137 loc) · 47.9 KB
/
PlantPypeline.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/python
#
# Adapted from the tutorial found at
# http://plantcv.readthedocs.io/en/latest/vis_tutorial/
#
import os
import sys
import numpy as np
import fnmatch
import argparse
import plantcv as pcv
import exifread
import csv
import tkFileDialog as fd
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import LatLongUTMconversion
import imutils
import time
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import tkFileDialog as fd
import scipy.misc as sp
from multiprocessing import Pool
import random
def calculate_ndvi(r, g, b):
""" NDVI is the (NIR - Red) / (NIR + Red) """
nir = r
red = g
ndvi = (nir - red) / (nir + red)
return ndvi
def calculate_vari(r, g, b):
""" Visible Atmospherically Ressitant Index to measure 'how green' """
vari = (g - r) / (g + r - b)
return vari
def calculate_tgi(r, g, b):
""" Triangular Greenness Index to estimate leaf chlorophyll """
# the div g component is to normailze the green signal
tgi = (g - 0.39*r - 0.61*b) / g
#tgi = -0.5 * ((670. - 480.)*(r - g) - (670. - 550.)*(r - b))
return tgi
def calculate_ngrdi(r, g, b):
""" Normalized Green Red Difference Index. Also NGBDI or NDGI"""
ngrdi = (g - r) / (g + r)
return ngrdi
def calculate_gli(r, g, b):
""" Green Leaf Index """
gli = (2*g - r - b) / (2*g + r + b)
return gli
def check_ndvi(ndvi):
if ndvi >= 0. and ndvi <= 1.:
return True
return False
def rgb_filter(red, green, blue):
""" Run a STDev filter. """
red_mean = np.mean(red)
red_stdev = np.std(red)
green_mean = np.mean(green)
green_stdev = np.std(green)
blue_mean = np.mean(blue)
blue_stdev = np.std(blue)
red_min = red_mean - red_stdev
red_max = red_mean + red_stdev
green_min = green_mean - green_stdev
green_max = green_mean + green_stdev
blue_min = blue_mean - blue_stdev
blue_max = blue_mean + blue_stdev
red_trim = red[(red > red_min) & (red < red_max) &
(green > green_min) & (green < green_max) &
(blue > blue_min) & (blue < blue_max)]
green_trim = green[(red > red_min) & (red < red_max) &
(green > green_min) & (green < green_max) &
(blue > blue_min) & (blue < blue_max)]
blue_trim = blue[(red > red_min) & (red < red_max) &
(green > green_min) & (green < green_max) &
(blue > blue_min) & (blue < blue_max)]
return red_trim, green_trim, blue_trim
def read_exif(exif_files):
img_utm = {}
for exif in exif_files:
with open(exif, "rb") as ex:
reader = list(csv.reader(ex, delimiter=','))
# Take out header
reader.pop(0)
for row in reader:
#img_info[row[0]] = [float(row[3]), float(row[4])]
img_utm[row[0]] = [float(row[5]), float(row[6])]
return img_utm # img_path, lat, longi
def read_boxes(box_data):
with open(box_data, "rb") as bd:
reader = list(csv.reader(bd, delimiter=','))
reader.pop(0)
seed_box = {}
seed_id = []
for row in reader:
if row[4] not in seed_id and row[4] != "Br":
seed_id.append(row[4])
if row[3] not in seed_id and row[4] == "Br":
seed_id.append(row[3])
for i in range(len(seed_id)):
lat = []
longi = []
for row in reader:
if row[4] == seed_id[i] or row[3] == seed_id[i]:
coords = list(LatLongUTMconversion.LLtoUTM(23, float(row[0]), float(row[1])))[1:]
lat.append(float(coords[0]))
longi.append(float(coords[1]))
lat_max = round(max(lat), 6)
lat_min = round(min(lat), 6)
longi_max = round(max(longi), 6)
longi_min = round(min(longi), 6)
lat_avg = (lat_max + lat_min) / 2.
longi_avg = (longi_max + longi_min) / 2.
if len(seed_id[i]) > 8:
seed_id[i] = "Br_" + seed_id[i]
seed_box[seed_id[i]] = [lat_avg, longi_avg]
return seed_box, seed_id
def diff_calc(lat, longi, si_coords):
"""Calc the difference between the plot avg and the seed box avg"""
lat_diff = abs(lat - si_coords[0])
longi_diff = abs(longi - si_coords[1])
diff = (lat_diff**2 + longi_diff**2)**0.5
return diff
def diff_calc_utm_x(lat, longi, si_coords):
"""Calc the difference between the plot avg and the seed box avg"""
diff = abs(lat - si_coords[0])
return diff
def diff_calc_utm_y(longi, si_coords):
"""Calc the difference between the plot avg and the seed box avg"""
diff = abs(longi - si_coords[1])
return diff
def assign_plot(top_folder, groups_of_plot_paths, calcd_pir, calcd_dist):
img_id = []
for rang in range(len(groups_of_plot_paths)):
for plot in range(len(groups_of_plot_paths[rang])):
for img in range(len(groups_of_plot_paths[rang][plot])):
image = groups_of_plot_paths[rang][plot][img]
image_plot = calcd_pir[rang][plot]
diff = calcd_dist[rang][plot]
img_info = [image, image_plot, diff]
img_id.append(img_info)
assigned_plot = top_folder + "Plot_Match.csv"
with open(assigned_plot, "wb") as ap:
writer = csv.writer(ap, delimiter=",")
for assignment in img_id:
writer.writerow(assignment)
return img_id
def group_plots(img_path, dirt, image_ranges):
"""Group the plots together with dirt separating plots."""
groups_of_plot_paths = []
plot_path = []
range_paths = []
for r in range(len(image_ranges)):
for path in image_ranges[r]:
if path in dirt and len(plot_path) > 0:
range_paths.append(plot_path)
plot_path = []
elif path not in dirt:
plot_path.append(path)
if plot_path not in range_paths and len(plot_path) > 0:
range_paths.append(plot_path)
if range_paths not in groups_of_plot_paths and len(range_paths) > 0:
groups_of_plot_paths.append(range_paths)
range_paths = []
plot_path = []
return tuple(groups_of_plot_paths)
def group_plots_ra(img_path, dirt, image_ranges):
""" Group the plots together with dirt separating plots. """
groups_of_plot_paths = []
plot_path = []
for path in img_path:
if path in dirt and len(plot_path) > 0:
groups_of_plot_paths.append(plot_path)
plot_path = []
elif path not in dirt:
plot_path.append(path)
if plot_path not in groups_of_plot_paths and len(plot_path) > 0:
groups_of_plot_paths.append(plot_path)
return groups_of_plot_paths
def avg_plots(groups_of_plot_paths, img_info):
"""Avg the images within the plots"""
avgs = []
# extract a lat long from images and avg them over the plot
for rang in groups_of_plot_paths:
range_avgs = []
for plot in rang:
lats = []
longs = []
for image in plot:
coords = img_info[image]
lats.append(coords[0])
longs.append(coords[1])
avg_lat = sum(lats) / len(lats)
avg_long = sum(longs) / len(longs)
range_avgs.append([avg_lat, avg_long])
avgs.append(range_avgs)
print avgs, len(avgs)
return tuple(avgs)
# Mike's tidbit
def get_exif_data(image):
"""Returns a dictionary from the exif data of an PIL Image item.
Also converts the GPS Tags
"""
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = GPSTAGS.get(t, t)
gps_data[sub_decoded] = value[t]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data
# Mike's tidbit
def _get_if_exist(data, key):
if key in data:
return data[key]
return None
# Mike's tidbit
def _convert_to_degress(value):
"""Helper function to convert the GPS coordinates
stored in the EXIF to degress in float format
"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value[2][1]
s = float(s0) / float(s1)
return d + (m / 60.0) + (s / 3600.0)
# Mike's tidbit. It will take the Lat/Long
# information from the images and convert it
# to UTM Lat/Long which is used in QGIS or any mapping program.
# It calls the LatLongUTMconversion package which
# was borrowed from Dr. Kelly Thorp.
def get_lat_lon(exif_data):
"""Returns the latitude and longitude
if available, from the provided exif_data (obtained
through get_exif_data above)"""
lat = None
lon = None
if "GPSInfo" in exif_data:
gps_info = exif_data["GPSInfo"]
gps_latitude = _get_if_exist(gps_info, "GPSLatitude")
gps_latitude_ref = _get_if_exist(gps_info, 'GPSLatitudeRef')
gps_longitude = _get_if_exist(gps_info, 'GPSLongitude')
gps_longitude_ref = _get_if_exist(gps_info, 'GPSLongitudeRef')
if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
lat = _convert_to_degress(gps_latitude)
if gps_latitude_ref != "N":
lat = 0 - lat
lon = _convert_to_degress(gps_longitude)
if gps_longitude_ref != "E":
lon = 0 - lon
# Added to compensate for any false GPS data from the image.
# Some images (Canon specifically) were causing
# errors becuase the program incorrectly identified them as
# having GPS information. This was causing the
# program to abort when LatLongUTMconversion would be called with
# lat/lon variables that didn't have numbers.
# This required the if statement below to see if the lat/lon
# variables were still set to their initialized values.
if lat == None or lon == None:
UTMrec = [0,0,0]
else:
UTMrec = LatLongUTMconversion.LLtoUTM(23, float(lat), float(lon))
# return lat, lon
return UTMrec
# Added to Will's code to ask for the file path to the top level image folder.
# The folder dialog box appears
# when the program first starts and sets the top folder for the application
# to start walking through.
def AskForFilepath():
# User selects a folder containing all the raw data files
print "Select a folder containing all sensor files-"
filepath = fd.askdirectory()
return filepath
def convert(coord):
""" Convert the instance to actual floats. Returns coords as a list"""
# Covert instance to string then split it up
coord = str(coord)
coord_strip = coord.strip("[]")
coord_split = coord_strip.split(", ")
decimal = coord_split[2].split("/")
if len(decimal) == 2:
decimal = float(decimal[0]) / float(decimal[1])
else:
decimal = float(decimal[0])
coord = [float(coord_split[0]), float(coord_split[1]), decimal]
return coord
def exif_execution(top_folder):
match_list = []
match_folder = []
# find all matches in the sub dirs
for root, dirnames, filenames in os.walk(top_folder):
for filename in fnmatch.filter(filenames, 'IMG_*.jpg'):
match_list.append(os.path.join(root, filename))
if root not in match_folder:
match_folder.append(root)
exif_files = []
# Loop through available folders,
# then create a csv containing metadata (the gps coords)
# of the images within that folder
for path in match_folder:
exif_file = path + "\Exif_data.csv"
print "Working in " + path
exif_files.append(exif_file)
files_in_folder = []
# looks for files only in path
for i in match_list:
if (path in i) and (i not in files_in_folder):
files_in_folder.append(i)
# open new file in each dir
with open(exif_file, "wb") as ef:
writer = csv.writer(ef, delimiter=',')
header = ["Image_Path",
"Dimensions",
"Size",
"Latitude",
"Longitude",
"UTM_X",
"UTM_Y",
"Make",
"Model",
"Date Time Original",
"ISO Speed",
"Exposure Bias",
"Aperture Value",
"Metering Mode",
"Focal Length",
"FStop",
"Exposure Time"]
writer.writerow(header)
# extract GPS from each image
for file_ in files_in_folder:
# enters the exif data of all jpgs into the database
im = Image.open(file_)
# Place all the exif data into the exif_data variable
exif_data = get_exif_data(im)
# Need to convert the lat long that the GPS reciever gives
# us into something more meaningful to
# our GIS programs like ArcGIS and QGIS
# Call get_lat_lon procedure to do the UTM conversions for us
try:
UTMrec = get_lat_lon(exif_data)
except UnboundLocalError:
continue
# Getting physical data from the operating system ##
# How much hard drive space does this file consume.
physical_size = os.path.getsize(file_)
# Dividing the physical size by 1000 to display in Kilobytes
display_phy_size = long(physical_size / 1000)
# Adding the KB at the end so there is no doubt
# what the number represents
physical_size = str(display_phy_size) + "KB"
# This was already done during the conversion but needed to
# get the Latitude and Longitude again
# since the variables are local to the conversion Def above.
# Lazy programming, didn't have much
# time to complete this portion. This may be cleaned up later.
# The if statement had to be changed in this portion of the
# code because files that did not have
# GPS info were registering as though they did.
# This created an issue where no values were present
# for the lat/long which was causing the file writing process
# to raise an error. The code in the
# UTM conversion routine was also changed bacause images
# without GPS information were trying to pass
# values to the UTM conversion routine which was causing
# the program to abort also.
if UTMrec[1] != 0 or UTMrec[2] != 0:
gps_info = exif_data["GPSInfo"]
gps_latitude = _get_if_exist(gps_info, "GPSLatitude")
gps_latitude_ref = _get_if_exist(gps_info, 'GPSLatitudeRef')
gps_longitude = _get_if_exist(gps_info, 'GPSLongitude')
gps_longitude_ref = _get_if_exist(gps_info, 'GPSLongitudeRef')
if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
lat = _convert_to_degress(gps_latitude)
if gps_latitude_ref != "N":
lat = 0 - lat
lon = _convert_to_degress(gps_longitude)
if gps_longitude_ref != "E":
lon = 0 - lon
else:
lat = 0
lon = 0
line = im.filename, \
im.size, \
physical_size, \
lat, \
lon, \
str(UTMrec[1]), \
str(UTMrec[2]), \
exif_data["Make"], \
exif_data["Model"], \
exif_data["DateTimeOriginal"], \
exif_data["ISOSpeedRatings"], \
exif_data["ExposureBiasValue"], \
exif_data["ApertureValue"], \
exif_data["MeteringMode"], \
exif_data["FocalLength"], \
exif_data["FNumber"], \
exif_data["ExposureTime"]
print im.filename, \
lat, \
lon, \
str(UTMrec[1]), \
str(UTMrec[2])
writer.writerow(line)
print "Exif data extraction successful! "
return exif_files
# Run PlantCV to find object in image
def find_object(image, rand_int):
head, tail = os.path.split(image)
print "Finding object in image " + tail + "..."
# Read image
img, path, filename = pcv.readimage(image)
# Pipeline step
device = rand_int
debug = "print" # or "plot"
# Convert RGB to HSV and extract the Saturation channel
# hue, saturation, value
device, h = pcv.rgb2gray_hsv(img, 'h', device)
# Threshold the Saturation image
device, h_thresh = pcv.binary_threshold(h, 30, 255, 'light', device)
device, h_mblur = pcv.median_blur(h_thresh, 5, device)
device, h_cnt = pcv.median_blur(h_thresh, 5, device)
# Fill small objects
device, ab_fill = pcv.fill(h_mblur, h_mblur, 200, device)
# Apply Mask (for vis images, mask_color=white)
device, masked = pcv.apply_mask(img, h_mblur, 'white', device)
# Identify objects
device, id_objects,obj_hierarchy = pcv.find_objects(masked, h_mblur, device)
# Define ROI
device, roi1, roi_hierarchy = pcv.define_roi(masked, 'rectangle', device, None, 'default', False, 0, 0, 0, 0)
# Decide which objects to keep
device, roi_objects, hierarchy3, kept_mask, obj_area = pcv.roi_objects(img, 'partial', roi1, roi_hierarchy, id_objects, obj_hierarchy, device, debug)
return
def delete_masks(rint):
""" Delete the created masks of the image """
os.remove(rint + "_obj_on_img.png")
os.remove(rint + "_roi_mask.png")
os.remove(rint + "_roi_objects.png")
return
def find_images(top_folder):
""" Find the images with matches and return their path with plot id"""
match_list = []
all_plots = []
all_images = []
for root, dirnames, filenames in os.walk(top_folder):
for filename in fnmatch.filter(filenames, 'Plot_Match.csv'):
match_list.append(os.path.join(root, filename))
for f in match_list:
with open(f, "rb") as pm:
reader = list(csv.reader(pm, delimiter=","))
for r in range(len(reader)):
all_images.append(reader[r][0])
all_plots.append(reader[r][1])
return all_images, all_plots
def cull(vari, tgi, ngrdi, gli):
"""Find indices where values are not real. then remove them"""
vari_mask = []
tgi_mask = []
ngrdi_mask = []
gli_mask = []
for i in range(len(vari)):
if vari[i] < 0.:
vari_mask.append(i)
if tgi[i] < 0.:
tgi_mask.append(i)
if ngrdi[i] < 0.:
ngrdi_mask.append(i)
if gli[i] < 0.:
gli_mask.append(i)
vari_cull = np.delete(vari, vari_mask)
tgi_cull = np.delete(tgi, tgi_mask)
ngrdi_cull = np.delete(ngrdi, ngrdi_mask)
gli_cull = np.delete(gli, gli_mask)
return vari_cull, tgi_cull, ngrdi_cull, gli_cull
def rgb_counter(top_folder, image, plot_id, rint):
"""Find the pixel with plants and extract the band values
This is where the core data extraction happens. The plant image and the
masked plant image are compared, then wherever the mask shows there to
be a plant, that pixel is harvested. The other pixels are not included.
Then the VI are calculated but in the values of sums and counts of pixels
"""
mask = r"C:\Users\William.Yingling\Scripts\\" + rint + "_obj_on_img.png"
# Read image bands. then smoosh it to a 1D array
image_data = sp.imread(image).astype(np.float64)
image_slice_red = image_data[:, :, 0].flatten()
image_slice_green = image_data[:, :, 1].flatten()
image_slice_blue = image_data[:, :, 2].flatten()
# Read mask image and take green band from it.
# Where the mask is max val 255 means thats the plant object
mask_data = sp.imread(mask).astype(np.int)
mask_slice_green = mask_data[:, :, 1].flatten()
# If mask is not max val, then pixel represents not plant matter
# so give it a fake negative val so we can delete it in the next step
image_slice_red[mask_slice_green != 255] = -1
image_slice_green[mask_slice_green != 255] = -1
image_slice_blue[mask_slice_green != 255] = -1
# Find the indices where the negative value is
del_indices = np.argwhere(image_slice_green == -1)
# Create arrays where only plant matter is included
red_arr = np.delete(image_slice_red, del_indices)
green_arr = np.delete(image_slice_green, del_indices)
blue_arr = np.delete(image_slice_blue, del_indices)
# Filter the arrays to make sure they are within 1 std of themselves
try:
red, green, blue = rgb_filter(red_arr, green_arr, blue_arr)
except IndexError:
print "No masked Pixels!"
return
# Calculate Vegetation indices
vari_raw = calculate_vari(red, green, blue)
tgi_raw = calculate_tgi(red, green, blue)
ngrdi_raw = calculate_ngrdi(red, green, blue)
gli_raw = calculate_gli(red, green, blue)
# If VI are a negative number, remove
vari, tgi, ngrdi, gli = cull(vari_raw, tgi_raw, ngrdi_raw, gli_raw)
# sum the VIs
vari_sum = np.nansum(vari)
tgi_sum = np.nansum(tgi)
ngrdi_sum = np.nansum(ngrdi)
gli_sum = np.nansum(gli)
ndvi_file = top_folder + "\VI_Data.csv"
# Write vals to file
# Writes sum of the VIs and the number of vals. Avgs will be calcd later
with open(ndvi_file, "ab") as nf:
writer = csv.writer(nf, delimiter=',')
writer.writerow([image, plot_id,
vari_sum, len(vari),
tgi_sum, len(tgi),
ngrdi_sum, len(ngrdi),
gli_sum, len(gli)])
return
def filter_images(top_folder, image, rint, green_tolerance):
#print "Looking for dirt..."
mask = r"C:\Users\William.Yingling\Scripts\\" + rint + "_obj_on_img.png"
image_data = sp.imread(image).astype(np.float64)
image_slice_red = image_data[:, :, 0].flatten()
image_slice_green = image_data[:, :, 1].flatten()
image_slice_blue = image_data[:, :, 2].flatten()
mask_data = sp.imread(mask).astype(np.int)
#mask_slice_red = mask_data[:, :, 0].flatten()
mask_slice_green = mask_data[:, :, 1].flatten()
#mask_slice_blue = mask_data[:, :, 2].flatten()
gt_data = sp.imread(mask).astype(np.float64)
gt_slice = gt_data[:, :, 1]
band_size = float(gt_slice.size)
green_count = float(np.count_nonzero(gt_slice == 255))
ratio_green_pix = float(green_count) / float(band_size)
image_slice_red[mask_slice_green != 255] = -1
image_slice_green[mask_slice_green != 255] = -1
image_slice_blue[mask_slice_green != 255] = -1
del_indices = np.argwhere(image_slice_green == -1)
red_arr = np.delete(image_slice_red, del_indices)
green_arr = np.delete(image_slice_green, del_indices)
blue_arr = np.delete(image_slice_blue, del_indices)
# Pixel Check. Find the most average pixels of the group
try:
red, green, blue = rgb_filter(red_arr, green_arr, blue_arr)
except IndexError:
print "No masked Pixels!"
return
vari_raw = calculate_vari(red, green, blue)
tgi_raw = calculate_tgi(red, green, blue)
ngrdi_raw = calculate_ngrdi(red, green, blue)
gli_raw = calculate_gli(red, green, blue)
vari, tgi, ngrdi, gli = cull(vari_raw, tgi_raw, ngrdi_raw, gli_raw)
vari_sum = np.nansum(vari)
tgi_sum = np.nansum(tgi)
ngrdi_sum = np.nansum(ngrdi)
gli_sum = np.nansum(gli)
ndvi_file = top_folder + "\GreenTolerance.csv"
with open(ndvi_file, "ab") as nf:
writer = csv.writer(nf, delimiter=',')
writer.writerow([image, ratio_green_pix,
vari_sum, len(vari),
tgi_sum, len(tgi),
ngrdi_sum, len(ngrdi),
gli_sum, len(gli)])
# We found dirt
if ratio_green_pix < green_tolerance:
return None
return image
def create_vi_file(top_folder, file_name, image_list, plot_list, gt_file, dirt):
vi_file = top_folder + file_name
with open(gt_file, "rb") as gt:
reader = list(csv.reader(gt, delimiter=","))
vi_rows = []
for r, row in enumerate(reader):
if row[0] in dirt:
continue
for i, il in enumerate(image_list):
if il == row[0]:
# switch the green index for plot assignment
row[1] = plot_list[i]
vi_rows.append(row)
with open(vi_file, "wb") as nf:
writer = csv.writer(nf, delimiter=',')
header = ["Image_Path", "Plot",
"VARI", "VARI_Count",
"TGI", "TGI_Count",
"NDGRDI", "NGRDI_Count",
"GLI", "GLI_Count"]
writer.writerow(header)
for vir in vi_rows:
writer.writerow(vir)
return
def create_gt_file(vi_file):
with open(vi_file, "wb") as nf:
writer = csv.writer(nf, delimiter=',')
return
# Added to Will's code to ask for the file path to the top level image folder.
# The folder dialog box appears
# when the program first starts and sets the top folder for the application to
# start walking through.
def ask_for_top_folder():
# User selects a folder containing all the raw data files
print "Select a folder containing all sensor files-"
filepath = fd.askdirectory()
return filepath
def ask_for_box_data():
# User selects a folder containing all the raw data files
print "Select a folder containing all sensor files-"
filepath = fd.askopenfile()
return filepath
def read_csv(file_path):
""" Read the CSV File """
with open(file_path, "rb") as fp:
reader = list(csv.reader(fp, delimiter=","))
reader.pop(0)
return reader
def condense(contents, seed_ids):
""" Take the contents and then avg the plots' values """
condensed_file = []
for plot in seed_ids:
tot_vals = []
for row in contents:
# Hard Fault Error Catch
if len(row) != 10:
continue
if row[1] == plot:
tot_vals.append(row)
if len(tot_vals) == 0:
calcd_vals = [np.nan, np.nan, np.nan, np.nan]
else:
calcd_vals = avg_vals(tot_vals)
calcd_row = [plot] + calcd_vals
condensed_file.append(calcd_row)
return condensed_file
def make_csv(file_path, condensed):
""" Put the info into a csv """
with open(file_path, "wb") as f:
writer = csv.writer(f, delimiter=",")
header = ["Plot", "VARI", "TGI", "NDGRI", "GLI"]
writer.writerow(header)
for row in condensed:
writer.writerow(row)
return
def avg_vals(tot_vals):
""" Average the the values in the plot """
vals_t = np.array(tot_vals)
vals_transposed = np.transpose(vals_t)
vals = np.array(vals_transposed[2:]).astype(np.float64)
# if there are bad vals then give a value of nan
vals[0][vals[0] == np.inf] = np.nan
vals[1][vals[0] == np.inf] = np.nan
vals[2][vals[2] == np.inf] = np.nan
vals[3][vals[2] == np.inf] = np.nan
vals[4][vals[4] == np.inf] = np.nan
vals[5][vals[4] == np.inf] = np.nan
vals[6][vals[6] == np.inf] = np.nan
vals[7][vals[6] == np.inf] = np.nan
vari = np.nansum(vals[0])
v_counts = np.nansum(vals[1])
tgi = np.nansum(vals[2])
t_counts = np.nansum(vals[3])
ndgri = np.nansum(vals[4])
n_counts = np.nansum(vals[5])
gli = np.nansum(vals[6])
g_counts = np.nansum(vals[7])