<reponame>Leoravoe/HACK-CW<filename>ML Final Applications/ML Scripts/pyteserract_open-cv_OCR_model.py
# -*- coding: utf-8 -*-
"""exp-Model 1 Tryout-Text formatted pdf- USING Pytesseract and OpenCV.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1B6rjuascUSQoI4yR2fu2E2bfXTnxdQLO
"""

import numpy as np

"""Try - 1 Model 1 """

from pdf2image import convert_from_path

pdfs = r"D:\Hackoff Mod\Machine Learning.pdf"
pages = convert_from_path(pdfs, 350)

i = 1
for page in pages:
    image_name = "Page_" + str(i) + ".jpg"  
    page.save(image_name, "JPEG")
    i = i+1

import cv2
from PIL import Image

def mark_region(image_path):
    
    im = cv2.imread(image_path)

    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (9,9), 0)
    thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,30)

    # Dilate to combine adjacent text contours
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
    dilate = cv2.dilate(thresh, kernel, iterations=4)

    # Find contours, highlight text areas, and extract ROIs
    cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]

    line_items_coordinates = []
    for c in cnts:
        area = cv2.contourArea(c)
        x,y,w,h = cv2.boundingRect(c)

        if y >= 600 and x <= 1000:
            if area > 10000:
                image = cv2.rectangle(im, (x,y), (2200, y+h), color=(255,0,255), thickness=3)
                line_items_coordinates.append([(x,y), (2200, y+h)])

        if y >= 2400 and x<= 2000:
            image = cv2.rectangle(im, (x,y), (2200, y+h), color=(255,0,255), thickness=3)
            line_items_coordinates.append([(x,y), (2200, y+h)])


    return image, line_items_coordinates

imp=r"D:\Hackoff Mod\Page_1.jpg"
image, line_items_coordinates=mark_region(imp)

import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
import matplotlib.pyplot as plt
# load the original image
image = cv2.imread('Page_1.jpg')

# get co-ordinates to crop the image
c = line_items_coordinates[1]

# cropping image img = image[y0:y1, x0:x1]
img = image   

plt.figure(figsize=(10,10))
plt.imshow(img)

# convert the image to black and white for better OCR
ret,thresh1 = cv2.threshold(img,120,255,cv2.THRESH_BINARY)

# pytesseract image to string to get results
text = str(pytesseract.image_to_string(thresh1, config='--psm 6'))





"""## Model 2 using Scanned Image"""

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
import matplotlib.pyplot as plt
from autocorrect import spell
def ocr_core(filename):
    config = ('-l eng --oem 1 --psm 3')

    """
    This function will handle the core OCR processing of images.
    """
    text = pytesseract.image_to_string(Image.open(filename),config=config)  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image
    return spell(text.replace('\n',''))

print(ocr_core("Sample-handwritten-text-input-for-OCR.jpg"))

ocr_core("1 (4).png")










Final Applications/ML Scripts/pyteserract_open-cv_OCR_model.py
# -*- coding: utf-8 -*-
"""exp-Model 1 Tryout-Text formatted pdf- USING Pytesseract and OpenCV.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1B6rjuascUSQoI4yR2fu2E2bfXTnxdQLO
"""

import numpy as np

"""Try - 1 Model 1 """

from pdf2image import convert_from_path

pdfs = r"D:\Hackoff Mod\Machine Learning.pdf"
pages = convert_from_path(pdfs, 350)

i = 1
for page in pages:
    image_name = "Page_" + str(i) + ".jpg"  
    page.save(image_name, "JPEG")
    i = i+1

import cv2
from PIL import Image

def mark_region(image_path):
    
    im = cv2.imread(image_path)

    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (9,9), 0)
    thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,30)

    # Dilate to combine adjacent text contours
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
    dilate = cv2.dilate(thresh, kernel, iterations=4)

    # Find contours, highlight text areas, and extract ROIs
    cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]

    line_items_coordinates = []
    for c in cnts:
        area = cv2.contourArea(c)
        x,y,w,h = cv2.boundingRect(c)

        if y >= 600 and x <= 1000:
            if area > 10000:
                image = cv2.rectangle(im, (x,y), (2200, y+h), color=(255,0,255), thickness=3)
                line_items_coordinates.append([(x,y), (2200, y+h)])

        if y >= 2400 and x<= 2000:
            image = cv2.rectangle(im, (x,y), (2200, y+h), color=(255,0,255), thickness=3)
            line_items_coordinates.append([(x,y), (2200, y+h)])


    return image, line_items_coordinates

imp=r"D:\Hackoff Mod\Page_1.jpg"
image, line_items_coordinates=mark_region(imp)

import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
import matplotlib.pyplot as plt
# load the original image
image = cv2.imread('Page_1.jpg')

# get co-ordinates to crop the image
c = line_items_coordinates[1]

# cropping image img = image[y0:y1, x0:x1]
img = image   

plt.figure(figsize=(10,10))
plt.imshow(img)

# convert the image to black and white for better OCR
ret,thresh1 = cv2.threshold(img,120,255,cv2.THRESH_BINARY)

# pytesseract image to string to get results
text = str(pytesseract.image_to_string(thresh1, config='--psm 6'))





"""## Model 2 using Scanned Image"""

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
import matplotlib.pyplot as plt
from autocorrect import spell
def ocr_core(filename):
    config = ('-l eng --oem 1 --psm 3')

    """
    This function will handle the core OCR processing of images.
    """
    text = pytesseract.image_to_string(Image.open(filename),config=config)  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image
    return spell(text.replace('\n',''))

print(ocr_core("Sample-handwritten-text-input-for-OCR.jpg"))

ocr_core("1 (4).png")
# -*- coding: utf-8 -*- exp-Model 1 Tryout-Text formatted pdf- USING Pytesseract and OpenCV.ipynb  Automatically generated by Colaboratory.  Original file is located at     https://colab.research.google.com/drive/1B6rjuascUSQoI4yR2fu2E2bfXTnxdQLO Try - 1 Model 1 # Dilate to combine adjacent text contours # Find contours, highlight text areas, and extract ROIs # load the original image # get co-ordinates to crop the image # cropping image img = image[y0:y1, x0:x1] # convert the image to black and white for better OCR # pytesseract image to string to get results ## Model 2 using Scanned Image This function will handle the core OCR processing of images. # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image