karthikmn commited on
Commit
4bbab2f
Β·
verified Β·
1 Parent(s): ed632b9

Create refine.py

Browse files
Files changed (1) hide show
  1. refine.py +163 -0
refine.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from ultralytics import YOLO
3
+ import cv2
4
+ import easyocr
5
+ import numpy as np
6
+ import pandas as pd
7
+ from PIL import Image
8
+ import tempfile
9
+
10
+ # Upload image
11
+ @st.cache_resource
12
+ def load_model():
13
+ model = YOLO('yolo11n-custom.pt')
14
+ model.fuse()
15
+ return model
16
+
17
+ model = load_model()
18
+
19
+ reader = easyocr.Reader(['en'])
20
+ def apply_filters(image, noise, sharpen, grayscale, threshold, edges, invert, auto, blur, contrast, brightness, scale, denoise, hist_eq, gamma, clahe):
21
+ img = np.array(image)
22
+
23
+ # Auto Enhancement
24
+ if auto:
25
+ lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
26
+ l, a, b = cv2.split(lab)
27
+ clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
28
+ l = clahe.apply(l)
29
+ img = cv2.merge((l, a, b))
30
+ img = cv2.cvtColor(img, cv2.COLOR_LAB2RGB)
31
+
32
+
33
+ # Scaling
34
+ if scale != 1.0:
35
+ height, width = img.shape[:2]
36
+ img = cv2.resize(img, (int(width * scale), int(height * scale)))
37
+
38
+ # Noise Reduction (Bilateral Filtering)
39
+ if noise:
40
+ img = cv2.bilateralFilter(img, 9, 75, 75)
41
+
42
+ # Noise Reduction (Non-Local Means)
43
+ if denoise:
44
+ img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
45
+
46
+ # Sharpening
47
+ if sharpen:
48
+ kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
49
+ img = cv2.filter2D(img, -1, kernel)
50
+
51
+ # Convert to Grayscale
52
+ if grayscale or threshold or hist_eq or clahe:
53
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
54
+
55
+ # Histogram Equalization
56
+ if hist_eq:
57
+ img = cv2.equalizeHist(img)
58
+
59
+ # CLAHE (Contrast Limited Adaptive Histogram Equalization)
60
+ if clahe:
61
+ clahe_filter = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
62
+ img = clahe_filter.apply(img)
63
+
64
+ # Adaptive Thresholding
65
+ if threshold:
66
+ img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
67
+
68
+ # Edge Detection
69
+ if edges:
70
+ img = cv2.Canny(img, 100, 200)
71
+
72
+ # Invert Colors
73
+ if invert:
74
+ img = cv2.bitwise_not(img)
75
+
76
+ # Blur
77
+ if gamma != 1.0:
78
+ inv_gamma = 1.0 / gamma
79
+ table = np.array([(i / 255.0) ** inv_gamma * 255 for i in np.arange(0, 256)]).astype("uint8")
80
+ img = cv2.LUT(img, table)
81
+
82
+ # Blur
83
+ if blur:
84
+ img = cv2.GaussianBlur(img, (2*blur + 1, 2*blur + 1), 0)
85
+
86
+ # Contrast & Brightness
87
+ if contrast != 1.0 or brightness != 0:
88
+ img = cv2.convertScaleAbs(img, alpha=contrast, beta=brightness)
89
+
90
+ return img
91
+
92
+ st.title("πŸ–ΌοΈ Refine Image for Detection")
93
+ st.write("Enhance the license plate image for better recognition.")
94
+
95
+ uploaded_file = st.file_uploader("πŸ“€ Upload an image", type=["jpg", "png", "jpeg"])
96
+
97
+ if uploaded_file:
98
+ # Read image
99
+ img = Image.open(uploaded_file)
100
+ img = np.array(img)
101
+
102
+ # Detect license plates
103
+ st.write("πŸ” Detecting license plates...")
104
+ results = model.predict(img, conf=0.15, iou=0.3, classes=[0])
105
+ plates = results[0].boxes.xyxy if len(results) > 0 else []
106
+
107
+ if len(plates) == 0:
108
+ st.error("❌ No license plates detected. Try another image.")
109
+ else:
110
+ st.write("πŸ“Œ **Select a License Plate by Clicking Below**")
111
+
112
+ # Show detected plates in a grid
113
+ if "selected_plate_index" not in st.session_state:
114
+ st.session_state.selected_plate_index = 0
115
+
116
+ selected_plate_index = st.session_state.get("selected_plate_index", 0)
117
+ cols = st.columns(len(plates)) # Create dynamic columns
118
+
119
+ for i, (x1, y1, x2, y2) in enumerate(plates):
120
+ plate_img = img[int(y1):int(y2), int(x1):int(x2)]
121
+ plate_img = Image.fromarray(plate_img)
122
+
123
+ with cols[i]: # Place each image in a column
124
+ st.image(plate_img, caption=f"Plate {i+1}", use_container_width =True)
125
+ if st.button(f"Select Plate {i+1}", key=f"plate_{i}"):
126
+ st.session_state["selected_plate_index"] = i
127
+
128
+ # Get the selected plate
129
+ selected_index = st.session_state["selected_plate_index"]
130
+ x1, y1, x2, y2 = map(int, plates[selected_index])
131
+ cropped_plate = img[y1:y2, x1:x2]
132
+ refined_img = cropped_plate.copy()
133
+
134
+ # Sidebar for enhancements
135
+ st.sidebar.header("πŸ”§ Enhancement Options")
136
+ blur = st.sidebar.slider("πŸ”Ή Blur", 0, 10, 0)
137
+ contrast = st.sidebar.slider("πŸ”Ή Contrast", 0.5, 2.0, 1.0)
138
+ brightness = st.sidebar.slider("πŸ”Ή Brightness", 0.5, 2.0, 1.0)
139
+ gamma = st.sidebar.slider("Gamma Correction", 0.1, 3.0, 1.0, 0.1)
140
+ scale = st.sidebar.slider("πŸ”Ή Scale", 1.0, 10.0, 5.0)
141
+ noise = st.sidebar.checkbox("Noise Reduction (Bilateral)")
142
+ denoise = st.sidebar.checkbox("Denoise (Non-Local Means)")
143
+ sharpen = st.sidebar.checkbox("Sharpening")
144
+ hist_eq = st.sidebar.checkbox("Histogram Equalization")
145
+ clahe = st.sidebar.checkbox("CLAHE (Advanced Contrast)")
146
+ grayscale = st.sidebar.checkbox("Grayscale Conversion")
147
+ threshold = st.sidebar.checkbox("Adaptive Thresholding")
148
+ edges = st.sidebar.checkbox("Edge Detection")
149
+ invert = st.sidebar.checkbox("Invert Colors")
150
+ auto = st.sidebar.checkbox("Auto Enhancement")
151
+
152
+ refined_img = apply_filters(refined_img, noise, sharpen, grayscale, threshold, edges, invert, auto, blur, contrast, brightness, scale, denoise, hist_eq, gamma, clahe)
153
+
154
+ st.image(refined_img, caption="Refined License Plate", use_container_width=True)
155
+
156
+ if st.button("πŸ“– Detect License Plate Text"):
157
+ with st.spinner("πŸ”Ž Reading text..."):
158
+ ocr_result = reader.readtext(np.array(refined_img), detail=0, allowlist="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-")
159
+ plate_text = " ".join(ocr_result).upper() if ocr_result else "❌ No text detected."
160
+
161
+ # Show detected text
162
+ st.subheader("πŸ“œ Detected License Plate:")
163
+ st.code(plate_text, language="plaintext")