Spaces:
Sleeping

File size: 3,566 Bytes
af866ea
 
 
 
 
2679dc9
0246b5d
 
2679dc9
0246b5d
af866ea
 
 
0246b5d
2679dc9
0246b5d
 
 
 
 
 
2679dc9
0246b5d
 
 
 
 
 
 
 
2679dc9
 
0246b5d
2679dc9
0246b5d
af866ea
 
 
 
307232c
 
 
 
 
 
 
 
af866ea
2679dc9
af866ea
 
 
2679dc9
af866ea
 
 
 
2679dc9
af866ea
 
2679dc9
 
 
 
 
af866ea
 
 
2679dc9
af866ea
 
2679dc9
f50a16e
307232c
af866ea
2679dc9
 
 
 
d827f38
2679dc9
d827f38
307232c
af866ea
 
 
 
 
 
 
2679dc9
af866ea
 
 
 
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
import cv2
import numpy as np
import gradio as gr
from ultralytics import YOLO

# Constants
A4_WIDTH_CM = 21.0
A4_HEIGHT_CM = 29.7
A4_TOTAL_AREA_CM2 = A4_WIDTH_CM * A4_HEIGHT_CM  # 623.7 cm2

# Load model
model = YOLO('best.pt')

def get_paper_metrics(image):
    """Detects A4 paper and returns scale (px per cm)."""
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    _, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return None, 0
    
    paper_cnt = max(contours, key=cv2.contourArea)
    rect = cv2.minAreaRect(paper_cnt)
    (_, _), (w, h), _ = rect
    
    pixel_long = max(w, h)
    pixel_short = min(w, h)
    
    # Scale: average px per cm across both dimensions
    px_per_cm = ((pixel_long / A4_HEIGHT_CM) + (pixel_short / A4_WIDTH_CM)) / 2
    
    return paper_cnt, px_per_cm

def analyze_stains(img):
    # Gradio provides images in RGB, OpenCV uses BGR
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    annotated_frame = img.copy()

    h_img, w_img, _ = img.shape
    # --- DYNAMIC FONT SCALING ---
    # Base scale on a standard 1000px width
    base_w = 1000
    font_scale = max(0.5, w_img / base_w)
    thickness = max(1, int(2 * (w_img / base_w)))
    line_type = cv2.LINE_AA # Smoother lines for high res
    
    paper_cnt, px_per_cm = get_paper_metrics(img)
    
    if paper_cnt is not None and px_per_cm > 0:
        results = model(img)
        total_stain_area_cm2 = 0
        
        for result in results:
            if result.masks:
                for polygon in result.masks.xy:
                    # Calculate area in pixels
                    stain_area_px = cv2.contourArea(polygon.astype(np.float32))
                    
                    # Convert pixel area to cm2: Area_cm = Area_px / (px_per_cm^2)
                    stain_area_cm2 = stain_area_px / (px_per_cm ** 2)
                    total_stain_area_cm2 += stain_area_cm2
                    
                    # Get dimensions for labeling
                    x, y, w_px, h_px = cv2.boundingRect(polygon.astype(np.int32))
                    w_cm, h_cm = w_px / px_per_cm, h_px / px_per_cm
                    
                    # Draw polygon and label for individual stain
                    pts = polygon.astype(np.int32).reshape((-1, 1, 2))
                    cv2.polylines(annotated_frame, [pts], True, (0, 255, 0), 2)
                    dim_label = f"{stain_area_cm2:.2f}cm2"
                    cv2.putText(annotated_frame, dim_label, (x, y - 12), 
                                cv2.FONT_HERSHEY_SIMPLEX, font_scale, (90, 0, 90), thickness, line_type)

        # Calculate coverage using total metric surface area
        coverage = (total_stain_area_cm2 / A4_TOTAL_AREA_CM2) * 100
        
        # Display Total Area and Coverage
        margin_y = int(60 * font_scale)
        summary_label = f"Total Stain: {total_stain_area_cm2:.2f}cm2 | Coverage: {coverage:.2f}%"
        cv2.putText(annotated_frame, summary_label, (int(20 * font_scale), margin_y), 
                    cv2.FONT_HERSHEY_SIMPLEX, font_scale * 1.2, (0, 0, 255), thickness + 1, line_type)
    
    return cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)

interface = gr.Interface(
    fn=analyze_stains,
    inputs=gr.Image(type="numpy"),
    outputs=gr.Image(type="numpy"),
    title="A4 Stain Area & Coverage Analysis"
)

if __name__ == "__main__":
    interface.launch()