Blog, Pyresearch

OCR Techniques in Python Extracting Text from Images

OCR Techniques in Python: Extracting Text from Images

Optical Character Recognition (OCR) is the process of converting different types of images containing text—such as scanned documents, photographs, or even video frames—into editable and searchable data. OCR is widely used in tasks like digitizing books, automating form data entry, or recognizing text in street signs and number plates. In Python, there are several libraries, such as Tesseract and PaddleOCR, that make OCR accessible and easy to implement.

In this blog, we’ll explore how to get started with OCR in Python using these popular libraries and look at some practical applications like document scanning and number plate detection.

_______________________________________________________________________

What is OCR?

Optical Character Recognition (OCR) is a technology that allows software to “read” and interpret the text present in images. For example, it can convert a photo of a printed or handwritten document into digital text that you can edit or analyze. OCR finds practical applications in:

  • Document digitization: Converting scanned documents into editable files.
  • License plate recognition: Recognizing vehicle registration numbers.
  • Text extraction from images: Automating data entry from forms or receipts.
  • Assisting the visually impaired: Converting text from images into speech.

_______________________________________________________________________

Popular Python Libraries for OCR

1. Tesseract OCR

Tesseract is one of the most well-known open-source OCR libraries. Developed by Google, it’s capable of recognizing over 100 languages, and it works well for simple and moderately complex text extraction tasks. Tesseract is highly effective when combined with image preprocessing techniques to improve the quality of text detection.

Key Features:

  • Recognizes multiple languages.
  • Supports basic image preprocessing (e.g., thresholding, scaling).
  • Capable of detecting different fonts and text layouts.

2. PaddleOCR

PaddleOCR is another OCR library developed by PaddlePaddle, a deep learning framework. It’s particularly good for handling multi-language text, complex text layout, and text in challenging conditions (like low resolution or rotated text). It also supports a wide range of image preprocessing techniques to enhance text recognition.

Key Features:

  • State-of-the-art accuracy in text recognition.
  • Supports a wide range of languages and character sets.
  • Built-in support for text detection and recognition.

_______________________________________________________________________

Installing Tesseract and PaddleOCR

1. Installing Tesseract OCR

To use Tesseract with Python, you first need to install the Tesseract engine and the Python wrapper library pytesseract.

Steps:

  • Install Tesseract:
    • On Windows: Download and install Tesseract from here.
    • On Ubuntu: Use the following command:
sudo apt install tesseract-ocr
  • Install the Python wrapper pytesseract:
pip install pytesseract
  • Import and configure Tesseract in Python:
import pytesseract
from PIL import Image

# Set the path to your Tesseract installation
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

# Load an image and extract text
img = Image.open('sample_image.png')
text = pytesseract.image_to_string(img)
print(text)

2. Installing PaddleOCR

To use PaddleOCR, you need to install the PaddlePaddle framework and the PaddleOCR package.

Steps:

  • Install PaddleOCR and its dependencies:
pip install paddlepaddle
pip install paddleocr
  • Use PaddleOCR to extract text:
from paddleocr import PaddleOCR, draw_ocr
import cv2

# Initialize PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='en')

# Read image
img_path = 'sample_image.png'
result = ocr.ocr(img_path)

# Extract and print the detected text
for line in result:
    print(line[1][0])

_______________________________________________________________________

Practical Use Cases

1. Document Processing

OCR is widely used to automate document processing tasks, such as converting scanned invoices, forms, or contracts into digital, searchable files. Both Tesseract and PaddleOCR can handle such tasks effectively.

Example: Extracting Text from a Scanned Document

import pytesseract
from PIL import Image

# Load scanned image
image = Image.open('scanned_document.png')

# Perform OCR on the document
text = pytesseract.image_to_string(image)

# Output the extracted text
print(text)

By applying basic image preprocessing (e.g., converting the image to grayscale, binarization), you can enhance the accuracy of text extraction.

Image Preprocessing Example:

import cv2

# Load image and convert to grayscale
image = cv2.imread('scanned_document.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply thresholding to binarize the image
_, binary_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY)

# Save and pass the preprocessed image to Tesseract
cv2.imwrite('preprocessed_image.png', binary_image)
text = pytesseract.image_to_string('preprocessed_image.png')
print(text)

 

2. Number Plate Recognition

OCR can be used in security applications to automatically recognize vehicle license plates. This is especially useful for smart parking systems, traffic management, and surveillance.

Example: Recognizing Text from a Vehicle License Plate

import cv2
import pytesseract

# Load image of a vehicle
image = cv2.imread('vehicle_image.png')

# Preprocess the image (resize, grayscale)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_LINEAR)

# Perform OCR on the license plate
text = pytesseract.image_to_string(gray)
print("Detected License Plate Number:", text)

 

3. Real-Time OCR with IP Cameras

OCR can be used in real-time systems, such as monitoring camera feeds for detecting number plates, extracting text from billboards, or reading information from screens.

Example: Real-Time Text Detection from IP Camera Feed

import cv2
from paddleocr import PaddleOCR

# Initialize PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='en')

# Connect to an IP camera feed
camera_url = 'rtsp://username:password@ip_address:554/stream'
cap = cv2.VideoCapture(camera_url)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # Perform OCR on each frame
    result = ocr.ocr(frame)

    # Display the extracted text on the screen
    for line in result:
        print(line[1][0])

    # Show the camera feed
    cv2.imshow('Camera Feed', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

_______________________________________________________________________

Conclusion

OCR (Optical Character Recognition) is a powerful tool for extracting text from images, and with libraries like Tesseract and PaddleOCR, Python makes it easy to implement. Whether you’re digitizing documents, recognizing number plates, or performing real-time text detection from camera feeds, OCR can significantly improve efficiency in processing visual data. By combining OCR with image preprocessing techniques, you can further enhance the accuracy and quality of the extracted text.

author-avatar

About Muhammad Adeel Ashraf

Muhammad Adeel Ashraf is a Co-founder of Pyresearch, Adeel Ashraf is a pioneer in AI innovation who is committed to creating game-changing AI solutions. Pyresearch is a cutting-edge AI startup that provides businesses with cutting-edge machine learning, Deep Learning, and Computer Vision technology. Pyresearch focuses on providing state-of-the-art AI-driven research, consultancy, and customized solutions. With the mission of using artificial intelligence to spur innovation and growth, Pyresearch is dedicated to assisting businesses in realizing their potential in the AI-driven future.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *