Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

plant_model.py 7.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. # LIBRARIES
  2. import numpy as np
  3. import pandas as pd
  4. import matplotlib.pyplot as plt
  5. import math
  6. import cv2
  7. from glob import glob
  8. import itertools
  9. import os
  10. import tensorflow as tf
  11. # KERAS AND SKLEARN MODULES
  12. from keras.utils import np_utils
  13. from keras.preprocessing.image import ImageDataGenerator
  14. from keras.models import Sequential
  15. from keras.layers import Dense
  16. from keras.layers import Dropout
  17. from keras.layers import Flatten
  18. from keras.layers.convolutional import Conv2D
  19. from keras.layers.convolutional import MaxPooling2D
  20. from keras.layers import BatchNormalization
  21. from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, CSVLogger
  22. from sklearn import preprocessing
  23. from sklearn.model_selection import train_test_split
  24. from sklearn.metrics import confusion_matrix
  25. # GLOBAL VARIABLES
  26. scale = 70
  27. seed = 7
  28. class plantRecognition:
  29. def __init__(self):
  30. print("Recognise Image")
  31. self.path_to_images = '{}\*\*.jpg'.format(os.path.join(os.getcwd(), 'recognition\train'))
  32. self.images = glob(self.path_to_images)
  33. self.trainingset = []
  34. self.traininglabels = []
  35. self.new_train = []
  36. self.sets = []
  37. self.num = len(self.images)
  38. self.x_train = []
  39. self.x_test = []
  40. self.y_train = []
  41. self.y_test = []
  42. self.model = Sequential()
  43. def preprocessImages(self):
  44. count = 1
  45. # READING IMAGES AND RESIZING THEM
  46. for i in self.images:
  47. self.traininglabels.append(i.split('\\')[-2])
  48. count = count + 1
  49. self.traininglabels = pd.DataFrame(self.traininglabels)
  50. getEx = True
  51. for i in self.trainingset:
  52. blurr = cv2.GaussianBlur(i, (5, 5), 0)
  53. hsv = cv2.cvtColor(blurr, cv2.COLOR_BGR2HSV)
  54. # GREEN PARAMETERS
  55. lower = (25, 40, 50)
  56. upper = (75, 255, 255)
  57. mask = cv2.inRange(hsv, lower, upper)
  58. struc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
  59. mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, struc)
  60. boolean = mask > 0
  61. new = np.zeros_like(i, np.uint8)
  62. new[boolean] = i[boolean]
  63. self.new_train.append(new)
  64. # if getEx:
  65. # plt.subplot(2,3,1);plt.imshow(i) # ORIGINAL
  66. # plt.subplot(2,3,2);plt.imshow(blurr) # BLURRED
  67. # plt.subplot(2,3,3);plt.imshow(hsv) # HSV CONVERTED
  68. # plt.subplot(2,3,4);plt.imshow(mask) # MASKED
  69. # plt.subplot(2,3,5);plt.imshow(boolean) # BOOLEAN MASKED
  70. # plt.subplot(2,3,6);plt.imshow(new) # NEW PROCESSED IMAGE
  71. # plt.show()
  72. # getEx = False
  73. self.new_train = np.asarray(self.new_train)
  74. # for i in range(8):
  75. # plt.subplot(2,4,i+1)
  76. # plt.imshow(self.new_train[i])
  77. self.labels = preprocessing.LabelEncoder()
  78. self.labels.fit(self.traininglabels[0])
  79. self.encodedlabels = self.labels.transform(self.traininglabels[0])
  80. clearalllabels = np_utils.to_categorical(self.encodedlabels)
  81. self.classes = clearalllabels.shape[1]
  82. print('Classes' + str(self.labels.classes_))
  83. self.new_train = self.new_train / 255
  84. self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(self.new_train, clearalllabels,
  85. test_size=0.1, random_state=seed,
  86. stratify=clearalllabels)
  87. def createModel(self):
  88. generator = ImageDataGenerator(rotation_range=180, zoom_range=0.1, width_shift_range=0.1,
  89. height_shift_range=0.1, horizontal_flip=True, vertical_flip=True)
  90. generator.fit(self.x_train)
  91. np.random.seed(seed)
  92. self.model.add(Conv2D(filters=64, kernel_size=(5, 5), input_shape=(scale, scale, 3), activation='relu'))
  93. self.model.add(BatchNormalization(axis=3))
  94. self.model.add(Conv2D(filters=64, kernel_size=(5, 5), activation='relu'))
  95. self.model.add(MaxPooling2D((2, 2)))
  96. self.model.add(BatchNormalization(axis=3))
  97. self.model.add(Dropout(0.1))
  98. self.model.add(Conv2D(filters=128, kernel_size=(5, 5), activation='relu'))
  99. self.model.add(BatchNormalization(axis=3))
  100. self.model.add(Conv2D(filters=128, kernel_size=(5, 5), activation='relu'))
  101. self.model.add(MaxPooling2D((2, 2)))
  102. self.model.add(BatchNormalization(axis=3))
  103. self.model.add(Dropout(0.1))
  104. self.model.add(Conv2D(filters=256, kernel_size=(5, 5), activation='relu'))
  105. self.model.add(BatchNormalization(axis=3))
  106. self.model.add(Conv2D(filters=256, kernel_size=(5, 5), activation='relu'))
  107. self.model.add(MaxPooling2D((2, 2)))
  108. self.model.add(BatchNormalization(axis=3))
  109. self.model.add(Dropout(0.1))
  110. self.model.add(Flatten())
  111. self.model.add(Dense(256, activation='relu'))
  112. self.model.add(BatchNormalization())
  113. self.model.add(Dropout(0.5))
  114. self.model.add(Dense(256, activation='relu'))
  115. self.model.add(BatchNormalization())
  116. self.model.add(Dropout(0.5))
  117. self.model.add(Dense(self.classes, activation='softmax'))
  118. self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
  119. self.model.summary()
  120. def trainMdel(self):
  121. self.preprocessImages()
  122. self.createModel()
  123. print(self.x_test[0].shape)
  124. plt.imshow(self.x_test[10])
  125. history = self.model.fit(self.x_train, self.y_train, epochs=100)
  126. plt.plot(history.history['loss'])
  127. plt.xlabel('Epochs')
  128. plt.ylabel('Loss')
  129. plt.show()
  130. pred_labels = self.model.predict(self.x_test)
  131. print(pred_labels.shape)
  132. acc = self.model.evaluate(self.x_test, self.y_test)
  133. print("Testing accuracy : {}".format(acc[-1] * 100))
  134. self.saveModel()
  135. def saveModel(self):
  136. keras_file = "keras_model.h5"
  137. self.model.save(keras_file)
  138. # Convert to TensorFlow Lite model.
  139. converter = tf.lite.TFLiteConverter.from_keras_model_file(keras_file)
  140. tflite_model = converter.convert()
  141. open("converted_model.tflite", "wb").write(tflite_model)
  142. def predict(self, img_path):
  143. traininglabels = ['Akkapana', 'Cinnamon', 'Kohombo', 'Tumeric', 'TumericRoot']
  144. img = cv2.imread(img_path)
  145. img = cv2.resize(img, (70, 70))
  146. inputset = []
  147. inputset.append(img)
  148. new_img = []
  149. for i in inputset:
  150. blurr = cv2.GaussianBlur(i, (5, 5), 0)
  151. hsv = cv2.cvtColor(blurr, cv2.COLOR_BGR2HSV)
  152. lower = (25, 40, 50)
  153. upper = (75, 255, 255)
  154. mask = cv2.inRange(hsv, lower, upper)
  155. struc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
  156. mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, struc)
  157. boolean = mask > 0
  158. new = np.zeros_like(i, np.uint8)
  159. new[boolean] = i[boolean]
  160. new_img.append(new)
  161. new_img = np.asarray(new_img)
  162. new_img = new_img / 255
  163. loaded_model = tf.keras.models.load_model('keras_model.h5')
  164. result = loaded_model.predict_classes(new_img)
  165. return (traininglabels[result[0]])
  166. Obj = plantRecognition()
  167. print("\nPlant name:{}".format(Obj.predict("F:/JetBrain Project Files/Pycharm/human_organs_image_classifiaction/datasets/validation/Eye/images(11).jpg")))
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...