nnibras commited on
Commit
8c785df
·
verified ·
1 Parent(s): cceec7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -108
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import cv2
2
  import gradio as gr
3
  import numpy as np
@@ -6,12 +7,8 @@ from sklearn.model_selection import KFold
6
  from skimage.feature import graycomatrix, graycoprops
7
  from sklearn.neighbors import KNeighborsClassifier
8
  from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
9
- import pandas as pd
10
  from sklearn.model_selection import GridSearchCV
11
- from sklearn.neighbors import KNeighborsClassifier
12
  from skimage.feature import local_binary_pattern
13
- #import os
14
-
15
 
16
  # Visualize GLCM features for grass and wood
17
  def plot_features(features, title):
@@ -22,7 +19,6 @@ def plot_features(features, title):
22
  plt.legend()
23
  plt.show()
24
 
25
-
26
  # Define directories for grass and wood images
27
  grass_dir = "images/Grass/Train_Grass"
28
  wood_dir = "images/Wood/Train_Wood"
@@ -36,26 +32,23 @@ TARGET_SIZE = (30, 30)
36
  distances = [1]
37
  angles = [0]
38
 
39
-
40
  def load_and_convert_images(directory):
41
- """Load images from a directory and convert them to grayscale."""
42
  dataset = []
43
- for filename in os.listdir(directory):
44
- if filename.endswith((".jpg", ".png", ".jpeg")):
45
- img_path = os.path.join(directory, filename) # Construct full image path
46
- img = cv2.imread(img_path) # Read the image
47
- if img is not None:
48
- # resized_image = cv2.resize(img, TARGET_SIZE, interpolation=cv2.INTER_AREA) #resize the images
49
- gray_image = cv2.cvtColor(
50
- img, cv2.COLOR_BGR2GRAY
51
- ) # Convert to grayscale
52
- resized_image = cv2.resize(
53
- gray_image, TARGET_SIZE, interpolation=cv2.INTER_AREA
54
- )
55
- dataset.append(resized_image)
56
  return dataset
57
 
58
-
59
  def calc_glcm_features(images):
60
  features = []
61
  for img in images:
@@ -70,11 +63,8 @@ def calc_glcm_features(images):
70
  features.append([contrast, dissimilarity, homogeneity, energy, correlation])
71
  return features
72
 
73
-
74
- # Function to extract LBP features from an image
75
  def extract_lbp_features(images):
76
  """Extract LBP features from a list of images."""
77
-
78
  lbp_features = []
79
  for image in images:
80
  lbp = local_binary_pattern(image, N_POINTS, RADIUS, method="uniform")
@@ -83,26 +73,21 @@ def extract_lbp_features(images):
83
  lbp_features.append(lbp_hist)
84
  return lbp_features
85
 
86
-
87
  # Load datasets
88
  grass_dataset = load_and_convert_images(grass_dir)
89
  wood_dataset = load_and_convert_images(wood_dir)
90
 
91
  # Create labels (0 for grass, 1 for wood)
92
- grass_labels = [0] * len(grass_dataset) # Label all grass images as 0
93
- wood_labels = [1] * len(wood_dataset) # Label all wood images as 1
94
-
95
 
96
  # Calculate features
97
  grass_glcm_features = calc_glcm_features(grass_dataset)
98
  wood_glcm_features = calc_glcm_features(wood_dataset)
99
 
100
-
101
  grass_lbp_features = extract_lbp_features(grass_dataset)
102
  wood_lbp_features = extract_lbp_features(wood_dataset)
103
 
104
- ####TESTING...
105
-
106
  # GLCM features for grass and wood
107
  plot_features(np.array(grass_glcm_features), "GLCM Features for Grass Images")
108
  plot_features(np.array(wood_glcm_features), "GLCM Features for Wood Images")
@@ -111,9 +96,6 @@ plot_features(np.array(wood_glcm_features), "GLCM Features for Wood Images")
111
  plot_features(np.array(grass_lbp_features), "LBP Features for Grass Images")
112
  plot_features(np.array(wood_lbp_features), "LBP Features for Wood Images")
113
 
114
-
115
- ###MATPLOTLIB....
116
-
117
  # Combine labels and features for GLCM classifier
118
  glcm_features = grass_glcm_features + wood_glcm_features
119
  glcm_labels = grass_labels + wood_labels
@@ -121,7 +103,6 @@ glcm_labels = grass_labels + wood_labels
121
  # Convert to numpy array
122
  glcm_features = np.array(glcm_features)
123
 
124
-
125
  # Prepare labels and features for LBP classifier
126
  lbp_features = grass_lbp_features + wood_lbp_features
127
  lbp_labels = grass_labels + wood_labels
@@ -129,8 +110,6 @@ lbp_labels = grass_labels + wood_labels
129
  # Convert to numpy array
130
  lbp_features = np.array(lbp_features)
131
 
132
- print("block 2 run")
133
-
134
  num_grass = len(grass_dataset) # Number of grass images
135
  num_wood = len(wood_dataset) # Number of wood images
136
 
@@ -169,11 +148,6 @@ for train_index, test_index in kf.split(glcm_features):
169
  accuracy = accuracy_score(y_test, y_pred)
170
  glcm_accuracy_list.append(accuracy)
171
 
172
- # Optionally: Print confusion matrix and precision
173
-
174
- # print(f"Confusion Matrix for GLCM Fold:\n{confusion_matrix(y_test, y_pred)}")
175
- # print(f"Classification Report for GLCM Fold:\n{classification_report(y_test, y_pred, zero_division=0)}")
176
-
177
  # Print overall GLCM accuracy
178
  print(f"GLCM Cross-validated accuracy: {np.mean(glcm_accuracy_list) * 100:.2f}%")
179
 
@@ -189,70 +163,35 @@ for train_index, test_index in kf.split(lbp_features):
189
  x_train, x_test = lbp_features[train_index], lbp_features[test_index]
190
  y_train, y_test = y[train_index], y[test_index]
191
 
192
- lbp_classifier = KNeighborsClassifier(
193
- n_neighbors=lbp_grid_search.best_params_["n_neighbors"]
194
- )
195
  lbp_classifier.fit(x_train, y_train)
196
  y_pred = lbp_classifier.predict(x_test)
197
 
198
  accuracy = accuracy_score(y_test, y_pred)
199
  lbp_accuracy_list.append(accuracy)
200
 
201
- # Optionally: Print confusion matrix and precision
202
-
203
- # print(f"Confusion Matrix for LBP Fold:\n{confusion_matrix(y_test, y_pred)}")
204
- # print(f"Classification Report for LBP Fold:\n{classification_report(y_test, y_pred, zero_division=0)}")
205
-
206
  # Print overall LBP accuracy
207
  print(f"LBP Cross-validated accuracy: {np.mean(lbp_accuracy_list) * 100:.2f}%")
208
 
 
 
 
209
 
210
- def classify_texture(image, algorithm):
211
- # Resize and convert the image to grayscale
212
- resized_image = cv2.resize(image, TARGET_SIZE, interpolation=cv2.INTER_AREA)
213
- gray_image = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY) # Convert to grayscale
214
-
215
- # Select the feature extraction method based on the algorithm
216
  if algorithm == "GLCM":
217
- features = calc_glcm_features([gray_image]) # Use parentheses, pass as a list
218
- prediction = glcm_grid_search.predict(features)
219
  elif algorithm == "LBP":
220
- features = extract_lbp_features([gray_image])
221
- prediction = lbp_grid_search.predict(features)
222
  else:
223
  raise ValueError(f"Algorithm '{algorithm}' is not recognized.")
224
 
225
  return "Grass" if prediction[0] == 0 else "Wood"
226
 
227
-
228
- # Function to highlight regions
229
- def highlight_texture(image, result):
230
- overlay = image.copy()
231
- if result == "Grass":
232
- overlay[:, :] = [0, 255, 0] # Highlight grass regions in green
233
- else:
234
- overlay[:, :] = [165, 42, 42] # Highlight wood regions in brown
235
- return overlay
236
-
237
-
238
- # Define the Gradio interface
239
- def classify_uploaded_image(image, algorithm):
240
- # Convert the uploaded image to a format that OpenCV can process
241
- image = np.array(image, dtype=np.uint8) # Ensure correct type
242
-
243
- # Call the classify_texture function
244
- result = classify_texture(image, algorithm)
245
-
246
- return result
247
-
248
-
249
  # Gradio Interface Setup
250
  iface = gr.Interface(
251
  fn=classify_uploaded_image,
252
  inputs=[
253
- gr.Image(
254
- type="numpy", label="Upload an Image"
255
- ), # Image input, passing as NumPy array
256
  gr.Dropdown(choices=["GLCM", "LBP"], label="Algorithm"),
257
  ],
258
  outputs="text",
@@ -261,26 +200,3 @@ iface = gr.Interface(
261
 
262
  # Launch the interface
263
  iface.launch()
264
-
265
-
266
- # # Create Gradio interface
267
- # iface = gr.Interface(
268
- # fn=lambda image, algorithm: (result := classify_texture(image, algorithm), highlight_texture(image, result)),
269
- # inputs=[
270
- # gr.Image(type='numpy', label="Upload Image"),
271
- # gr.Radio(choices=['GLCM', 'LBP'], label="Select Algorithm")
272
- # ],
273
- # outputs=[gr.Textbox(label="Classification Result"), gr.Image(label="Highlighted Result")],
274
- # title="Texture Classification",
275
- # description="Upload an image and select the classification algorithm (GLCM or LBP). The result will show the classification and highlight the detected texture."
276
- # )
277
-
278
- # # Launch the interface
279
- # iface.launch()
280
-
281
- # Example of testing with a specific image
282
- test_grass_image = cv2.imread("grass.jpg")
283
- test_wood_image = cv2.imread("wood.jpg")
284
-
285
- print("Testing with Grass Image Prediction:", classify_texture(test_grass_image, "LBP"))
286
- print("Testing with Wood Image Prediction:", classify_texture(test_wood_image, "LBP"))
 
1
+ import glob
2
  import cv2
3
  import gradio as gr
4
  import numpy as np
 
7
  from skimage.feature import graycomatrix, graycoprops
8
  from sklearn.neighbors import KNeighborsClassifier
9
  from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
 
10
  from sklearn.model_selection import GridSearchCV
 
11
  from skimage.feature import local_binary_pattern
 
 
12
 
13
  # Visualize GLCM features for grass and wood
14
  def plot_features(features, title):
 
19
  plt.legend()
20
  plt.show()
21
 
 
22
  # Define directories for grass and wood images
23
  grass_dir = "images/Grass/Train_Grass"
24
  wood_dir = "images/Wood/Train_Wood"
 
32
  distances = [1]
33
  angles = [0]
34
 
35
+ # Use glob to load images from the directory
36
  def load_and_convert_images(directory):
37
+ """Load images from a directory using glob and convert them to grayscale."""
38
  dataset = []
39
+ image_paths = glob.glob(f"{directory}/*.jpg") + glob.glob(f"{directory}/*.png") + glob.glob(f"{directory}/*.jpeg")
40
+
41
+ for img_path in image_paths:
42
+ img = cv2.imread(img_path) # Read the image
43
+ if img is not None:
44
+ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale
45
+ resized_image = cv2.resize(gray_image, TARGET_SIZE, interpolation=cv2.INTER_AREA)
46
+ dataset.append(resized_image)
47
+ else:
48
+ print(f"Warning: Failed to load image {img_path}")
49
+
 
 
50
  return dataset
51
 
 
52
  def calc_glcm_features(images):
53
  features = []
54
  for img in images:
 
63
  features.append([contrast, dissimilarity, homogeneity, energy, correlation])
64
  return features
65
 
 
 
66
  def extract_lbp_features(images):
67
  """Extract LBP features from a list of images."""
 
68
  lbp_features = []
69
  for image in images:
70
  lbp = local_binary_pattern(image, N_POINTS, RADIUS, method="uniform")
 
73
  lbp_features.append(lbp_hist)
74
  return lbp_features
75
 
 
76
  # Load datasets
77
  grass_dataset = load_and_convert_images(grass_dir)
78
  wood_dataset = load_and_convert_images(wood_dir)
79
 
80
  # Create labels (0 for grass, 1 for wood)
81
+ grass_labels = [0] * len(grass_dataset)
82
+ wood_labels = [1] * len(wood_dataset)
 
83
 
84
  # Calculate features
85
  grass_glcm_features = calc_glcm_features(grass_dataset)
86
  wood_glcm_features = calc_glcm_features(wood_dataset)
87
 
 
88
  grass_lbp_features = extract_lbp_features(grass_dataset)
89
  wood_lbp_features = extract_lbp_features(wood_dataset)
90
 
 
 
91
  # GLCM features for grass and wood
92
  plot_features(np.array(grass_glcm_features), "GLCM Features for Grass Images")
93
  plot_features(np.array(wood_glcm_features), "GLCM Features for Wood Images")
 
96
  plot_features(np.array(grass_lbp_features), "LBP Features for Grass Images")
97
  plot_features(np.array(wood_lbp_features), "LBP Features for Wood Images")
98
 
 
 
 
99
  # Combine labels and features for GLCM classifier
100
  glcm_features = grass_glcm_features + wood_glcm_features
101
  glcm_labels = grass_labels + wood_labels
 
103
  # Convert to numpy array
104
  glcm_features = np.array(glcm_features)
105
 
 
106
  # Prepare labels and features for LBP classifier
107
  lbp_features = grass_lbp_features + wood_lbp_features
108
  lbp_labels = grass_labels + wood_labels
 
110
  # Convert to numpy array
111
  lbp_features = np.array(lbp_features)
112
 
 
 
113
  num_grass = len(grass_dataset) # Number of grass images
114
  num_wood = len(wood_dataset) # Number of wood images
115
 
 
148
  accuracy = accuracy_score(y_test, y_pred)
149
  glcm_accuracy_list.append(accuracy)
150
 
 
 
 
 
 
151
  # Print overall GLCM accuracy
152
  print(f"GLCM Cross-validated accuracy: {np.mean(glcm_accuracy_list) * 100:.2f}%")
153
 
 
163
  x_train, x_test = lbp_features[train_index], lbp_features[test_index]
164
  y_train, y_test = y[train_index], y[test_index]
165
 
 
 
 
166
  lbp_classifier.fit(x_train, y_train)
167
  y_pred = lbp_classifier.predict(x_test)
168
 
169
  accuracy = accuracy_score(y_test, y_pred)
170
  lbp_accuracy_list.append(accuracy)
171
 
 
 
 
 
 
172
  # Print overall LBP accuracy
173
  print(f"LBP Cross-validated accuracy: {np.mean(lbp_accuracy_list) * 100:.2f}%")
174
 
175
+ # Define the Gradio interface
176
+ def classify_uploaded_image(image, algorithm):
177
+ image = np.array(image, dtype=np.uint8) # Ensure correct type
178
 
 
 
 
 
 
 
179
  if algorithm == "GLCM":
180
+ features = calc_glcm_features([image]) # Use parentheses, pass as a list
181
+ prediction = glcm_knn.predict(features)
182
  elif algorithm == "LBP":
183
+ features = extract_lbp_features([image])
184
+ prediction = lbp_knn.predict(features)
185
  else:
186
  raise ValueError(f"Algorithm '{algorithm}' is not recognized.")
187
 
188
  return "Grass" if prediction[0] == 0 else "Wood"
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  # Gradio Interface Setup
191
  iface = gr.Interface(
192
  fn=classify_uploaded_image,
193
  inputs=[
194
+ gr.Image(type="numpy", label="Upload an Image"),
 
 
195
  gr.Dropdown(choices=["GLCM", "LBP"], label="Algorithm"),
196
  ],
197
  outputs="text",
 
200
 
201
  # Launch the interface
202
  iface.launch()