ruanhelansantos commited on
Commit
cc62ae3
·
verified ·
1 Parent(s): 35b2312

Upload utils.py

Browse files
Files changed (1) hide show
  1. utils.py +54 -0
utils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils.py
2
+ # ECG Condition Classifier - Image Preprocessing Utilities
3
+
4
+ from PIL import Image
5
+ import numpy as np
6
+
7
+ # Target input size expected by ViT models
8
+ TARGET_SIZE = (224, 224)
9
+
10
+ def load_and_preprocess(image):
11
+ """
12
+ Accepts a PIL Image or file path.
13
+ Returns a clean, resized PIL Image ready for the classifier pipeline.
14
+ """
15
+ # If a file path was passed instead of a PIL image, open it
16
+ if isinstance(image, str):
17
+ image = Image.open(image)
18
+
19
+ # Convert to RGB - handles grayscale ECGs and RGBA screenshots
20
+ if image.mode != "RGB":
21
+ image = image.convert("RGB")
22
+
23
+ # Resize to ViT expected input dimensions
24
+ image = image.resize(TARGET_SIZE, Image.LANCZOS)
25
+
26
+ return image
27
+
28
+
29
+ def validate_image(image):
30
+ """
31
+ Basic sanity checks on uploaded image.
32
+ Returns (is_valid: bool, message: str)
33
+ """
34
+ if image is None:
35
+ return False, "No image provided. Please upload an ECG image."
36
+
37
+ # Check minimum resolution - too small likely isn't a real ECG
38
+ if hasattr(image, 'size'):
39
+ w, h = image.size
40
+ if w < 50 or h < 50:
41
+ return False, "Image resolution too low. Please upload a clearer ECG image."
42
+
43
+ return True, "OK"
44
+
45
+
46
+ def get_image_info(image):
47
+ """
48
+ Returns a simple string summary of the uploaded image.
49
+ Useful for debugging in the Gradio interface.
50
+ """
51
+ if image is None:
52
+ return "No image loaded."
53
+ w, h = image.size
54
+ return f"Image loaded: {w}x{h}px | Mode: {image.mode}"