Repository navigation
Expand file tree
/
Copy pathnpk_image_processing.py
More file actions
427 lines (349 loc) · 13.3 KB
/
Copy pathnpk_image_processing.py
File metadata and controls
427 lines (349 loc) · 13.3 KB
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
import cv2
import numpy as np
# ==========================================
# ANALYTE CALIBRATION DATA
# ==========================================
# NPK feature values below are still placeholders and should be replaced
# with values measured from your own chart under the same setup.
# pH uses a different feature because the chart spans red -> green.
ANALYTE_CONFIG = {
"Ammonia_N": {
"unit": "mg/L",
"result_label": "Concentration",
"feature_key": "feature",
"calibration": [
{"feature": 30, "value": 0},
{"feature": 45, "value": 10},
{"feature": 65, "value": 50},
{"feature": 90, "value": 100},
{"feature": 120, "value": 200},
{"feature": 150, "value": 500},
],
"target": 150.0,
},
"Phosphorus_P": {
"unit": "mg/L",
"result_label": "Concentration",
"feature_key": "feature",
"calibration": [
{"feature": 20, "value": 0},
{"feature": 35, "value": 20},
{"feature": 55, "value": 50},
{"feature": 75, "value": 80},
{"feature": 95, "value": 120},
{"feature": 120, "value": 240},
],
"target": 80.0,
},
"Potassium_K": {
"unit": "mg/L",
"result_label": "Concentration",
"feature_key": "feature",
"calibration": [
{"feature": 18, "value": 0},
{"feature": 32, "value": 20},
{"feature": 48, "value": 50},
{"feature": 62, "value": 80},
{"feature": 78, "value": 120},
{"feature": 95, "value": 240},
],
"target": 120.0,
},
"pH": {
"unit": "pH",
"result_label": "pH",
"feature_key": "ph_feature",
"calibration": [
{"feature": -8.0, "value": 4.0},
{"feature": -4.0, "value": 5.0},
{"feature": -1.0, "value": 6.0},
{"feature": 8.0, "value": 7.0},
{"feature": 40.0, "value": 8.0},
{"feature": 65.0, "value": 9.0},
{"feature": 82.0, "value": 10.0},
],
"ideal_range": (6.0, 7.0),
},
}
def normalize_mode(mode_name):
if isinstance(mode_name, str) and mode_name.lower() == "ph":
return "pH"
return mode_name
def get_mode_config(mode_name):
mode_name = normalize_mode(mode_name)
if mode_name not in ANALYTE_CONFIG:
raise ValueError(
f"Unknown mode '{mode_name}'. "
f"Choose from: {', '.join(ANALYTE_CONFIG)}"
)
return mode_name, ANALYTE_CONFIG[mode_name]
def interpolate_result(x_feature, mode_name):
"""
Linear interpolation:
C = C1 + ((x - x1) / (x2 - x1)) * (C2 - C1)
"""
mode_name, config = get_mode_config(mode_name)
points = sorted(config["calibration"], key=lambda item: item["feature"])
if len(points) < 2:
raise ValueError(f"Calibration for '{mode_name}' must contain at least 2 points.")
if x_feature <= points[0]["feature"]:
return float(points[0]["value"])
if x_feature >= points[-1]["feature"]:
return float(points[-1]["value"])
for i in range(len(points) - 1):
p1, p2 = points[i], points[i + 1]
if p1["feature"] <= x_feature <= p2["feature"]:
x1, c1 = p1["feature"], p1["value"]
x2, c2 = p2["feature"], p2["value"]
if x2 == x1:
return float(c1)
concentration = c1 + ((x_feature - x1) / (x2 - x1)) * (c2 - c1)
return round(float(concentration), 2)
return round(float(points[-1]["value"]), 2)
def extract_roi_hsv_fallback(img, x_ratio=0.4, y_ratio=0.45, w_ratio=0.2, h_ratio=0.15):
"""Fallback ROI when automatic liquid detection is not available."""
h, w, _ = img.shape
roi_x = int(w * x_ratio)
roi_y = int(h * y_ratio)
roi_w = max(1, int(w * w_ratio))
roi_h = max(1, int(h * h_ratio))
roi_x2 = min(w, roi_x + roi_w)
roi_y2 = min(h, roi_y + roi_h)
if roi_x >= roi_x2 or roi_y >= roi_y2:
raise ValueError("ROI is empty. Check the ROI ratios or use a larger image.")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
roi = hsv[roi_y:roi_y2, roi_x:roi_x2]
if roi.size == 0:
raise ValueError("ROI contains no pixels.")
return roi, (roi_x, roi_y, roi_x2, roi_y2)
def detect_liquid_roi_box(img):
"""
Detect the colored liquid area automatically.
The search is limited to the lower center of the frame where the vial usually appears.
"""
h, w = img.shape[:2]
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
sat = hsv[:, :, 1]
val = hsv[:, :, 2]
search_x1 = int(w * 0.18)
search_x2 = int(w * 0.82)
search_y1 = int(h * 0.28)
search_mask = np.zeros((h, w), dtype=np.uint8)
search_mask[search_y1:, search_x1:search_x2] = 255
sat_blur = cv2.GaussianBlur(sat, (9, 9), 0)
search_sat = sat_blur[search_y1:, search_x1:search_x2]
if search_sat.size == 0:
raise ValueError("Auto ROI search window is empty.")
sat_threshold = max(20, int(np.percentile(search_sat, 75) * 0.55))
liquid_mask = (
(sat_blur >= sat_threshold)
& (val >= 50)
& (search_mask > 0)
).astype(np.uint8) * 255
liquid_mask = cv2.morphologyEx(
liquid_mask,
cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15)),
)
liquid_mask = cv2.morphologyEx(
liquid_mask,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)),
)
contours, _ = cv2.findContours(
liquid_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
min_area = h * w * 0.002
best_box = None
best_score = -1.0
for contour in contours:
x, y, box_w, box_h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
if area < min_area:
continue
cx = x + (box_w / 2.0)
cy = y + (box_h / 2.0)
center_score = max(0.0, 1.0 - abs((cx / w) - 0.5) / 0.5)
bottom_score = cy / h
score = area * (0.6 + 0.4 * center_score) * (0.5 + 0.5 * bottom_score)
if score > best_score:
best_score = score
best_box = (x, y, x + box_w, y + box_h)
if best_box is None:
raise ValueError("Could not find a liquid contour for auto ROI.")
x1, y1, x2, y2 = best_box
inset_x = max(4, int((x2 - x1) * 0.12))
inset_y = max(4, int((y2 - y1) * 0.15))
inner_x1 = max(0, x1 + inset_x)
inner_y1 = max(0, y1 + inset_y)
inner_x2 = min(w, x2 - inset_x)
inner_y2 = min(h, y2 - inset_y)
inner_w = inner_x2 - inner_x1
inner_h = inner_y2 - inner_y1
if inner_w <= 0 or inner_h <= 0:
raise ValueError("Auto ROI collapsed after applying margins.")
square_size = max(20, int(min(inner_w, inner_h) * 0.6))
center_x = (inner_x1 + inner_x2) / 2.0
center_y = (inner_y1 + inner_y2) / 2.0
roi_x1 = max(0, int(round(center_x - (square_size / 2.0))))
roi_y1 = max(0, int(round(center_y - (square_size / 2.0))))
roi_x2 = roi_x1 + square_size
roi_y2 = roi_y1 + square_size
if roi_x2 > w:
roi_x2 = w
roi_x1 = w - square_size
if roi_y2 > h:
roi_y2 = h
roi_y1 = h - square_size
roi_box = (roi_x1, roi_y1, roi_x2, roi_y2)
if roi_box[0] >= roi_box[2] or roi_box[1] >= roi_box[3]:
raise ValueError("Auto ROI collapsed after applying margins.")
return roi_box
def extract_roi_hsv(img):
"""Extract the liquid ROI automatically, then fall back to fixed ratios if needed."""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
try:
roi_x1, roi_y1, roi_x2, roi_y2 = detect_liquid_roi_box(img)
roi = hsv[roi_y1:roi_y2, roi_x1:roi_x2]
roi_method = "auto"
except ValueError:
roi, (roi_x1, roi_y1, roi_x2, roi_y2) = extract_roi_hsv_fallback(img)
roi_method = "fallback"
if roi.size == 0:
raise ValueError("ROI contains no pixels.")
return roi, (roi_x1, roi_y1, roi_x2, roi_y2), roi_method
def unwrap_ph_hue(hue_value):
# OpenCV hue wraps red close to 179, so unwrap it for the pH chart.
return hue_value - 180.0 if hue_value > 150.0 else hue_value
def extract_color_feature(img):
"""
Return feature data for both NPK and pH modes.
NPK uses a hue+saturation feature.
pH uses an unwrapped hue feature to handle the red-to-green chart.
"""
roi, roi_box, roi_method = extract_roi_hsv(img)
hue = float(np.median(roi[:, :, 0]))
sat = float(np.median(roi[:, :, 1]))
val = float(np.median(roi[:, :, 2]))
feature = round((0.7 * hue) + (0.3 * sat), 2)
ph_feature = round(unwrap_ph_hue(hue), 2)
return {
"feature": feature,
"ph_feature": ph_feature,
"hue": round(hue, 2),
"saturation": round(sat, 2),
"value": round(val, 2),
"roi_box": roi_box,
"roi_method": roi_method,
}
def build_recommendation(result_value, mode_name):
mode_name, config = get_mode_config(mode_name)
if mode_name == "pH":
low_limit, high_limit = config["ideal_range"]
if result_value < low_limit:
return f"ACIDIC: Soil pH is low. Consider raising it toward {low_limit}-{high_limit}."
if result_value > high_limit:
return f"ALKALINE: Soil pH is high. Consider lowering it toward {low_limit}-{high_limit}."
return f"OPTIMAL: Soil pH is within the ideal range of {low_limit}-{high_limit}."
target = config["target"]
if result_value < target:
deficiency = round(target - result_value, 2)
return f"LOW: Add about {deficiency} mg/L worth of fertilizer."
excess = round(result_value - target, 2)
if excess > 0:
return "OPTIMAL/HIGH: No additional fertilizer needed."
return "OPTIMAL: No additional fertilizer needed."
def analyze_soil_vial(image_path, nutrient_mode="Ammonia_N", show_window=True):
nutrient_mode, config = get_mode_config(nutrient_mode)
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(f"Could not load image: {image_path}")
feature_data = extract_color_feature(img)
active_feature = feature_data[config["feature_key"]]
result_value = interpolate_result(active_feature, nutrient_mode)
recommendation = build_recommendation(result_value, nutrient_mode)
roi_x1, roi_y1, roi_x2, roi_y2 = feature_data["roi_box"]
cv2.rectangle(img, (roi_x1, roi_y1), (roi_x2, roi_y2), (0, 255, 0), 3)
cv2.putText(
img,
f"Mode: {nutrient_mode}",
(40, 50),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255, 255, 255),
2,
)
cv2.putText(
img,
f"{config['result_label']}: {result_value} {config['unit']}",
(40, 95),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 255, 0),
2,
)
cv2.putText(
img,
(
f"H:{feature_data['hue']} S:{feature_data['saturation']} "
f"F:{feature_data['feature']} pHF:{feature_data['ph_feature']}"
),
(40, 140),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(255, 255, 255),
2,
)
print("\n--- ANALYSIS COMPLETE ---")
print(f"Mode: {nutrient_mode}")
print(f"Detected Hue: {feature_data['hue']}")
print(f"Detected Saturation: {feature_data['saturation']}")
print(f"NPK Feature: {feature_data['feature']}")
print(f"pH Feature: {feature_data['ph_feature']}")
print(f"ROI Method: {feature_data['roi_method']}")
print(f"{config['result_label']}: {result_value} {config['unit']}")
print(f"Advice: {recommendation}")
if show_window:
cv2.imshow("Thesis System Output", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return {
"mode": nutrient_mode,
"hue": feature_data["hue"],
"saturation": feature_data["saturation"],
"value": feature_data["value"],
"feature": feature_data["feature"],
"ph_feature": feature_data["ph_feature"],
"roi_method": feature_data["roi_method"],
"result": result_value,
"unit": config["unit"],
"recommendation": recommendation,
}
def calibration_helper(chart_image_path, nutrient_mode):
"""
Reads the sample ROI from a chart image and prints the measured feature.
Run this on each known concentration patch to refine calibration data.
"""
nutrient_mode, config = get_mode_config(nutrient_mode)
img = cv2.imread(chart_image_path)
if img is None:
raise FileNotFoundError(f"Could not load chart image: {chart_image_path}")
feature_data = extract_color_feature(img)
print("\n--- CALIBRATION READING ---")
print(f"Mode: {nutrient_mode}")
print(f"Hue: {feature_data['hue']}")
print(f"Saturation: {feature_data['saturation']}")
print(f"Value: {feature_data['value']}")
print(f"NPK feature to store: {feature_data['feature']}")
print(f"pH feature to store: {feature_data['ph_feature']}")
print(f"ROI method: {feature_data['roi_method']}")
print(f"Active feature for {nutrient_mode}: {feature_data[config['feature_key']]}")
return feature_data
if __name__ == "__main__":
try:
analyze_soil_vial("images/NPK 01/N.jpg", "Ammonia_N")
analyze_soil_vial("images/NPK 01/P.jpg", "Phosphorus_P")
analyze_soil_vial("images/NPK 01/K.jpg", "Potassium_K")
# analyze_soil_vial("images/NPK 03 /Ph.jpg", "pH")
except Exception as exc:
print(f"Error: {exc}")