-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprossing_dataset.py
280 lines (226 loc) · 10.2 KB
/
preprossing_dataset.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
# -*- coding: utf-8 -*-
"""preprossing_dataset.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/13Bt9ft5FBk0gjnXFr9cOlG6ZtZIQvF_k
"""
pip install numpy opencv-python matplotlib
!pip install opencv-python matplotlib
from google.colab import drive
drive.mount('/content/drive')
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
def preprocess_image(image_path, display_steps=False):
# Load the original image
image = cv2.imread(image_path)
if display_steps:
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title("Original Image")
plt.axis('off')
plt.show()
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Block B: Artifacts removal
# i. Otsu Thresholding
_, thresh = cv2.threshold(image_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
if display_steps:
plt.imshow(thresh, cmap='gray')
plt.title("After Otsu Thresholding")
plt.axis('off')
plt.show()
# ii. Contours Detection
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# iii. ROI Extraction
cnt = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(cnt)
roi = image[y:y+h, x:x+w]
if display_steps:
plt.imshow(cv2.cvtColor(roi, cv2.COLOR_BGR2RGB))
plt.title("After ROI Extraction")
plt.axis('off')
plt.show()
# Block C: Noise removal (Gaussian Blurring)
roi_blur = cv2.GaussianBlur(roi, (5, 5), 0)
if display_steps:
plt.imshow(cv2.cvtColor(roi_blur, cv2.COLOR_BGR2RGB))
plt.title("After Noise Removal")
plt.axis('off')
plt.show()
# Block D: Image enhancement (CLAHE in the Y channel)
roi_lab = cv2.cvtColor(roi_blur, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(roi_lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l_clahe = clahe.apply(l)
final_lab = cv2.merge((l_clahe, a, b))
final_image = cv2.cvtColor(final_lab, cv2.COLOR_LAB2BGR)
if display_steps:
plt.imshow(cv2.cvtColor(final_image, cv2.COLOR_BGR2RGB))
plt.title("After Image Enhancement")
plt.axis('off')
plt.show()
return final_image
def process_folder(input_folder, output_folder, display_steps=False):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for subdir in os.listdir(input_folder):
subdir_path = os.path.join(input_folder, subdir)
if os.path.isdir(subdir_path):
output_subdir = os.path.join(output_folder, subdir)
if not os.path.exists(output_subdir):
os.makedirs(output_subdir)
for filename in os.listdir(subdir_path):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
input_path = os.path.join(subdir_path, filename)
output_path = os.path.join(output_subdir, filename)
processed_image = preprocess_image(input_path, display_steps)
cv2.imwrite(output_path, processed_image)
print(f"Processed and saved: {filename} in {subdir}")
# Example usage
base_folder = input("Please enter the base folder path of your dataset: ")
output_base_folder = input("Please enter the base path to save the preprocessed data: ")
display_steps = input("Do you want to display preprocessing steps for each image? (yes/no): ").lower() == 'yes'
for folder in ["train", "test", "val"]:
input_folder = os.path.join(base_folder, folder)
output_folder = os.path.join(output_base_folder, folder)
process_folder(input_folder, output_folder, display_steps)
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
def preprocess_image(image_path, display_steps=False):
# Load the original image
image = cv2.imread(image_path)
fig, axs = plt.subplots(1, 7, figsize=(20, 5)) # Create a new figure with 7 subplots in a single row
if display_steps:
axs[0].imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
axs[0].set_title("Original Image")
axs[0].axis('off')
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Block B: Artifacts removal
# i. Otsu Thresholding
_, thresh = cv2.threshold(image_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
if display_steps:
axs[1].imshow(thresh, cmap='gray')
axs[1].set_title("After Otsu Thresholding")
axs[1].axis('off')
# ii. Contours Detection
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# iii. ROI Extraction
cnt = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(cnt)
roi = image[y:y+h, x:x+w]
if display_steps:
axs[2].imshow(cv2.cvtColor(roi, cv2.COLOR_BGR2RGB))
axs[2].set_title("After ROI Extraction")
axs[2].axis('off')
# Block C: Noise removal (Gaussian Blurring)
roi_blur = cv2.GaussianBlur(roi, (5, 5), 0)
if display_steps:
axs[3].imshow(cv2.cvtColor(roi_blur, cv2.COLOR_BGR2RGB))
axs[3].set_title("After Noise Removal")
axs[3].axis('off')
# Block D: Image enhancement (CLAHE in the Y channel)
roi_lab = cv2.cvtColor(roi_blur, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(roi_lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l_clahe = clahe.apply(l)
final_lab = cv2.merge((l_clahe, a, b))
final_image = cv2.cvtColor(final_lab, cv2.COLOR_LAB2BGR)
if display_steps:
axs[4].imshow(cv2.cvtColor(final_image, cv2.COLOR_BGR2RGB))
axs[4].set_title("After Image Enhancement")
axs[4].axis('off')
# Save the final image to the output path
output_path = os.path.join(output_folder, filename)
cv2.imwrite(output_path, final_image)
print(f"Processed and saved: {filename}")
if display_steps:
axs[5].imshow(cv2.cvtColor(cv2.imread(output_path), cv2.COLOR_BGR2RGB))
axs[5].set_title("Saved Image")
axs[5].axis('off')
plt.show() # Show all subplots
return final_image
# ... rest of your code ...
base_folder = input("Please enter the base folder path of your dataset: ")
output_base_folder = input("Please enter the base path to save the preprocessed data: ")
display_steps = input("Do you want to display preprocessing steps for each image? (yes/no): ").lower() == 'yes'
for folder in ["train", "test", "val"]:
input_folder = os.path.join(base_folder, folder)
output_folder = os.path.join(output_base_folder, folder)
process_folder(input_folder, output_folder, display_steps)
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
def preprocess_image(image_path, display_steps=False):
# Load the original image
image = cv2.imread(image_path)
fig, axs = plt.subplots(1, 7, figsize=(20, 5)) # Create a new figure with 7 subplots in a single row
if display_steps:
axs[0].imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
axs[0].set_title("Original Image")
axs[0].axis('off')
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Block B: Artifacts removal
# i. Otsu Thresholding
_, thresh = cv2.threshold(image_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
if display_steps:
axs[1].imshow(thresh, cmap='gray')
axs[1].set_title("After Otsu Thresholding")
axs[1].axis('off')
# ii. Contours Detection
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# iii. ROI Extraction
cnt = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(cnt)
roi = image[y:y+h, x:x+w]
if display_steps:
axs[2].imshow(cv2.cvtColor(roi, cv2.COLOR_BGR2RGB))
axs[2].set_title("After ROI Extraction")
axs[2].axis('off')
# Block C: Noise removal (Gaussian Blurring)
roi_blur = cv2.GaussianBlur(roi, (5, 5), 0)
if display_steps:
axs[3].imshow(cv2.cvtColor(roi_blur, cv2.COLOR_BGR2RGB))
axs[3].set_title("After Noise Removal")
axs[3].axis('off')
# Block D: Image enhancement (CLAHE in the Y channel)
roi_lab = cv2.cvtColor(roi_blur, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(roi_lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l_clahe = clahe.apply(l)
final_lab = cv2.merge((l_clahe, a, b))
final_image = cv2.cvtColor(final_lab, cv2.COLOR_LAB2BGR)
if display_steps:
axs[4].imshow(cv2.cvtColor(final_image, cv2.COLOR_BGR2RGB))
axs[4].set_title("After Image Enhancement")
axs[4].axis('off')
return final_image, axs # Return the final image and the axs array for further use
def process_folder(input_folder, output_folder, display_steps=False):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for subdir, _, files in os.walk(input_folder):
output_subdir = os.path.join(output_folder, os.path.relpath(subdir, input_folder))
if not os.path.exists(output_subdir):
os.makedirs(output_subdir)
for filename in files:
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
input_path = os.path.join(subdir, filename)
output_path = os.path.join(output_subdir, filename)
processed_image, axs = preprocess_image(input_path, display_steps) # Get axs from preprocess_image
cv2.imwrite(output_path, processed_image)
print(f"Processed and saved: {filename} in {os.path.relpath(subdir, input_folder)}")
if display_steps:
axs[5].imshow(cv2.cvtColor(cv2.imread(output_path), cv2.COLOR_BGR2RGB))
axs[5].set_title("Saved Image")
axs[5].axis('off')
plt.show() # Show all subplots
# Example usage
base_folder = input("Please enter the base folder path of your dataset: ")
output_base_folder = input("Please enter the base path to save the preprocessed data: ")
display_steps = input("Do you want to display preprocessing steps for each image? (yes/no): ").lower() == 'yes'
for folder in ["train", "test", "val"]:
input_folder = os.path.join(base_folder, folder)
output_folder = os.path.join(output_base_folder, folder)
process_folder(input_folder, output_folder, display_steps)