CyberChaos(さいばかおす)

プログラミング言語、トランスパイラ、RPA、ChatGPT、データマイニング、リバースエンジニアリングのための忘備録

OCRリーダープロトタイプ作成

2024-01-23 22:04:23 | python
Tesseractのインストールパスを次のように指定するだけで動くようになった。環境構築とか環境変数とかパスがどうのこうのとか難しいことは抜きにして、Tesseractをインストールするだけで済むようになっている。
C:Program FilesTesseract-OCR esseract.exe

各自Tesseractをどこにインストールしたか覚えておいて、上記の部分を書き換えれば良い。もちろんPyQt5とかライブラリのインストールもpip install ライブラリ名で忘れずに。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QTextEdit, QFileDialog
from PyQt5.QtGui import QPixmap, QImage, QFont
from PIL import Image as PilImage
import pytesseract

class OCRApp(QMainWindow):
def __init__(self):
super().__init__()

self.image_path = None

# Tesseractのインストールパスを指定
tesseract_path = r'C:Program FilesTesseract-OCR esseract.exe'
pytesseract.pytesseract.tesseract_cmd = tesseract_path

self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)

self.init_ui()

def init_ui(self):
layout = QVBoxLayout()

self.image_label = QLabel("画像がここに表示されます")
layout.addWidget(self.image_label)

file_button = QPushButton("ファイルを選択", self)
file_button.clicked.connect(self.select_file)
layout.addWidget(file_button)

ocr_button = QPushButton("OCR実行", self)
ocr_button.clicked.connect(self.perform_ocr)
layout.addWidget(ocr_button)

self.result_text = QTextEdit("OCR結果がここに表示されます")
layout.addWidget(self.result_text)

self.central_widget.setLayout(layout)

def select_file(self):
options = QFileDialog.Options()
options |= QFileDialog.ReadOnly
file_path, _ = QFileDialog.getOpenFileName(self, "ファイルを選択", "", "Images (*.png *.jpg *.jpeg);;All Files (*)", options=options)
if file_path:
self.image_path = file_path
self.display_selected_image()

def display_selected_image(self):
try:
pil_image = PilImage.open(self.image_path)
pil_image = pil_image.resize((300, 300)) # サイズを適当に変更

qimage = self.pil_image_to_qimage(pil_image)
pixmap = QPixmap.fromImage(qimage)

self.image_label.setPixmap(pixmap)
except Exception as e:
self.result_text.setPlainText(f"Error: {str(e)}")

def pil_image_to_qimage(self, pil_image):
width, height = pil_image.size
bytes_per_line = 3 * width
image = QImage(pil_image.tobytes("raw", "RGB"), width, height, bytes_per_line, QImage.Format_RGB888)
return image

def perform_ocr(self):
if self.image_path:
try:
image = PilImage.open(self.image_path)
text = pytesseract.image_to_string(image, lang='jpn')
self.result_text.setPlainText(text)
except Exception as e:
self.result_text.setPlainText(f"Error: {str(e)}")
else:
self.result_text.setPlainText("ファイルが選択されていません.")

if __name__ == "__main__":
app = QApplication(sys.argv)

# フォントをMS Gothicに設定
font = QFont("MS Gothic", 12)
app.setFont(font)

window = OCRApp()
window.setWindowTitle("OCR Reader")
window.setGeometry(100, 100, 500, 500)
window.show()

sys.exit(app.exec_())

結果は上々、後はディープラーニングでチューニングできるように改造するだけ。



最新の画像もっと見る

コメントを投稿

ブログ作成者から承認されるまでコメントは反映されません。