MalekCode03 commited on
Commit
a0a2522
·
verified ·
1 Parent(s): ad8cdc0

Upload 5 files

Browse files
Files changed (5) hide show
  1. .dockerignore +8 -0
  2. Dockerfile +34 -0
  3. alpr_module.py +72 -0
  4. main.py +38 -0
  5. requirements.txt +6 -0
.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ *.db
6
+ .env
7
+ .vscode/
8
+ .idea/
Dockerfile ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base image with Python
2
+ FROM python:3.10-slim
3
+
4
+ # Set environment variables
5
+ ENV PYTHONDONTWRITEBYTECODE=1
6
+ ENV PYTHONUNBUFFERED=1
7
+ ENV KMP_DUPLICATE_LIB_OK=TRUE
8
+
9
+ # Set working directory
10
+ WORKDIR /app
11
+
12
+ # Install system dependencies
13
+ RUN apt-get update && apt-get install -y \
14
+ build-essential \
15
+ libgl1-mesa-glx \
16
+ libglib2.0-0 \
17
+ libsm6 \
18
+ libxrender1 \
19
+ libxext6 \
20
+ && rm -rf /var/lib/apt/lists/*
21
+
22
+ # Copy requirements and install Python packages
23
+ COPY requirements.txt .
24
+ RUN pip install --upgrade pip
25
+ RUN pip install --no-cache-dir -r requirements.txt
26
+
27
+ # Copy the app code
28
+ COPY . .
29
+
30
+ # Expose FastAPI default port
31
+ EXPOSE 8000
32
+
33
+ # Run the FastAPI app with uvicorn
34
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
alpr_module.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import easyocr
4
+ from inference_sdk import InferenceHTTPClient
5
+
6
+ # تعريف العميل
7
+ CLIENT = InferenceHTTPClient(
8
+ api_url="https://serverless.roboflow.com",
9
+ api_key="4m9tZRxBfEK8C4no7zsZ"
10
+ )
11
+ reader = easyocr.Reader(['en'])
12
+ def detect_license_plate(image_path, model_id="license-plate-recognition-rxg4e/11"):
13
+ """إجراء التنبؤ باستخدام نموذج Roboflow"""
14
+ result = CLIENT.infer(image_path, model_id=model_id)
15
+ return result
16
+
17
+ def extract_plate_from_image(image_path, predictions):
18
+ """استخلاص صورة اللوحة من الصورة الكاملة بناءً على التنبؤات"""
19
+ image = cv2.imread(image_path)
20
+ max_confidence = 0
21
+ best_coords = None
22
+
23
+ for prediction in predictions['predictions']:
24
+ confidence = prediction['confidence']
25
+ if confidence > max_confidence:
26
+ max_confidence = confidence
27
+ x = int(prediction['x'])
28
+ y = int(prediction['y'])
29
+ width = int(prediction['width'])
30
+ height = int(prediction['height'])
31
+ x1 = int(x - width / 2)
32
+ y1 = int(y - height / 2)
33
+ x2 = int(x + width / 2)
34
+ y2 = int(y + height / 2)
35
+ best_coords = (x1, y1, x2, y2)
36
+
37
+ if not best_coords:
38
+ return None # لم يتم الكشف عن أي لوحة
39
+
40
+ x1, y1, x2, y2 = best_coords
41
+ polygon_points = np.array([
42
+ [x1, y1],
43
+ [x2, y1],
44
+ [x2, y2],
45
+ [x1, y2]
46
+ ], dtype=np.int32)
47
+
48
+ mask = np.zeros(image.shape[:2], dtype=np.uint8)
49
+ cv2.fillPoly(mask, [polygon_points], 255)
50
+
51
+ masked_image = cv2.bitwise_and(image, image, mask=mask)
52
+ x, y, w, h = cv2.boundingRect(polygon_points)
53
+ cropped_plate = masked_image[y:y+h, x:x+w]
54
+
55
+ return cropped_plate
56
+
57
+ def enhance_image_for_ocr(image):
58
+ """تحسين الصورة لاستخلاص النصوص باستخدام EasyOCR"""
59
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
60
+ return gray
61
+
62
+ def extract_license_number(image):
63
+ """استخراج الأرقام من صورة اللوحة"""
64
+ result = reader.readtext(image)
65
+ plate_numbers = []
66
+
67
+ for detection in result:
68
+ text = detection[1]
69
+ numbers_only = ''.join(c for c in text if c.isdigit())
70
+ if numbers_only:
71
+ plate_numbers.append(numbers_only)
72
+ return plate_numbers
main.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
3
+ from fastapi import FastAPI,UploadFile,File
4
+ from alpr_module import detect_license_plate, extract_plate_from_image, enhance_image_for_ocr, extract_license_number
5
+ import tempfile
6
+
7
+
8
+
9
+
10
+ app = FastAPI()
11
+
12
+
13
+
14
+
15
+
16
+ @app.post("/")
17
+ async def recognize_plate(file: UploadFile = File(...)):
18
+ try:
19
+ # حفظ الصورة مؤقتاً
20
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
21
+ tmp.write(await file.read())
22
+ tmp_path = tmp.name
23
+ # الخطوات
24
+ predictions = detect_license_plate(tmp_path)
25
+ plate_img = extract_plate_from_image(tmp_path, predictions)
26
+ if plate_img is None:
27
+ os.remove(tmp_path)
28
+ return JSONResponse(status_code=404, content={"error": "لم يتم اكتشاف أي لوحة"})
29
+ enhanced_img = enhance_image_for_ocr(plate_img)
30
+ numbers = extract_license_number(enhanced_img)
31
+ os.remove(tmp_path)
32
+ if numbers:
33
+ longest = max(numbers, key=len)
34
+ return {"plate_number": longest}
35
+ else:
36
+ return {"plate_number": None}
37
+ except Exception as e:
38
+ return JSONResponse(status_code=500, content={"error": str(e)})
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ opencv-python
2
+ numpy
3
+ easyocr
4
+ inference-sdk
5
+ fastapi
6
+ uvicorn