Downloads · 30 days
7
12% of all-time downloads
omasayeddd/egyptian-license-plate-detector
egyptian-license-plate-detector is a machine learning model from omasayeddd. Use it for the machine learning task on the model card, and read the license before you ship it in a product. The card lists the license as mit.
This is a YOLOv8n model trained to detect Egyptian license plates, converted to ONNX format.
Downloads · 30 days
7
12% of all-time downloads
All-time downloads
57
Public
Repo size
18.3 MB
Likes
0
Public
Click a slice to open those files.
.pt18.3 MB · 100%
From the Hugging Face model README
This is a YOLOv8n model trained to detect Egyptian license plates, converted to ONNX format.
Model Details:
Usage: This model can be used for real-time detection of Egyptian license plates in images or video streams. It is intended to be part of a larger system that includes an OCR component for reading the plate characters.
Files:
best.onnx: The ONNX converted YOLOv8n model.config.json: Configuration file with model metadata and labels.Example Python Usage (with onnxruntime and easyocr for OCR):
import onnxruntime as ort
import numpy as np
import cv2
import easyocr
def preprocess_image(image_path, img_size=(640, 640)):
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_resized = cv2.resize(img, img_size)
img_normalized = img_resized.astype(np.float32) / 255.0
img_transposed = np.transpose(img_normalized, (2, 0, 1)) # HWC to CHW
img_batch = np.expand_dims(img_transposed, axis=0) # Add batch dimension
return img, img_batch
def postprocess_output(output, original_img_shape, img_size=(640, 640), conf_threshold=0.25, iou_threshold=0.7):
# output format is (batch_size, 5 + num_classes, num_boxes)
predictions = np.squeeze(output).T # Transpose to (num_boxes, 5 + num_classes)
# Filter out low confidence detections
scores = np.max(predictions[:, 4:], axis=1)
predictions = predictions[scores > conf_threshold]
scores = scores[scores > conf_threshold]
if len(predictions) == 0:
return []
# Get class IDs and bounding boxes
class_ids = np.argmax(predictions[:, 4:], axis=1)
boxes = predictions[:, :4]
# Convert boxes from normalized YOLO format to pixel coordinates
# x_center, y_center, width, height
x_center, y_center, width, height = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
x1 = (x_center - width / 2) * img_size[0]
y1 = (y_center - height / 2) * img_size[1]
x2 = (x_center + width / 2) * img_size[0]
y2 = (y_center + height / 2) * img_size[1]
# Scale bounding boxes to original image size
ratio_w = original_img_shape[1] / img_size[0]
ratio_h = original_img_shape[0] / img_size[1]
x1 *= ratio_w
y1 *= ratio_h
x2 *= ratio_w
y2 *= ratio_h
bboxes = np.column_stack([x1, y1, x2, y2]).astype(int)
# Apply Non-Maximum Suppression
indices = cv2.dnn.NMSBoxes(bboxes.tolist(), scores.tolist(), conf_threshold, iou_threshold)
if len(indices) > 0:
indices = indices.flatten()
return [{'box': bboxes[i], 'score': scores[i], 'class_id': class_ids[i]} for i in indices]
return []
# Load ONNX model
session = ort.InferenceSession("best.onnx")
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
# Initialize EasyOCR reader
reader = easyocr.Reader(['ar', 'en'], gpu=True) # Set gpu=False if no GPU available
# Example usage
image_path = "path/to/your/image.jpg"
original_img, preprocessed_img = preprocess_image(image_path)
# Run inference
outputs = session.run([output_name], {input_name: preprocessed_img})
# Post-process and get detections
detector_results = postprocess_output(outputs[0], original_img.shape)
if detector_results:
for res in detector_results:
x1, y1, x2, y2 = res['box']
plate_crop = original_img[y1:y2, x1:x2]
# OCR on the cropped plate
ocr_result = reader.readtext(plate_crop, detail=0)
plate_text = " ".join(ocr_result)
print(f"Detected plate: {plate_text} (Confidence: {res['score']:.2f})")
# Visualize (optional)
img_with_box = original_img.copy()
cv2.rectangle(img_with_box, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img_with_box, plate_text, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# plt.imshow(img_with_box)
# plt.title(plate_text)
# plt.axis('off')
# plt.show()
else:
print("No license plate detected.")