我有一个包含笔迹的多页 .pdf(扫描图像),我想裁剪并存储为新的单独图像。例如,在下面的视觉效果中,我想将 2 个框内的笔迹提取为单独的图像。如何使用 python 自动为大型多页 .pdf 执行此操作?
我尝试使用 PyPDF2
包根据 (x,y) 坐标裁剪其中一个手写框,但是这种方法对我来说不起作用,因为手写框的边界/坐标pdf 中的每一页不会总是相同的。我相信检测框将是一种更好的自动裁剪方法。不确定它是否有用,但下面是我用于 (x,y) 坐标方法的代码:
from PyPDF2 import PdfFileReader, PdfFileWriter
reader = PdfFileReader("data/samples.pdf", "r")
# getting the first page
page = reader.getPage(0)
writer = PdfFileWriter()
# Loop through all pages in pdf object to crop based on (x,y) coordinates
for i in range(reader.getNumPages()):
page = reader.getPage(i)
page.cropBox.setLowerLeft((42, 115))
page.cropBox.setUpperRight((500, 245))
writer.addPage(page)
with open("samples_cropped.pdf", "wb") as fp:
writer.write(fp)
预先感谢您的帮助
最佳答案
这是一个使用 OpenCV 的简单方法
- 将图像转换为灰度和高斯模糊
- 阈值图像
- 寻找轮廓
- 遍历轮廓并使用轮廓区域进行过滤
- 提取投资返回率
提取 ROI 后,您可以将每个 ROI 保存为单独的图像,然后使用 pytesseract
或其他工具执行 OCR 文本提取。
结果
你提到这个
The boundaries/coordinates of the handwriting boxes wont always be the same for each page in the pdf.
目前,您使用 (x,y)
坐标的方法不是很可靠,因为框可能位于图像上的任何位置。更好的方法是使用最小阈值轮廓区域进行过滤以检测框。根据您要检测的盒子的大小,您可以调整变量。如果你想要额外的过滤来防止误报,你可以添加到 aspect ratio作为另一种过滤机制。例如,计算每个轮廓的纵横比,然后如果它在边界内(比如 0.8
到 1.2
对于正方形/矩形 ROI)那么它就是一个有效框。
import cv2
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.threshold(blurred, 230,255,cv2.THRESH_BINARY_INV)[1]
# Find contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Iterate thorugh contours and filter for ROI
image_number = 0
min_area = 10000
for c in cnts:
area = cv2.contourArea(c)
if area > min_area:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]
cv2.imwrite("ROI_{}.png".format(image_number), ROI)
image_number += 1
cv2.imshow('image', image)
cv2.waitKey(0)
关于python - 检测 .pdf 或图像中的框并将其裁剪为单个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57068541/