Detecting Text Regions
Before reading text, you can detect where text is located in an image. This is useful for processing specific regions and ignoring non-text areas.
8 min•By Priygop Team•Updated 2026
Text Region Detection
Text Region Detection
import cv2
import numpy as np
import pytesseract
def detect_text_regions(image_path):
"""Detect where text is located in an image."""
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Get bounding boxes for each detected word
data = pytesseract.image_to_data(
gray,
output_type=pytesseract.Output.DICT,
config="--psm 11" # Sparse text detection
)
result = image.copy()
text_regions = []
for i in range(len(data["text"])):
conf = int(data["conf"][i])
text = data["text"][i].strip()
if conf > 50 and text: # Only confident detections
x = data["left"][i]
y = data["top"][i]
w = data["width"][i]
h = data["height"][i]
text_regions.append({
"text": text,
"confidence": conf,
"bbox": (x, y, w, h)
})
# Draw bounding box
cv2.rectangle(result, (x, y), (x+w, y+h), (0, 255, 0), 2)
print(f"Detected {len(text_regions)} text regions")
for region in text_regions[:10]:
print(f" '{region['text']}' (confidence: {region['confidence']}%)")
cv2.imwrite("text_regions.jpg", result)
return text_regions
detect_text_regions("document.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment