1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで選択した範囲の文字列を読みとって、txtファイルに出力してみた(そしてショートカット起動へ...)

Last updated at Posted at 2024-08-24

今回つくるやつは、以下を組み合わせたやつ

  1. ショートカットキーに、Pythonを実行するためのbatファイルを登録
  2. PyQt5で作ったSnipping Tool
  3. pytesseractで、文字識別

対象者

  • なんか暇つぶしに作りたい人
  • Pythonを学びたい初学者
  • リモートデスクトップ先の文字をコピりたいやつ
  • なんか同じようなものを作ろうとして、詰んでるやつ

注意書き

2024年08月24日(土)時点での実装です
(だいたい5年経ってたら大きく仕様変わってるかも)

準備するもの(手順は後述)

  1. Pythonの実行環境(実行環境は自力で作って)
  2. tessreractインストール(これの「tessreractインストール」の部分だけをみて作って)
  3. Pythonを実行するだけの、batファイル
  4. Pythonファイル
  5. Windows 11
  6. テストステロン

1.batファイルに登録したmain.pyの作成

1-1. エディタで下記の内容をmain.pyとして保存する

# -*- coding: utf-8 -*-

import sys
from PyQt5 import QtWidgets, QtCore, QtGui
import tkinter as tk
from PIL import ImageGrab
import numpy as np
import cv2
import pytesseract
import os

class MyWidget(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()
        root = tk.Tk()
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        self.setGeometry(0,0,screen_width, screen_height)
        self.setWindowTitle("")
        self.setWindowOpacity(0.3)
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.begin = QtCore.QPoint()
        self.end = QtCore.QPoint()

        print("Capture the screen...")
        self.show()

    def paintEvent(self, event):
        qp = QtGui.QPainter(self)
        qp.setPen(QtGui.QPen(QtGui.QColor("black"), 3))
        qp.setBrush(QtGui.QColor(128, 128, 255, 128))
        qp.drawRect(QtCore.QRect(self.begin, self.end))       

    def mousePressEvent(self, event):
        self.begin = event.pos()
        self.end = self.begin
        self.update()

    def mouseMoveEvent(self, event):
        self.end = event.pos()
        self.update()

    def mouseReleaseEvent(self, event):
        self.end = event.pos()
        self.close()

        x1 = min(self.begin.x(), self.end.x())
        y1 = min(self.begin.y(), self.end.y())
        x2 = max(self.begin.x(), self.end.x())
        y2 = max(self.begin.y(), self.end.y())

        img = ImageGrab.grab(bbox=(x1,y1,x2,y2))
        img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)

        # Tesseractのフルパスを指定
        pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

        # OCR結果を保存するディレクトリのパス
        OUTPUT_DIR = './'

        # OCRでテキストを抽出
        config = '--tessdata-dir "C:\\Program Files\\Tesseract-OCR\\tessdata"'
        text = pytesseract.image_to_string(img, config=config)

        # テキストファイルに出力
        output_file_path = os.path.join(OUTPUT_DIR, f"OCR.txt")
        with open(output_file_path, 'w', encoding='utf-8') as f:
            f.write(text)
            
        cv2.destroyAllWindows()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MyWidget()
    window.show()
    app.aboutToQuit.connect(app.deleteLater)
    sys.exit(app.exec_())


2.ショートカットキーに、Pythonを実行するbatを登録

2-1.batファイルを以下の通りに作る、名前は好きにしていいよ、ただmain.pyと同じディレクトリに保存して

@echo off
start "" "python" "main.py"

2-2.「エクスプローラー」上で、作ったbatファイルを右クリック->その他のオプションを確認->ショートカットの作成(S)をクリック
image.png

2-3. 出来上がったショートカットファイルを、デスクトップに置く

デスクトップに置かないと、ショートカットキーが実行できない)らしい

2-4.デスクトップにあるショートカットファイルを右クリック->プロパティ->「ショートカット」タブ->ショートカットキーに、任意のキーを登録->適用->OK

「Ctrl+Alt」との組み合わせは必須で、なおかつ他のソフトで使用されていないようなやつにしたほうがいいよ

感想

なんか面白いものを作ってみたくて、思いついたものをいろいろなサイトを参考にしながら作ってみた。
妥協したところはありつつも、結構面白いものができて満足です。
次回は「e-typingをスクレイピング&文字識別して、ランキング1位取ってみた」を公開します!

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?