make the best possible python code for ocr of a image in wich there can be 3d TEXT which…
- User
make the best possible python code for ocr of a image in wich there can be 3d TEXT which can also be tilted
- Assistant
make the best possible python code for ocr of a image in wich there can be 3d TEXT which can also be tilted
To perform OCR (Optical Character Recognition) on images containing 3D text that may be tilted, we need a robust approach that can handle perspective distortions, skewness, and varying lighting conditions. Below is a Python code that leverages OpenCV for image preprocessing and EasyOCR, a deep learning-based OCR library, to accurately recognize text in such challenging images.
Prerequisites:
pip install opencv-python
pip install easyocr
pip install numpy
Python Code:
import cv2
import numpy as np
import easyocr
import matplotlib.pyplot as plt
# Load the image
image_path = 'image.jpg' # Replace with your image path
image = cv2.imread(image_path)
# Resize image if it's too large (optional)
# image = cv2.resize(image, (0, 0), fx=0.5, fy=0.5)
# Preprocessing
def preprocess_image(image):
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Reduce noise with bilateral filter
gray = cv2.bilateralFilter(gray, 11, 17, 17)
# Edge detection
edged = cv2.Canny(gray, 30, 200)
# Find contours for perspective correction
contours, _ = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]
# Assume the largest contour with 4 corners is the text area
screenCnt = None
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.015 * peri, True)
if len(approx) == 4:
screenCnt = approx
break
if screenCnt is not None:
# Apply perspective transform
pts = screenCnt.reshape(4, 2)
rect = order_points(pts)
(tl, tr, br, bl) = rect
widthA = np.linalg.norm(br - bl)
widthB = np.linalg.norm(tr - tl)
maxWidth = max(int(widthA), int(widthB))
heightA = np.linalg.norm(tr - br)
heightB = np.linalg.norm(tl - bl)
maxHeight = max(int(heightA), int(heightB))
dst = np.array([
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]], dtype="float32")
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
# Convert to grayscale
gray_warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
else:
gray_warped = gray
# Thresholding to get binary image
_, thresh = cv2.threshold(gray_warped, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Deskew image
thresh = deskew(thresh)
return thresh
def order_points(pts):
# Initial ordering of points: top-left, top-right, bottom-right, bottom-left
rect = np.zeros((4, 2), dtype="float32")
# Sum and difference to find corners
s = pts.sum(axis=1)
diff = np.diff(pts, axis=1)
rect[0] = pts[np.argmin(s)] # Top-left has smallest sum
rect[2] = pts[np.argmax(s)] # Bottom-right has largest sum
rect[1] = pts[np.argmin(diff)] # Top-right has smallest difference
rect[3] = pts[np.argmax(diff)] # Bottom-left has largest difference
return rect
def deskew(image):
# Calculate skew angle and rotate
coords = np.column_stack(np.where(image > 0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h),
flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated
# Preprocess the image
preprocessed_image = preprocess_image(image)
# Initialize EasyOCR reader
reader = easyocr.Reader(['en']) # Specify the languages you want to use
# Perform OCR
result = reader.readtext(preprocessed_image)
# Display results
for (bbox, text, prob) in result:
print(f'Detected text: {text} (Confidence: {prob:.2f})')
# Draw bounding box and text on the original image
bbox = np.int0(bbox)
cv2.polylines(image, [bbox], True, (0, 255, 0), 2)
cv2.putText(image, text, (bbox[0][0], bbox[0][1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# Save and display the result image
cv2.imwrite('result.jpg', image)
Explanation:
Image Loading and Resizing:
Preprocessing:
OCR with EasyOCR:
Saving Results:
result.jpg.Notes:
Handling 3D Text and Tilt: The preprocessing steps aim to flatten the image and correct distortions caused by 3D text and tilt. Perspective transformation and deskewing are crucial for improving OCR accuracy in such cases.
Advanced Techniques: Depending on the complexity of the image, additional preprocessing like shadow removal, contrast enhancement, or using morphological operations might be necessary.
EasyOCR Advantages:
Visualization:
To visualize the result within a Jupyter notebook or a script, you can use:
# Convert image from BGR to RGB for plotting
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Display the image
plt.figure(figsize=(10, 10))
plt.imshow(image_rgb)
plt.axis('off')
plt.show()
Conclusion:
This code provides a robust solution for performing OCR on images with 3D and tilted text. By combining image preprocessing techniques with a powerful OCR engine like EasyOCR, it maximizes the chances of accurately recognizing text in challenging conditions.
Not yet included in a published release.