-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSeedlings.py
3447 lines (2412 loc) · 106 KB
/
Seedlings.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
# coding: utf-8
# # Plant Seedlings Classification
# #### Determine a seedling Species from an image
# # Tags
#
# `#Plant` `#Seedlings` `#Leaf` `#OpenCV2` `#Matplotlib` `#Seaborn` `#LabelEncoder` `#PCA` `#t-SNE` `#EigenVector` `#CNN` `#TransferLearning` `#Xception` `#VGG` `#Keras` `#Sklearn` `#ClassifierComparison` `#XGB`
# * `Author : Indiano`
# * `September 2018`
#
# ---
#
# ## Content
#
#
# 1. Introduction (5 min)
# * Objective
# * Description
# * Evaluation
# * Imports Libraries
# 2. Data Understanding (15 min)
# * Helper Functions
# * Load data
# * Basic Statistical summaries and visualisations
# 3. Data Preparation (25 min)
# * Sanitize Data
# * Categorize Class Labels
# * Advanced Statistical Summaries & Visualisations
# * PCA Visualization
# * t-SNE Visualization (2D & 3D)
# * Normalization
# 4. Modeling, Evaluation & Submission (25 min)
# * CNN
# * Transfer Learning using Xception, VGG, ImageNet
# * XGB using only countour features
# 5. Deployment (5 min)
# * Submit result to Kaggle leaderboard
# 6. Further Improvements
# * Some ideas for increasing the accuracy
#
# [Adopted from Cross Industry Standard Process for Data Mining (CRISP-DM)](http://www.sv-europe.com/crisp-dm-methodology/)
#
# ![CripsDM](https://i.pinimg.com/originals/d3/fe/6d/d3fe6d904580fa4e642225ae6d18f0da.jpg "Process diagram showing the relationship between the different phases of CRISP-DM")
# # 1. Introduction
# [Based on Kaggle Plant Seedlings Classification](https://www.kaggle.com/c/plant-seedlings-classification)
# ## 1.1 Objective
# Classify `an image` of `seedling` into one the following `12 different` seedling `classes`.
#
# 1. **Black-grass**
# 2. **Charlock**
# 3. **Cleavers**
# 4. **Common Chickweed**
# 5. **Common wheat**
# 6. **Fat Hen**
# 7. **Loose Silky-bent**
# 8. **Maize**
# 9. **Scentless Mayweed**
# 10. **Shepherds Purse**
# 11. **Small-flowered Cranesbill**
# 12. **Sugar beet**
# ## 1.2 Description
# Can you differentiate a `weed` from a crop `seedling`?
#
# The ability to do so effectively can mean `better crop yields` and `better stewardship of the environment`.
#
# The Aarhus University Signal Processing group, in collaboration with University of Southern Denmark, has recently released a dataset containing images of approximately 960 unique plants belonging to 12 species at several growth stages.
#
# We're hosting this dataset as a Kaggle competition in order to give it wider exposure, to give the community an opportunity to experiment with different image recognition techniques, as well to provide a place to cross-pollenate ideas.
# ### Citation
# [A Public Image Database for Benchmark of Plant Seedling Classification Algorithms](https://arxiv.org/abs/1711.05458v1)
# ## 1.3 Evaluation
# Submissions are evaluated on MeanFScore, which at Kaggle is actually a micro-averaged F1-score.
#
# Given positive/negative rates for each class k, the resulting score is computed this way:
#
#
# $Precisionmicro=∑k∈CTPk∑k∈CTPk+FPk$
#
# $Recallmicro=∑k∈CTPk∑k∈CTPk+FNk$
#
#
# F1-score is the harmonic mean of precision and recall
#
#
# $MeanFScore=F1micro= $\Frac{2PrecisionmicroRecallmicro}{Precisionmicro+Recallmicro}$
#
# ## 1.4 Imports
# In[119]:
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
# Theano MKL Problem
import os
os.environ["MKL_THREADING_LAYER"] = "GNU"
# Formatting
import pprint as pretty
from tabulate import tabulate
# Memory usage
import ipython_memory_usage.ipython_memory_usage as imu
# System related libraries
import os
import importlib
from joblib import Parallel, delayed
from sklearn.externals import joblib
from time import time
# Handle table-like data and matrices
import pickle
import numpy as np
import pandas as pd
# Collections
from itertools import product, compress
from functools import reduce
from operator import itemgetter
from collections import defaultdict
from glob import glob
# Image
import imageio
import cv2
# Sklearn
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler, LabelEncoder, MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn import decomposition
from sklearn.neighbors import KernelDensity
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from skimage.transform import resize as imresize
# Modelling Algorithms
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.linear_model import LogisticRegression, Ridge, Lasso, RandomizedLasso
from sklearn.svm import SVC, LinearSVC
from xgboost import XGBClassifier
# Modelling Helpers
from sklearn.model_selection import train_test_split, StratifiedKFold
# Keras
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input, Dense, Flatten, Activation, Dropout, Maximum, ZeroPadding2D
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import concatenate
from keras import regularizers
from keras.layers import BatchNormalization
from keras.optimizers import Adam, SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, TensorBoard
from keras.layers.advanced_activations import LeakyReLU
from keras.utils import to_categorical
from keras.applications import xception, vgg16
# Auto-ML
import autosklearn.classification
from tpot import TPOTClassifier
# Visualization
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from mpl_toolkits.axes_grid1 import ImageGrid
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
import seaborn as sns
from IPython.display import display, HTML
from tqdm import tqdm
# Configure visualisations
plt.style.use('ggplot')
sns.set_style('white')
# pylab.rcParams[ 'figure.figsize' ] = 8 , 6
get_ipython().run_line_magic('matplotlib', 'inline')
# Monitoring memory usage in jupyter notebooks; mprof run test.py & mprof plot
# %memit
get_ipython().run_line_magic('load_ext', 'memory_profiler')
# In[2]:
from subprocess import check_output
print(check_output(["ls", "./"]).decode("utf8"))
# In[3]:
get_ipython().run_line_magic('ls', 'data/all/train')
# In[4]:
get_ipython().run_line_magic('memit', '')
# In[5]:
# Same as label_to_id_dict
CLASS = {
'Black-grass': 0,
'Charlock': 1,
'Cleavers': 2,
'Common Chickweed': 3,
'Common wheat': 4,
'Fat Hen': 5,
'Loose Silky-bent': 6,
'Maize': 7,
'Scentless Mayweed': 8,
'Shepherds Purse': 9,
'Small-flowered Cranesbill': 10,
'Sugar beet': 11
}
# Same as id_to_label_dict
INV_CLASS = {
0: 'Black-grass',
1: 'Charlock',
2: 'Cleavers',
3: 'Common Chickweed',
4: 'Common wheat',
5: 'Fat Hen',
6: 'Loose Silky-bent',
7: 'Maize',
8: 'Scentless Mayweed',
9: 'Shepherds Purse',
10: 'Small-flowered Cranesbill',
11: 'Sugar beet'
}
# # 2. Data Understanding
# In[6]:
# Data directory
root_dir = './data/all'
train_dir = os.path.join(root_dir, 'train')
test_dir = os.path.join(root_dir, 'test')
# ## 2.1 Helper Functions
# ### 2.1.1 Mask, Segment & Sharpen Functions
# The `create_mask_for_plant` function returns an image `mask matrix` of image_height * image_width shape. The mask matrix contains only boolean values of 0 & 1 indicating seedlings background and foreground region.
#
# At the end, we will do `morphological close operation` to keep the original shape of the foreground (1 blob on the mask image) but `close the spurious small holes`.
#
# ![alt text](https://www.cs.auckland.ac.nz/courses/compsci773s1c/lectures/ImageProcessing-html/mor-pri-erosion.gif "Morphological Operations")
# In[12]:
# Segment Mask & Sharpen for the plant
def create_mask_for_plant(image):
# Convert to HSV image
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Create mask
sensitivity = 35
lower_hsv = np.array([60 - sensitivity, 100, 50])
upper_hsv = np.array([60 + sensitivity, 255, 255])
mask = cv2.inRange(image_hsv, lower_hsv, upper_hsv)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
return mask
def segment_plant(image):
mask = create_mask_for_plant(image)
output = cv2.bitwise_and(image, image, mask=mask)
return output
def sharpen_image(image):
image_blurred = cv2.GaussianBlur(image, (0, 0), 3)
image_sharp = cv2.addWeighted(image, 1.5, image_blurred, -0.5, 0)
return image_sharp
# Mask, Segment & Sharpen an Image
def mark_segment_sharpen_image(img, img_size=(45, 45)):
# Resize image
img = cv2.resize(img.copy(), img_size, interpolation=cv2.INTER_AREA)
image_mask = create_mask_for_plant(img)
image_segmented = segment_plant(img)
image_sharpened = sharpen_image(image_segmented)
return img, image_mask, image_segmented, image_sharpened
# ### 2.1.2 Contour Calculation Functions
# In[101]:
# Find contours and calculate the largest contour & total area
def find_contours(mask_image):
return cv2.findContours(mask_image, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
def calculate_largest_contour_area(contours):
if len(contours) == 0:
return 0
c = max(contours, key=cv2.contourArea)
return cv2.contourArea(c)
def calculate_contours_area(contours, min_contour_area=250):
area = 0
for c in contours:
c_area = cv2.contourArea(c)
if c_area >= min_contour_area:
area += c_area
return area
# ### 2.1.3 Visualize Images Functions
# In[7]:
# Plot the plant images on a grid according to each class label
def image_grid_plot_for_classes(labels=['Black-grass'], nb_cols=12):
fig = plt.figure(1, figsize=(nb_cols, nb_cols))
grid = ImageGrid(
fig, 111, nrows_ncols=(len(labels), nb_cols), axes_pad=0.05)
# Iterating over different class labels
for i, label in enumerate(labels):
for j in range(0, nb_cols):
axs = grid[i * nb_cols + j]
axs.imshow(cv2.resize(images_per_class[label][j], (150, 150)))
axs.axis('off')
# Class label text
axs.text(170, 75, label, verticalalignment='center')
plt.show()
# Plot the plant images on a grid according to each class label
def grid_plot_for_class(labels=['Black-grass'], nb_cols=12):
nb_rows, nb_cols = len(labels), nb_cols
fig, axs = plt.subplots(nb_rows, nb_cols, figsize=(12, 12))
# Iterating over different class labels
for i, label in enumerate(labels):
for j in range(0, nb_cols):
axs[i, j].imshow(
cv2.resize(images_per_class[label][j], (150, 150)),
aspect='auto')
axs[i, j].axis('off')
axs[i, j].text(170, 75, label, verticalalignment='center')
plt.show()
# Plot the plant images according to each class label
def plot_for_class(label, nb_rows=3, nb_cols=3):
fig, axs = plt.subplots(nb_rows, nb_cols, figsize=(12, 12))
n = 0
for i in range(0, nb_rows):
for j in range(0, nb_cols):
axs[i, j].xaxis.set_ticklabels([])
axs[i, j].yaxis.set_ticklabels([])
axs[i, j].imshow(images_per_class[label][n])
n += 1
# visualize_scatter_with_images
def visualize_scatter_with_images(X_2d_data,
images,
figsize=(45, 45),
image_zoom=1):
fig, ax = plt.subplots(figsize=figsize)
artists = []
for xy, i in zip(X_2d_data, images):
x0, y0 = xy
img = OffsetImage(i, zoom=image_zoom)
ab = AnnotationBbox(img, (x0, y0), xycoords='data', frameon=False)
artists.append(ax.add_artist(ab))
ax.update_datalim(X_2d_data)
ax.autoscale()
plt.show()
# visualize_scatter
def visualize_scatter(data_2d, label_ids, figsize=(20, 20)):
plt.figure(figsize=figsize)
plt.grid()
nb_classes = len(np.unique(label_ids))
for label_id in np.unique(label_ids):
plt.scatter(
data_2d[np.where(label_ids == label_id), 0],
data_2d[np.where(label_ids == label_id), 1],
marker='o',
color=plt.cm.Set1(label_id / float(nb_classes)),
linewidth='1',
alpha=0.8,
label=id_to_label_dict[label_id])
plt.legend(loc='best')
# visualize_scatter with 3D animation
def visualize_scatter_3D(data_3d, label_ids):
fig = plt.figure(figsize=(25, 25))
ax = fig.add_subplot(111, projection='3d')
plt.grid()
nb_classes = len(np.unique(label_ids))
for label_id in np.unique(label_ids):
ax.scatter(
data_3d[np.where(label_ids == label_id), 0],
data_3d[np.where(label_ids == label_id), 1],
data_3d[np.where(label_ids == label_id), 2],
alpha=0.8,
color=plt.cm.Set1(label_id / float(nb_classes)),
marker='o',
label=id_to_label_dict[label_id])
ax.legend(loc='best')
ax.view_init(25, 45)
ax.set_xlim(-2.5, 2.5)
ax.set_ylim(-2.5, 2.5)
ax.set_zlim(-2.5, 2.5)
# Create GIF
anima = animation.FuncAnimation(
fig,
lambda frame_number: ax.view_init(30, 4 * frame_number),
interval=175,
frames=90)
anima.save(
os.path.join('./visualization', 'seedlings_3D.gif'),
writer='imagemagick')
# ### 2.1.4 Plot the missclassified plant images on a grid & Confusion Matrix
# In[85]:
# Plot the missclassified plant images on a grid
def grid_plot_for_class(missclassified, nb_cols=3):
nb_rows = int(missclassified.shape[0] / nb_cols) + 1
fig = plt.figure(figsize=(15, 15))
# Iterating over different missclassified images
for index, (_, image) in enumerate(missclassified.iterrows()):
# Add a subplot. Either a 3-digit integer or three separate integers describing the position of the subplot.
# If the three integers are R, C, and P in order, the subplot will take the Pth position on
# a grid with R rows and C columns.
axs = fig.add_subplot(nb_rows, nb_cols, index + 1)
axs.text(
0, -15, INV_CLASS[image['Prediction']], horizontalalignment='left')
axs.imshow(cv2.resize(image['Image'], (150, 150)), aspect='auto')
axs.text(
75,
-15,
'True: {}'.format(INV_CLASS[image['True']]),
horizontalalignment='left')
axs.axis('off')
plt.show()
# Plot the confusion matrix
def plot_confusion_matrix(cm,
target_names,
plt_name,
rootdir='./',
save_dir='save/',
title='Confusion matrix',
cmap=None,
normalize=False):
"""
plot_confusion_matrix function prints & plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
:param cm:confusion matrix from sklearn.metrics.confusion_matrix
:param target_names:classification classes list eg. [0, 1] ['high', 'medium', 'low']
:param rootdir:str
:param save_dir:str
:param plt_name:str
:param title:str
:param cmap:color map list
:param normalize:bool
:return:
"""
plt_name += '_ConfusionMatrix'
if normalize:
plt_name = '{}_Normalized'.format(plt_name)
accuracy = np.trace(cm) / float(np.sum(cm))
misclass = 1 - accuracy
if cmap is None:
cmap = plt.get_cmap('Blues')
plt.figure(figsize=(12, 10))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
if target_names is not None:
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i, j in product(range(cm.shape[0]), range(cm.shape[1])):
if normalize:
plt.text(
j,
i,
"{:0.4f}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
else:
plt.text(
j,
i,
"{:,}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label\n\nAccuracy={:0.4f}; Misclassified={:0.4f}'.
format(accuracy, misclass))
print('\n\nSaving Confusion Matrices in the {} directory'.format(rootdir +
save_dir))
plt.savefig(
rootdir + save_dir + '/{}.png'.format(plt_name),
dpi=200,
format='png',
bbox_inches='tight')
plt.show()
plt.close()
# ## 2.2 Load Data
# Let's read the seedlings images in `BGR` (Blue/Green/Red) OpenCV's default format. It won't affect the segmentation in-case if you'd like to use `RGB` format. Anyhow, `HSV` (Hue/Saturation/Value) color space will be used for the processing of images.
# ### First Approach: Using Simple dictionary
# In[7]:
# Flatten the plant images data after Segmentation & Masking
def load_seedlings(train_dir=os.path.join(root_dir, 'train'),
init_img_size=(150, 150),
final_img_size=(45, 45)):
images = []
labels = []
images_per_class = defaultdict(list)
for class_folder_name in os.listdir(train_dir):
class_folder_path = os.path.join(train_dir, class_folder_name)
for image_path in glob(os.path.join(class_folder_path, "*.png")):
# Read an image
image = cv2.imread(image_path, cv2.IMREAD_COLOR)
# Stats for each seedlings class
images_per_class[class_folder_name].append(image)
# Resize image to default init_img_size pixels 150*150
image = cv2.resize(
image, init_img_size, interpolation=cv2.INTER_AREA)
# Segementation
image = segment_plant(image)
# BGR2GRAY conversion
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Resize image to default final_img_size pixels 45*45
if (init_img_size != final_img_size):
image = cv2.resize(
image, img_size, interpolation=cv2.INTER_AREA)
image = image.flatten()
images.append(image)
labels.append(class_folder_name)
images = np.array(images)
labels = np.array(labels)
return images, labels, images_per_class
# In[11]:
# Load Images, Labels & images_per_class dict
try:
print('Loading Images, Labels & images_per_class dict ...')
images = joblib.load(os.path.join('./save/pickles', 'images.pickle'))
labels = joblib.load(os.path.join('./save/pickles', 'labels.pickle'))
images_per_class = joblib.load(
os.path.join('./save/pickles', 'images_per_class.pickle'))
print('Loading done.')
except Exception as e:
print('Stacktrace', e)
print('Images, Labels or images_per_class dict does not exist.')
if not (images.size or labels.size) or (not images_per_class):
print('Running load_seedlings method ...')
images, labels, images_per_class = load_seedlings()
print('Dumping Images, Labels & images_per_class dict ...')
# Dumping dicts
joblib.dump(images, os.path.join('./save/pickles', 'images.pickle'))
joblib.dump(labels, os.path.join('./save/pickles', 'labels.pickle'))
joblib.dump(images_per_class,
os.path.join('./save/pickles', 'images_per_class.pickle'))
print('Images, Labels or images_per_class dict dumping done.')
# #### Number of images per class
# In[42]:
for key, value in images_per_class.items():
print("{0} -> {1}".format(key, len(value)))
# ### Second Approach: Using Train & Test dictionary
# In[5]:
# Resize all image to 51x51
def img_reshape(img):
img = imresize(img, (51, 51, 3))
return img
# get image tag
def img_label(path):
return str(str(path.split('/')[-1]))
# get plant class on image
def img_class(path):
return str(path.split('/')[-2])
# fill train and test dict
def fill_dict(paths, some_dict):
text = ''
if 'train' in paths[0]:
text = 'Start fill train_dict'
elif 'test' in paths[0]:
text = 'Start fill test_dict'
for p in tqdm(paths, ascii=True, ncols=85, desc=text):
img = imageio.imread(p)
img = img_reshape(img)
some_dict['image'].append(img)
some_dict['label'].append(img_label(p))
if 'train' in paths[0]:
some_dict['class'].append(img_class(p))
return some_dict
# read image from dir. and fill train and test dict
def reader():
file_ext = []
train_path = []
test_path = []
for root, dirs, files in os.walk('./data/all'):
if dirs != []:
print('Root:\n' + str(root))
print('Dirs:\n' + str(dirs))
else:
for f in files:
ext = os.path.splitext(str(f))[1][1:]
if ext not in file_ext:
file_ext.append(ext)
if 'train' in root:
path = os.path.join(root, f)
train_path.append(path)
elif 'test' in root:
path = os.path.join(root, f)
test_path.append(path)
train_dict = {'image': [], 'label': [], 'class': []}
test_dict = {'image': [], 'label': []}
train_dict = fill_dict(train_path, train_dict)
test_dict = fill_dict(test_path, test_dict)
return train_dict, test_dict
# ## 2.3 Basic Statistical Summaries & Visualisations¶
# To understand the data we are now going to consider some key facts about seedlings `class` and `count`.
# In[39]:
# Dataframe containing seedlings class and count
images_per_class_df = pd.DataFrame({
'Class': list(images_per_class.keys()),
'Count': [len(value) for value in images_per_class.values()]
})
images_per_class_df.head()
# In[38]:
# Plot seedlings by class and count
seaborn = sns.FacetGrid(images_per_class_df, size=5, aspect=2)
seaborn.map(sns.barplot, 'Class', 'Count', palette='deep')
seaborn.set_xticklabels(rotation=30)
seaborn.add_legend()
# Plot an `image grid` of `Small-flowered Cranesbill` plant seedlings
# In[34]:
plot_for_class("Small-flowered Cranesbill", nb_rows=10, nb_cols=10)
# Plot an `image grid` of `Maize` plant seedlings
# In[49]:
plot_for_class("Maize", nb_rows=10, nb_cols=10)
# Plot an `image grid` of `All` seedling
# In[137]:
image_grid_plot_for_classes(list(images_per_class.keys()), nb_cols=12)
# In[182]:
grid_plot_for_class(list(images_per_class.keys()), nb_cols=12)
# # 3. Data Preparation
#
# After statistics analysis & visualizing the different aspects of images, we will `sanitize` or clean the training data for our model.
# ## 3.1 Sanitize Data
# As we can see that each image has a background which makes contour of plant leaves obscure or unclear. Hence we will segregate background from foreground and hope it might help us achieve better accuracy.
#
# For removing the background, we'll use the fact that all plant leaves are green and we can create a mask to remove background.
# ### Masking, Segmenting & Sharpening Green
#
# For creating mask, which will remove background, we need to convert BGR/RGB image to HSV. HSV is alternative of the BGR/RGB color model. In HSV, it is easier to represent a color range than in BGR/RGB color space.
#
# Being a simple object detection problem, we will use the color of the object for background segregation. The HSV color-space is suitable for color detection because we can define a color with `Hue` and it's variations or spectrum using `Saturation` & `Value`. eg. Red, Darker Red, Lighter Red.
#
# The following figure illustrates the HSV color space.
#
# ![alt text](https://www.mathworks.com/help/images/hsvcone.gif "HSV to RGB Color Space")
#
# As hue varies from 0 to 1.0, the corresponding colors vary from red through yellow, green, cyan, blue, magenta, and back to red, so that there are actually red values both at 0 and 1.0. As saturation varies from 0 to 1.0, the corresponding colors (hues) vary from unsaturated (shades of gray) to fully saturated (no white component). As value, or brightness, varies from 0 to 1.0, the corresponding colors become increasingly brighter.
#
# [HSV to RGB Color Space](https://www.mathworks.com/help/images/convert-from-hsv-to-rgb-color-space.html)
# In[60]:
# Plot the plant images according to each class label
def plot_masked_image(images, nb_cols=4):
# Generate figure, axes
fig, axes = plt.subplots(
nrows=len(images), ncols=nb_cols, figsize=(12, 12))
# Iterating over different trials & parameters
for index, image in enumerate(images):
# Mask, Segment & Sharpen
image_mask = create_mask_for_plant(image)
image_segmented = segment_plant(image)
image_sharpen = sharpen_image(image_segmented)
# Show images
axes[index, 0].imshow(image)
axes[index, 1].imshow(image_mask)
axes[index, 2].imshow(image_segmented)
axes[index, 3].imshow(image_sharpen)
# Set x, y tick labels
axes[index, 0].xaxis.set_ticklabels([])
axes[index, 0].yaxis.set_ticklabels([])
axes[index, 1].xaxis.set_ticklabels([])
axes[index, 1].yaxis.set_ticklabels([])
axes[index, 2].xaxis.set_ticklabels([])
axes[index, 2].yaxis.set_ticklabels([])
axes[index, 3].xaxis.set_ticklabels([])
axes[index, 3].yaxis.set_ticklabels([])
plt.show()
# In[61]:
plot_masked_image(images_per_class["Small-flowered Cranesbill"][97:101])
# In[19]:
# Test image to see the changes
image = images_per_class["Small-flowered Cranesbill"][97]
image_mask = create_mask_for_plant(image)
image_segmented = segment_plant(image)
image_sharpened = sharpen_image(image_segmented)
# Segment Mask & Sharpen for the plant using mark_segment_sharpen_image method
# image, image_mask, image_segmented, image_sharpened = mark_segment_sharpen_image(image, img_size=(150, 150))
fig, axs = plt.subplots(1, 4, figsize=(20, 20))
axs[0].imshow(image)
axs[1].imshow(image_mask)
axs[2].imshow(image_segmented)
axs[3].imshow(image_sharpened)
# ## 3.2 Categorize Class Labels
# Let's create a dictionary and reverse dictionary containing mapping from label to id & vice-versa.
# ### First Approach: Using Simple dictionary with for loop
# In[124]:
# Create a mapping from a flower class to an unique integer id & vice-versa
label_to_id_dict = {v: i for i, v in enumerate(np.unique(labels))}
id_to_label_dict = {v: k for k, v in label_to_id_dict.items()}
# Covert train images label into id
label_ids = np.array([label_to_id_dict[x] for x in labels])
# ### Second Approach: Using LabelEncoder
# In[104]:
# Plot of label types numbers
pd.Series(labels).value_counts().plot(
kind='pie', title='Labels Distribution', figsize=(5, 5))
plt.show()
# Encode labels and create classes
le = LabelEncoder()
le.fit(labels)
labels_encoded = le.transform(labels)
print("\n\nClasses: ", le.classes_)
# Convert labels into categorical values
labels_onehot = to_categorical(labels_encoded)
print("\nNumber of One Hot encoded class labels: ", labels_onehot.shape[1])
# ## 3.3 Advanced Statistical Summaries & Visualisations¶
# ### 3.3.1 Contours Statistics
# From the mask image, we can extract some features like the contour area and number of components etc. and understand how the area of a plant changes according to each class.
#
# We can extract much more interesting information from `contours`. Please have a look below for further information.
#
# Additional read: https://en.wikipedia.org/wiki/Image_moment
# In[99]:
# Load images_per_class dictionary
images_per_class = joblib.load(
os.path.join('./save/pickles', 'images_per_class.pickle'))