I have document rotated by random.randint(-90, 90) degrees, I want to make it straight…
- User
I have document rotated by random.randint(-90, 90) degrees, I want to make it straight again, find the approach in python the code I used to rotate: import cv2 import numpy as np import os import random import fitz # PyMuPDF from PIL import Image
input_dir = "Data" output_dir = "Rotated_Data"
Ensure the output directory exists
if not os.path.exists(output_dir): os.makedirs(output_dir)
def rotate_image(image: np.ndarray, angle: float) -> np.ndarray: """Rotate the input image by a given angle.""" image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) return cv2.warpAffine( image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR, borderValue=(255, 255, 255), )
def pdf_to_images(pdf_path: str, dpi: int = 300) -> list: """Convert PDF file to a list of PIL images with specified DPI for better quality.""" doc = fitz.open(pdf_path) images = [] zoom_x = dpi / 72 # zoom factor for x zoom_y = dpi / 72 # zoom factor for y mat = fitz.Matrix(zoom_x, zoom_y)
codefor page_number in range(len(doc)): page = doc.load_page(page_number) pix = page.get_pixmap(matrix=mat, alpha=False) # Use matrix for high resolution img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) images.append(img) doc.close() return imagesdef images_to_pdf(images: list, output_path: str): """Convert a list of PIL images into a PDF file.""" if images: images[0].save(output_path, save_all=True, append_images=images[1:], resolution=300.0)
for file in os.listdir(input_dir): if file.endswith(".pdf"): pdf_path = os.path.join(input_dir, file) output_pdf_path = os.path.join(output_dir, f"{os.path.splitext(file)[0]}_rotated.pdf")
code# Convert PDF to images with high DPI for better quality images = pdf_to_images(pdf_path, dpi=300) # Rotate each image by a random angle and convert back to PIL format rotated_images = [] for img in images: image_np = np.array(img) angle = random.randint(-90, 90) rotated_image_np = rotate_image(image_np, angle) rotated_image = Image.fromarray(rotated_image_np) rotated_images.append(rotated_image) # Convert images back to a PDF images_to_pdf(rotated_images, output_pdf_path) - Assistant
- User
Is there any other option to do it with for example PyMuPDF library
- Assistant
- User
blocks = page.get_text("blocks") it is False
- Assistant
- User
import fitz # PyMuPDF import numpy as np from PIL import Image import os
def get_skew_angle(page) -> float: """Estimating the skew angle from text blocks in a PDF page.""" blocks = page.get_text("blocks") # Retrieve text blocks angles = [] if blocks: for b in blocks: x0, y0, x1, y1 = b[:4] print(x0, y0, x1, y1) angle = np.degrees(np.arctan2(y1 - y0, x1 - x0)) angles.append(angle)
code# Calculate the median angle if angles: median_angle = np.median(angles) else: median_angle = 0 print(median_angle) return median_angle - Assistant