Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét

& nbsp; · Bassem Marji · 23 phút Đọc · Cập nhật tháng 7 năm 2022 · Xử lý tệp PDF · Bassem Marji · 23 min read · Updated jul 2022 · PDF File Handling

Tiết lộ: Bài đăng này có thể chứa các liên kết liên kết, có nghĩa là khi bạn nhấp vào liên kết và mua hàng, chúng tôi nhận được hoa hồng.: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.

Ngày nay, các công ty có quy mô trung bình và lớn có số lượng lớn các tài liệu in trong sử dụng hàng ngày. Trong số đó có hóa đơn, biên lai, tài liệu công ty, báo cáo và thông cáo phương tiện truyền thông.

Đối với các công ty đó, việc sử dụng máy quét OCR có thể tiết kiệm một khoảng thời gian đáng kể trong khi cải thiện hiệu quả cũng như độ chính xác. & NBSP;

Thuật toán nhận dạng ký tự quang (OCR) cho phép các máy tính phân tích tự động phân tích các tài liệu in hoặc viết tay và chuẩn bị dữ liệu văn bản thành các định dạng có thể chỉnh sửa để máy tính xử lý chúng một cách hiệu quả. Hệ thống OCR biến đổi hình ảnh hai chiều của văn bản có thể chứa văn bản in hoặc viết tay từ biểu diễn hình ảnh của nó thành văn bản có thể đọc được bằng máy.

Nói chung, một động cơ OCR liên quan đến nhiều bước cần thiết để đào tạo thuật toán học máy để giải quyết vấn đề hiệu quả với sự trợ giúp của nhận dạng ký tự quang học.

Các bước sau đây có thể khác nhau từ động cơ này sang động cơ khác là cần thiết để tiếp cận nhận dạng ký tự tự động: Trong hướng dẫn này, tôi sẽ cho bạn thấy như sau:

Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét
Within this tutorial, I am going to show you the following:

  • Cách chạy máy quét OCR trên tệp hình ảnh.
  • Cách tái cấu trúc hoặc làm nổi bật một văn bản cụ thể trong một tệp hình ảnh.
  • Cách chạy máy quét OCR trên tệp PDF hoặc bộ sưu tập các tệp PDF.

Xin lưu ý rằng hướng dẫn này là về việc trích xuất văn bản từ hình ảnh trong các tài liệu PDF, nếu bạn muốn trích xuất tất cả văn bản từ PDF, thay vào đó hãy kiểm tra hướng dẫn này.

Để bắt đầu, chúng tôi cần sử dụng các thư viện sau:

Tesseract OCR: & NBSP; là công cụ nhận dạng văn bản nguồn mở có sẵn theo giấy phép Apache 2.0 và sự phát triển của nó đã được Google tài trợ từ năm 2006. Vào năm 2006, Tesseract được coi là một trong những động cơ OCR nguồn mở chính xác nhất . Bạn có thể sử dụng nó trực tiếp hoặc có thể sử dụng API để trích xuất văn bản in từ hình ảnh. Phần tốt nhất là nó hỗ trợ nhiều ngôn ngữ. & NBSP; is an open-source text recognition engine that is available under the Apache 2.0 license and its development has been sponsored by Google since 2006. In the year 2006, Tesseract was considered one of the most accurate open-source OCR engines. You can use it directly or can use the API to extract the printed text from images. The best part is that it supports an extensive variety of languages. 

Cài đặt động cơ Tesseract nằm ngoài phạm vi của bài viết này. Tuy nhiên, bạn cần làm theo hướng dẫn cài đặt chính thức của Tesseract để cài đặt nó trên hệ điều hành của bạn.

Để xác thực thiết lập Tesseract, vui lòng chạy lệnh sau và kiểm tra đầu ra được tạo:

Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét
Python-Tesseract: là một trình bao bọc Python cho động cơ Google Tesseract-acr. Nó cũng hữu ích như một tập lệnh gọi độc lập cho Tesseract, vì nó có thể đọc tất cả các loại hình ảnh được hỗ trợ bởi các thư viện hình ảnh Gối và Leptonica, bao gồm JPEG, PNG, GIF, BMP, TIFF và những người khác. is a Python wrapper for Google’s Tesseract-OCR Engine. It is also useful as a stand-alone invocation script to tesseract, as it can read all image types supported by the Pillow and Leptonica imaging libraries, including jpeg, png, gif, bmp, tiff, and others.

OpenCV: là một thư viện nguồn mở Python, cho tầm nhìn máy tính, học máy và xử lý hình ảnh. OpenCV hỗ trợ nhiều ngôn ngữ lập trình như Python, C ++, Java, v.v. Nó có thể xử lý hình ảnh và video để xác định các đối tượng, khuôn mặt hoặc thậm chí là chữ viết tay của con người. is a Python open-source library, for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. 

PyMUPDF: MUPDF là một giải pháp phiên dịch PDF, XPS và Ebook có thể sử dụng rất linh hoạt cao, có thể sử dụng trên một loạt các ứng dụng như trình kết xuất, trình xem hoặc bộ công cụ PDF. PymUPDF là một liên kết python cho MUPDF. Nó là một trình xem PDF và XPS nhẹ.: MuPDF is a highly versatile, customizable PDF, XPS, and eBook interpreter solution that can be used across a wide range of applications as a PDF renderer, viewer, or toolkit. PyMuPDF is a Python binding for MuPDF. It is a lightweight PDF and XPS viewer.

Numpy: là gói xử lý mảng đa năng. Nó cung cấp một đối tượng mảng đa chiều hiệu suất cao và các công cụ để làm việc với các mảng này. Đây là gói cơ bản để điện toán khoa học với Python. Bên cạnh đó, Numpy cũng có thể được sử dụng như một thùng chứa đa chiều hiệu quả của dữ liệu chung. is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Besides, Numpy can also be used as an efficient multi-dimensional container of generic data.

Gối: Được xây dựng trên đỉnh PIL (Thư viện hình ảnh Python). Nó là một mô -đun thiết yếu để xử lý hình ảnh trong Python. is built on top of PIL (Python Image Library). It is an essential module for image processing in Python.

PANDAS: là một thư viện Python được cấp nguồn BSD, cung cấp các cấu trúc dữ liệu và công cụ phân tích dữ liệu hiệu suất cao, dễ sử dụng cho ngôn ngữ lập trình Python. & NBSP; is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. 

FileType: Gói Python nhỏ và không phụ thuộc để suy ra loại tệp và loại MIME. Small and dependency-free Python package to deduce file type and MIME type.

Hướng dẫn này nhằm phát triển tiện ích dựa trên dòng chỉ huy nhẹ để trích xuất, tái cấu trúc hoặc làm nổi bật một văn bản có trong một hình ảnh hoặc tệp PDF được quét hoặc trong thư mục chứa một bộ sưu tập các tệp PDF.

Thành lập

Để bắt đầu, hãy cài đặt các yêu cầu:

$ pip install Filetype==1.0.7 numpy==1.19.4 opencv-python==4.4.0.46 pandas==1.1.4 Pillow==8.0.1 PyMuPDF==1.18.9 pytesseract==0.3.7

Hãy bắt đầu bằng cách nhập các thư viện cần thiết:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
1 là nơi tọa lạc thực thi Tesseract. Rõ ràng, bạn cần thay đổi nó cho trường hợp của bạn.

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im

Hàm này chuyển đổi bộ đệm pixmap đại diện cho một ảnh chụp màn hình được chụp bằng thư viện PyMUPDF thành một mảng numpy.PyMuPDF library into a NumPy array.

Để cải thiện độ chính xác của Tesseract, hãy xác định một số chức năng tiền xử lý bằng OpenCV:

# Image Pre-Processing Functions to improve output accurracy
# Convert to grayscale
def grayscale(img):
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Remove noise
def remove_noise(img):
    return cv2.medianBlur(img, 5)

# Thresholding
def threshold(img):
    # return cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    return cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# dilation
def dilate(img):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.dilate(img, kernel, iterations=1)

# erosion
def erode(img):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.erode(img, kernel, iterations=1)

# opening -- erosion followed by a dilation
def opening(img):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

# canny edge detection
def canny(img):
    return cv2.Canny(img, 100, 200)

# skew correction
def deskew(img):
    coords = np.column_stack(np.where(img > 0))
    angle = cv2.minAreaRect(coords)[-1]
    if angle < -45:
        angle = -(90 + angle)
    else:
        angle = -angle
    (h, w) = img.shape[:2]
    center = (w//2, h//2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    rotated = cv2.warpAffine(
        img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    return rotated

# template matching
def match_template(img, template):
    return cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)

def convert_img2bin(img):
    """
    Pre-processes the image and generates a binary output
    """
    # Convert the image into a grayscale image
    output_img = grayscale(img)
    # Invert the grayscale image by flipping pixel values.
    # All pixels that are grater than 0 are set to 0 and all pixels that are = to 0 are set to 255
    output_img = cv2.bitwise_not(output_img)
    # Converting image to binary by Thresholding in order to show a clear separation between white and blacl pixels.
    output_img = threshold(output_img)
    return output_img

Chúng tôi đã xác định các chức năng cho nhiều tác vụ tiền xử lý, bao gồm chuyển đổi hình ảnh thành thang độ xám, lật các giá trị pixel, tách các pixel trắng và đen, và nhiều hơn nữa.

Tiếp theo, hãy xác định chức năng để hiển thị hình ảnh:

def display_img(title, img):
    """Displays an image on screen and maintains the output until the user presses a key"""
    cv2.namedWindow('img', cv2.WINDOW_NORMAL)
    cv2.setWindowTitle('img', title)
    cv2.resizeWindow('img', 1200, 900)
    # Display Image on screen
    cv2.imshow('img', img)
    # Mantain output until user presses a key
    cv2.waitKey(0)
    # Destroy windows when user presses a key
    cv2.destroyAllWindows()

Hàm

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
2 hiển thị trên màn hình một hình ảnh trong cửa sổ có tiêu đề được đặt thành tham số
def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
3 và duy trì cửa sổ này mở cho đến khi người dùng nhấn phím trên bàn phím.

def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text

Hàm ở trên lặp lại trong suốt văn bản chụp của một hình ảnh và sắp xếp dòng văn bản được lấy theo từng dòng. Nó phụ thuộc vào bố cục hình ảnh và có thể yêu cầu điều chỉnh cho một số định dạng hình ảnh.

Liên quan: Cách hợp nhất các tệp PDF trong Python. How to Merge PDF Files in Python.

Tiếp theo, hãy xác định một hàm để tìm kiếm văn bản bằng cách sử dụng các biểu thức thông thường:

def search_for_text(ss_details, search_str):
    """Search for the search string within the image content"""
    # Find all matches within one page
    results = re.findall(search_str, ss_details['text'], re.IGNORECASE)
    # In case multiple matches within one page
    for result in results:
        yield result

Chúng tôi sẽ sử dụng chức năng này để tìm kiếm văn bản cụ thể trong nội dung lấy của hình ảnh. Nó trả về một máy phát của các trận đấu tìm thấy.

def save_page_content(pdfContent, page_id, page_data):
    """Appends the content of a scanned page, line by line, to a pandas DataFrame."""
    if page_data:
        for idx, line in enumerate(page_data, 1):
            line = ' '.join(line)
            pdfContent = pdfContent.append(
                {'page': page_id, 'line_id': idx, 'line': line}, ignore_index=True
            )
    return pdfContent

Chức năng

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
4 Bổ số nội dung lấy của một dòng hình ảnh theo từng dòng sau khi quét nó đến
def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
5 Pandas DataFrame.

Bây giờ chúng ta hãy tạo một chức năng để lưu DataFrame kết quả vào tệp CSV:

def save_file_content(pdfContent, input_file):
    """Outputs the content of the pandas DataFrame to a CSV file having the same path as the input_file
    but with different extension (.csv)"""
    content_file = os.path.join(os.path.dirname(input_file), os.path.splitext(
        os.path.basename(input_file))[0] + ".csv")
    pdfContent.to_csv(content_file, sep=',', index=False)
    return content_file

Tiếp theo, hãy viết một hàm tính toán điểm tin cậy của văn bản được lấy từ hình ảnh được quét:

def calculate_ss_confidence(ss_details: dict):
    """Calculate the confidence score of the text grabbed from the scanned image."""
    # page_num  --> Page number of the detected text or item
    # block_num --> Block number of the detected text or item
    # par_num   --> Paragraph number of the detected text or item
    # line_num  --> Line number of the detected text or item
    # Convert the dict to dataFrame
    df = pd.DataFrame.from_dict(ss_details)
    # Convert the field conf (confidence) to numeric
    df['conf'] = pd.to_numeric(df['conf'], errors='coerce')
    # Elliminate records with negative confidence
    df = df[df.conf != -1]
    # Calculate the mean confidence by page
    conf = df.groupby(['page_num'])['conf'].mean().tolist()
    return conf[0]

Đi đến chức năng chính: Quét hình ảnh:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
0

Những điều trên thực hiện như sau:

  • Quét một bộ đệm hình ảnh hoặc một tệp hình ảnh.
  • Xử lý trước hình ảnh.
  • Chạy động cơ Tesseract với các tham số được xác định trước.
  • Tính điểm tin cậy của nội dung lấy của hình ảnh.
  • Vẽ một hình chữ nhật màu xanh lá cây xung quanh các mục văn bản có thể đọc có điểm tin cậy lớn hơn 30.
  • Tìm kiếm một văn bản cụ thể trong hình ảnh lấy nội dung.
  • Điểm nổi bật hoặc tái cấu trúc các trận đấu tìm thấy của văn bản được tìm kiếm.
  • Hiển thị một cửa sổ hiển thị các trường văn bản có thể đọc được hoặc văn bản được tô sáng hoặc văn bản được tái cấu trúc.
  • Tạo nội dung văn bản của hình ảnh.
  • In một bản tóm tắt cho bảng điều khiển.
import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
1

Hàm

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
6 chuyển đổi một hình ảnh thành một mảng byte.

Hàm

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
7 thực hiện như sau:

  • Mở tệp PDF đầu vào.
  • Mở bộ đệm bộ nhớ để lưu trữ tệp PDF đầu ra.
  • Tạo một khung dữ liệu gấu trúc để lưu trữ số liệu thống kê của trang.
  • Lặp lại thông qua các trang đã chọn của tệp PDF đầu vào.
  • Lấy một ảnh chụp màn hình (hình ảnh) của trang đã chọn của tệp PDF đầu vào.
  • Chuyển đổi ảnh chụp màn hình (pix) thành một mảng numpy.
  • Quét ảnh chụp màn hình lấy.
  • Thu thập số liệu thống kê của màn hình (trang).
  • Lưu nội dung của ảnh chụp màn hình.
  • Thêm ảnh chụp màn hình cập nhật vào tệp đầu ra.
  • Lưu toàn bộ nội dung của tệp PDF đầu vào vào tệp CSV.
  • Lưu tệp PDF đầu ra nếu được yêu cầu.
  • In một bản tóm tắt cho bảng điều khiển.

Hàm

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
6 chuyển đổi một hình ảnh thành một mảng byte.

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
2

Hàm

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
7 thực hiện như sau:

Mở tệp PDF đầu vào.

  • Mở bộ đệm bộ nhớ để lưu trữ tệp PDF đầu ra.
  • Tạo một khung dữ liệu gấu trúc để lưu trữ số liệu thống kê của trang.
  • Lặp lại thông qua các trang đã chọn của tệp PDF đầu vào.
  • Lấy một ảnh chụp màn hình (hình ảnh) của trang đã chọn của tệp PDF đầu vào.
  • Chuyển đổi ảnh chụp màn hình (pix) thành một mảng numpy.
  • Quét ảnh chụp màn hình lấy.

Thu thập số liệu thống kê của màn hình (trang).

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
3

Lưu nội dung của ảnh chụp màn hình.

Thêm ảnh chụp màn hình cập nhật vào tệp đầu ra.

Lưu toàn bộ nội dung của tệp PDF đầu vào vào tệp CSV.

  • Lưu tệp PDF đầu ra nếu được yêu cầu.
  • Hãy thêm một chức năng khác để xử lý một thư mục chứa nhiều tệp PDF:
  • Tạo một khung dữ liệu gấu trúc để lưu trữ số liệu thống kê của trang.
  • Lặp lại thông qua các trang đã chọn của tệp PDF đầu vào.
  • Lấy một ảnh chụp màn hình (hình ảnh) của trang đã chọn của tệp PDF đầu vào.
  • Chuyển đổi ảnh chụp màn hình (pix) thành một mảng numpy.
  • Quét ảnh chụp màn hình lấy.
  • def display_img(title, img):
        """Displays an image on screen and maintains the output until the user presses a key"""
        cv2.namedWindow('img', cv2.WINDOW_NORMAL)
        cv2.setWindowTitle('img', title)
        cv2.resizeWindow('img', 1200, 900)
        # Display Image on screen
        cv2.imshow('img', img)
        # Mantain output until user presses a key
        cv2.waitKey(0)
        # Destroy windows when user presses a key
        cv2.destroyAllWindows()
    4: Hiển thị cửa sổ hiển thị so sánh giữa hình ảnh gốc và hình ảnh được xử lý.
  • # Image Pre-Processing Functions to improve output accurracy
    # Convert to grayscale
    def grayscale(img):
        return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Remove noise
    def remove_noise(img):
        return cv2.medianBlur(img, 5)
    
    # Thresholding
    def threshold(img):
        # return cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
        return cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    
    # dilation
    def dilate(img):
        kernel = np.ones((5, 5), np.uint8)
        return cv2.dilate(img, kernel, iterations=1)
    
    # erosion
    def erode(img):
        kernel = np.ones((5, 5), np.uint8)
        return cv2.erode(img, kernel, iterations=1)
    
    # opening -- erosion followed by a dilation
    def opening(img):
        kernel = np.ones((5, 5), np.uint8)
        return cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
    
    # canny edge detection
    def canny(img):
        return cv2.Canny(img, 100, 200)
    
    # skew correction
    def deskew(img):
        coords = np.column_stack(np.where(img > 0))
        angle = cv2.minAreaRect(coords)[-1]
        if angle < -45:
            angle = -(90 + angle)
        else:
            angle = -angle
        (h, w) = img.shape[:2]
        center = (w//2, h//2)
        M = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated = cv2.warpAffine(
            img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
        return rotated
    
    # template matching
    def match_template(img, template):
        return cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    
    def convert_img2bin(img):
        """
        Pre-processes the image and generates a binary output
        """
        # Convert the image into a grayscale image
        output_img = grayscale(img)
        # Invert the grayscale image by flipping pixel values.
        # All pixels that are grater than 0 are set to 0 and all pixels that are = to 0 are set to 255
        output_img = cv2.bitwise_not(output_img)
        # Converting image to binary by Thresholding in order to show a clear separation between white and blacl pixels.
        output_img = threshold(output_img)
        return output_img
    0: có xử lý một thư mục đệ quy hay không. & Nbsp; Điền vào đối số này bị hạn chế bởi việc lựa chọn một thư mục. & NBSP;

Cuối cùng, chúng ta hãy viết mã chính sử dụng các chức năng được xác định trước đó:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
4

Hãy kiểm tra chương trình của chúng tôi:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
5

Output:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
6

Trước khi khám phá các kịch bản thử nghiệm của chúng tôi, hãy cẩn thận với những điều sau:

  • Để tránh gặp lỗi
    def display_img(title, img):
        """Displays an image on screen and maintains the output until the user presses a key"""
        cv2.namedWindow('img', cv2.WINDOW_NORMAL)
        cv2.setWindowTitle('img', title)
        cv2.resizeWindow('img', 1200, 900)
        # Display Image on screen
        cv2.imshow('img', img)
        # Mantain output until user presses a key
        cv2.waitKey(0)
        # Destroy windows when user presses a key
        cv2.destroyAllWindows()
    6, vui lòng đóng tệp đầu vào trước khi chạy tiện ích này.
  • Chuỗi tìm kiếm tuân thủ các quy tắc của các biểu thức thông thường bằng mô-đun RE tích hợp của Python. Ví dụ: đặt chuỗi tìm kiếm thành "organi [sz] e" phù hợp với cả "tổ chức" và "tổ chức".

Trước tiên, chúng ta hãy cố gắng nhập hình ảnh (bạn có thể lấy nó ở đây nếu bạn muốn nhận cùng một đầu ra), mà không cần bất kỳ tệp PDF nào liên quan:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
7

Những điều sau đây sẽ là đầu ra:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
8

Và một hình ảnh mới đã xuất hiện trong thư mục hiện tại:

Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét
Bạn có thể vượt qua
def display_img(title, img):
    """Displays an image on screen and maintains the output until the user presses a key"""
    cv2.namedWindow('img', cv2.WINDOW_NORMAL)
    cv2.setWindowTitle('img', title)
    cv2.resizeWindow('img', 1200, 900)
    # Display Image on screen
    cv2.imshow('img', img)
    # Mantain output until user presses a key
    cv2.waitKey(0)
    # Destroy windows when user presses a key
    cv2.destroyAllWindows()
7 hoặc
def display_img(title, img):
    """Displays an image on screen and maintains the output until the user presses a key"""
    cv2.namedWindow('img', cv2.WINDOW_NORMAL)
    cv2.setWindowTitle('img', title)
    cv2.resizeWindow('img', 1200, 900)
    # Display Image on screen
    cv2.imshow('img', img)
    # Mantain output until user presses a key
    cv2.waitKey(0)
    # Destroy windows when user presses a key
    cv2.destroyAllWindows()
8 để làm nổi bật tất cả văn bản được phát hiện (với một định dạng khác, để phân biệt chuỗi tìm kiếm với các chuỗi khác).

Bạn cũng có thể vượt qua

def display_img(title, img):
    """Displays an image on screen and maintains the output until the user presses a key"""
    cv2.namedWindow('img', cv2.WINDOW_NORMAL)
    cv2.setWindowTitle('img', title)
    cv2.resizeWindow('img', 1200, 900)
    # Display Image on screen
    cv2.imshow('img', img)
    # Mantain output until user presses a key
    cv2.waitKey(0)
    # Destroy windows when user presses a key
    cv2.destroyAllWindows()
9 hoặc
def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text
0 để hiển thị hình ảnh gốc và hình ảnh được chỉnh sửa trong cùng một cửa sổ.

Bây giờ đang hoạt động cho hình ảnh, hãy thử các tệp PDF:

import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype

# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
9

def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text
1 là một tệp PDF đơn giản chứa hình ảnh trong ví dụ trước (một lần nữa, bạn có thể lấy nó ở đây).

Lần này chúng tôi đã chuyển một tệp PDF cho đối số

def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text
2 và
def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text
3 là tệp PDF kết quả (trong đó tất cả các điểm nổi bật xảy ra). Lệnh trên tạo ra đầu ra sau:

def pix2np(pix):
    """
    Converts a pixmap buffer into a numpy array
    """
    # pix.samples = sequence of bytes of the image pixels like RGBA
    #pix.h = height in pixels
    #pix.w = width in pixels
    # pix.n = number of components per pixel (depends on the colorspace and alpha)
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
        pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    except IndexError:
        # Convert Gray to RGB
        im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # RGB To BGR
    return im
0

Tệp

def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text
3 được sản xuất sau khi thực hiện, trong đó nó bao gồm cùng một PDF gốc nhưng với văn bản được tô sáng. Ngoài ra, chúng tôi hiện có số liệu thống kê về tệp PDF của chúng tôi, trong đó 192 từ đã được phát hiện và 3 từ được khớp bằng cách sử dụng tìm kiếm của chúng tôi với độ tin cậy khoảng 83,2%.

Một tệp CSV cũng được tạo bao gồm văn bản được phát hiện từ hình ảnh trên mỗi dòng.

Sự kết luận

Có những thông số khác mà chúng tôi không sử dụng trong các ví dụ của mình, vui lòng khám phá chúng. Bạn cũng có thể chuyển toàn bộ thư mục cho đối số

def generate_ss_text(ss_details):
    """Loops through the captured text of an image and arranges this text line by line.
    This function depends on the image layout."""
    # Arrange the captured text after scanning the page
    parse_text = []
    word_list = []
    last_word = ''
    # Loop through the captured text of the entire page
    for word in ss_details['text']:
        # If the word captured is not empty
        if word != '':
            # Add it to the line word list
            word_list.append(word)
            last_word = word
        if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
            parse_text.append(word_list)
            word_list = []
    return parse_text
2 để quét một bộ sưu tập các tệp PDF.

Tesseract là hoàn hảo để quét các tài liệu sạch và rõ ràng. Quét chất lượng kém có thể tạo ra kết quả kém trong OCR. Thông thường, nó không cung cấp kết quả chính xác của các hình ảnh bị ảnh hưởng bởi các tạo tác bao gồm tắc một phần, phối cảnh bị bóp méo và nền tảng phức tạp.

Nhận mã đầy đủ ở đây.

Dưới đây là một số hướng dẫn PDF liên quan khác:

  • Cách làm mờ các tệp PDF trong Python.
  • Cách làm nổi bật và tái cấu trúc văn bản trong các tệp PDF với Python.
  • Làm thế nào để trích xuất hình ảnh từ PDF trong Python.
  • Làm thế nào để trích xuất tất cả các liên kết PDF trong Python.
  • Làm thế nào để trích xuất các bảng từ PDF trong Python.
  • Cách ký các tệp PDF trong Python.
  • Làm thế nào để trích xuất siêu dữ liệu PDF trong Python.

Cuối cùng, nếu bạn là người mới bắt đầu và muốn học Python, tôi khuyên bạn nên tham gia khóa học & nbsp; Python cho mọi người Coursera, trong đó bạn sẽ tìm hiểu rất nhiều về Python. Bạn cũng có thể kiểm tra trang tài nguyên và khóa học của chúng tôi để xem tài nguyên Python tôi đề xuất về các chủ đề khác nhau!

Happy Coding ♥

Xem đầy đủ mã


Cũng đọc


Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét

Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét

Hướng dẫn extract data from scanned pdf python - trích xuất dữ liệu từ pdf python được quét


Bảng bình luận

Làm cách nào để trích xuất dữ liệu từ PDF được quét?

5 cách để trích xuất dữ liệu từ các tài liệu PDF..
Sao chép và dán..
Bộ chuyển đổi PDF ..
Nhập dữ liệu thủ công gia công ..
Công cụ trích xuất bảng PDF ..
Tự động hóa trích xuất dữ liệu PDF ..

Làm cách nào để trích xuất dữ liệu cụ thể từ PDF trong Python?

Có một vài thư viện Python sử dụng mà bạn có thể trích xuất dữ liệu từ PDFS. Ví dụ: bạn có thể sử dụng thư viện PYPDF2 để trích xuất văn bản từ các tệp PDF trong đó văn bản theo cách tuần tự hoặc được định dạng, tức là trong các dòng hoặc biểu mẫu. Bạn cũng có thể trích xuất các bảng trong các tệp PDF thông qua thư viện Camelot.use the PyPDF2 library for extracting text from PDFs where text is in a sequential or formatted manner i.e. in lines or forms. You can also extract tables in PDFs through the Camelot library.

Làm cách nào để đọc một bản pdf được quét trong Python?

Đầu tiên, chúng ta cần chuyển đổi các trang của PDF thành hình ảnh và sau đó, sử dụng OCR (nhận dạng ký tự quang học) để đọc nội dung từ hình ảnh và lưu trữ trong tệp văn bản ...
Lưu trữ đĩa được sử dụng để lưu trữ các hình ảnh trong hệ thống cục bộ.....
Sử dụng OCR không thể đảm bảo độ chính xác 100% ..

Làm cách nào để trích xuất dữ liệu cụ thể từ PDF?

Cách tiếp cận bản sao & dán là lựa chọn thực tế nhất khi xử lý một số lượng nhỏ các tài liệu PDF đơn giản ...
Mở từng tệp PDF ..
Lựa chọn một phần dữ liệu hoặc văn bản trên một trang hoặc bộ trang cụ thể ..
Sao chép thông tin đã chọn ..
Dán thông tin đã sao chép vào tệp tài liệu, XLS hoặc CSV ..