BHT25 / scripts /ocrpdf.py
sudeshna84's picture
Upload ocrpdf.py
0f11d3e verified
import pytesseract
from PIL import Image
import os
import cv2
# Set Tesseract path (change if needed)
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
# Input and output folders
input_folder = "input_images"
output_folder = "ocr_output"
# Create output folder if not exists
os.makedirs(output_folder, exist_ok=True)
# Choose language (change as needed)
lang = 'ben' # 'hin' or 'tel'
# Process all images
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tif')):
img_path = os.path.join(input_folder, filename)
img = cv2.imread(img_path)
# Preprocessing
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# OCR
text = pytesseract.image_to_string(thresh, lang=lang, config='--psm 6')
# Output file name
output_file = os.path.splitext(filename)[0] + ".txt"
output_path = os.path.join(output_folder, output_file)
# Save text
with open(output_path, "w", encoding="utf-8") as f:
f.write(text)
print(f"Processed: {filename}{output_file}")
print("Batch OCR completed.")