import easyocr as ocr #OCR import streamlit as st #Web App import numpy as np #Image Processing import torch import cv2 import pandas as pd import os import matplotlib.pyplot as plt from PIL import Image, ImageDraw, ImageFont, ImageOps #title st.title("Lector de Matrículas 🚘") #subtitle st.markdown("## Usando `YoloV5` y `EasyOCR`") #image uploader image = st.file_uploader(label="",type=['png','jpg','jpeg']) def get_optimal_font_scale(text, width): for scale in reversed(range(0, 60, 1)): textSize = cv2.getTextSize(text, fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=scale/10, thickness=1) new_width = textSize[0][0] if (new_width <= width): return scale/10 return 1 @st.cache def load_models(): reader = ocr.Reader(['es'],model_storage_directory='.') plate_detector = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt') return reader, plate_detector def detect(img, reader, plate_detector): p = 0.03 model = plate_detector results = model(img) coor = results.pandas().xyxy[0] coor = coor.astype({'xmin':'int', 'ymin':'int', 'xmax': 'int', 'ymax': 'int'}) if len(coor) == 0: img = Image.fromarray(img) I = ImageDraw.Draw(img) myFont = ImageFont.truetype('MESPREG.ttf', 200) I.text((100, 10), "No se detecta matricula", fill=(242, 190, 0), font=myFont) img = img[:, :, ::-1] return img, "No se detecta matricula" crop = img[coor["ymin"][0]-int(img.shape[1]*p):coor["ymax"][0]+int(img.shape[1]*p), coor["xmin"][0]-int(img.shape[0]*p):coor["xmax"][0]+int(img.shape[0]*p)] #Read text result = reader.readtext(crop, allowlist="BCDFGHJKLMNPQRSTVWXYZ1234567890") matricula = "" for detection in result: if detection[2] > 0.5: matricula = matricula + ' ' + detection[1] plate = matricula.split() plate.sort(key=len, reverse = True) plate = ''.join(plate)[:7].upper() plate = plate[0:4].replace("L","4") + plate[4:] img = Image.fromarray(img) I = ImageDraw.Draw(img) myFont = ImageFont.truetype('MESPREG.ttf', 300) I.text((100, 10), plate, fill=(242, 190, 0), font=myFont) img = np.array(img) img = img[:, :, ::-1] return img, plate reader, plate_detector = load_models() #load model if image is not None: input_image = Image.open(image) #read image input_image = ImageOps.exif_transpose(input_image) input_image = np.array(input_image) input_image = input_image[:, :, ::-1].copy() with st.spinner("🤖 ¡Trabajando! "): result, matricula = detect(input_image, reader, plate_detector) st.write("Matrícula:",matricula) st.image(result) else: st.write("Sube una imagen")