from tempfile import NamedTemporaryFile
from django.shortcuts import render, redirect
from .models import LicensePlate
from .forms import LicensePlateForm
import numpy as np
import cv2
import pytesseract
def home(request):
if request.method == 'POST':
form = LicensePlateForm(request.POST, request.FILES)
if form.is_valid():
# Save the uploaded image to a temporary file
image_file = request.FILES['image']
temp_file = NamedTemporaryFile()
for chunk in image_file.chunks():
temp_file.write(chunk)
temp_file.flush()
# Load the image and convert it to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Load the Haar cascade for detecting Russian license plates
cascade_path = 'haarcascade_russian_plate_number.xml'
cascade = cv2.CascadeClassifier(cascade_path)
# Detect the license plate in the image
license_plates = cascade.detectMultiScale(gray, 1.1, 4)
# Extract the text from the license plate using OCR
for (x, y, w, h) in license_plates:
license_plate = image[y:y+h, x:x+w]
text = pytesseract.image_to_string(license_plate)
# Save the extracted text to the database
car = LicensePlate(image=request.FILES['image'], license_plate=text)
car.save()
# Render the template with the extracted text and the uploaded image
return render(request, 'home.html', {'form': form, 'text': text, 'image': image_file})
else:
form = LicensePlateForm()
return render(request, 'home.html', {'form': form})