Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,108 +1,117 @@
|
|
1 |
from flask import Flask, request, render_template, send_file
|
2 |
from inference_sdk import InferenceHTTPClient
|
3 |
-
from PIL import Image, ImageDraw, ImageFont
|
4 |
import os
|
5 |
from collections import defaultdict
|
6 |
|
7 |
-
# Define a writable directory for saving image segments
|
8 |
-
SEGMENT_DIR = "static/segments"
|
9 |
-
|
10 |
-
# Ensure the "static/segments" directory exists
|
11 |
-
if not os.path.exists(SEGMENT_DIR):
|
12 |
-
os.makedirs(SEGMENT_DIR)
|
13 |
-
|
14 |
app = Flask(__name__)
|
15 |
|
|
|
|
|
|
|
|
|
|
|
16 |
# Securely get API key from Hugging Face Secrets
|
17 |
API_KEY = os.getenv("ROBOFLOW_API_KEY")
|
18 |
|
19 |
# Initialize the Roboflow client
|
20 |
CLIENT = InferenceHTTPClient(
|
21 |
api_url="https://detect.roboflow.com",
|
22 |
-
api_key=API_KEY
|
23 |
)
|
24 |
|
25 |
# Model settings
|
26 |
MODEL_ID = "hvacsym/5"
|
27 |
-
CONFIDENCE_THRESHOLD =
|
28 |
-
GRID_SIZE = (
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
def process_image(image_path):
|
32 |
-
"""Processes an
|
|
|
33 |
original_image = Image.open(image_path)
|
|
|
34 |
width, height = original_image.size
|
35 |
seg_w, seg_h = width // GRID_SIZE[1], height // GRID_SIZE[0]
|
36 |
-
|
37 |
-
# Create a copy of the image
|
38 |
final_image = original_image.copy()
|
39 |
draw_final = ImageDraw.Draw(final_image)
|
40 |
-
|
41 |
-
# Load font
|
42 |
-
try:
|
43 |
-
font = ImageFont.truetype("arial.ttf", 15)
|
44 |
-
except:
|
45 |
-
font = ImageFont.load_default()
|
46 |
-
|
47 |
-
# Dictionary for total counts
|
48 |
total_counts = defaultdict(int)
|
49 |
-
|
50 |
# Process each segment
|
51 |
for row in range(GRID_SIZE[0]):
|
52 |
for col in range(GRID_SIZE[1]):
|
53 |
x1, y1 = col * seg_w, row * seg_h
|
54 |
x2, y2 = (col + 1) * seg_w, (row + 1) * seg_h
|
55 |
-
|
56 |
segment = original_image.crop((x1, y1, x2, y2))
|
57 |
-
segment_path =
|
|
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
# Run inference
|
62 |
result = CLIENT.infer(segment_path, model_id=MODEL_ID)
|
|
|
|
|
63 |
filtered_predictions = [
|
64 |
pred for pred in result["predictions"] if pred["confidence"] * 100 >= CONFIDENCE_THRESHOLD
|
65 |
]
|
66 |
-
|
67 |
-
# Draw bounding boxes and
|
68 |
for obj in filtered_predictions:
|
69 |
-
sx, sy, sw, sh = obj["x"], obj["y"], obj["width"], obj["height"]
|
70 |
class_name = obj["class"]
|
71 |
-
confidence = obj["confidence"]
|
72 |
total_counts[class_name] += 1
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
x_max, y_max = x1 + (sx + sw // 2), y1 + (sy + sh // 2)
|
77 |
-
|
78 |
# Draw bounding box
|
79 |
-
draw_final.rectangle([x_min, y_min, x_max, y_max], outline=
|
80 |
-
|
81 |
-
# Draw label
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
final_image.save(final_image_path)
|
88 |
-
|
89 |
return final_image_path, total_counts
|
90 |
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
@app.route("/", methods=["GET", "POST"])
|
95 |
def index():
|
96 |
if request.method == "POST":
|
97 |
image_file = request.files["image"]
|
98 |
if image_file:
|
99 |
-
#
|
100 |
-
|
101 |
-
os.makedirs(static_dir, exist_ok=True) # ✅ Create if it doesn't exist
|
102 |
|
103 |
-
image_path = os.path.join(
|
104 |
-
|
105 |
-
image_file.save(image_path) # ✅ Save file without modifying permissions
|
106 |
|
107 |
# Process image
|
108 |
final_image_path, total_counts = process_image(image_path)
|
@@ -111,6 +120,5 @@ def index():
|
|
111 |
|
112 |
return render_template("index.html", final_image=None, counts=None)
|
113 |
|
114 |
-
|
115 |
if __name__ == "__main__":
|
116 |
app.run(host="0.0.0.0", port=7860)
|
|
|
1 |
from flask import Flask, request, render_template, send_file
|
2 |
from inference_sdk import InferenceHTTPClient
|
3 |
+
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
|
4 |
import os
|
5 |
from collections import defaultdict
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
app = Flask(__name__)
|
8 |
|
9 |
+
# Ensure the "static/processed" directory exists for output images
|
10 |
+
PROCESSED_DIR = "static/processed"
|
11 |
+
if not os.path.exists(PROCESSED_DIR):
|
12 |
+
os.makedirs(PROCESSED_DIR, exist_ok=True)
|
13 |
+
|
14 |
# Securely get API key from Hugging Face Secrets
|
15 |
API_KEY = os.getenv("ROBOFLOW_API_KEY")
|
16 |
|
17 |
# Initialize the Roboflow client
|
18 |
CLIENT = InferenceHTTPClient(
|
19 |
api_url="https://detect.roboflow.com",
|
20 |
+
api_key=API_KEY # Secure way to use API key
|
21 |
)
|
22 |
|
23 |
# Model settings
|
24 |
MODEL_ID = "hvacsym/5"
|
25 |
+
CONFIDENCE_THRESHOLD = 0.3 # Confidence threshold for filtering predictions
|
26 |
+
GRID_SIZE = (3, 3) # 3x3 segmentation
|
27 |
+
|
28 |
+
# Colors for bounding boxes
|
29 |
+
RED = (255, 0, 0)
|
30 |
+
GREEN = (0, 255, 0)
|
31 |
+
WHITE = (255, 255, 255)
|
32 |
+
BLACK = (0, 0, 0)
|
33 |
+
|
34 |
+
# Load font for labeling
|
35 |
+
try:
|
36 |
+
font = ImageFont.truetype("arial.ttf", 14)
|
37 |
+
except:
|
38 |
+
font = ImageFont.load_default()
|
39 |
+
|
40 |
+
def enhance_image(image):
|
41 |
+
"""Enhance image by adjusting brightness and contrast."""
|
42 |
+
if image.mode != 'L':
|
43 |
+
image = image.convert('L')
|
44 |
+
brightness = ImageEnhance.Brightness(image)
|
45 |
+
image = brightness.enhance(1.3)
|
46 |
+
contrast = ImageEnhance.Contrast(image)
|
47 |
+
image = contrast.enhance(1.2)
|
48 |
+
return image.convert('RGB') # Convert back to RGB for colored boxes
|
49 |
|
50 |
def process_image(image_path):
|
51 |
+
"""Processes an image by running inference and drawing bounding boxes."""
|
52 |
+
# Load and enhance the original image
|
53 |
original_image = Image.open(image_path)
|
54 |
+
original_image = enhance_image(original_image)
|
55 |
width, height = original_image.size
|
56 |
seg_w, seg_h = width // GRID_SIZE[1], height // GRID_SIZE[0]
|
57 |
+
|
58 |
+
# Create a copy of the full image to draw bounding boxes
|
59 |
final_image = original_image.copy()
|
60 |
draw_final = ImageDraw.Draw(final_image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
total_counts = defaultdict(int)
|
62 |
+
|
63 |
# Process each segment
|
64 |
for row in range(GRID_SIZE[0]):
|
65 |
for col in range(GRID_SIZE[1]):
|
66 |
x1, y1 = col * seg_w, row * seg_h
|
67 |
x2, y2 = (col + 1) * seg_w, (row + 1) * seg_h
|
|
|
68 |
segment = original_image.crop((x1, y1, x2, y2))
|
69 |
+
segment_path = f"static/processed/segment_{row}_{col}.png"
|
70 |
+
segment.save(segment_path)
|
71 |
|
72 |
+
# Run inference on the segment
|
|
|
|
|
73 |
result = CLIENT.infer(segment_path, model_id=MODEL_ID)
|
74 |
+
|
75 |
+
# Filter predictions based on confidence
|
76 |
filtered_predictions = [
|
77 |
pred for pred in result["predictions"] if pred["confidence"] * 100 >= CONFIDENCE_THRESHOLD
|
78 |
]
|
79 |
+
|
80 |
+
# Draw bounding boxes and count labels
|
81 |
for obj in filtered_predictions:
|
|
|
82 |
class_name = obj["class"]
|
|
|
83 |
total_counts[class_name] += 1
|
84 |
+
x_min, y_min = x1 + obj["x"] - obj["width"] // 2, y1 + obj["y"] - obj["height"] // 2
|
85 |
+
x_max, y_max = x1 + obj["x"] + obj["width"] // 2, y1 + obj["y"] + obj["height"] // 2
|
86 |
+
|
|
|
|
|
87 |
# Draw bounding box
|
88 |
+
draw_final.rectangle([x_min, y_min, x_max, y_max], outline=GREEN, width=2)
|
89 |
+
|
90 |
+
# Draw extended label above the bounding box
|
91 |
+
text_size = draw_final.textbbox((0, 0), class_name, font=font)
|
92 |
+
text_width = text_size[2] - text_size[0]
|
93 |
+
text_height = text_size[3] - text_size[1]
|
94 |
+
text_x = x_min
|
95 |
+
text_y = y_min - text_height - 5 if y_min - text_height - 5 > 0 else y_max + 5
|
96 |
+
|
97 |
+
draw_final.rectangle([text_x, text_y, text_x + text_width + 6, text_y + text_height + 2], fill=BLACK)
|
98 |
+
draw_final.text((text_x + 3, text_y), class_name, fill=WHITE, font=font)
|
99 |
+
|
100 |
+
# Save the final processed image
|
101 |
+
final_image_path = "static/processed/processed_image.png"
|
102 |
final_image.save(final_image_path)
|
|
|
103 |
return final_image_path, total_counts
|
104 |
|
|
|
|
|
|
|
105 |
@app.route("/", methods=["GET", "POST"])
|
106 |
def index():
|
107 |
if request.method == "POST":
|
108 |
image_file = request.files["image"]
|
109 |
if image_file:
|
110 |
+
# Ensure static/processed directory exists
|
111 |
+
os.makedirs(PROCESSED_DIR, exist_ok=True)
|
|
|
112 |
|
113 |
+
image_path = os.path.join(PROCESSED_DIR, "uploaded_image.png")
|
114 |
+
image_file.save(image_path)
|
|
|
115 |
|
116 |
# Process image
|
117 |
final_image_path, total_counts = process_image(image_path)
|
|
|
120 |
|
121 |
return render_template("index.html", final_image=None, counts=None)
|
122 |
|
|
|
123 |
if __name__ == "__main__":
|
124 |
app.run(host="0.0.0.0", port=7860)
|