Jaganpinka commited on
Commit
0978a08
·
verified ·
1 Parent(s): 8652101

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +60 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image
4
+ import gradio as gr
5
+ from transformers import SamModel, SamProcessor
6
+
7
+ # Download model automatically (no .pth needed)
8
+ processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
9
+ model = SamModel.from_pretrained("facebook/sam-vit-base")
10
+
11
+ def auto_dimension(image, height, width):
12
+ image_np = np.array(image)
13
+
14
+ # Prepare for SAM
15
+ inputs = processor(image, input_points=None, return_tensors="pt")
16
+
17
+ # Run SAM
18
+ outputs = model(**inputs)
19
+ masks = processor.post_process_masks(
20
+ outputs.pred_masks,
21
+ inputs["original_sizes"],
22
+ inputs["reshaped_input_sizes"]
23
+ )
24
+ mask = masks[0][0].numpy().astype(np.uint8) * 255
25
+
26
+ # Find largest contour
27
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
28
+ cnt = max(contours, key=cv2.contourArea)
29
+ x, y, w, h = cv2.boundingRect(cnt)
30
+
31
+ # Scale using real height
32
+ scale = height / h
33
+ computed_width = w * scale
34
+
35
+ output = image_np.copy()
36
+
37
+ # Draw dimension lines
38
+ def draw_dim(pt1, pt2, text):
39
+ cv2.line(output, pt1, pt2, (0, 255, 0), 3)
40
+ cv2.putText(output, text, (pt1[0]+10, pt1[1]-10),
41
+ cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2)
42
+
43
+ draw_dim((x-40, y), (x-40, y+h), f"H: {height} cm")
44
+ draw_dim((x, y+h+40), (x+w, y+h+40), f"W: {width} cm")
45
+
46
+ return Image.fromarray(output)
47
+
48
+ iface = gr.Interface(
49
+ fn=auto_dimension,
50
+ inputs=[
51
+ gr.Image(type="pil"),
52
+ gr.Number(label="Height (cm)"),
53
+ gr.Number(label="Width (cm)")
54
+ ],
55
+ outputs=gr.Image(),
56
+ title="Automatic Dimension Overlay Tool",
57
+ description="Upload an image → enter real dimensions → AI adds dimension graphics automatically."
58
+ )
59
+
60
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ opencv-python-headless
4
+ numpy
5
+ Pillow
6
+ gradio