usama1355 commited on
Commit
320e664
·
verified ·
1 Parent(s): bb486a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -7
app.py CHANGED
@@ -328,6 +328,7 @@ async def predict_tomato(file: UploadFile = File(...)):
328
  "message": "Please upload a clear image of a PLANT leaf."
329
  })
330
 
 
331
  # --- SMART BACKGROUND REMOVAL ---
332
  image_array = np.array(image).astype(np.float32)
333
 
@@ -335,23 +336,27 @@ async def predict_tomato(file: UploadFile = File(...)):
335
  G = image_array[:, :, 1]
336
  B = image_array[:, :, 2]
337
 
338
- # Brightness: pixel must be very bright overall
339
  brightness = (R + G + B) / 3.0
340
- is_bright = brightness > 200
341
 
342
- # Saturation: true background has no color R, G, B are all similar
343
- # A green leaf pixel will have G much higher than R and B
344
  channel_range = (
345
  np.maximum(np.maximum(R, G), B) -
346
  np.minimum(np.minimum(R, G), B)
347
  )
348
- is_unsaturated = channel_range < 30 # low color variation = background
 
 
 
 
349
 
350
- # Only replace pixels that are BOTH bright AND colorless
351
- background_mask = is_bright & is_unsaturated
352
  image_array[background_mask] = [0, 0, 0]
353
 
354
  image = Image.fromarray(image_array.astype(np.uint8))
 
355
 
356
  # 1. Standard Resize
357
  image = image.resize((224, 224))
 
328
  "message": "Please upload a clear image of a PLANT leaf."
329
  })
330
 
331
+ # --- SMART BACKGROUND REMOVAL ---
332
  # --- SMART BACKGROUND REMOVAL ---
333
  image_array = np.array(image).astype(np.float32)
334
 
 
336
  G = image_array[:, :, 1]
337
  B = image_array[:, :, 2]
338
 
339
+ # Brightness: must be very bright (tightened from 200 → 220)
340
  brightness = (R + G + B) / 3.0
341
+ is_bright = brightness > 220
342
 
343
+ # Saturation: tightened from 30 15 to avoid removing leaf tissue
 
344
  channel_range = (
345
  np.maximum(np.maximum(R, G), B) -
346
  np.minimum(np.minimum(R, G), B)
347
  )
348
+ is_unsaturated = channel_range < 15
349
+
350
+ # Extra guard: true background has no dominant green channel
351
+ # Leaf pixels always have G notably higher than R and B
352
+ is_not_green = (G - R) < 15
353
 
354
+ # All three must be true to be considered background
355
+ background_mask = is_bright & is_unsaturated & is_not_green
356
  image_array[background_mask] = [0, 0, 0]
357
 
358
  image = Image.fromarray(image_array.astype(np.uint8))
359
+
360
 
361
  # 1. Standard Resize
362
  image = image.resize((224, 224))