ocr / OcrApp /model_check.py
sanket1234's picture
Upload 174 files
5648283 verified
Raw History Blame Contribute Delete
5.05 kB
from ultralytics import YOLO
import cv2 as cv
import numpy as np
from ocr_formbase.settings import BASE_DIR
import json
from PIL import Image
from .static_paths import *
import math
import os
# Load a pretrained YOLOv8n model
def Predict_model(image_name,model_name):
try:
model = YOLO(model_name)
# Define path to the image file
source = f'{BASE_DIR}/media/{image_name}'
# hide_conf = True
img_narrey = cv.imread(source)
# Getting a Json co-ordinates and data
results = model.predict(img_narrey,conf=0.10,iou=0.1,agnostic_nms=True)[0]
data_list = results.tojson()
data = json.loads(data_list)
Total_data = []
for val in data:
label_name = val['name']
value = val['box']
confidence_score = val['confidence']
# print(value)
text_data = cropping_image(source,value)
Total_data.append([label_name,text_data[0],confidence_score])
for i in data:
if i["confidence"]>0.02:
# print((i["box"]['x2'], i["box"]['y2']))
text_x, text_y = int(i["box"]['x1']), int(i["box"]['y1']) - 10
cv.rectangle(img_narrey, (int(i["box"]['x1']), int(i["box"]['y1'])), (int(i["box"]['x2']), int(i["box"]['y2'])), (0, 0,255), 2)
# print(data[0],'---------->>---------')
# for i in data:
# print(i['name'],": ",i["confidence"])
# if i["confidence"]>0.02:
# res = results.plot(line_width =1)
# res = res[:,:,::-1]
# img = Image.fromarray(res)
# img = img.save("abc.jpg")
# for result in res:
# boxes = result.boxes.cpu().numpy() # get boxes on cpu in numpy
# for box in boxes: # iterate boxes
# r = box.xyxy[0].astype(int) # get corner points as int
# print(r,'--------------------------') # print boxes
# cv.rectangle(img, r[:2], r[2:], (0,255,0), 2) # draw boxes on img
# print(img_narrey,'========================================')
cv.imwrite(f"{BASE_DIR}/media/predict_images/{image_name}",img_narrey)
# os.remove(source)
return (f'predict_images/{image_name}',Total_data)
except Exception as e:
print(e)
Total_data = [['Image is not selected as per selected model...']]
return (f'predict_images/{image_name}',Total_data)
def cropping_image(source,value):
# img_narrey = cv.imread(source,0)
img_obj = Image.open(source)
left = math.floor(value['x1'])
top = math.floor(value['y1'])
width = math.floor(value['x2'])
height = math.floor(value['y2'])
# for idx, text_region in enumerate(text_regions):
# x1, y1, x2, y2 = text_region
# Create a blank white image with adjusted coordinates
blank_image = Image.new('RGB', (width - left + 7, height - top + 10), (255, 255, 255))
# Paste the cropped region onto the blank image
cropped_image_obj = img_obj.crop((left, top, width, height))
# cropped_image_arrey = img_narrey[top:height, left:width]
blank_image.paste(cropped_image_obj, (2, 5))
bg_added_arrey = np.array(blank_image)
cv.imwrite(f"{BASE_DIR}/media/crop-images/{left+top}_1.jpg",bg_added_arrey)
text_data = data_extraction(bg_added_arrey,left+top)
return text_data,
def data_extraction(bg_added_arrey,name):
height,width = bg_added_arrey.shape[:2]
resized = cv.resize(bg_added_arrey, (width*5,height*5), interpolation=cv.INTER_LANCZOS4)
gray_resized = cv.cvtColor(resized, cv.COLOR_BGR2GRAY)
# result1 = cv.dilate(img,kernel=kernel,iterations=2)
ret, thresh1 = cv.threshold(gray_resized, 255, 255, cv.THRESH_OTSU)
kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
sharpened = cv.filter2D(thresh1, -2, kernel)
# Apply erosion
kernel_erosion = np.ones((5, 5), np.uint8)
eroded = cv.erode(sharpened, kernel_erosion, iterations=1)
# Apply dilation
kernel_dilation = np.ones((3, 3), np.uint8)
dilated = cv.dilate(sharpened, kernel_dilation, iterations=0)
# Add white background
dilated_with_bg = np.ones_like(dilated) * 255
dilated_with_bg[dilated == 0] = 0
cv.imwrite(f"{BASE_DIR}/media/crop-images/{name}.jpg",dilated_with_bg)
# image = Image.fromarray(dilated_with_bg)
extracted_text = pytesseract.image_to_string(dilated_with_bg, config='--psm 6')
# reader = easyocr.Reader(['en'], gpu=False)
# extracted_text = reader.readtext(dilated_with_bg)
# extracted_text = [item[1] for item in extracted_text]
print(extracted_text)
return extracted_text