Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
|
2 |
import cv2 as cv
|
3 |
import numpy as np
|
4 |
import gradio as gr
|
@@ -7,7 +6,7 @@ from huggingface_hub import hf_hub_download
|
|
7 |
|
8 |
# Download ONNX model from Hugging Face
|
9 |
model_path = hf_hub_download(repo_id="opencv/image_classification_mobilenet", filename="image_classification_mobilenetv1_2022apr.onnx")
|
10 |
-
top_k = 10
|
11 |
backend_id = cv.dnn.DNN_BACKEND_OPENCV
|
12 |
target_id = cv.dnn.DNN_TARGET_CPU
|
13 |
|
@@ -18,42 +17,58 @@ def add_hsv_noise(image, hue_noise=0, saturation_noise=0, value_noise=0):
|
|
18 |
"""Add HSV noise to an image"""
|
19 |
if image is None:
|
20 |
return None
|
21 |
-
|
22 |
# Convert BGR to HSV (OpenCV uses BGR by default)
|
23 |
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV).astype(np.float32)
|
24 |
-
|
25 |
# Add noise to each channel
|
26 |
hsv[:, :, 0] = np.clip(hsv[:, :, 0] + hue_noise, 0, 179) # Hue: 0-179
|
27 |
hsv[:, :, 1] = np.clip(hsv[:, :, 1] + saturation_noise, 0, 255) # Saturation: 0-255
|
28 |
hsv[:, :, 2] = np.clip(hsv[:, :, 2] + value_noise, 0, 255) # Value: 0-255
|
29 |
-
|
30 |
# Convert back to BGR
|
31 |
bgr = cv.cvtColor(hsv.astype(np.uint8), cv.COLOR_HSV2BGR)
|
32 |
-
|
33 |
return bgr
|
34 |
|
35 |
def classify_image_with_noise(input_image, top_n, hue_noise, saturation_noise, value_noise):
|
36 |
-
"""Classify image with HSV noise applied"""
|
37 |
if input_image is None:
|
38 |
return None, "Please upload an image first."
|
39 |
-
|
40 |
# Apply HSV noise
|
41 |
noisy_image = add_hsv_noise(input_image, hue_noise, saturation_noise, value_noise)
|
42 |
-
|
43 |
# Resize and crop as in original code
|
44 |
image = cv.resize(noisy_image, (256, 256))
|
45 |
image = image[16:240, 16:240, :]
|
46 |
-
|
47 |
-
#
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
# Convert BGR to RGB for display in Gradio
|
55 |
display_image = cv.cvtColor(noisy_image, cv.COLOR_BGR2RGB)
|
56 |
-
|
57 |
return display_image, result_str
|
58 |
|
59 |
def clear_output_on_change(img):
|
@@ -73,42 +88,32 @@ with gr.Blocks(css='''.example * {
|
|
73 |
|
74 |
with gr.Row():
|
75 |
with gr.Column():
|
76 |
-
# Input controls
|
77 |
image_input = gr.Image(type="numpy", label="Upload Image")
|
78 |
-
|
79 |
gr.Markdown("### Classification Settings")
|
80 |
top_n = gr.Slider(minimum=1, maximum=10, value=5, step=1, label="Top N Classes")
|
81 |
-
|
82 |
gr.Markdown("### HSV Noise Controls")
|
83 |
hue_noise = gr.Slider(minimum=-50, maximum=50, value=0, step=1, label="Hue Noise (-50 to 50)")
|
84 |
saturation_noise = gr.Slider(minimum=-100, maximum=100, value=0, step=5, label="Saturation Noise (-100 to 100)")
|
85 |
value_noise = gr.Slider(minimum=-100, maximum=100, value=0, step=5, label="Value/Brightness Noise (-100 to 100)")
|
86 |
-
|
87 |
with gr.Column():
|
88 |
-
# Output displays
|
89 |
noisy_image_output = gr.Image(label="Image with Noise Applied")
|
90 |
-
output_box = gr.Textbox(label="Top Predictions", lines=10, max_lines=15)
|
91 |
|
92 |
-
# Clear outputs when new image is uploaded
|
93 |
image_input.change(fn=clear_output_on_change, inputs=image_input, outputs=[output_box, noisy_image_output])
|
94 |
|
95 |
with gr.Row():
|
96 |
submit_btn = gr.Button("Submit", variant="primary")
|
97 |
clear_btn = gr.Button("Clear")
|
98 |
|
99 |
-
# Set up real-time updates for sliders
|
100 |
inputs = [image_input, top_n, hue_noise, saturation_noise, value_noise]
|
101 |
outputs = [noisy_image_output, output_box]
|
102 |
-
|
103 |
-
# Update predictions when sliders change (real-time)
|
104 |
for slider in [top_n, hue_noise, saturation_noise, value_noise]:
|
105 |
-
slider.change(
|
106 |
-
|
107 |
-
inputs=inputs,
|
108 |
-
outputs=outputs
|
109 |
-
)
|
110 |
-
|
111 |
-
# Manual submit button
|
112 |
submit_btn.click(fn=classify_image_with_noise, inputs=inputs, outputs=outputs)
|
113 |
clear_btn.click(fn=clear_all, outputs=[image_input, noisy_image_output, output_box])
|
114 |
|
@@ -123,4 +128,4 @@ with gr.Blocks(css='''.example * {
|
|
123 |
)
|
124 |
|
125 |
if __name__ == "__main__":
|
126 |
-
demo.launch()
|
|
|
|
|
1 |
import cv2 as cv
|
2 |
import numpy as np
|
3 |
import gradio as gr
|
|
|
6 |
|
7 |
# Download ONNX model from Hugging Face
|
8 |
model_path = hf_hub_download(repo_id="opencv/image_classification_mobilenet", filename="image_classification_mobilenetv1_2022apr.onnx")
|
9 |
+
top_k = 10
|
10 |
backend_id = cv.dnn.DNN_BACKEND_OPENCV
|
11 |
target_id = cv.dnn.DNN_TARGET_CPU
|
12 |
|
|
|
17 |
"""Add HSV noise to an image"""
|
18 |
if image is None:
|
19 |
return None
|
20 |
+
|
21 |
# Convert BGR to HSV (OpenCV uses BGR by default)
|
22 |
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV).astype(np.float32)
|
23 |
+
|
24 |
# Add noise to each channel
|
25 |
hsv[:, :, 0] = np.clip(hsv[:, :, 0] + hue_noise, 0, 179) # Hue: 0-179
|
26 |
hsv[:, :, 1] = np.clip(hsv[:, :, 1] + saturation_noise, 0, 255) # Saturation: 0-255
|
27 |
hsv[:, :, 2] = np.clip(hsv[:, :, 2] + value_noise, 0, 255) # Value: 0-255
|
28 |
+
|
29 |
# Convert back to BGR
|
30 |
bgr = cv.cvtColor(hsv.astype(np.uint8), cv.COLOR_HSV2BGR)
|
31 |
+
|
32 |
return bgr
|
33 |
|
34 |
def classify_image_with_noise(input_image, top_n, hue_noise, saturation_noise, value_noise):
|
35 |
+
"""Classify image with HSV noise applied and return exact confidence scores"""
|
36 |
if input_image is None:
|
37 |
return None, "Please upload an image first."
|
38 |
+
|
39 |
# Apply HSV noise
|
40 |
noisy_image = add_hsv_noise(input_image, hue_noise, saturation_noise, value_noise)
|
41 |
+
|
42 |
# Resize and crop as in original code
|
43 |
image = cv.resize(noisy_image, (256, 256))
|
44 |
image = image[16:240, 16:240, :]
|
45 |
+
|
46 |
+
# Preprocess manually to get raw scores
|
47 |
+
input_blob = model._preprocess(image)
|
48 |
+
|
49 |
+
# Forward pass
|
50 |
+
model.model.setInput(input_blob, model.input_names)
|
51 |
+
output_blob = model.model.forward(model.output_names)
|
52 |
+
|
53 |
+
# Get raw probabilities (apply softmax if needed)
|
54 |
+
raw_scores = output_blob[0] # First batch
|
55 |
+
probabilities = np.exp(raw_scores) / np.sum(np.exp(raw_scores)) # Softmax
|
56 |
+
|
57 |
+
# Get top N indices and their scores
|
58 |
+
top_indices = np.argsort(probabilities)[::-1][:top_n]
|
59 |
+
|
60 |
+
# Format results with exact confidence scores
|
61 |
+
result_lines = []
|
62 |
+
for i, idx in enumerate(top_indices):
|
63 |
+
label = model._labels[idx]
|
64 |
+
confidence = probabilities[idx]
|
65 |
+
result_lines.append(f"{i+1}. {label}: {confidence:.6f} ({confidence*100:.4f}%)")
|
66 |
+
|
67 |
+
result_str = "\n".join(result_lines)
|
68 |
+
|
69 |
# Convert BGR to RGB for display in Gradio
|
70 |
display_image = cv.cvtColor(noisy_image, cv.COLOR_BGR2RGB)
|
71 |
+
|
72 |
return display_image, result_str
|
73 |
|
74 |
def clear_output_on_change(img):
|
|
|
88 |
|
89 |
with gr.Row():
|
90 |
with gr.Column():
|
|
|
91 |
image_input = gr.Image(type="numpy", label="Upload Image")
|
92 |
+
|
93 |
gr.Markdown("### Classification Settings")
|
94 |
top_n = gr.Slider(minimum=1, maximum=10, value=5, step=1, label="Top N Classes")
|
95 |
+
|
96 |
gr.Markdown("### HSV Noise Controls")
|
97 |
hue_noise = gr.Slider(minimum=-50, maximum=50, value=0, step=1, label="Hue Noise (-50 to 50)")
|
98 |
saturation_noise = gr.Slider(minimum=-100, maximum=100, value=0, step=5, label="Saturation Noise (-100 to 100)")
|
99 |
value_noise = gr.Slider(minimum=-100, maximum=100, value=0, step=5, label="Value/Brightness Noise (-100 to 100)")
|
100 |
+
|
101 |
with gr.Column():
|
|
|
102 |
noisy_image_output = gr.Image(label="Image with Noise Applied")
|
103 |
+
output_box = gr.Textbox(label="Top Predictions with Confidence Scores", lines=10, max_lines=15)
|
104 |
|
|
|
105 |
image_input.change(fn=clear_output_on_change, inputs=image_input, outputs=[output_box, noisy_image_output])
|
106 |
|
107 |
with gr.Row():
|
108 |
submit_btn = gr.Button("Submit", variant="primary")
|
109 |
clear_btn = gr.Button("Clear")
|
110 |
|
|
|
111 |
inputs = [image_input, top_n, hue_noise, saturation_noise, value_noise]
|
112 |
outputs = [noisy_image_output, output_box]
|
113 |
+
|
|
|
114 |
for slider in [top_n, hue_noise, saturation_noise, value_noise]:
|
115 |
+
slider.change(fn=classify_image_with_noise, inputs=inputs, outputs=outputs)
|
116 |
+
|
|
|
|
|
|
|
|
|
|
|
117 |
submit_btn.click(fn=classify_image_with_noise, inputs=inputs, outputs=outputs)
|
118 |
clear_btn.click(fn=clear_all, outputs=[image_input, noisy_image_output, output_box])
|
119 |
|
|
|
128 |
)
|
129 |
|
130 |
if __name__ == "__main__":
|
131 |
+
demo.launch()
|