11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Windows】【Python】PDFファイルを画像化してOpenCVで扱う

Last updated at Posted at 2019-05-31

PythonでPDFを画像として取り込みたかったためメモ。

pdf2imageを利用して実現しています。pillowに依存にしているようなため、以下でインストール。

pip install pdf2image
pip install pillow

また、PDF閲覧にpopplerライブラリを利用するため、「Poppler for Windows」から、poppler-0.68.0_x86.7z(2019/5/31時点最新版)をダウンロードして適当な場所に解凍。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# pyinstaller --onefile pdfcrop.py

import os
import numpy as np
import cv2 as cv
import pdf2image


def main():
    # popplerへの環境変数PATHを一時的に付与 ###################################
    poppler_path = os.path.join(os.getcwd(), "poppler-0.68.0", "bin")
    os.environ["PATH"] += os.pathsep + poppler_path

    # pdf2imageを用いてPDFファイルを画像へ変換 ################################
    filepath = os.path.abspath(os.path.dirname(__file__))
    filepath = os.path.join(filepath, "pdf", "template.pdf")

    pdfimages = pdf2image.convert_from_path(filepath)

    # 読み込んだ画像はRGB形式のためBRGへ変換し画面表示 #########################
    cvimage = np.asarray(pdfimages[0])
    cvimage = cv.cvtColor(cvimage, cv.COLOR_RGB2BGR)
    cvimage = cv.resize(cvimage, (480, 640))

    cv.imshow("pdf2image sample", cvimage)

    cv.waitKey(-1)


if __name__ == '__main__':
    main()

以上。

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?