OCR Menggunakan Tesseract di Python Dengan Mendefinisikan Region of Interest (ROI)

NDID Engineering Blog
NDID Engineering
Published in
4 min readOct 6, 2023

Author: Hariz Zakka

Dalam postingan blog ini, saya akan mencoba menjelaskan teknologi OCR (Optical Character Recognition) menggunakan Tesseract di Python untuk mendeteksi lokasi kata/teks tertentu dengan mendefinisikan region of interest (ROI) pada teks gambar. Kita dapat menggunakan library pytesseract untuk deteksi dan ekstraksi teks pada gambar dan cv2 (OpenCV) untuk pemrosesan gambar.

Instal library yang diperlukan:

1. Pastikan Tesseract telah terinstal di sistem Anda sesuai dengan OS yang digunakan.

2. Berikut perintah untuk menginstal library pytesseract dan OpenCV di python.

Import library yang diperlukan kemudian muat gambar dan ubah warna gambar menjadi grayscale menggunakan OpenCV.

import cv2
import pytesseract

# Load the image
image_path = 'path_to_your_image_file'
image = cv2.imread(image_path)

# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imshow("Gray Scale", gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Berikut adalah gambar yang akan digunakan sebagai sampel data dan hasil grayscale.

Selanjutnya adalah melakukan OCR pada gambar yang sudah menjadi grayscale untuk mendapatkan struktur data menggunakan fungsi pytesseract.image_to_data(). Fungsi ini digunakan untuk mengekstrak informasi terstruktur dan memungkinkan kita mengakses informasi lebih detail tentang teks yang ditemukan dalam gambar.

Berikut cara menggunakan fungsi pytesseract.image_to_data() dan output yang dikeluarkan.

# Perform OCR on the grayscale image to get structured data
data = pytesseract.image_to_data(gray_image, output_type=pytesseract.Output.DICT)
print(data)
{
'level': [1, 2, 3, 4, 5, 5, 5, 5],
'page_num': [1, 1, 1, 1, 1, 1, 1, 1],
'block_num': [0, 1, 1, 1, 1, 1, 1, 1],
'par_num': [0, 0, 1, 1, 1, 1, 1, 1],
'line_num': [0, 0, 0, 1, 1, 1, 1, 1],
'word_num': [0, 0, 0, 0, 1, 2, 3, 4],
'left': [0, 8, 8, 8, 8, 141, 190, 340],
'top': [0, 13, 13, 13, 15, 13, 16, 13],
'width': [455, 419, 419, 419, 119, 37, 137, 87],
'height': [72, 41, 41, 41, 39, 33, 30, 41],
'conf': [-1, -1, -1, -1, 96, 96, 96, 90],
'text': ['', '', '', '', 'Region', 'of', 'Interest', '(ROI)']
}

Pada informasi diatas, kita akan menggunakan left, top, width, dan height untuk mendapatkan koordinat Region of Interest (ROI). Agar mengetahui koordinat dari setiap kata dengan tepat, kita bisa mendefinisikannya sebagai berikut.

# Iterate through the detected components (words)
for i in range(len(data['text'])):
text = data['text'][i].strip()
left, top, width, height = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
conf = data['conf'][i]

# Filter out empty text (non-text components)
if text.strip() != '':
# Print the text and its bounding box coordinates
print(f"Text: {text}, Bounding Box (x, y, w, h): ({left}, {top}, {width}, {height})")

Output yang dihasilkan adalah sebagai berikut.

Text: Region, Bounding Box (left, top, width, height): (8, 15, 119, 39)
Text: of, Bounding Box (left, top, width, height): (141, 13, 37, 33)
Text: Interest, Bounding Box (left, top, width, height): (190, 16, 137, 30)
Text: (ROI), Bounding Box (left, top, width, height): (340, 13, 87, 41)

Kita bisa mengetahui setiap koordinat dari masing-masing kata. Misalkan kita akan mengekstraksi kata (ROI) dari gambar, maka kita bisa mendefinisikannya sebagai berikut.

# Define a region of interest (ROI) based on left and top coordinates
roi_left = 340 # Adjust as needed
roi_top = 13 # Adjust as needed
roi_width = 87 # Adjust as needed
roi_height = 41 # Adjust as needed

# Iterate through the detected components (words)
for i in range(len(data['text'])):
text = data['text'][i].strip()
left, top, width, height = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
conf = data['conf'][i]

# Filter out empty text (non-text components)
if text.strip() != '':
# Print the text and its bounding box coordinates
print(f"Text: {text}, Bounding Box (x, y, w, h): ({left}, {top}, {width}, {height})")

# Check if the detected text is within the specified ROI
if (left >= roi_left and left + width <= roi_left + roi_width) and \
(top >= roi_top and top + height <= roi_top + roi_height) and text.strip() != '':
# Process or save the text and bounding box as needed
print(f"Extract Detected text: '{text}'")
print(f"Bounding Box Coordinates: (left={left}, top={top}, width={width}, height={height})")
print(f"Confidence: {conf}")
img = cv2.rectangle(image, (left, top), (left + width, top + height), (0, 255, 0), 2)

# Crop the image to the ROI
roi_image = image[roi_top:roi_top+roi_height, roi_left:roi_left+roi_width]

cv2.imshow("Display Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Text: Region, Bounding Box (x, y, w, h): (8, 15, 119, 39)
Text: of, Bounding Box (x, y, w, h): (141, 13, 37, 33)
Text: Interest, Bounding Box (x, y, w, h): (190, 16, 137, 30)
Text: (ROI), Bounding Box (x, y, w, h): (340, 13, 87, 41)
Extract Detected text: '(ROI)'
Bounding Box Coordinates: (left=340, top=13, width=87, height=41)
Confidence: 90

kita telah mencapai akhir topik dan terima kasih untuk Anda yang telah membaca blog ini. Jika Anda memiliki sesuatu yang ingin ditambahkan ke diskusi, silakan tinggalkan komentar.

--

--