From 0b4e0c0580a5db5c251d59fda95c9351ab65a570 Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Sun, 7 Jun 2026 04:07:21 +0000 Subject: [PATCH] Add 10 ocr python-java tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: general Source: AI Search API Tutorials: - How to OCR PDF with Aspose OCR Cloud – Complete Guide - Python OCR Tutorial – Recognize Image Text with GPU Acceleration - Extract Text from Images PDF – Python Guide to Convert Scanned Documents to Text - How to Preprocess Images for OCR – Complete Python Guide - OCR PNG Image in Python – Full Step‑by‑Step Guide - How to OCR PDF in Python – Create Searchable PDF from Images - Run OCR on Image with Python – Complete Step‑by‑Step Guide - Extract Text from Image Using Python OCR – Complete Guide - How to OCR PDF in Python – Complete Step‑by‑Step Guide - recognize text from image in Python – Full OCR Engine Setup Guide Auto-generated by Professionalize.Tutorials Agent --- .../_index.md | 216 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 219 +++++++++++ .../_index.md | 292 +++++++++++++++ .../_index.md | 205 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 334 +++++++++++++++++ .../_index.md | 302 ++++++++++++++++ .../_index.md | 272 ++++++++++++++ .../_index.md | 337 +++++++++++++++++ .../_index.md | 214 +++++++++++ .../_index.md | 215 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 290 +++++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 232 ++++++++++++ .../_index.md | 332 +++++++++++++++++ .../_index.md | 282 +++++++++++++++ .../_index.md | 270 ++++++++++++++ .../_index.md | 335 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 277 ++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 236 ++++++++++++ .../_index.md | 320 +++++++++++++++++ .../_index.md | 288 +++++++++++++++ .../_index.md | 259 +++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 275 ++++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 235 ++++++++++++ .../_index.md | 336 +++++++++++++++++ .../_index.md | 301 ++++++++++++++++ .../_index.md | 276 ++++++++++++++ .../_index.md | 330 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 219 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 294 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 236 ++++++++++++ .../_index.md | 336 +++++++++++++++++ .../_index.md | 303 ++++++++++++++++ .../_index.md | 274 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 295 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 320 +++++++++++++++++ .../_index.md | 302 ++++++++++++++++ .../_index.md | 275 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 219 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 294 +++++++++++++++ .../_index.md | 206 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 319 ++++++++++++++++ .../_index.md | 286 +++++++++++++++ .../_index.md | 261 ++++++++++++++ .../_index.md | 340 ++++++++++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 294 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 235 ++++++++++++ .../_index.md | 322 +++++++++++++++++ .../_index.md | 301 ++++++++++++++++ .../_index.md | 275 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 216 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 292 +++++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 235 ++++++++++++ .../_index.md | 319 ++++++++++++++++ .../_index.md | 300 ++++++++++++++++ .../_index.md | 262 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 214 +++++++++++ .../_index.md | 214 +++++++++++ .../_index.md | 215 +++++++++++ .../_index.md | 290 +++++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 232 ++++++++++++ .../_index.md | 317 ++++++++++++++++ .../_index.md | 286 +++++++++++++++ .../_index.md | 270 ++++++++++++++ .../_index.md | 335 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 294 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 336 +++++++++++++++++ .../_index.md | 301 ++++++++++++++++ .../_index.md | 276 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 294 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 331 +++++++++++++++++ .../_index.md | 301 ++++++++++++++++ .../_index.md | 272 ++++++++++++++ .../_index.md | 340 ++++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 275 ++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 235 ++++++++++++ .../_index.md | 319 ++++++++++++++++ .../_index.md | 302 ++++++++++++++++ .../_index.md | 275 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 214 +++++++++++ .../_index.md | 214 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 291 +++++++++++++++ .../_index.md | 200 +++++++++++ .../_index.md | 231 ++++++++++++ .../_index.md | 332 +++++++++++++++++ .../_index.md | 284 +++++++++++++++ .../_index.md | 270 ++++++++++++++ .../_index.md | 333 +++++++++++++++++ .../_index.md | 216 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 292 +++++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 232 ++++++++++++ .../_index.md | 334 +++++++++++++++++ .../_index.md | 286 +++++++++++++++ .../_index.md | 277 ++++++++++++++ .../_index.md | 337 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 219 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 275 ++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 232 ++++++++++++ .../_index.md | 335 +++++++++++++++++ .../_index.md | 303 ++++++++++++++++ .../_index.md | 269 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 293 +++++++++++++++ .../_index.md | 205 +++++++++++ .../_index.md | 236 ++++++++++++ .../_index.md | 319 ++++++++++++++++ .../_index.md | 285 +++++++++++++++ .../_index.md | 274 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 219 +++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 293 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 324 +++++++++++++++++ .../_index.md | 293 +++++++++++++++ .../_index.md | 261 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 292 +++++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 319 ++++++++++++++++ .../_index.md | 302 ++++++++++++++++ .../_index.md | 261 ++++++++++++++ .../_index.md | 339 +++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 290 +++++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 331 +++++++++++++++++ .../_index.md | 300 ++++++++++++++++ .../_index.md | 259 +++++++++++++ .../_index.md | 338 +++++++++++++++++ .../_index.md | 216 +++++++++++ .../_index.md | 215 +++++++++++ .../_index.md | 219 +++++++++++ .../_index.md | 292 +++++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 232 ++++++++++++ .../_index.md | 334 +++++++++++++++++ .../_index.md | 300 ++++++++++++++++ .../_index.md | 274 ++++++++++++++ .../_index.md | 334 +++++++++++++++++ .../_index.md | 220 ++++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 217 +++++++++++ .../_index.md | 295 +++++++++++++++ .../_index.md | 204 +++++++++++ .../_index.md | 234 ++++++++++++ .../_index.md | 333 +++++++++++++++++ .../_index.md | 301 ++++++++++++++++ .../_index.md | 274 ++++++++++++++ .../_index.md | 340 ++++++++++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 218 +++++++++++ .../_index.md | 221 ++++++++++++ .../_index.md | 293 +++++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 235 ++++++++++++ .../_index.md | 319 ++++++++++++++++ .../_index.md | 301 ++++++++++++++++ .../_index.md | 260 ++++++++++++++ .../_index.md | 338 +++++++++++++++++ 230 files changed, 60051 insertions(+) create mode 100644 ocr/arabic/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/arabic/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/arabic/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/arabic/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/arabic/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/arabic/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/arabic/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/arabic/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/chinese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/chinese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/chinese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/chinese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/chinese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/chinese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/chinese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/chinese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/czech/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/czech/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/czech/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/czech/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/czech/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/czech/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/czech/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/czech/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/czech/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/czech/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/dutch/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/dutch/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/dutch/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/dutch/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/dutch/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/dutch/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/dutch/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/dutch/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/english/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/english/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/english/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/english/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/english/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/english/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/english/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/english/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/english/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/english/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/french/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/french/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/french/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/french/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/french/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/french/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/french/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/french/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/french/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/french/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/german/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/german/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/german/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/german/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/german/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/german/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/german/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/german/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/german/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/german/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/greek/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/greek/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/greek/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/greek/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/greek/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/greek/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/greek/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/greek/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/greek/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/greek/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hindi/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/hindi/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/hindi/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/hindi/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/hindi/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/hindi/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/hindi/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/hindi/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/hongkong/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/hongkong/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/hongkong/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/hungarian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/hungarian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/hungarian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/indonesian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/indonesian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/indonesian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/italian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/italian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/italian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/italian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/italian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/italian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/italian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/italian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/italian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/italian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/japanese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/japanese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/japanese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/japanese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/japanese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/japanese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/japanese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/japanese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/korean/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/korean/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/korean/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/korean/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/korean/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/korean/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/korean/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/korean/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/korean/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/korean/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/polish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/polish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/polish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/polish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/polish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/polish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/polish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/polish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/polish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/polish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/portuguese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/portuguese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/portuguese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/russian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/russian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/russian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/russian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/russian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/russian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/russian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/russian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/russian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/russian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/spanish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/spanish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/spanish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/spanish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/spanish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/spanish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/spanish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/spanish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/swedish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/swedish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/swedish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/swedish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/swedish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/swedish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/swedish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/swedish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/thai/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/thai/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/thai/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/thai/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/thai/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/thai/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/thai/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/thai/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/thai/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/thai/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/turkish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/turkish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/turkish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/turkish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/turkish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/turkish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/turkish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/turkish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md create mode 100644 ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md create mode 100644 ocr/vietnamese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md create mode 100644 ocr/vietnamese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md create mode 100644 ocr/vietnamese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md diff --git a/ocr/arabic/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/arabic/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..d0b92f068 --- /dev/null +++ b/ocr/arabic/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-06-06 +description: استخراج النص من الصورة باستخدام OCR في بايثون خلال دقائق. اكتشف OCR للصور + متعددة اللغات، واكتشاف اللغة تلقائيًا، وكيفية استخراج نص OCR بدقة. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: ar +og_description: استخراج النص من الصورة باستخدام OCR في بايثون بسرعة. تعلم OCR للصور + متعددة اللغات، واكتشاف اللغة تلقائيًا، وكيفية استخراج نص OCR خطوة بخطوة. +og_title: استخراج النص من الصورة باستخدام بايثون OCR – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: استخراج النص من الصورة باستخدام بايثون OCR – دليل كامل +url: /ar/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استخراج النص من صورة باستخدام Python OCR – دليل كامل + +هل احتجت يوماً إلى **استخراج النص من صورة** لكن لم تكن متأكدًا أي مكتبة يمكنها التعامل مع عدة لغات تلقائيًا؟ لست وحدك—المطورون يسألون باستمرار *كيفية استخراج نص OCR* عند التعامل مع مستندات دولية، إيصالات، أو منشورات ممسوحة. في هذا الدرس سنستعرض مثالًا عمليًا بلغة Python لا يقتصر على استخراج النص من الصورة فحسب، بل **يكشف اللغة** تلقائيًا، مما يجعل OCR للصور متعددة اللغات سهلًا للغاية. + +سنغطي كل شيء بدءًا من تثبيت حزمة OCR إلى تمكين **auto detect language OCR**، تشغيل المحرك على صورة تجريبية، وأخيرًا طباعة كل من اللغة المكتشفة والسلسلة المستخرجة. بنهاية الدرس ستحصل على مقتطف يمكن إعادة استخدامه في أي مشروع، سواء كنت تبني خط أنابيب ترجمة أو خدمة استيعاب بيانات. + +## إعداد البيئة لاستخراج النص من الصورة + +قبل الغوص في الكود، تأكد أن جهازك يلبي المتطلبات الدنيا التالية: + +- Python 3.8 أو أحدث (المكتبة تستخدم type hints التي تتجاهلها الإصدارات القديمة) +- `pip` لإدارة الحزم +- ملف صورة يحتوي على نص على الأقل بلغتين مختلفتين (مثال: الإنجليزية + الإسبانية) + +ستحتاج أيضًا إلى مكتبة OCR التي تشغل هذا المثال. من أجل هذا الدليل سنستخدم الحزمة الوهمية `ocr`، التي تحاكي الأدوات الواقعية الشهيرة مثل Tesseract أو EasyOCR لكنها تقدم واجهة Python نظيفة. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **نصيحة احترافية:** إذا واجهت أخطاء صلاحية، أضف `python -m` قبل الأمر أو استخدم بيئة افتراضية—هذا يحافظ على حزم الموقع العامة مرتبة. + +## إنشاء كائن محرك OCR + +الآن بعد أن أصبحت المكتبة جاهزة، الخطوة المنطقية الأولى هي **إنشاء كائن محرك OCR**. فكر في المحرك كماسح ذكي يمكنك ضبطه قبل تغذيته بالصور. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +لماذا ننشئ كائن المحرك منفصلًا بدلاً من استدعاء طريقة ثابتة؟ كائن المحرك يحتفظ بحالة التكوين (مثل تفضيلات اللغة) التي قد ترغب في إعادة استخدامها عبر عدة صور، مما يوفر عليك عبء إعادة تهيئته في كل مرة. + +## تمكين وضع الكشف التلقائي للغة OCR + +معظم أدوات OCR تتطلب منك تحديد رمز اللغة—`eng` للإنجليزية، `spa` للإسبانية، وهكذا. التخمين اليدوي للغة يُفقدك هدف **OCR للصور متعددة اللغات**. لحسن الحظ، حزمة `ocr` تقدم وضع *auto detect language OCR* الذي يفحص الصورة ويختار نموذج اللغة الأنسب خلف الكواليس. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +تمكين **detect language OCR** بهذه الطريقة يعني أنك لن تحتاج إلى الحفاظ على قائمة طويلة من رموز اللغات. سيحاول المحرك مطابقة الخط الذي يراه—Latin، Cyrillic، Han، إلخ—ويحمّل النموذج المناسب تلقائيًا. + +## تنفيذ OCR للصور متعددة اللغات + +بعد تهيئة المحرك، حان الوقت فعليًا **لاستخراج النص من الصورة**. الطريقة `recognize_image` تستقبل مسار الملف وتعيد كائن نتيجة يحتوي على كل من النص الخام واللغة التي تم اكتشافها. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +إذا كنت تتساءل *كيف تستخرج نص OCR* من ملف PDF بدلًا من PNG، فإن نفس المحرك يقدم `recognize_pdf`—فقط غيّر اسم الطريقة. منطق الكشف الأساسي يبقى هو نفسه، لذا ستحصل على نفس ميزة **auto detect language OCR**. + +## عرض اللغة المكتشفة والنص المستخرج + +أخيرًا، نطبع ما اكتشفه المحرك. كائن النتيجة يوفّر `detected_language` (علامة BCP‑47 مثل `en` أو `es`) و`text`، الذي يحمل ناتج OCR الخام. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +تشغيل السكريبت على صورتنا التجريبية يجب أن ينتج شيئًا مشابهًا لـ: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +لاحظ كيف حدد المحرك الإنجليزية كلغة أساسية، لكنه لا يزال يلتقط السطر الإسباني—تمامًا ما تتوقعه من حل **OCR للصور متعددة اللغات** قوي. + +### ماذا لو فشل الكشف؟ + +أحيانًا قد يلجأ محرك OCR إلى لغة افتراضية (عادةً الإنجليزية) إذا كانت الصورة غير واضحة أو الخط غريب جدًا. في تلك الحالات يمكنك فرض قائمة لغات: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +لكن تذكر، فرض اللغات يُفقدك راحة **auto detect language OCR**، لذا استخدمه فقط عندما تكون على علم بمجموعة لغات محددة. + +## الأخطاء الشائعة وكيفية استخراج نص OCR بثقة + +حتى مع الكشف التلقائي، قد تواجه بعض العقبات: + +1. **صور منخفضة الدقة** – تنخفض دقة OCR بشكل حاد تحت 150 dpi. قم بزيادة الدقة أو اطلب مسحًا عالي الدقة. +2. **الضوضاء وعيوب الضغط** – طبّق مرشح عتبة بسيط (`opencv` أو `Pillow`) قبل تمرير الصورة إلى المحرك. +3. **خطوط مختلطة في صفحة واحدة** – بعض المحركات تكافح مع الأحرف اللاتينية وCJK معًا. قسّم الصفحة إلى مناطق وشغّل التعرف بشكل منفصل إذا لزم الأمر. + +معالجة هذه القضايا تحسّن بشكل كبير جودة عملية **استخراج النص من صورة**، خاصةً عند التعامل مع مستندات متعددة اللغات في العالم الحقيقي. + +## مثال كامل جاهز للتنفيذ + +فيما يلي السكريبت الكامل الجاهز للتنفيذ الذي يجمع كل الخطوات التي ناقشناها. احفظه باسم `multilingual_ocr.py` وشغّله من سطر الأوامر. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**الناتج المتوقع** (مع افتراض أن الصورة التجريبية تحتوي على نص إنجليزي وإسباني): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +لا تتردد في استبدال `multilang_page.png` بأي صورة تحتوي نصًا بلغات أخرى—بفضل **auto detect language OCR**، سيظل السكريبت يعطك علامة لغة منطقية والنص المقابل. + +![مثال لاستخراج النص من صورة](https://example.com/ocr-sample.png "استخراج النص من صورة") + +## الخلاصة + +أنت الآن تعرف بالضبط **كيفية استخراج نص OCR** من صورة، وكيفية تمكين **auto detect language OCR**، وكيفية التعامل مع سيناريوهات **OCR للصور متعددة اللغات** بأقل قدر من الكود. بإنشاء كائن محرك OCR، وتفعيل الكشف التلقائي للغة، واستدعاء `recognize_image`، يمكنك سحب كل من معرف اللغة والنص الخام بثقة. + +ما الخطوة التالية؟ جرّب تمرير السلاسل المستخرجة إلى واجهة برمجة تطبيقات ترجمة، احفظها في قاعدة بيانات قابلة للبحث، أو اجمع عدة صفحات في تقرير PDF واحد. يمكنك أيضًا تجربة محركات OCR مختلفة (Tesseract، EasyOCR، Google Vision) مع الحفاظ على نفس سير العمل عالي المستوى—بفضل واجهة **detect language OCR** المتسقة. + +إذا صادفت أي شذوذ، راجع قسم “الأخطاء الشائعة” أو عدّل خطوات ما قبل معالجة الصورة. برمجة سعيدة، ولتكن مشاريعك القادمة مليئة بنصوص مكتشفة بشكل صحيح ومستخرجة بدقة! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك الخاصة. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/arabic/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..e1b08de80 --- /dev/null +++ b/ocr/arabic/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: استخراج النص من ملفات PDF التي تحتوي على صور باستخدام OCR في بايثون. + تعلم كيفية تحويل المستندات الممسوحة ضوئياً إلى نص بسرعة باستخدام التعرف غير المتزامن + على دفعات. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: ar +og_description: استخراج النص من صور PDF باستخدام بايثون. يوضح هذا الدليل خطوة بخطوة + كيفية تحويل المستندات الممسوحة ضوئياً إلى نص باستخدام OCR غير المتزامن. +og_title: استخراج النص من صور PDF – دليل Python OCR +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: استخراج النص من ملفات PDF الصور – دليل بايثون لتحويل المستندات الممسوحة ضوئياً + إلى نص +url: /ar/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استخراج النص من ملفات PDF التي تحتوي على صور – دليل بايثون لتحويل المستندات الممسوحة ضوئياً إلى نص + +هل احتجت يوماً إلى **استخراج النص من ملفات PDF التي تحتوي على صور** دون قضاء ساعات في إعادة الكتابة؟ في هذا الدليل سنوضح لك كيفية **تحويل المستندات الممسوحة ضوئياً إلى نص** باستخدام سير عمل OCR غير متزامن بسيط في بايثون. + +إذا كنت قد حدقت في مجموعة من ملفات PDF الممسوحة وتفكرت، “يجب أن يكون هناك طريقة أسرع”، فأنت في المكان الصحيح. سنستعرض كل سطر من الشيفرة، نشرح لماذا كل جزء مهم، وحتى نتناول بعض الحالات الخاصة التي قد تواجهها. + +## ما ستتعلمه + +- كيفية تشغيل محرك OCR وتحديد لغة التعرف. +- آلية تمرير قائمة مختلطة من PNGs و PDFs إلى مُعَرِّف دفعي. +- تشغيل مهمة OCR بشكل غير متزامن بحيث يبقى تطبيقك مستجيباً. +- سحب النتائج، ربطها بالملفات المصدر، وطباعة مخرجات نظيفة. + +**المتطلبات المسبقة**: بايثون 3.8+، فهم أساسي لـ `asyncio` أو `concurrent.futures`، ومكتبة OCR توفر فئة `OcrEngine` مشابهة للمثال (مثل Aspose.OCR، أو غلاف Tesseract، أو غلاف مخصص). لا حاجة لإعدادات معقدة—فقط قم بتثبيت المكتبة وستكون جاهزاً. + +![استخراج النص من ملفات PDF التي تحتوي على صور](https://example.com/placeholder.png "لقطة شاشة لمخرجات OCR – استخراج النص من ملفات PDF التي تحتوي على صور") + +## استخراج النص من ملفات PDF التي تحتوي على صور – إعداد محرك OCR + +أول شيء تحتاجه هو نسخة من محرك OCR مُكوَّنة للغة مستنداتك. في مثالنا سنستخدم اللغة الفرنسية، لكن يمكنك استبدالها بأي لغة مدعومة. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**لماذا هذا مهم**: ضبط اللغة مسبقاً يحسّن الدقة بشكل كبير. يستخدم المحرك قواميس ونماذج حروف مخصَّصة للغة؛ تمريره بلغة خاطئة هو سبب شائع للمخرجات المشوَّهة. + +## إعداد قائمة الملفات – الصور وPDF معاً + +يمكن لمُعَرِّف الدفعات التعامل مع كل من الصور النقطية (`.png`, `.jpg`) وحاويات PDF. ما عليك سوى تمرير قائمة بايثون عادية من مسارات الملفات. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**نصيحة**: احرص على أن تكون القائمة مسطحة؛ سيقوم المحرك داخلياً بفك كل صفحة PDF إلى صور قبل التعرف. إذا كان لديك آلاف الملفات، فكر في تقسيم القائمة إلى دفعات أصغر لتجنب ارتفاع استهلاك الذاكرة. + +## بدء التعرف الدفعي غير المتزامن + +بدلاً من حجز الخيط الرئيسي، نطلق مهمة OCR في الخلفية. تُعيد الطريقة كائن `Future` سيحمل في النهاية قائمة من كائنات `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**كيف يعمل**: تحت الغطاء، يُنشئ المحرك مجموعة من الخيوط (أو مهمة غير متزامنة، حسب التنفيذ). هذا يتيح لك متابعة أعمال أخرى—مثل تحديث واجهة المستخدم، جلب ملفات إضافية، أو تسجيل التقدم—بينما يتم تنفيذ الجزء الثقيل في مكان آخر. + +## القيام بشيء مفيد أثناء تشغيل OCR + +خطأ شائع هو الجلوس بلا فعل واستطلاع الـ `Future` في حلقة ضيقة. بدلاً من ذلك، يمكنك تنفيذ أي عمل غير مرتبط. للعرض، سنطبع سطر حالة بسيط. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## جمع النتائج بمجرد اكتمال الـ Future + +عندما تكون جاهزاً لجمع مخرجات OCR، استخدم `as_completed` من `concurrent.futures`. هذا النمط يعمل سواء كان لديك `Future` واحد أو عدة. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**ما ستراه**: مسار كل ملف يليه تمثيل النص المستخرج. بالنسبة لملفات PDF، يحتوي `result.text` على النص المدمج لجميع الصفحات. + +### النتيجة المتوقعة (مثال) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +إذا لاحظت فقدان أحرف، تحقق من أن اللغة التي ضبطتها تتطابق مع لغة المستند، وفكّر في معالجة الصور مسبقاً (تصحيح الميل، زيادة التباين) قبل تمريرها إلى المحرك. + +## التعامل مع الحالات الخاصة والمشكلات الشائعة + +| الحالة | ما يجب فعله | +|-----------|------------| +| **لغات مختلطة** | أجرِ تمريرة لاكتشاف اللغة أولاً، ثم أنشئ محركات منفصلة لكل لغة. | +| **ملفات PDF ضخمة (> 100 ميغابايت)** | قسّم الـ PDF إلى صفحات منفردة على القرص (مثلاً باستخدام `PyPDF2`) ومرّرها كمدخلات منفصلة. | +| **أنظمة كتابة غير لاتينية** | تأكّد من أن مكتبة OCR تتضمن حزمة اللغة المطلوبة؛ بعض المكتبات تحتاج إلى تنزيل ملفات بيانات إضافية. | +| **عنق زجاجة في الأداء** | زد حجم مجموعة الخيوط (`engine.set_thread_pool_size(8)`) أو انتقل إلى خلفية مدعومة بالـ GPU إذا كانت متاحة. | +| **نص مفقود في صور منخفضة الدقة** | عالج الصور باستخدام OpenCV: `cv2.resize`, `cv2.threshold`, و `cv2.medianBlur` لتحسين القابلية للقراءة. | + +## مثال كامل يعمل (جاهز للنسخ واللصق) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +احفظه باسم `extract_text_async.py`، استبدل `YOUR_DIRECTORY` بمسار ملفاتك، ثبّت حزمة OCR (`pip install your-ocr-lib`)، ثم شغّل `python extract_text_async.py`. يجب أن ترى مخرجات الكونسول كما هو موضح أعلاه. + +## الخطوات التالية – ما بعد الاستخراج الأساسي + +- **ما بعد المعالجة**: إزالة الفراغات الزائدة، توحيد Unicode (`unicodedata.normalize`)، أو تشغيل مدقق إملائي لتنظيف ضوضاء OCR. +- **مخرجات منظمة**: تصدير النتائج إلى CSV أو JSON أو مباشرة إلى قاعدة بيانات للبحث اللاحق. +- **دفعات متوازية**: إذا كان لديك مئات الملفات، أنشئ عدة `Future` واستخدم طابوراً لإبقاء المعالج مشغولاً دون إغراق الذاكرة. +- **التكامل مع أطر الويب**: اربط هذا السكربت بنقطة نهاية Flask أو FastAPI لتوفير OCR حسب الطلب كخدمة. + +--- + +### TL;DR + +أنت الآن تعرف كيف **استخراج النص من ملفات PDF التي تحتوي على صور** باستخدام سكربت بايثون بسيط يعمل OCR بشكل غير متزامن، مما يتيح لك **تحويل المستندات الممسوحة ضوئياً إلى نص** بينما يظل برنامجك مستجيباً. جرّب ضبط إعدادات اللغة، حجم الدفعات، وتقنيات ما قبل المعالجة للحصول على أقصى دقة ممكنة. + +هل لديك طريقة مبتكرة تريد مشاركتها—مثل OCR للملاحظات المكتوبة يدوياً أو خدمة سحابية؟ اترك تعليقاً، ونتمنى لك برمجة سعيدة! + +## ما الذي ينبغي أن تتعلمه لاحقاً؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [استخراج النص من صورة باستخدام Aspose OCR – دليل خطوة بخطوة](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [استخراج النص من الصور باستخدام عملية OCR على المجلدات](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [استخراج النص من الصور باستخدام Aspose.OCR – الأحرف المسموح بها](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..fd0a18687 --- /dev/null +++ b/ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-06-06 +description: كيفية إجراء التعرف الضوئي على الأحرف (OCR) لملف PDF باستخدام بايثون، + استخراج النص من PDF، تحويل نص PDF الممسوح ضوئياً، وتغيير لغة OCR في بضع أسطر من + الشيفرة فقط. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: ar +og_description: 'كيفية التعرف الضوئي على النص في ملفات PDF باستخدام بايثون: دليل عملي + يوضح لك كيفية استخراج النص من ملفات PDF، تحويل نص PDF الممسوح ضوئياً، وتغيير لغة + التعرف الضوئي بسهولة.' +og_title: كيفية إجراء OCR لملف PDF في بايثون – دليل برمجة كامل +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: كيفية تحويل PDF إلى نص باستخدام OCR في بايثون – دليل كامل خطوة بخطوة +url: /ar/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية التعرف الضوئي على النص في ملفات PDF باستخدام بايثون – دليل خطوة بخطوة كامل + +هل تساءلت يومًا **كيف تقوم بالتعرف الضوئي على النص في ملفات PDF** دون دفع تكاليف أدوات SaaS باهظة؟ لست وحدك. سواء كنت تقوم برقمنة الكتب القديمة، أو استخراج البيانات من الفواتير، أو تحتاج فقط إلى نص قابل للبحث من تقرير ممسوح ضوئيًا، فإن إتقان التعرف الضوئي على النص في PDF باستخدام بايثون يمكن أن يوفر لك ساعات من النسخ اليدوي. + +في هذا الدرس سنستعرض مثالًا مختصرًا وعاملاً ي **يستخرج النص من PDF**، ويظهر لك كيفية **تحويل نص PDF الممسوح ضوئيًا** إلى سلاسل قابلة للتحرير، بل ويظهر أيضًا كيفية **تغيير لغة التعرف الضوئي** إذا لم يكن مستندك باللغة الإنجليزية. في النهاية ستحصل على مقتطف قابل لإعادة الاستخدام يمكنك إدراجه في أي مشروع. + +## المتطلبات المسبقة والإعداد + +- Python 3.8+ مثبت (الكود يعمل على 3.9، 3.10، والإصدارات الأحدث) +- حزمة `ocr` التي توفر الفئة `OcrEngine` (يمكنك تثبيتها عبر `pip install ocr-lib` – استبدل باسم الحزمة الحقيقي الذي تستخدمه) +- ملف PDF تريد معالجته؛ في العرض التجريبي سنستخدم `high_res_book.pdf` الموجود في مجلد يسمى `YOUR_DIRECTORY` + +إذا كنت تستخدم بيئة افتراضية (موصى بها بشدة)، فقم بتنشيطها أولاً: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **نصيحة احترافية:** احفظ ملفات PDF الخاصة بك في دليل مخصص `data/` لتجنب مشاكل المسارات لاحقًا. + +## الخطوة 1: إنشاء مثيل محرك التعرف الضوئي (كيفية التعرف الضوئي على PDF – التهيئة) + +أول شيء تحتاج إلى القيام به عندما تريد **إجراء التعرف الضوئي على PDF** هو إنشاء مثيل للمحرك. فكر في المحرك كالعقل الذي سيقرأ كل صفحة، يفسر الرموز، ويعيد لك نصًا عاديًا. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +لماذا هذا مهم: بدون محرك لا يكون لديك سياق لإعدادات اللغة، خيارات العرض، أو معالجة PDF. كائن `OcrEngine` يحتفظ بكل هذه الإعدادات الافتراضية ويسمح لك بتعديلها لاحقًا. + +## الخطوة 2: تعيين لغة التعرف (تغيير لغة OCR) + +معظم مكتبات OCR تكون افتراضيًا باللغة الإنجليزية، ولكن ماذا لو كان مستندك بالفرنسية أو الألمانية أو حتى اليابانية؟ تغيير اللغة يكون بسيطًا كاستدعاء `set_recognition_language`. هذا يلبي متطلبات **تغيير لغة OCR** ويضمن دقة أعلى. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **لماذا قد تحتاج هذا:** غالبًا ما يحتوي أرشيف متعدد اللغات على صفحات مختلطة اللغات. تبديل اللغات أثناء التشغيل يمنع الأخطاء في التعرف على أحرف مثل “ß” أو “ñ”. + +## الخطوة 3: تكوين خيارات عرض PDF (تحويل نص PDF الممسوح بفعالية) + +عند التعامل مع ملفات PDF الممسوحة، تؤثر الدقة ووضع اللون بشكل كبير على جودة OCR. العرض بدقة 300 DPI بالأبيض‑الأسود هو النقطة المثالية لمعظم المستندات—عالية بما يكفي لالتقاط التفاصيل ولكن منخفضة بما يكفي للحفاظ على استهلاك الذاكرة معقولًا. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +قد تبدو الاستدعاءات المتسلسلة فاخرة، لكنها مجرد API سلسة تُعيد نفس كائن الخيارات في كل مرة. إذا كنت تحتاج إلى اللون (مثلاً للرسوم البيانية الملونة)، استبدل `"grayscale"` بـ `"color"`. + +## الخطوة 4: التعرف على PDF واستخراج نص الصفحة الأولى (استخراج النص من PDF) + +الآن يأتي جوهر **كيفية التعرف الضوئي على PDF**: تمرير مسار الملف إلى المحرك واستخراج النص المعترف به. تُعيد الطريقة قائمة بنتائج الصفحات؛ كل نتيجة تحتوي على خاصية `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +إذا كنت تحتاج المستند بالكامل، قم بالتكرار على `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### ماذا لو كان PDF مشفرًا؟ + +بعض ملفات PDF محمية بكلمة مرور. في هذه الحالة يمكنك تمرير كلمة المرور إلى `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +سيقوم المحرك بفك التشفير أثناء التشغيل قبل إجراء OCR—لا خطوات إضافية مطلوبة. + +## الخطوة 5: ما بعد معالجة النص المستخرج (تحسين استخراج النص من PDF) + +غالبًا ما يحتوي ناتج OCR الخام على فواصل أسطر، مسافات إضافية، أو أحرف تم التعرف عليها بشكل خاطئ أحيانًا. روتين تنظيف سريع يجعل السلسلة المستخرجة جاهزة للمعالجة اللاحقة (فهرسة البحث، تخزين قاعدة البيانات، إلخ). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +يمكنك الآن بأمان **استخراج النص من PDF** وإدخاله في أي خط أنابيب NLP، محرك بحث، أو عملية بسيطة `open(...).write()`. + +## إضافي: معالجة دفعة متعددة من ملفات PDF (توسيع أداء OCR على PDF) + +إذا كان لديك مجلد مليء بملفات PDF الممسوحة، قم بلف المنطق داخل حلقة: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +هذا المقتطف يوضح كيفية **إجراء OCR على PDF** بشكل جماعي، وهو احتياج شائع لمشاريع الرقمنة. + +## النتيجة المتوقعة + +تشغيل مثال الصفحة الواحدة (الخطوة 4) يجب أن يطبع شيئًا مشابهًا لـ: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +إذا قمت بمعالجة كتاب متعدد الصفحات، سيعرض الطرفية النص المنظف لكل صفحة، وستترك سكريبت الدفعة ملف `.txt` بجانب كل PDF. + +## المشكلات الشائعة وكيفية تجنبها + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| PDF مصدر منخفض الدقة | حروف مشوشة، كلمات مفقودة | زيادة DPI (`set_dpi(400)` أو أعلى) | +| إعداد لغة خاطئ | العديد من الرموز غير المعروفة، خاصة الأحرف ذات اللكنات | استخدم `engine.set_recognition_language(ocr.Language.FRENCH)` أو التعداد المناسب | +| PDF كبير يسبب خطأ في الذاكرة | `MemoryError` أو تعطل بعد بضع صفحات | معالجة الصفحات على دفعات (`engine.recognize_pdf(..., max_pages=10)`) | +| خطوط مفقودة في PDF | ناتج فارغ لبعض الصفحات | تأكد من أن PDF يحتوي فعليًا على صور نقطية؛ بعض ملفات PDF هي فقط متجهية وتحتاج إلى معالجة مختلفة | + +## توضيح الصورة + +فيما يلي تصور سريع لسير العمل. نص alt مكتوب عمدًا ليتوافق مع تحسين محركات البحث. + +![مخطط سير عمل كيفية التعرف الضوئي على PDF يوضح تهيئة المحرك، إعداد اللغة، خيارات العرض، التعرف، واستخراج النص](/images/ocr-workflow.png) + +*المخطط غير مطلوب لتشغيل الكود، لكنه يساعد المتعلمين البصريين على رؤية موضع كل خطوة.* + +## الخلاصة + +لقد غطينا **كيفية التعرف الضوئي على PDF** باستخدام بايثون من البداية إلى النهاية: إنشاء محرك OCR، **تغيير لغة OCR**، تكوين العرض لتحويل **نص PDF الممسوح**، وأخيرًا **استخراج النص من PDF** للاستخدام لاحقًا. المثال الكامل القابل للتنفيذ جاهز للإدراج في أي مشروع، والسكريبت الاختياري للدفعة يوضح لك كيفية توسيع الحل. + +Next, you might want to explore: + +- إضافة **إجراء OCR على PDF** لأرشيفات متعددة اللغات عبر التكرار على قائمة اللغات. +- دمج النص المستخرج مع Elasticsearch للبحث النصي الكامل. +- استخدام OCR لإنشاء ملفات PDF قابلة للبحث عن طريق تضمين طبقة النص مرة أخرى في الملف الأصلي (العديد من المكتبات توفر طريقة `save_as_searchable_pdf`). + +لا تتردد في التجربة، تعديل إعدادات DPI، أو التحويل إلى محرك OCR مختلف. الأساسيات تبقى كما هي، والآن لديك أساس قوي للبناء عليه. + +برمجة سعيدة، ولتصبح مستنداتك الممسوحة ضوئيًا قابلة للبحث أخيرًا! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [التعرف على نص PDF – عمليات OCR مع Aspose.OCR للـ Java](/ocr/english/java/ocr-operations/) +- [كيفية التعرف الضوئي على نص الصورة مع اللغة باستخدام Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [كيفية التعرف الضوئي على PDF في .NET مع Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..b5002b487 --- /dev/null +++ b/ocr/arabic/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-06 +description: كيفية التعرف الضوئي على النص في ملفات PDF وإنشاء ملفات PDF قابلة للبحث + من الصور باستخدام بايثون. تعلم إضافة نص قابل للبحث وتحويل الصورة إلى PDF/A في دقائق. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: ar +og_description: كيفية تحويل PDF إلى نص باستخدام OCR خطوة بخطوة. تعلم إضافة نص قابل + للبحث وتحويل الصورة إلى PDF/A باستخدام سكريبت بايثون بسيط. +og_title: كيفية تحويل PDF إلى نص باستخدام OCR – دليل سريع لإنشاء ملفات PDF قابلة للبحث +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: كيفية إجراء OCR لملف PDF باستخدام بايثون – إنشاء ملف PDF قابل للبحث من الصور +url: /ar/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية تحويل PDF إلى نص قابل للبحث – تحويل الصور الممسوحة ضوئياً إلى ملفات PDF قابلة للبحث + +هل تساءلت يومًا **كيف تقوم بعمل OCR لملفات PDF** عندما يكون لديك فقط صورة ممسوحة ضوئيًا لفاتورة أو إيصال؟ لست وحدك. في العديد من المكاتب تصل الأوراق الواردة كملفات PNG أو JPEG مسطحة، والخطوة التالية—جعل المحتوى قابلًا للبحث—تبدو كصندوق أسود. + +الخبر السار؟ ببضع أسطر من Python يمكنك **إنشاء ملفات PDF قابلة للبحث**، **إضافة نص قابل للبحث**، وحتى **تحويل الصورة إلى PDF/A** للأرشفة طويلة الأمد. في هذا الدرس سنستعرض كل خطوة، نشرح لماذا هي مهمة، ونزودك بسكريبت جاهز يمكنك وضعه في أي مشروع. + +> **نصيحة احترافية:** نفس النهج يعمل مع المسحات متعددة الصفحات؛ فقط قم بتكرار العملية على الملفات والمحرك سيتولى الجزء الثقيل. + +--- + +## ما ستحتاجه + +قبل أن نبدأ، تأكد من وجود ما يلي على جهازك: + +| المتطلب | لماذا هو مهم | +|-------------|----------------| +| Python 3.9 أو أحدث | صsyntax حديث ودعم أفضل للمكتبات | +| محرك OCR قائم على `pdfium` (مثل `pdfocr` أو SDK تجاري) | يتعامل مع كل من التعرف على الصور وتوليد PDF/A | +| ملف صورة (PNG, JPEG, TIFF) تريد تحويله إلى PDF قابل للبحث | مصدر النص | +| صلاحية كتابة إلى مجلد الإخراج | حتى يتمكن السكريبت من حفظ ملف PDF الجديد | + +إذا لم تقم بتثبيت SDK الخاص بـ OCR بعد، نفّذ: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +هذا كل شيء—بدون تبعيات نظام معقدة، مجرد تثبيت عبر pip. + +--- + +## كيف تقوم بعمل OCR لملف PDF – نظرة عامة + +على مستوى عالٍ، تتكون العملية من ثلاث إجراءات بسيطة: + +1. **التعرف** على النص داخل الصورة مع الحفاظ على الرسومات الأصلية. +2. **تصدير** نتيجة OCR مع الصورة الأصلية كـ **PDF/A قابل للبحث** (نسخة PDF الصديقة للأرشفة). +3. **التحقق** من أن الملف الناتج يحتوي على نص قابل للتحديد والبحث فوق الصورة الأصلية. + +سترى أدناه كل خطوة في الكود، مع شرح *السبب* وراء الأوامر. + +--- + +## الخطوة 1: التعرف على النص من الصورة + +أولًا نطلب من محرك OCR قراءة البكسلات وإرجاع كائن نتيجة يحتوي على كل من الصورة الخام والنص المستخرج. فكر فيه كأن المحرك “يقرأ” الفاتورة لك. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### لماذا هذا مهم + +- **الحفاظ على الرسومات** يعني أن التخطيط البصري (الجداول، الشعارات، الأختام) يبقى تمامًا كما التقطه الماسح. +- عادةً يحتوي كائن `result` على طبقة نص مخفية سندمجها لاحقًا في PDF. +- استخدام `recognize_image` بدلاً من `recognize_pdf` يتجنب خطوة تحويل إضافية، مما يسرّع المعالجة للصور ذات الصفحة الواحدة. + +#### تنوعات شائعة + +- إذا كان لديك **TIFF متعدد الصفحات**، مرّر مسار الملف مباشرة؛ معظم المحركات ستعامل كل صفحة كصورة منفصلة. +- بالنسبة لملفات PDF التي تحتوي بالفعل على صور، يمكنك استدعاء `engine.recognize_pdf("file.pdf")` وتجاوز هذه الخطوة تمامًا. + +--- + +## الخطوة 2: تصدير نتيجة OCR كـ PDF/A قابل للبحث + +الآن نأخذ الـ `result` من الخطوة 1 ونخبر المحرك بكتابة ملف جديد. العلامة المفتاحية هنا هي *PDF/A*—الإصدار المعياري ISO من PDF المصمم للحفظ طويل الأمد. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### لماذا هذا مهم + +- **PDF قابل للبحث**: يحتوي الملف الناتج على طبقة نص مخفية قابلة للتحديد. يمكنك الآن الضغط على Ctrl + F للبحث داخل المستند. +- **امتثال PDF/A**: بعض المؤسسات (القانونية، المالية) تتطلب PDF/A لسجلات التدقيق؛ هذه الخطوة تلبي ذلك تلقائيًا. +- الطريقة أيضًا **تضيف نصًا قابلًا للبحث** دون تسطيح الصورة، لذا يبقى الوضوح البصري مثالياً. + +#### حالة خاصة: هل تحتاج إلى PDF عادي بدلاً من PDF/A؟ + +إذا لم تكن مهتمًا بـ PDF/A، استبدل `save_as_pdfa` بـ `save_as_pdf`. يبقى باقي سير العمل كما هو. + +--- + +## الخطوة 3: التحقق من PDF القابل للبحث + +فحص سريع يحمّيك من الأخطاء الغامضة لاحقًا. افتح الملف المُولد في أي عارض PDF، حاول تحديد كلمة، واستخدم وظيفة البحث. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### النتيجة المتوقعة + +عند تشغيل السكريبت، سيطبع الطرفية: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +عند فتح الملف، يجب أن ترى صورة الفاتورة الأصلية مع طبقة نص خفيفة غير مرئية. حدد أي كلمة وستلاحظ أنها قابلة للتحديد—**هذا هو النص القابل للبحث** الذي أضفته للتو. + +--- + +## إضافة نص قابل للبحث إلى ملفات PDF موجودة (إضافة) + +أحيانًا يكون لديك PDF بالفعل وتحتاج إلى **إضافة نص قابل للبحث** إليه. يمكن لنفس المحرك أن يدمج نتائج OCR فوق PDF موجود: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +هنا يقوم `apply_to` بدمج الطبقة المخفية مع الصفحات الأصلية، مما يتيح لك **إنشاء PDF قابل للبحث** دون الحاجة لإعادة المسح. + +--- + +## الأخطاء الشائعة والنصائح + +| الخطأ | كيفية تجنبه | +|---------|-----------------| +| **صور المصدر منخفضة الدقة** (< 150 dpi) | قم بزيادة الدقة أو اطلب مسحًا بدقة أعلى؛ دقة OCR تنخفض بشكل كبير تحت 150 dpi. | +| **غياب بيانات اللغة** | ثبّت حزم اللغة المناسبة لمحرك OCR الخاص بك (`pip install pdfocr[eng,spa]`). | +| **مجلد الإخراج غير قابل للكتابة** | شغّل السكريبت بصلاحيات كافية أو اختر دليلًا مختلفًا. | +| **فشل التحقق من PDF/A** | تأكد من عدم تضمين خطوط غير مدعومة أو JavaScript؛ معظم SDKs تتعامل مع ذلك تلقائيًا عند استخدام `save_as_pdfa`. | + +--- + +## السكريبت الكامل – حل بملف واحد + +فيما يلي سكريبت مستقل يربط كل شيء معًا. انسخه، استبدل مسارات العناصر النائبة، وستكون جاهزًا **لتحويل الصورة إلى PDF/A** في ثوانٍ. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**ما يفعله هذا السكريبت:** +1. يحمّل محرك OCR. +2. يقرأ الصورة المختارة ويستخرج النص. +3. يكتب **PDF/A قابل للبحث** يمكنك توزيعه أو أرشفته فورًا. + +لا تتردد في تغليف منطق `main` داخل دالة تعالج مجلدًا كاملًا—فقط كرّر `os.listdir()` وطبق الخطوات الثلاث على كل ملف. + +--- + +## الخطوات التالية والمواضيع ذات الصلة + +الآن بعد أن أتقنت **كيفية عمل OCR لملفات PDF**، فكر في استكشاف الأفكار التالية: + +- **المعالجة الدفعة:** استخدم `concurrent.futures` لعمل OCR على عشرات الفواتير بالتوازي. +- **إدخال البيانات الوصفية:** أضف تواريخ الإنشاء أو أرقام الفواتير إلى بيانات PDF الوصفية لتسهيل الفهرسة. +- **PDFs هجينة:** اجمع النص القابل للبحث مع الصور الأصلية المدمجة للحصول على “نسخة رقمية” من المستند الورقي. +- **مخرجات بديلة:** صدّر إلى **DOCX** أو **HTML** إذا كانت الأنظمة اللاحقة تحتاج صيغًا قابلة للتحرير. + +كل من هذه الأفكار يبني على المفاهيم الأساسية التي تعلمتها—التعرف، التصدير، والتحقق. + +--- + +## الخلاصة + +باختصار، الآن تعرف **كيفية عمل OCR لملفات PDF** عن طريق تحويل صورة بسيطة إلى **PDF/A قابل للبحث** باستخدام بضعة أسطر من Python. يتولى السكريبت الجزء الثقيل، يحافظ على الرسومات الأصلية، ويعطيك مستندًا متوافقًا مع المعايير يمكنك البحث فيه، أرشفته أو مشاركته. + +جرّبه على فواتيرك، إيصالاتك، أو عقودك الممسوحة. إذا واجهت أي صعوبات، اترك تعليقًا أدناه أو راجع الوثائق الرسمية للـ SDK—غالبًا ما تكون مليئة بأمثلة إضافية. Happy coding, and enjoy the newfound ability to make any image instantly searchable! + +![مثال على كيفية OCR PDF يظهر الصورة الأصلية وطبقة PDF القابلة للبحث](placeholder.png "مثال على كيفية OCR PDF") + +## ما الذي ينبغي أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شرح خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف طرق تنفيذ بديلة في مشاريعك. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/arabic/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..76c4b7216 --- /dev/null +++ b/ocr/arabic/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-06-06 +description: كيفية التعرف الضوئي على النص في PDF باستخدام Aspose OCR Cloud. تعلم استخراج + النص من PDF، تحويل صفحة PDF إلى PNG، وحفظ صور صفحات PDF باستخدام Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: ar +og_description: كيفية التعرف الضوئي على النص في ملفات PDF باستخدام Aspose OCR Cloud. + يوضح هذا الدليل كيفية استخراج النص العادي من PDF، وتحويل صفحة PDF إلى PNG، وحفظ + صور صفحات PDF. +og_title: كيفية التعرف الضوئي على النص في ملفات PDF باستخدام Aspose OCR Cloud – خطوة + بخطوة +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: كيفية التعرف الضوئي على النص في ملفات PDF باستخدام Aspose OCR Cloud – دليل + كامل +url: /ar/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية OCR PDF باستخدام Aspose OCR Cloud – دليل كامل + +هل تساءلت يومًا **how to OCR PDF** ملفات دون التعامل مع أدوات سطح مكتب ثقيلة؟ لست وحدك—العديد من المطورين يواجهون هذه المشكلة عندما يحتاجون إلى طريقة سريعة برمجية لاستخراج النص من المستندات الممسوحة ضوئيًا. الخبر السار؟ مع Aspose OCR Cloud يمكنك **extract text from PDF**، تحويل كل صفحة إلى PNG، وحتى **save PDF page images** للاستخدام لاحقًا، كل ذلك من خلال سكريبت Python مرتب. + +في هذا الدرس سنستعرض كل ما تحتاج معرفته: من تثبيت الـ SDK، ترخيص المحرك، والتعرف على ملفات PDF متعددة الصفحات، إلى استخراج النص العادي، تحويل الصفحات إلى PNG، وحفظ تلك الصور على القرص. في النهاية ستحصل على قطعة شفرة قابلة لإعادة الاستخدام يمكنك إدراجها في أي مشروع يحتاج إلى قدرات **how to OCR PDF**. + +## ما ستحتاجه + +- **Python 3.8+** (الكود يعمل على 3.10 وما بعده أيضًا) +- حساب Aspose OCR Cloud – ستحصل على ملف ترخيص تجريبي مجاني (`Aspose.OCR.lic`) +- حزمة `asposeocrcloud` (`pip install asposeocrcloud`) +- ملف PDF ممسوح ضوئيًا متعدد الصفحات تريد معالجته + +هذا كل شيء. لا ملفات تنفيذية إضافية، لا تبعيات أصلية، فقط Python نقي. + +## كيفية OCR PDF – الإعداد والترخيص + +قبل أن تتمكن من استدعاء أي طرق OCR، عليك إبلاغ الـ SDK بهويتك. تستخدم Aspose ملف ترخيص خفيف الوزن تضعه في مكان يمكن للسكريبت الوصول إليه. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*نصيحة احترافية:* إذا تخطيت خطوة الترخيص، سيستمر الـ SDK في العمل لكنه سيضيف علامة مائية صغيرة إلى الصور الناتجة. وهذا ليس مثالياً للإنتاج. + +## الخطوة 2: تثبيت Aspose OCR Cloud Python SDK + +افتح الطرفية وشغّل: + +```bash +pip install asposeocrcloud +``` + +تجلب الحزمة جميع الاعتمادات المطلوبة (requests, pillow، إلخ) لذا لا تحتاج للبحث عن أي شيء آخر. + +## الخطوة 3: إنشاء محرك OCR واختيار لغة + +المحرك هو قلب العملية. يمكنك تحديد أي لغة تدعمها Aspose؛ الإنجليزية تعمل في معظم الحالات. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +لماذا نحدد اللغة؟ لأن محرك OCR يستخدم قواميس خاصة باللغة لتحسين الدقة. إذا كنت تعالج ملفات PDF بالفرنسية، استبدل `ENGLISH` بـ `FRENCH`. + +## الخطوة 4: الإشارة إلى ملف PDF متعدد الصفحات + +امنح المحرك المسار الكامل للملف الذي تريد معالجته. المسارات النسبية مقبولة طالما أنها تُحل من دليل عمل السكريبت. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +تأكد من أن الملف قابل للقراءة؛ وإلا ستظهر لك رسالة `FileNotFoundError`. + +## الخطوة 5: تشغيل OCR – ستحصل على قائمة بالنتائج + +استدعاء `recognize_pdf` يُعيد قائمة حيث كل عنصر يمثل صفحة واحدة من ملف PDF الأصلي. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +كل `OcrResult` يحتوي على خاصيتين مفيدتين: + +* `text` – تمثيل النص العادي للصفحة (مفيد لـ **extract plain text pdf**) +* `image` – كائن Pillow `Image` للصفحة المُرَسَمة (مثالي لـ **convert pdf page png**) + +## الخطوة 6: استخراج النص من PDF وتحويل الصفحات إلى PNG + +الآن نقوم بالتكرار عبر النتائج، طباعة النص المستخرج، وحفظ نسخة PNG لكل صفحة. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### مخرجات وحدة التحكم المتوقعة + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +ستجد أيضًا `page_1.png`، `page_2.png`، … في `YOUR_DIRECTORY`. هذه هي صور الصفحات المرسومة التي يمكنك تمريرها إلى خطوط معالجة الصور اللاحقة. + +## الخطوة 7: حفظ صور صفحات PDF (معالجة لاحقة اختيارية) + +إذا كنت تحتاج فقط إلى الصور دون النص، يمكنك تخطي سطر `print(res.text)`. وعلى العكس، إذا أردت تخزين النص في ملفات `.txt` منفصلة، فقط أضف عملية كتابة صغيرة: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +هذه الإضافة الصغيرة توضح مدى سهولة **save PDF page images** مع حفظ المحتوى المستخرج. + +## مثال كامل يعمل + +بجمع كل شيء معًا، إليك السكريبت الكامل الذي يمكنك نسخه ولصقه في `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +شغّله باستخدام: + +```bash +python ocr_pdf.py +``` + +يجب أن ترى طباعة النص لكل صفحة في وحدة التحكم وسلسلة من ملفات PNG + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية OCR PDF في .NET باستخدام Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [التعرف على نص PDF – عمليات OCR مع Aspose.OCR للـ Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [تحويل الصور إلى PDF C# – حفظ نتيجة OCR متعددة الصفحات](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/arabic/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..a21baa7ad --- /dev/null +++ b/ocr/arabic/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: كيفية معالجة الصور مسبقًا للتعرف الضوئي على الأحرف (OCR) باستخدام بايثون. + تعلم كيفية تحويل الصورة إلى ثنائية باستخدام طريقة أوتسو، وكيفية تصحيح انحراف المستندات + الممسوحة ضوئيًا، وتحسين دقة التعرف الضوئي على النص الألماني. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: ar +og_description: كيفية معالجة الصور مسبقًا للتعرف الضوئي على الأحرف (OCR) في بايثون. + يوضح هذا الدرس كيفية تحويل الصورة إلى ثنائية باستخدام طريقة أوتسو، وكيفية تصحيح + ميل المستندات الممسوحة، وكيفية تحسين دقة OCR للصور الألمانية. +og_title: كيفية معالجة الصور مسبقًا للتعرف الضوئي على الأحرف – دليل بايثون كامل +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: كيفية معالجة الصور مسبقًا للتعرف الضوئي على الأحرف – دليل بايثون الكامل +url: /ar/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية معالجة الصور قبل OCR – دليل بايثون كامل + +هل تساءلت يومًا **كيف تُعالج الصور قبل OCR** لتظهر النصوص واضحة كالكريستال؟ لست وحدك. المستندات الممسوحة ضوئيًا—وخاصة الصفحات الألمانية المزعجة—يمكن أن تكون كابوسًا لأي محرك OCR. الخبر السار؟ بعض خطوات المعالجة الذكية يمكن أن تحول مسحًا ضبابيًا ومبقعًا إلى صورة نظيفة قابلة للقراءة آليًا. + +في هذا الدرس سنستعرض مثالًا عمليًا يوضح **كيف تُعالج الصور قبل OCR** باستخدام بايثون. ستتعلم **تحويل الصورة إلى ثنائية باستخدام Otsu**، **كيفية تصحيح ميل المستندات الممسوحة**، وبشكل عام **كيفية تحسين دقة OCR** عندما تحتاج إلى **استخراج النص من ملفات صورة ألمانية**. لا إطالة، فقط سكريبت يعمل يمكنك نسخه ولصقه اليوم. + +## ما الذي ستحتاجه + +- **Python 3.9+** (أي نسخة حديثة تعمل) +- مكتبة OCR تُوفر فئة `OcrEngine` – للعرض سنفترض حزمة `ocr` عامة. ثبّتها عبر `pip install ocr-lib`. +- مسح ألماني مشوش (`noisy_german_scan.tif`) تريد اختباره. +- فهم أساسي لدوال بايثون (إذا كتبت `def` من قبل، فأنت جاهز). + +> **نصيحة محترف:** إذا كنت تستخدم SDK OCR مختلف (مثال: Tesseract عبر `pytesseract`)، فإن المفاهيم تبقى نفسها—فقط عدّل أسماء الطرق. + +## نظرة عامة على الحل + +1. **إنشاء كائن محرك OCR.** +2. **تعيين لغة التعرف إلى الألمانية.** +3. **بناء خط أنابيب معالجة مخصص** يتضمن تصحيح الميل، إزالة الضوضاء، التحويل إلى ثنائي (Otsu)، وتمديد التباين. +4. **إرفاق خط الأنابيب بالمحرك** بحيث تمر كل صورة من خلاله تلقائيًا. +5. **تشغيل OCR** على مسح ألماني مشوش. +6. **طباعة النص المستخرج** للتحقق من النتيجة. + +فيما يلي نُفصِّل كل خطوة، نشرح **لماذا** هي مهمة، ونُظهر الشيفرة الدقيقة التي تحتاجها. + +![مثال على كيفية معالجة الصور قبل OCR](image.png "مثال على كيفية معالجة الصور قبل OCR") + +## الخطوة 1: إنشاء كائن محرك OCR + +أولًا وقبل كل شيء—بدون محرك، لا يحدث شيء. كائن `OcrEngine` هو نقطة الدخول التي تُنسّق جميع المعالجات اللاحقة. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*لماذا هذا مهم:* تهيئة المحرك تُعد الموارد الداخلية (مثل نماذج اللغة) وتمنحك مساحة نظيفة لإرفاق خط أنابيب مخصص لاحقًا. + +## الخطوة 2: تعيين لغة التعرف إلى الألمانية + +دقة OCR تعتمد بشكل كبير على اللغة. بإخبار المحرك أن يتوقع الألمانية، تُفعِّل مجموعة الأحرف والنموذج اللغوي المناسب. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +إذا تخطيت هذه الخطوة، قد يَفترض المحرك اللغة الإنجليزية افتراضيًا، ما يؤدي إلى أخطاء في التعرف على الأحرف المُعقَّدة مثل الـä، الـö، الـü وحرف الـß—وهي مشاكل شائعة عند التعامل مع المستندات الألمانية. + +## الخطوة 3: بناء خط أنابيب معالجة مخصص + +هذا هو جوهر **كيفية معالجة الصور قبل OCR**. سنسلسلة أربع تحويلات: + +| التحويل | ما يفعله | لماذا يساعد | +|---------|----------|--------------| +| **تصحيح الميل** | يدور الصورة لتصبح أفقية (حد أقصى 5°) | المسحات نادراً ما تكون محاذاة تمامًا؛ تصحيح الميل يزيل الانحراف الذي يربك تجزئة الأحرف. | +| **إزالة الضوضاء** | يقلل البقع العشوائية (قوة 0.7) | الضوضاء تُنشئ حواف زائفة قد يفسرها محرك OCR كأحرف. | +| **تحويل إلى ثنائي (Otsu)** | يحول إلى أبيض‑أسود باستخدام طريقة Otsu | الصورة الثنائية النظيفة تُعطي المحرك تباينًا حادًا بين النص (المقدمة) والخلفية. | +| **تمديد التباين** | يوسّع النطاق الديناميكي | يحسّن قابلية قراءة الخطوط الخفيفة، خاصة في المستندات القديمة. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### كيفية تصحيح ميل المستندات الممسوحة + +استدعاء `deskew` أعلاه هو الجواب الملموس على **كيفية تصحيح ميل المستندات الممسوحة**. داخليًا يقدّر زاوية الخط النصي السائدة عبر تحويل Hough ويُدوّر الصورة للعودة إلى الوضع الصحيح. إذا كانت مستنداتك مائلة بأكثر من 5°، زد قيمة `max_angle`، لكن احذر من ظهور تشوهات نتيجة الدوران الزائد. + +### تحويل الصورة إلى ثنائية باستخدام Otsu + +السطر `binarize(method="otsu")` يجيب مباشرة على الاستفسار **تحويل الصورة إلى ثنائية باستخدام Otsu**. خوارزمية Otsu تحسب عتبة تُقلل التباين داخل الفئات، وهو مثالي للمستندات ذات التوزيع الثنائي (نص داكن مقابل خلفية فاتحة). + +## الخطوة 4: إرفاق خط الأنابيب بالمحرك + +الآن نخبر محرك OCR بتشغيل كل صورة واردة عبر خط الأنابيب الذي بنيناه للتو. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*لماذا هذا مهم:* بدون التسجيل، سيعالج المحرك المسح الخام متجاهلًا كل التنظيف الذي أعددناه. هذه الخطوة تضمن **كيفية تحسين دقة OCR** عبر تطبيق نفس المعالجة مسبقًا على كل صورة. + +## الخطوة 5: التعرف على النص من مسح ألماني مشوش + +حان الوقت لتجميع كل شيء. نمرّر للمحرك صورة ألمانية مشوشة ونتركه يقوم بالعمل الشاق. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +إذا كنت مهتمًا بالأداء، يمكنك قياس زمن الاستدعاء: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## الخطوة 6: إخراج النص المعترف به + +أخيرًا، نطبع السلسلة المستخرجة. هذا هو الجواب المباشر على **استخراج النص من صورة ألمانية**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### النتيجة المتوقعة + +باستخدام مسح تجريبي يحتوي على الجملة “Die schnelle braune Füchsin springt über den faulen Hund.” يجب أن ترى شيئًا مشابهًا لـ: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +إذا ظل الإخراج يحتوي على أحرف مشوشة، ففكّر في تعديل قوة `denoise` أو زيادة `max_angle` لتصحيح الميل. + +## الأخطاء الشائعة وكيفية التعامل معها + +- **نموذج اللغة مفقود:** نسيان `set_recognition_language(Language.GERMAN)` غالبًا ما يؤدي إلى فقدان الأحرف المُعقَّدة. تحقق من استدعاء الدالة. +- **إزالة ضوضاء مفرطة:** قوة أعلى من 0.9 قد تمحو الخطوط الرفيعة، خاصة في الخطوط القديمة. حافظ على 0.5‑0.7 في أغلب الحالات. +- **صيغة ملف غير صحيحة:** بعض محركات OCR لا تتعامل مع ملفات TIFF متعددة الصفحات. إذا كان لديك مستند متعدد الصفحات، قسّمه إلى ملفات صفحة واحدة أولًا. +- **ترتيب الخط الأنابيب:** الترتيب المعروض (تصحيح الميل → إزالة الضوضاء → تحويل إلى ثنائي → تمديد التباين) مقصود. تحويل الصورة إلى ثنائية قبل إزالة الضوضاء قد يحفظ الضوضاء؛ لذا دائمًا أزل الضوضاء أولًا. + +## توسيع خط الأنابيب (ما التالي؟) + +الآن بعد أن لديك أساسًا قويًا، قد ترغب في: + +- **إضافة فتح مورفولوجي** لتنظيف البقع الصغيرة (`.morph_open(kernel=3)`). +- **دمج نموذج لغوي** لتصحيح ما بعد المعالجة (`ocr_engine.apply_spellcheck()`). +- **توازي معالجة الدفعات** للمجموعات الكبيرة باستخدام `concurrent.futures`. + +كل هذه توسعات طبيعية تحافظ على فكرة **كيفية معالجة الصور قبل OCR** بينما تعزز **كيفية تحسين دقة OCR** أكثر. + +## الخلاصة + +لقد غطينا **كيفية معالجة الصور قبل OCR** من البداية حتى النهاية: إنشاء محرك، تعيين اللغة الألمانية، بناء خط أنابيب **يحول الصورة إلى ثنائية باستخدام Otsu**، **كيفية تصحيح ميل المستندات الممسوحة**، وأخيرًا **استخراج النص من صورة ألمانية** بثقة أعلى. باتباع الخطوات الستة أعلاه ستلاحظ قفزة ملحوظة في جودة التعرف—وداعًا للتصحيحات اليدوية المتواصلة. + +جرّب السكريبت على مسحاتك الخاصة، العب بالمعاملات، ودع النتائج تتحدث عن نفسها. هل لديك أسئلة حول تعديل معين في المعالجة؟ اترك تعليقًا، وسنغوص أعمق معًا. + +برمجة سعيدة، ولتكن OCR دائمًا دقيقة! + +## ماذا يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شاملة مع شيفرات تعمل بالكامل وشروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..54c6fd2ee --- /dev/null +++ b/ocr/arabic/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-06-06 +description: التعرف الضوئي على الأحرف (OCR) لصورة PNG باستخدام بايثون – تعلم كيفية + استخراج النص من الصورة، تشغيل مثال OCR بايثون، وحتى قراءة النص اليوناني القديم بسهولة. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: ar +og_description: شرح OCR لصورة PNG في بايثون. يوضح هذا الدليل كيفية استخراج النص من + الصورة، تشغيل مثال OCR بايثون، وقراءة اليونانية القديمة بسهولة. +og_title: التعرف الضوئي على الأحرف لصورة PNG في بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: التعرف الضوئي على الأحرف (OCR) لصورة PNG في بايثون – دليل كامل خطوة بخطوة +url: /ar/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# صورة PNG OCR في بايثون – دليل خطوة بخطوة كامل + +هل تساءلت يومًا كيف يمكنك **OCR PNG image** مباشرةً من سكريبت بايثون؟ ربما لديك مجلد مليء بالمخطوطات القديمة الممسوحة وتحتاج إلى **extract text from image** دون كتابة كل شيء يدويًا. الخبر السار هو أنك لا تحتاج إلى دكتوراه في رؤية الحاسوب—فقط بضع أسطر من الكود والمكتبة المناسبة، وستتمكن من قراءة اليونانية القديمة في ثوانٍ. + +في هذا الدرس سنستعرض **python OCR example** يتعرف على النص من ملف PNG، يضبط اللغة إلى اليونانية البوليتونية، ويطبع النتيجة. بنهاية الدرس ستعرف بالضبط كيف **recognize image text**، وكيفية التعامل مع المشكلات الشائعة، وكيفية تعديل السكريبت للغات أو صيغ صور أخرى. + +## ما ستتعلمه + +- تثبيت وتكوين مكتبة OCR لبايثون (pytesseract + Tesseract OCR) +- إنشاء نسخة من محرك OCR وتحميل ملف PNG +- ضبط لغة التعرف إلى اليونانية البوليتونية لتتمكن من **read ancient greek** +- إخراج النص المُتعرف عليه وحل المشكلات النموذجية +- توسيع السكريبت لمعالجة دفعات متعددة من PNGs أو تغيير اللغة + +### المتطلبات المسبقة + +| المتطلب | لماذا هو مهم | +|-------------|----------------| +| Python 3.8+ | الصياغة الحديثة وتلميحات الأنواع | +| حزمة `pytesseract` | غلاف خفيف حول محرك Tesseract | +| ملفات ثنائية لـ Tesseract OCR (≥ 5.0) | المحرك الفعلي الذي يقوم بالمعالجة | +| بيانات اللغة اليونانية (`grc.traineddata`) | ضرورية لـ **read ancient greek** بشكل صحيح | +| صورة PNG تريد تحليلها (مثال: `ancient_greek.png`) | هدفنا لتجربة **ocr png image** | + +يمكنك تثبيت الجانب الخاص ببايثون باستخدام: + +```bash +pip install pytesseract Pillow +``` + +وعلى Ubuntu/macOS يمكنك إضافة المحرك نفسه: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +لا تنس تحميل بيانات التدريب للغة اليونانية البوليتونية: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(قد يختلف المسار؛ عدل `TESSDATA_PREFIX` إذا لزم الأمر.)* + +--- + +## OCR PNG Image: إنشاء نسخة المحرك + +أول شيء نحتاجه هو كائن يتواصل مع Tesseract. في `pytesseract` يتم الوصول إلى المحرك عبر دوال على مستوى الوحدة، لكن لتوضيح الفكرة سنغلفه داخل فئة صغيرة. هذا يعكس مفهوم “المحرك” الذي رأيته في المقتطف الأصلي. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**لماذا نغلفه؟** +- يحافظ على واجهة برمجة التطبيقات العامة كما في المقتطف الأصلي، مما يجعل الانتقال سهلًا. +- يتيح لنا إضافة سجلات أو معالجة أخطاء لاحقًا دون تعديل التدفق الرئيسي. +- يوضح ممارسات OOP الجيدة—وهو ما يقدره المطورون ذوو الخبرة. + +--- + +## استخراج النص من الصورة: ضبط اللغة إلى اليونانية البوليتونية + +الآن بعد أن لدينا محركًا، نحتاج إلى إخبارها أي لغة نتوقعها. اليونانية البوليتونية تستخدم علامات تشكيل لا تغطيها بيانات “greek” القياسية، لذا نوجه Tesseract إلى ملف التدريب `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +إذا أردت **extract text from image** بلغة أخرى، ما عليك سوى استبدال `"grc"` بـ `"eng"` للإنجليزية، `"fra"` للفرنسية، إلخ. نفس السطر يعمل مع أي لغة تم تثبيتها. + +--- + +## التعرف على نص الصورة: تشغيل OCR على PNG + +بعد ضبط اللغة، نمرر ملف PNG إلى المحرك. المثال الأصلي استخدم مسارًا ثابتًا؛ سنجعل الأمر أكثر مرونة باستخدام كائنات `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**نصائح وحالات خاصة** + +- **الملف غير موجود** – غلف الاستدعاء بـ `try/except FileNotFoundError` لتقديم رسالة ودية. +- **PNG منخفض الدقة** – فكر في ما قبل المعالجة (مثل تغيير الحجم، التحويل إلى ثنائي) باستخدام Pillow قبل OCR. +- **نص غير يوناني** – سيحاول Tesseract التعرف لكنه سيقلّ الدقة بشكل كبير. احرص دائمًا على مطابقة اللغة. + +--- + +## إخراج النص المتعرف عليه + +أخيرًا، نطبع النتيجة. في مشروع حقيقي قد تكتبها إلى قاعدة بيانات، ملف CSV، أو حتى تمررها إلى خط أنابيب ترجمة. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +عند تشغيل السكريبت على مسح واضح لنقش يوناني قديم، يجب أن ترى شيئًا مثل: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +إذا كان الإخراج مشوشًا، تحقق من أن ملف **greek.traineddata** موجود في المجلد الصحيح وأن PNG ليس صاخبًا جدًا. + +--- + +## مثال كامل يعمل (كل الخطوات في سكريبت واحد) + +فيما يلي البرنامج الكامل الجاهز للتنفيذ. احفظه باسم `ocr_greek.py` وشغّله باستخدام `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**الإخراج المتوقع** (مقتطع للوضوح): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +إذا رأيت الأحرف اليونانية الصحيحة، تهانينا—لقد نجحت في إجراء عملية **ocr png image** باستخدام بايثون! + +--- + +## أسئلة شائعة ونصائح احترافية + +### كيف أحسن الدقة على PNG صاخب؟ + +- حول الصورة إلى تدرج رمادي: `img = img.convert('L')` +- طبق عتبة ثنائية: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- قم بتكبير الصورة: `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +هذه الخطوات غالبًا ما تحول كابوس **recognize image text** إلى نتيجة نظيفة. + +### هل يمكنني معالجة مجلد كامل من PNGs؟ + +بالتأكيد. غلف استدعاء `recognize_image` داخل حلقة `for` على `Path.glob("*.png")`. خزن كل نتيجة في قاموس أو اكتبها إلى CSV للتحليل لاحقًا. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### ماذا لو أردت استخراج الأرقام فقط؟ + +مرّر سلسلة **config** مخصصة إلى `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +بهذه الطريقة يمكنك **extract text from image** التي تحتوي على جداول أو أرقام تسلسلية أو طوابع زمنية. + +### هل يمكن الحصول على درجات الثقة؟ + +نعم—استخدم `pytesseract.image_to_data` الذي يُرجع ملف TSV يحتوي على الثقة لكل كلمة. يمكنك تصفية الكلمات ذات الثقة المنخفضة قبل تجميع السلسلة النهائية. + +--- + +## توسيع الدرس + +الآن بعد أن أتقنت الأساسيات، فكر في استكشاف المواضيع ذات الصلة: + +- **Batch OCR مع multiprocessing** – تسريع معالجة مجموعات كبيرة من PNGs. +- **خطوط OCR + NLP هجينة** – ترجمة النص اليوناني القديم تلقائيًا إلى الإنجليزية الحديثة. +- **محركات بديلة** – جرّب `easyocr` أو طرق تعتمد على `opencv` لحالات استخدام محددة. +- **خدمات OCR سحابية** – Google Vision، Azure Computer Vision، أو AWS Textract للتوسع بدون خوادم. + +كل هذه تبني على **python ocr example** الذي غطيناه، لذا ستشعر بالراحة في الغوص أعمق. + +--- + +## الخلاصة + +قمنا بأخذ مقتطف بسيط وتحويله إلى سير عمل **ocr png image** قوي في بايثون. بإنشاء `OcrEngine`، ضبط اللغة إلى اليونانية البوليتونية، تمرير PNG، وطباعة النتيجة، أصبحت الآن تعرف كيف **extract text from image**، **recognize image text**، وحتى **read ancient greek**. + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/arabic/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..ddba9bea3 --- /dev/null +++ b/ocr/arabic/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-06 +description: دورة تعليمية في Python للتعرف الضوئي على الأحرف توضح كيفية التعرف على + نص الصورة، وإجراء OCR عالي الدقة واستخراج النص الإسباني باستخدام OCR المعجل بوحدة + معالجة الرسومات. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: ar +og_description: دورة تعليمية في OCR باستخدام بايثون تُرشدك إلى التعرف على نصوص الصور، + OCR عالي الدقة، واستخراج النص الإسباني مع تسريع باستخدام وحدة معالجة الرسومات. +og_title: دورة بايثون للتعرف الضوئي على الحروف – التعرف على النص باستخدام تسريع GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: دورة بايثون للتعرف الضوئي على الأحرف – التعرف على نص الصورة باستخدام تسريع + وحدة المعالجة الرسومية +url: /ar/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# دليل OCR بلغة Python – التعرف على نص الصورة مع تسريع GPU + +هل تساءلت يومًا كيف **تتعرف على نص الصورة** في سكريبت Python دون قضاء ساعات في تعديل الإعدادات؟ لست وحدك. في هذا **python ocr tutorial** سنظهر لك طريقة نظيفة وشاملة لاستخراج النص الإسباني من صورة عالية الدقة، وسنضيف تسريع GPU لتصبح العملية سريعة كالبرق. + +فكر فيها كعرض سريع أثناء استراحة القهوة يمكنك توسيعه لاحقًا إلى خط أنابيب جاهز للإنتاج. بنهاية هذا الدليل ستحصل على برنامج قابل للتنفيذ يقوم بـ **high resolution OCR**، يستخدم GPU مدعوم بـ CUDA، ويُخرج الأحرف الإسبانية الدقيقة التي تحتاجها. + +## ما ستتعلمه + +- كيفية تثبيت واستيراد مكتبة OCR حديثة تدعم تسريع GPU. +- كيفية إنشاء مثيل محرك OCR وتعيينه **لتعرف على نص الصورة** بالإسبانية. +- كيفية تمكين **gpu accelerated OCR** للحصول على سرعات هائلة على ملفات عالية الدقة. +- كيفية التعامل مع الحالات الحدية مثل نقص تعريفات CUDA أو الرجوع إلى CPU. +- نصائح لتحسين الدقة عندما تحتاج إلى **استخراج النص الإسباني** من مسحات ضوضائية. + +### المتطلبات المسبقة + +- Python 3.9+ (الكود يعمل على 3.10 وما بعده أيضًا). +- GPU متوافق مع CUDA (اختياري لكن يُنصح به بشدة). +- معرفة أساسية بـ pip وبيئات افتراضية. + +إذا كنت تفتقد أيًا من هذه المتطلبات، سيظل الدليل يعمل — فقط تخطى خطوة GPU وستعود المكتبة تلقائيًا إلى CPU. + +--- + +## دليل OCR بلغة Python: تثبيت الحزم المطلوبة + +أولاً، نحتاج إلى محرك OCR قوي. لهذا الدليل سنستخدم الحزمة المفتوحة المصدر **`easyocr`**، التي تأتي بدعم مدمج لـ GPU عندما يتم اكتشاف جهاز متوافق. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **نصيحة احترافية:** إذا كان لديك PyTorch مثبتًا بالفعل، تأكد من أنه يتطابق مع نسخة CUDA الخاصة بك (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). الإصدارات غير المتطابقة هي مصدر شائع لأخطاء “GPU غير موجود”. + +--- + +## الخطوة 1: إنشاء مثيل محرك OCR + +الآن نقوم بتشغيل المحرك. EasyOCR يطلق على الفئة الرئيسية اسم `Reader`. المُنشئ يقبل قائمة بأكواد اللغات؛ سنمرر `"es"` للإسبانية. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*لماذا هذا مهم:* من خلال إعلان اللغة مسبقًا، يقوم المحرك بتحميل الأوزان العصبية الضرورية فقط، مما يوفر الذاكرة ويسرّع الاستدلال — مفيد بشكل خاص عندما تتعامل مع **high resolution OCR** لاحقًا. + +--- + +## الخطوة 2: إعداد صورة عالية الدقة + +الصور عالية الدقة تعطي النموذج المزيد من البكسلات للعمل معها، مما يترجم عادةً إلى تحسين في التعرف على الأحرف. لنفترض أن لديك ملفًا اسمه `high_res_spanish.png` موجودًا في مجلد اسمه `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +إذا لم يكن لديك عينة عالية الدقة جاهزة، يمكنك تنزيل واحدة مجانية من Unsplash أو إنشاء صورة اصطناعية باستخدام Pillow. المفتاح هو الحفاظ على DPI أعلى من 300 للحصول على أفضل النتائج. + +--- + +## الخطوة 3: تمكين تسريع GPU (اختياري لكن موصى به) + +EasyOCR بالفعل يحاول استخدام GPU عندما تضبط `gpu=True`. ومع ذلك، من الممارسات الجيدة التحقق من أن الجهاز يُستخدم فعليًا، خاصةً في الأنظمة متعددة الـ GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*لماذا نتحقق من ذلك؟* إذا عاد السكريبت صامتًا إلى CPU، قد تتساءل لماذا عملية تستغرق 5 ثوانٍ فجأة تأخذ 30 ثانية. هذا الفحص الصغير يجعل السلوك شفافًا ويحافظ على توقعية خط أنابيب **gpu accelerated OCR** الخاص بك. + +--- + +## الخطوة 4: تنفيذ OCR عالي الدقة والتعرف على نص الصورة + +الآن الجزء الممتع — قراءة النص فعليًا. طريقة `readtext` في EasyOCR تُعيد قائمة من tuples تحتوي على المربع المحيط، السلسلة المعترف بها، ونسبة الثقة. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +إذا كنت تحتاج السلسلة الخام بدون إحداثيات، اضبط `detail=0`. بالنسبة لمعظم حالات **recognize image text**، الإعداد الافتراضي (`detail=1`) يمنحك ما يكفي من السياق للمعالجة اللاحقة. + +--- + +## الخطوة 5: استخراج النص الإسباني وتنظيف المخرجات + +نظرًا لأننا طلبنا من EasyOCR اللغة الإسبانية، فإن السلاسل المسترجعة تكون بالفعل بهذه اللغة. مع ذلك، قد ترغب في دمجها، إزالة المسافات الفارغة، أو تصفية الاكتشافات ذات الثقة المنخفضة. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**ماذا لو كانت الثقة منخفضة؟** يمكنك إما خفض العتبة (مع خطر الضوضاء) أو معالجة الصورة مسبقًا (زيادة التباين، تحويل إلى ثنائي، أو تصحيح الميل). هذه الحيل شائعة عند التعامل مع **high resolution OCR** على المستندات الممسوحة. + +--- + +## الخطوة 6: معالجة الحالات الحدية وتحسين الأداء + +حتى النماذج المدربة بأفضل شكل تواجه بعض السيناريوهات الصعبة. أدناه بعض الإصلاحات السريعة التي يمكنك لصقها في السكريبت. + +### 6.1 الرجوع إلى CPU عندما لا يتوفر GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 تقليل حجم الصور الكبيرة جدًا + +إذا كانت صورتك أكبر من 4000 × 4000 px، قد تنفد ذاكرة GPU. قلل الحجم بنسبة متناسبة مع الحفاظ على DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +هذه المقاطع تجعل السكريبت قويًا، سواء كنت تعمل على محطة عمل أو على لابتوب متوسط المواصفات. + +--- + +## مثال كامل يعمل + +بجمع كل ما سبق، إليك السكريبت الكامل الذي يمكنك نسخه ولصقه وتشغيله فورًا: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**الإخراج المتوقع (مثال):** + + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك الخاصة. + +- [استخراج النص من صورة باستخدام Aspose OCR – دليل خطوة بخطوة](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [كيفية التعرف على نص الصورة باستخدام اللغة مع Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [كيفية التعرف على مستطيلات الصفحة لتعرف نص OCR في Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/arabic/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..3ddc51c6e --- /dev/null +++ b/ocr/arabic/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-06 +description: التعرف على النص من الصورة باستخدام محرك OCR في بايثون. تعلم كيفية تكوين + محرك OCR في بايثون واستخراج النص من الصورة باستخدام المعالجة السحابية في دقائق. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: ar +og_description: التعرف على النص من الصورة باستخدام محرك OCR بايثون. يوضح هذا الدليل + كيفية تكوين محرك OCR بايثون واستخراج النص من الصورة بكفاءة. +og_title: التعرف على النص من الصورة في بايثون – دليل الإعداد الكامل +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: التعرف على النص من الصورة في بايثون – دليل إعداد محرك OCR الكامل +url: /ar/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# التعرف على النص من صورة في بايثون – دليل الإعداد الكامل + +هل تساءلت يومًا كيف **recognize text from image** باستخدام بضع أسطر فقط من بايثون؟ لست وحدك. سواء كنت تبني ماسحًا للإيصالات، أو محولًا للوثائق، أو مشروعًا هواية بسيطًا، فإن القدرة على استخراج النص من صورة هي مهارة تُعطي نتائج سريعة. + +في هذا الدرس سنستعرض العملية بالكامل—بدءًا من إعداد **configure OCR engine python**، مرورًا بالمصادقة السحابية، وأخيرًا إظهار كيفية **extract text from image** بنتيجة موثوقة. لا سحر، فقط خطوات واضحة يمكنك نسخها ولصقها وتشغيلها اليوم. + +## ما ستتعلمه + +- كيفية تثبيت واستيراد مكتبة OCR المطلوبة. +- الأوامر الدقيقة لـ **configure OCR engine python** للمعالجة السحابية. +- سكريبت كامل قابل للتنفيذ يقوم بـ **recognize text from image** ويطبع النتيجة. +- نصائح للتعامل مع المشكلات الشائعة مثل مفاتيح API المفقودة أو صيغ الصور غير المدعومة. +- أفكار متقدمة مثل المعالجة الدفعية والاحتياطي المحلي. + +### المتطلبات المسبقة + +- Python 3.8+ مثبت على جهازك. +- اتصال بالإنترنت (المثال يستخدم خدمة OCR سحابية). +- مفتاح API صالح من مزود OCR (سترى أين تُدخل المفتاح). + +إذا كان لديك كل ذلك، فلنبدأ—بدون إطالة، دليل عملي يعمل. + +--- + +## الخطوة 1: تثبيت مكتبة OCR واستيرادها + +قبل أن تتمكن من **configure OCR engine python**، تحتاج إلى المكتبة التي تتواصل مع الخدمة السحابية. في مثالنا سنستخدم حزمة خيالية تمثيلية تسمى `ocrcloud`. استبدلها بالحزمة الفعلية التي تستخدمها (مثل `easyocr`، `google-cloud-vision`، إلخ). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**لماذا هذا مهم:** استيراد الصنف يمنحك الوصول إلى طرق مثل `use_cloud()` و `set_api_key()`. بدون الاستيراد، سيتسبب باقي السكريبت في رفع `NameError`. + +*نصيحة محترف:* قم بتثبيت النسخة المحددة في ملف `requirements.txt` (`ocrcloud==2.1.0`) لتجنب التغييرات المفاجئة لاحقًا. + +--- + +## الخطوة 2: إنشاء و **configure OCR engine python** للوضع السحابي + +الآن نقوم فعليًا بـ **configure OCR engine python**. يبدأ المحرك في الوضع المحلي افتراضيًا؛ التحويل إلى الوضع السحابي يسمح لك بتحميل تحليل الصور الثقيلة إلى خوادم قوية. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**شرح:** +- `OcrEngine()` ينشئ كائن محرك جديد—كأنها لوحة فارغة. +- `use_cloud(True)` يبدّل المفتاح، مخبرًا المحرك بإرسال الصور عبر HTTPS بدلاً من معالجتها محليًا. هذا ضروري للحصول على نتائج عالية الدقة على الخطوط المعقدة أو الصور منخفضة الدقة. + +--- + +## الخطوة 3: المصادقة باستخدام مفتاح API السحابي الخاص بك + +معظم خدمات OCR السحابية تتطلب مفتاح API. تُظهر هذه الخطوة كيفية إدخال الاعتماد بأمان. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**ملاحظة أمان:** لا تقم أبدًا بكتابة المفتاح مباشرة في مستودع عام. في بيئة الإنتاج ستستخرجه من متغيّر بيئة: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## الخطوة 4: **recognize text from image** – إرسال صورة عن بُعد للمعالجة + +مع تكوين المحرك، يمكننا أخيرًا **recognize text from image**. الطريقة `recognize_image()` تقبل مسارًا أو URL وتعيد كائنًا يحتوي على النص المستخرج. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**ماذا يحدث خلف الكواليس؟** +يتم رفع بايتات الصورة إلى نقطة النهاية الخاصة بالمزود، تُعالج بواسطة نموذج تعلم عميق، وتُعاد النتيجة كنص عادي. إذا كانت الصورة كبيرة، قد تقوم الخدمة تلقائيًا بتقليل حجمها لتسريع العملية. + +--- + +## الخطوة 5: إخراج نتيجة **extract text from image** + +الآن بعد أن أنجزت خدمة OCR مهمتها، نطبع النص ببساطة. في التطبيقات الحقيقية قد تخزنه في قاعدة بيانات أو تمرره إلى دالة أخرى. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**الناتج المتوقع:** (مثال) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +إذا ظهر الناتج مشوشًا، تأكد من وضوح الصورة وأنك اخترت نموذج اللغة الصحيح (العديد من الخدمات تسمح بتحديد `engine.set_language("en")`). + +--- + +## التعامل مع الحالات الحدية والمشكلات الشائعة + +### 1. مفتاح API مفقود أو غير صالح +إذا ظهرت لك رسالة خطأ في المصادقة، تأكد من: +- أن المفتاح فعال وغير منتهي الصلاحية. +- أنه يُقرأ من المتغيّر البيئي بشكل صحيح. +- أن شبكتك تسمح بحركة مرور HTTPS الصادرة. + +### 2. صيغ صور غير مدعومة +معظم واجهات OCR تقبل JPEG، PNG، و PDF. تجربة BMP أو TIFF قد تُسبب استجابة “format not supported”. يمكن التحويل باستخدام Pillow إذا لزم الأمر: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. حدود المعدل +غالبًا ما تفرض الخدمات السحابية حدًا للطلبات في الدقيقة. إذا وصلت إلى الحد، نفّذ تقنية الـ exponential back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. الاحتياطي إلى OCR محلي +إذا تعطل السحابة، يمكنك العودة إلى الوضع المحلي: + +```python +engine.use_cloud(False) # revert to local mode +``` + +وجود احتياطي يجعل تطبيقك أكثر مرونة. + +--- + +## مثال كامل يعمل + +نجمع كل ما سبق في سكريبت يمكنك تشغيله الآن (فقط استبدل القيم النائبة). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**تشغيله:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +يجب أن ترى النص المستخرج يُطبع في الطرفية، مؤكدًا أنك نجحت في **recognize text from image** و **extract text from image** باستخدام سير عمل **configure OCR engine python** صحيح. + +--- + +## الخلاصة + +لقد استعرضنا عملية كاملة من البداية إلى النهاية تمكنك من **recognize text from image** في بايثون، بدءًا من تثبيت المكتبة مرورًا بالمصادقة على خدمة سحابية وأخيرًا **extract text from image** باستدعاء دالة واحدة. من خلال **configure OCR engine python** بطريقة صحيحة، ستحصل على مرونة (سحابي vs. محلي) وموثوقية (معالجة الأخطاء). + +ما الخطوة التالية؟ جرّب معالجة دفعات من الإيصالات، أضف اكتشاف اللغة، أو جرب ملفات PDF كمدخلات. السماء هي الحد عندما تتقن الأساسيات. + +برمجة سعيدة، ولا تتردد في طرح أي سؤال في التعليقات—لا شيء يُقارن بالتعلم المشترك! + +## ما الذي ينبغي أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0cdd8972c --- /dev/null +++ b/ocr/arabic/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,337 @@ +--- +category: general +date: 2026-06-06 +description: قم بتشغيل OCR على الصورة باستخدام بايثون وعرض درجات الثقة. تعلّم كيفية + تصفية الكلمات ذات الثقة المنخفضة، وضبط العتبات، ومعالجة الحالات الخاصة. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: ar +og_description: قم بتشغيل OCR على صورة في بايثون، افحص مستويات الثقة، وقم بتصفية الكلمات + ذات الثقة المنخفضة. هذا الدرس يوجهك عبر مثال كامل قابل للتنفيذ. +og_title: تشغيل OCR على الصورة باستخدام بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: تشغيل التعرف الضوئي على الأحرف (OCR) على صورة باستخدام بايثون – دليل كامل خطوة + بخطوة +url: /ar/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تشغيل OCR على الصورة باستخدام بايثون – دليل خطوة بخطوة كامل + +هل احتجت يومًا إلى **run OCR on image** ملفات ولكن لم تكن متأكدًا من كيفية استخراج نص موثوق منها؟ أنت لست وحدك—العديد من المطورين يواجهون نفس المشكلة عندما تبدو الكلمات المستخرجة غير ثابتة وتكون درجة الثقة غامضة. + +في هذا الدليل سنغوص مباشرةً في حل عملي: ستتعرف على كيفية **run OCR on image**، قراءة الثقة العامة، واستخراج أي كلمات ذات ثقة منخفضة قد تحتاج إلى مراجعة يدوية. في النهاية ستحصل على سكريبت قابل لإعادة الاستخدام، وتفهم لماذا كل سطر مهم، وتعرف كيف تعدل عتبة الثقة لمشاريعك الخاصة. + +## ما يغطيه هذا الدرس + +سنستعرض سير العمل بالكامل—من تحميل الصورة إلى طباعة تقرير منظم للكلمات التي سقطت تحت علامة 80 % من الثقة. على طول الطريق سنناقش: + +* اختيار محرك OCR قوي (سنستخدم **EasyOCR**، مكتبة OCR شائعة في بايثون) +* تفسير خاصية `confidence` التي تُرجعها كل نتيجة OCR +* تصفية الكلمات باستخدام **عتبة ثقة OCR** مخصصة +* توسيع السكريبت لمعالجة دفعات أو استخدام محركات بديلة مثل **pytesseract** + +لا تحتاج إلى خبرة سابقة في OCR، فقط إلمام أساسي ببايثون وبيئة عمل (يوصى بـ Python 3.9+). + +هل أنت مستعد لتحويل لقطات الشاشة الضبابية إلى نص نظيف قابل للبحث؟ لنبدأ. + +--- + +## ## كيفية تشغيل OCR على الصورة باستخدام بايثون + +قلب الدرس هو مقطع من ثلاث خطوات يعكس الكود الذي رأيته بالفعل. أدناه سنفصل كل سطر، نشرح السبب، ثم نعطيك سكريبت جاهز للنسخ واللصق. + +### الخطوة 1: تثبيت واستيراد محرك OCR + +أولًا، تأكد من توفر مكتبة OCR. **EasyOCR** يعمل مباشرةً للعديد من اللغات ويعطيك درجة ثقة لكل كلمة. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*لماذا EasyOCR؟* إنه يجمع نموذج تعلم عميق تم تدريبه على مجموعات بيانات متنوعة، لذا عادةً ما تحصل على قيم ثقة أعلى من محرك Tesseract القديم، خاصةً على الصور ذات الجودة المختلطة. + +> **نصيحة احترافية:** إذا كنت تعمل في بيئة محدودة (مثل حاوية Docker صغيرة)، قد يكون `pytesseract` أخف وزنًا، لكنك ستفقد بعض الدقة الحديثة التي يوفرها EasyOCR. + +### الخطوة 2: تشغيل OCR على الصورة + +الآن نقوم فعليًا بـ **run OCR on image**. تم استبدال طريقة `recognize_image` من المثال الأصلي بنداء `readtext` الخاص بـ EasyOCR، والذي يُرجع قائمة من tuples على الشكل `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +كل عنصر في `ocr_results` يبدو كالتالي: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +العنصر الثالث (`0.92` في المثال) هو درجة الثقة التي تتراوح بين 0 إلى 1. + +### الخطوة 3: تلخيص الثقة العامة + +على عكس المقتطف السابق الذي طبع خاصية `confidence` واحدة، يقدم EasyOCR ثقة لكل كلمة. للحصول على فكرة عامة، سنحسب المتوسط: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*لماذا المتوسط؟* يمنحك فحصًا سريعًا للصحّة—إذا كانت الثقة العامة أقل من، لنقل، 70 %، فربما تحتاج إلى تحسين الصورة (إضاءة أفضل، معالجة مسبقة، إلخ). + +### الخطوة 4: سرد الكلمات ذات الثقة المنخفضة + +الآن يأتي الجزء الذي يجيب مباشرةً على طلب “قائمة الكلمات التي تكون ثقتها أقل من العتبة المطلوبة”. سنحدد **عتبة ثقة OCR** بـ 0.80 (80 %) افتراضيًا، لكن يمكنك تعديلها. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +الحلقة تطبع كل كلمة لم تتجاوز العتبة، مع نسبة الثقة الخاصة بها. هذا هو النظير الدقيق لحلقة `for recognized_word in recognition_result.words` الأصلية، لكنه الآن يعمل مع صيغة إخراج EasyOCR. + +--- + +## ## فهم درجات ثقة OCR + +الثقة ليست رقمًا سحريًا؛ إنها تقدير النموذج لمدى تأكده من النسخ المعين. إليك بعض الأمور التي يجب مراعاتها: + +| الحالة | الثقة المتوقعة | ما الذي يجب فعله | +|-----------|-------------------|------------| +| مسح واضح وعالي الدقة | 0.95 – 1.00 | لا حاجة لأي عمل إضافي | +| ضبابية طفيفة أو إضاءة غير متساوية | 0.80 – 0.94 | فكر في معالجة مسبقة بسيطة (زيادة التباين) | +| ضوضاء شديدة، نص مائل | < 0.70 | طبّق معالجة مسبقة للصورة (تصحيح الميل، إزالة الضوضاء) أو انتقل إلى محرك OCR مختلف | + +> **احذر:** بعض اللغات (مثل الخط اليدوي المتصل) تنتج بطبيعتها درجات أقل. عدّل العتبة وفقًا لذلك. + +### حالات الحافة والاختلافات + +1. **معالجة دفعات** – إذا كنت بحاجة إلى **run OCR on image** لملفات متعددة دفعةً واحدة، غلف المنطق أعلاه بحلقة تتنقل عبر دليل. +2. **لغات متعددة** – مرّر قائمة مثل `['en', 'fr']` إلى `easyocr.Reader` وسيكتشف المحرك كلا اللغتين. +3. **محركات بديلة** – هل تريد تجربة **pytesseract**؟ استبدل كتلة القارئ بـ: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + بعد ذلك ستحتاج إلى تجميع ثقة كل حرف إلى ثقة كلمة—عمل إضافي قليل لكنه ممكن. +4. **حيل المعالجة المسبقة** – تطبيق فلاتر OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) يمكن أن يعزز الثقة للصور المليئة بالضوضاء. + +--- + +## ## سكريبت كامل جاهز للتنفيذ + +فيما يلي ملف بايثون كامل يمكنك وضعه في مشروعك. احفظه باسم `ocr_report.py` وشغّله بـ `python ocr_report.py`. تأكد أن مسار الصورة يشير إلى ملف حقيقي. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**المخرجات المتوقعة** (ستختلف أرقامك): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +إذا تجاوزت كل كلمة عتبة الـ 80 % ستظهر لك الرسالة الودية “All words meet the confidence threshold.” بدلاً من ذلك. + +--- + +## ## الأسئلة المتكررة (FAQ) + +**س: هل يعمل هذا مع ملفات PDF؟** +ج: ليس مباشرة. حوّل كل صفحة PDF إلى صورة أولًا (مثلاً باستخدام `pdf2image`) ثم أدخل ملف PNG/JPEG إلى السكريبت. + +**س: أرقام الثقة لدي كلها منخفضة — ماذا يمكنني أن أفعل؟** +ج: جرّب معالجة مسبقة للصورة: زد التباين، أزل الضوضاء الخلفية، أو قم بتدوير الصورة لتصبح أفقية. EasyOCR يقبل أيضًا معامل `contrast_ths` يمكنك ضبطه. + +**س: هل يمكنني تصدير النتائج إلى CSV؟** +ج: بالتأكيد. بعد حلقة الكلمات منخفضة الثقة، اكتب `ocr_results` إلى `csv.DictWriter` حيث يحتوي كل صف على `text`، `confidence`، وإحداثيات المربع المحيط. + +**س: هل هناك نسخة مسرعة باستخدام GPU؟** +ج: EasyOCR يستخدم CUDA تلقائيًا إذا كان هناك GPU متوافق وPyTorch مثبت. تحقق من `torch.cuda.is_available()` قبل تشغيل السكريبت. + +--- + +## الخلاصة + +لقد قمنا للتو بـ **run OCR on image** باستخدام بايثون، فحصنا الثقة العامة، وعزلنا أي كلمات ذات ثقة منخفضة تحتاج إلى + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [كيفية ضبط قيمة العتبة في التعرف على الصور باستخدام OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [كيفية استخدام Aspose OCR للحصول على نتيجة JSON في التعرف على الصور](/ocr/english/net/text-recognition/get-result-as-json/) +- [استخراج النص من الصورة – تحسين OCR باستخدام Aspose.OCR لـ .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/chinese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..49e95770a --- /dev/null +++ b/ocr/chinese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python OCR 在几分钟内从图像中提取文本。了解多语言图像 OCR、自动检测语言的 OCR,以及如何准确提取 OCR 文本。 +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: zh +og_description: 使用 Python OCR 快速提取图像中的文本。学习多语言图像 OCR、自动检测语言的 OCR,以及一步步提取 OCR 文本的方法。 +og_title: 使用 Python OCR 从图像提取文本 – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: 使用 Python OCR 从图像中提取文本 – 完整指南 +url: /zh/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Python OCR 从图像提取文本 – 完整指南 + +是否曾经需要**从图像中提取文本**,却不确定哪个库能够自动处理多语言?你并不孤单——开发者在处理国际文档、收据或扫描传单时,常常会问*如何提取 OCR 文本*。在本教程中,我们将通过一个实用的 Python 示例,演示不仅可以从图像中提取文本,还能**实时检测语言**,让多语言图像 OCR 轻而易举。 + +我们将从安装 OCR 包、启用**自动检测语言 OCR**、在示例图片上运行引擎,到最终打印检测到的语言和提取的字符串,全部一步步讲解。完成后,你将拥有一段可复用的代码片段,能够直接嵌入任何项目,无论是构建翻译流水线还是数据摄取服务。 + +## 提取图像文本 – 环境搭建 + +在编写代码之前,请确保你的工作站满足以下最低要求: + +- Python 3.8 或更高(该库使用了旧版本不支持的类型提示) +- `pip` 用于包管理 +- 一张包含至少两种不同语言文本的图像文件(例如 English + Spanish) + +你还需要为本演示准备的 OCR 库。为了本指南的方便,我们使用虚构的 `ocr` 包,它的功能类似于 Tesseract、EasyOCR 等主流工具,但提供了简洁的 Python API。 + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **小技巧:** 如果遇到权限错误,可在命令前加上 `python -m`,或使用虚拟环境——这样可以保持全局 site‑packages 的整洁。 + +## 创建 OCR 引擎实例 + +库准备好后,第一步是**创建 OCR 引擎实例**。可以把引擎想象成一个可在喂入图像前进行配置的智能扫描仪。 + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +为什么要单独实例化引擎,而不是直接调用静态方法?引擎对象保存了配置状态(如语言偏好),这样在处理多张图片时可以复用,避免每次都重新初始化带来的开销。 + +## 启用自动检测语言 OCR + +大多数 OCR 工具需要你手动指定语言代码——`eng` 表示英语,`spa` 表示西班牙语,依此类推。手动猜测语言会破坏**多语言图像 OCR**工作流的初衷。幸运的是,`ocr` 包提供了*自动检测语言 OCR*模式,能够在后台检查图像并自动选择最佳语言模型。 + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +以这种方式启用**检测语言 OCR**,就不必维护冗长的语言代码列表。引擎会尝试匹配图像中出现的文字脚本——拉丁文、西里尔文、汉字等——并自动加载相应模型。 + +## 执行多语言图像 OCR + +引擎准备就绪后,就可以真正**从图像中提取文本**了。`recognize_image` 方法接受文件路径,返回一个结果对象,包含原始文本以及检测到的语言。 + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +如果你想知道*如何从 PDF 而不是 PNG 提取 OCR 文本*,同一引擎提供 `recognize_pdf`——只需更换方法名即可。底层的检测逻辑保持不变,仍然受益于相同的**自动检测语言 OCR**特性。 + +## 显示检测到的语言和提取的文本 + +最后,我们输出引擎发现的内容。结果对象公开 `detected_language`(如 `en`、`es` 的 BCP‑47 标签)和 `text`(原始 OCR 输出)。 + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +在示例图片上运行脚本,应该会得到类似以下的输出: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +可以看到,引擎正确识别出英语为主要语言,同时也捕获了西班牙语行——这正是一个健壮的**多语言图像 OCR**解决方案所应具备的表现。 + +### 检测失败怎么办? + +如果图像模糊或脚本过于冷门,OCR 引擎可能会回退到默认语言(通常是英语)。此时可以强制指定语言列表: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +但请记住,强制指定语言会削弱**自动检测语言 OCR**的便利性,仅在已知语言子集的情况下使用。 + +## 常见陷阱及可靠提取 OCR 文本的技巧 + +即使开启了自动检测,仍有一些常见问题可能导致错误: + +1. **低分辨率图像** – 当分辨率低于 150 dpi 时,OCR 准确率会急剧下降。请放大图像或获取更高分辨率的扫描件。 +2. **噪声和压缩伪影** – 在将图像送入引擎前,使用简单的阈值过滤(`opencv` 或 `Pillow`)进行预处理。 +3. **单页混合脚本** – 某些引擎在同时处理拉丁文和中日韩字符时会出现困难。必要时将页面划分为多个区域,分别进行识别。 + +解决这些问题可以显著提升**从图像提取文本**的质量,尤其是在处理真实世界的多语言文档时。 + +## 完整可运行示例 + +下面是结合上述所有步骤的完整脚本。将其保存为 `multilingual_ocr.py`,然后在命令行执行。 + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**预期输出**(假设示例图片包含英文和西班牙文): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +你可以将 `multilang_page.png` 替换为任何包含其他语言文本的图片——得益于**自动检测语言 OCR**,脚本仍会返回合理的语言标签和对应的文本。 + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## 结论 + +现在,你已经掌握了**如何从图像中提取 OCR 文本**、如何启用**自动检测语言 OCR**,以及如何用最少的代码处理**多语言图像 OCR**场景。通过创建 OCR 引擎实例、打开自动语言检测,并调用 `recognize_image`,你可以可靠地获取语言标识和原始文本。 + +接下来可以尝试将提取的字符串送入翻译 API、存入可检索的数据库,或将多页合并为单个 PDF 报告。你也可以在保持相同高层工作流的前提下,尝试不同的 OCR 后端(Tesseract、EasyOCR、Google Vision)——这得益于统一的**检测语言 OCR**接口。 + +如果遇到奇怪的问题,请回顾“常见陷阱”章节或微调图像预处理步骤。祝编码愉快,愿你的下一个项目充满正确检测、完美提取的文本! + +## 接下来该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你在已有技巧的基础上进一步扩展。每篇资源都提供完整可运行的代码示例和逐步解释,助你掌握更多 API 功能并探索替代实现方案。 + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/chinese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..6034b6dd7 --- /dev/null +++ b/ocr/chinese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python OCR 从图像 PDF 中提取文本。了解如何使用异步批量识别快速将扫描文档转换为文本。 +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: zh +og_description: 使用 Python 从图像 PDF 中提取文本。本分步指南展示了如何使用异步 OCR 将扫描文档转换为文本。 +og_title: 从图像 PDF 中提取文本 – Python OCR 教程 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: 从图像 PDF 中提取文本 – Python 指南:将扫描文档转换为文本 +url: /zh/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 从图片 PDF 中提取文本 – Python 将扫描文档转换为文本的指南 + +是否曾经想要 **从图片 pdf 中提取文本**,却不想花费数小时手动重新输入?在本指南中,我们将展示如何使用 Python 中的简单异步 OCR 工作流 **将扫描文档转换为文本**。 + +如果你曾盯着一堆扫描的 PDF,心想“一定有更快的方法”,那么你来对地方了。我们会逐行讲解代码,说明每一部分为何重要,并且覆盖一些可能遇到的边缘情况。 + +## 你将学到 + +- 如何启动 OCR 引擎并设置识别语言。 +- 将 PNG 与 PDF 混合列表喂入批量识别器的工作原理。 +- 异步运行 OCR 任务,使你的应用保持响应。 +- 拉取结果、将其与源文件配对并打印整洁的输出。 + +**先决条件**:Python 3.8+、对 `asyncio` 或 `concurrent.futures` 有基本了解,以及一个提供类似 `OcrEngine` 类的 OCR 库(如 Aspose.OCR、Tesseract 包装器或自定义包装器)。无需繁重的配置——只需安装库即可开始。 + +![extract text from images pdf](https://example.com/placeholder.png "Screenshot of OCR output – extract text from images pdf") + +## 从图片 PDF 中提取文本 – 设置 OCR 引擎 + +首先需要一个已为文档语言配置好的 OCR 引擎实例。本例使用法语,你可以替换为任何受支持的语言。 + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**为什么重要**:提前设置语言可以显著提升准确率。引擎会使用语言特定的词典和字符模型;使用错误的语言是导致乱码的常见原因。 + +## 准备文件列表 – 同时包含图片和 PDF + +我们的批量识别器可以处理光栅图像(`.png`、`.jpg`)和 PDF 容器。只需提供一个普通的 Python 文件路径列表。 + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**提示**:保持列表为一维;引擎会在内部将每个 PDF 页面解包为图像后再进行识别。如果文件数量达数千,建议将列表分块,以避免内存峰值。 + +## 启动异步批量识别 + +我们不在主线程中阻塞,而是在后台启动 OCR 任务。该方法返回一个 `Future`,最终会持有 `OcrResult` 对象列表。 + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**工作原理**:底层引擎会创建线程池(或异步任务,取决于实现),这让你可以在 OCR 进行时继续执行其他工作——比如更新 UI、获取更多文件或记录进度。 + +## OCR 运行时做点有用的事 + +常见错误是空闲等待并在紧循环中轮询 `Future`。相反,你可以执行任何不相关的工作。这里我们仅打印一行状态信息作示例。 + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## 当 Future 完成后收集结果 + +准备好获取 OCR 输出时,使用 `concurrent.futures` 的 `as_completed`。无论是单个还是多个 Future,这种模式都适用。 + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**你会看到**:每个文件路径后面跟随提取出的纯文本。对于 PDF,`result.text` 包含所有页面的合并文本。 + +### 预期输出(示例) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +如果发现缺失字符,请再次确认所设置的语言与文档语言匹配,并考虑在喂入引擎前对图像进行预处理(去倾斜、提升对比度)。 + +## 处理边缘情况和常见陷阱 + +| 情况 | 处理方法 | +|-----------|------------| +| **混合语言** | 首先进行语言检测,然后为每种语言实例化单独的引擎。 | +| **超大 PDF(> 100 MB)** | 使用 `PyPDF2` 等工具将 PDF 拆分为单页文件,再分别作为条目喂入。 | +| **非拉丁文字** | 确认 OCR 库已包含所需语言包;有些库需要额外下载数据文件。 | +| **性能瓶颈** | 增大线程池规模(`engine.set_thread_pool_size(8)`)或在可用时切换到 GPU 加速后端。 | +| **低分辨率图像缺失文本** | 使用 OpenCV 预处理:`cv2.resize`、`cv2.threshold`、`cv2.medianBlur` 提高可读性。 | + +## 完整可运行示例(复制粘贴即用) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +将其保存为 `extract_text_async.py`,将 `YOUR_DIRECTORY` 替换为你的文件路径,安装 OCR 包(`pip install your-ocr-lib`),然后运行 `python extract_text_async.py`。你将看到前文示例的控制台输出。 + +## 后续步骤 – 超越基础提取 + +- **后处理**:去除多余空白、Unicode 正规化(`unicodedata.normalize`),或使用拼写检查器清理 OCR 噪声。 +- **结构化输出**:将结果导出为 CSV、JSON,或直接写入数据库,以供后续检索。 +- **并行批次**:如果文件数以百计,可启动多个 Future 并使用队列保持 CPU 高负载而不致内存耗尽。 +- **与 Web 框架集成**:将此脚本接入 Flask 或 FastAPI 接口,提供按需 OCR 即服务。 + +--- + +### TL;DR + +你现在已经掌握了使用最小化的 Python 脚本 **异步运行 OCR**,从而 **将扫描文档转换为文本**,且程序保持响应。尝试调节语言设置、批量大小和预处理技巧,以获取最高的字符准确率。 + +有什么新想法想分享——比如手写笔记的 OCR 或基于云的服务?欢迎留言,祝编码愉快! + + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在已有技巧之上进一步深入。每篇资源都提供完整可运行的代码示例,并配有逐步解释,助你掌握更多 API 功能并探索在项目中的替代实现方式。 + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Images Using Aspose.OCR – Allowed Characters](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e81ab4427 --- /dev/null +++ b/ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Python 对 PDF 进行 OCR,提取 PDF 文本,转换扫描版 PDF 文本,并在几行代码内更改 OCR 语言。 +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: zh +og_description: 如何使用 Python 对 PDF 进行 OCR:一本实用指南,教你如何从 PDF 中提取文本、转换扫描 PDF 文本,并轻松更改 + OCR 语言。 +og_title: 如何在 Python 中对 PDF 进行 OCR – 完整编程教程 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: 如何在 Python 中对 PDF 进行 OCR – 完整分步指南 +url: /zh/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Python 中进行 PDF OCR – 完整分步指南 + +有没有想过在不支付昂贵 SaaS 工具费用的情况下 **如何对 PDF 进行 OCR**?你并不是唯一有此需求的人。无论是数字化旧书、从发票中提取数据,还是仅仅需要从扫描报告中获取可搜索的文本,掌握 Python 中的 PDF OCR 都可以为你节省数小时的手动复制工作。 + +在本教程中,我们将演示一个简洁、可运行的示例,**从 PDF 中提取文本**,展示如何 **将扫描的 PDF 文本** 转换为可编辑的字符串,并演示如果文档不是英文时如何 **更改 OCR 语言**。完成后,你将拥有一个可在任何项目中直接使用的代码片段。 + +## 前置条件与设置 + +在开始之前,请确保你已经具备: + +- 已安装 Python 3.8+(代码在 3.9、3.10 以及更高版本均可运行) +- 提供 `OcrEngine` 类的 `ocr` 包(可通过 `pip install ocr-lib` 安装——请替换为你实际使用的包名) +- 一个待处理的 PDF 文件;演示中我们使用放在 `YOUR_DIRECTORY` 文件夹下的 `high_res_book.pdf` + +如果你使用虚拟环境(强烈推荐),请先激活它: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **专业提示:** 将 PDF 文件统一放在专用的 `data/` 目录下,可避免后期路径相关的麻烦。 + +## 步骤 1:创建 OCR 引擎实例(How to OCR PDF – 初始化) + +当你想要 **对 PDF 执行 OCR** 时,首先需要实例化引擎。可以把引擎想象成大脑,它会读取每一页、解释字形,并返回纯文本。 + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +为什么这很重要:没有引擎,你将没有语言设置、渲染选项或 PDF 处理的上下文。`OcrEngine` 对象保存了所有默认值,并允许你随后进行微调。 + +## 步骤 2:设置识别语言(Change OCR Language) + +大多数 OCR 库默认使用英语,但如果你的文档是法语、德语甚至日语怎么办?只需调用 `set_recognition_language` 即可更改语言。这满足 **change OCR language** 的需求,并提升识别准确度。 + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **为何可能需要这样做:** 多语言档案常包含混合语言的页面。即时切换语言可防止字符如 “ß” 或 “ñ” 被误识别。 + +## 步骤 3:配置 PDF 渲染选项(Convert Scanned PDF Text Effectively) + +处理扫描版 PDF 时,分辨率和颜色模式会显著影响 OCR 质量。以 300 DPI 的灰度模式渲染是大多数文档的最佳平衡——既能捕捉细节,又能保持内存占用在合理范围。 + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +链式调用看起来很炫,但其实只是返回同一个选项对象的流式 API。如果需要彩色(例如彩色图表),将 `"grayscale"` 替换为 `"color"` 即可。 + +## 步骤 4:识别 PDF 并获取首页文本(Extract Text from PDF) + +现在进入 **如何对 PDF 进行 OCR** 的核心:将文件路径交给引擎并提取识别后的文本。该方法返回一个页面结果列表,每个结果都包含 `text` 属性。 + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +如果需要整本文档,可遍历 `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### 如果 PDF 被加密怎么办? + +有些 PDF 受密码保护。这种情况下可以将密码传递给 `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +引擎会在执行 OCR 前即时解密——无需额外步骤。 + +## 步骤 5:后处理提取的文本(Fine‑Tuning Extract Text from PDF) + +原始 OCR 输出常包含换行、额外空格或偶尔的误识别字符。快速的清理例程可以让提取的字符串准备好用于后续处理(搜索索引、数据库存储等)。 + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +现在你可以安全地 **从 PDF 中提取文本**,并将其输入任意 NLP 流程、搜索引擎或简单的 `open(...).write()` 操作。 + +## 额外内容:批量处理多个 PDF(Scaling Perform OCR on PDF) + +如果文件夹中充满了扫描版 PDF,只需将逻辑包装在循环中: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +该代码片段展示了如何批量 **对 PDF 执行 OCR**,这在数字化项目中非常常见。 + +## 预期输出 + +运行单页示例(步骤 4)应打印类似以下内容: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +如果处理的是多页书籍,控制台会显示每页的清理后文本,批处理脚本会在每个 PDF 旁生成相应的 `.txt` 文件。 + +## 常见陷阱及避免方法 + +| 问题 | 症状 | 解决方案 | +|------|------|----------| +| 低分辨率源 PDF | 字符乱码、缺失单词 | 提高 DPI(`set_dpi(400)` 或更高) | +| 语言设置错误 | 大量未知符号,尤其是带重音的字符 | 使用 `engine.set_recognition_language(ocr.Language.FRENCH)` 或相应的枚举 | +| 大文件导致内存错误 | `MemoryError` 或在几页后崩溃 | 分块处理页面(`engine.recognize_pdf(..., max_pages=10)`) | +| PDF 中缺少字体 | 某些页面输出为空白 | 确认 PDF 实际包含光栅图像;有些 PDF 为矢量文件,需要不同的处理方式 | + +## 图片示例 + +下面是一张工作流的快速示意图。alt 文本特意采用 SEO 友好的描述。 + +![如何进行 PDF OCR 工作流图,展示引擎初始化、语言设置、渲染选项、识别和文本提取](/images/ocr-workflow.png) + +*该图并非代码运行的必需,但有助于视觉学习者了解每一步的定位。* + +## 结论 + +我们已经从头到尾覆盖了在 Python 中 **如何对 PDF 进行 OCR**:创建 OCR 引擎、**更改 OCR 语言**、配置渲染以 **转换扫描的 PDF 文本**,以及最终 **从 PDF 中提取文本** 供后续使用。完整、可运行的示例已准备好直接嵌入任何项目,且可选的批处理脚本展示了如何扩展该方案。 + +接下来,你可能想探索: + +- 通过遍历语言列表,为多语言档案添加 **对 PDF 执行 OCR** 的功能。 +- 将提取的文本与 Elasticsearch 集成,实现全文搜索。 +- 使用 OCR 创建可搜索的 PDF,方法是将文本层嵌入原始文件(许多库提供 `save_as_searchable_pdf` 方法)。 + +欢迎随意实验,调整 DPI 设置,或切换到其他 OCR 后端。基本原理保持不变,而你已经拥有了坚实的基础来进一步构建。 + +祝编码愉快,愿你的扫描文档终成可搜索的资源! + +## 接下来该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你在自己的项目中进一步掌握 API 功能并探索替代实现方式。每篇资源都提供完整的可运行代码示例和逐步解释。 + +- [识别 PDF 文本 – 使用 Aspose.OCR for Java 的 OCR 操作](/ocr/english/java/ocr-operations/) +- [使用 Aspose.OCR 进行图像文本 OCR 并选择语言](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [如何在 .NET 中使用 Aspose.OCR 进行 PDF OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..8f27a7a0e --- /dev/null +++ b/ocr/chinese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Python 对 PDF 进行 OCR 并从图像创建可搜索的 PDF 文件。学习在几分钟内添加可搜索文本并将图像转换为 PDF/A。 +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: zh +og_description: 一步步教你对 PDF 进行 OCR。学习使用简单的 Python 脚本添加可搜索文本并将图像转换为 PDF/A。 +og_title: 如何对PDF进行OCR – 创建可搜索PDF的快速指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: 如何在 Python 中对 PDF 进行 OCR – 从图像创建可搜索的 PDF +url: /zh/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何对 PDF 进行 OCR – 将扫描图像转换为可搜索的 PDF + +是否曾经想过 **如何对 PDF 进行 OCR**,当你手头只有发票或收据的扫描图像时?你并不孤单。在许多办公室,收到的纸质文件往往是平面的 PNG 或 JPEG,接下来——让这些内容可搜索——常常像是一个黑盒。 + +好消息是,只需几行 Python 代码,你就可以 **创建可搜索的 PDF**,**添加可搜索的文本**,甚至 **将图像转换为 PDF/A** 以便长期存档。在本教程中,我们将逐步演示每一步,解释其意义,并提供一个可直接运行的脚本,供你在任何项目中使用。 + +> **小技巧:** 同样的方法适用于多页扫描,只需遍历文件,引擎会自动完成繁重的工作。 + +--- + +## 所需条件 + +在开始之前,请确保你的机器上具备以下条件: + +| 条件 | 为什么重要 | +|------|------------| +| Python 3.9 或更高版本 | 支持现代语法并拥有更好的库兼容性 | +| 基于 `pdfium` 的 OCR 引擎(如 `pdfocr` 或商业 SDK) | 同时处理图像识别和 PDF/A 生成 | +| 需要转换为可搜索 PDF 的图像文件(PNG、JPEG、TIFF) | 文本的来源 | +| 对输出文件夹的写入权限 | 脚本才能保存新生成的 PDF | + +如果尚未安装 OCR SDK,请运行: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +就这么简单——无需复杂的系统依赖,只需一次 pip 安装。 + +--- + +## OCR PDF 概览 + +从宏观上看,这个过程包括三个简单的操作: + +1. **识别** 图像中的文字,同时保留原始图形。 +2. **导出** OCR 结果并将原始图像一起保存为 **可搜索的 PDF/A**(适合长期保存的 PDF 版本)。 +3. **验证** 生成的文件是否在原始图片上叠加了可选中、可搜索的文字层。 + +下面的代码展示了每一步,并解释了背后的 *why*。 + +--- + +## 步骤 1:从图像中识别文字 + +首先让 OCR 引擎读取像素并返回一个结果对象,该对象同时包含原始图像和提取的文字。可以把它想象成引擎为你“阅读”发票。 + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### 为什么重要 + +- **保留图形** 意味着布局(表格、徽标、印章)保持扫描时的原始样子。 +- `result` 对象通常包含一个隐藏的文字层,稍后我们会把它嵌入 PDF。 +- 使用 `recognize_image` 而非 `recognize_pdf` 可以避免额外的转换步骤,从而加快单页图像的处理速度。 + +#### 常见变体 + +- 如果你有 **多页 TIFF**,直接传入文件路径;大多数引擎会把每页当作单独的图像处理。 +- 对于已经包含图像的 PDF,你可以调用 `engine.recognize_pdf("file.pdf")`,直接跳过此步骤。 + +--- + +## 步骤 2:将 OCR 结果导出为可搜索的 PDF/A + +现在我们把步骤 1 中得到的 `result` 交给引擎,生成一个新文件。这里的关键标志是 *PDF/A*——PDF 的 ISO 标准长期保存版本。 + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### 为什么重要 + +- **可搜索的 PDF**:输出文件包含隐藏的、可选中的文字层。现在可以使用 Ctrl + F 在文档中搜索。 +- **PDF/A 合规**:某些组织(法律、金融)要求使用 PDF/A 进行审计存档;此步骤会自动满足该要求。 +- 此方法还能 **在不扁平化图像的情况下添加可搜索文字**,保持视觉保真度。 + +#### 边缘情况:需要普通 PDF? + +如果不在乎 PDF/A,只需将 `save_as_pdfa` 替换为 `save_as_pdf`,其余工作流保持不变。 + +--- + +## 步骤 3:验证可搜索的 PDF + +一次快速的完整性检查可以帮助你避免后期的神秘错误。用任意 PDF 查看器打开生成的文件,尝试选中一个单词并使用搜索功能。 + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### 预期输出 + +运行脚本后,控制台会打印: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +打开文件后,你应当看到原始发票图像上叠加了一层淡淡的、不可见的文字层。选中任意单词,你会发现它是可选中的——**这就是刚刚添加的可搜索文字**。 + +--- + +## 为已有 PDF 添加可搜索文字(进阶) + +有时你已经拥有一个 PDF,但仍需要 **为其添加可搜索文字**。同样的引擎可以将 OCR 结果覆盖到已有的 PDF 上: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +这里的 `apply_to` 会把隐藏层与原始页面合并,让你 **在不重新扫描的情况下创建可搜索 PDF**。 + +--- + +## 常见陷阱与技巧 + +| 陷阱 | 如何避免 | +|------|----------| +| **低分辨率源图像** (< 150 dpi) | 放大或请求更高分辨率的扫描;低于 150 dpi 时 OCR 准确率会显著下降。 | +| **缺少语言数据** | 为你的 OCR 引擎安装相应的语言包(`pip install pdfocr[eng,spa]`)。 | +| **输出文件夹不可写** | 以足够权限运行脚本或选择其他目录。 | +| **PDF/A 验证失败** | 确保未嵌入不受支持的字体或 JavaScript;大多数 SDK 在使用 `save_as_pdfa` 时会自动处理。 | + +--- + +## 完整脚本 – 单文件解决方案 + +下面是一段自包含的脚本,整合了上述所有步骤。复制粘贴后,替换占位路径,即可在几秒钟内 **将图像转换为 PDF/A**。 + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**脚本功能概述:** +1. 加载 OCR 引擎。 +2. 读取指定图像并提取文字。 +3. 写入 **可搜索的 PDF/A**,即可直接分发或归档。 + +如果需要一次性处理整个文件夹,只需将 `main` 逻辑包装成函数,遍历 `os.listdir()` 并对每个文件重复上述三步。 + +--- + +## 后续步骤与相关主题 + +掌握了 **如何对 PDF 进行 OCR** 之后,你可以进一步探索以下方向: + +- **批量处理:** 使用 `concurrent.futures` 并行 OCR 处理数十份发票。 +- **元数据注入:** 为 PDF 添加创建日期或发票编号,便于后续索引。 +- **混合 PDF:** 将可搜索文字与原始图像嵌入同一文件,形成文档的 “数字孪生”。 +- **其他输出格式:** 如需可编辑的下游系统,可导出为 **DOCX** 或 **HTML**。 + +这些都建立在你刚学到的核心概念之上——识别、导出、验证。 + +--- + +## 小结 + +简而言之,你现在已经掌握了 **如何对 PDF 进行 OCR**:只需三行 Python 代码,就能把普通图像转换为 **可搜索的 PDF/A**。脚本负责繁重的工作,保留原始图形,并生成符合标准的文档,供搜索、归档或共享使用。 + +试着用自己的发票、收据或扫描合同来运行它吧。如果遇到问题,欢迎在下方留言或查阅 SDK 官方文档——通常会有更多示例。祝编码愉快,尽情享受让任何图像瞬间可搜索的全新能力! + +![如何对 PDF 进行 OCR 示例,展示原始图像与可搜索 PDF 的叠加效果](placeholder.png "如何对 PDF 进行 OCR 示例") + +## 接下来该学习什么? + +以下教程涵盖与本指南紧密相关的主题,每篇都提供完整可运行的代码示例和逐步解释,帮助你掌握更多 API 功能并在项目中探索替代实现方案。 + +- [如何在 .NET 中使用 Aspose.OCR 进行 PDF OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [使用 Aspose.OCR for Java 进行 PDF 文本识别 – OCR 操作](/ocr/english/java/ocr-operations/) +- [C# 将图像转换为 PDF – 保存多页 OCR 结果](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/chinese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..253d98ab4 --- /dev/null +++ b/ocr/chinese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Aspose OCR Cloud 对 PDF 进行 OCR。学习从 PDF 中提取文本、将 PDF 页面转换为 PNG,并在 Python + 中保存 PDF 页面图像。 +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: zh +og_description: 如何使用 Aspose OCR Cloud 对 PDF 进行 OCR。本指南展示了如何提取纯文本 PDF、将 PDF 页面转换为 PNG,以及保存 + PDF 页面图像。 +og_title: 如何使用 Aspose OCR Cloud 对 PDF 进行 OCR – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: 如何使用 Aspose OCR Cloud 对 PDF 进行 OCR – 完整指南 +url: /zh/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Aspose OCR Cloud 对 PDF 进行 OCR – 完整指南 + +是否曾经想过 **如何对 PDF 进行 OCR** 而不必使用笨重的桌面工具?你并不孤单——许多开发者在需要快速、可编程地从扫描文档中提取文本时都会遇到这个难题。好消息是?使用 Aspose OCR Cloud,你可以 **从 PDF 中提取文本**、将每页转换为 PNG,甚至 **保存 PDF 页面图像** 以供后续使用,全部通过一个简洁的 Python 脚本完成。 + +在本教程中,我们将逐步讲解你需要了解的所有内容:从安装 SDK、授权引擎、识别多页 PDF,到提取纯文本、将页面转换为 PNG,以及将这些图像持久化到磁盘。完成后,你将拥有一个可复用的代码片段,能够在任何需要 **如何对 PDF 进行 OCR** 功能的项目中直接使用。 + +## 你需要准备的环境 + +- **Python 3.8+**(代码在 3.10 及更高版本同样适用) +- Aspose OCR Cloud 账户——你将获得一个免费试用的许可证文件 (`Aspose.OCR.lic`) +- `asposeocrcloud` 包(`pip install asposeocrcloud`) +- 一份需要处理的扫描版多页 PDF + +就这些。无需额外的二进制文件、无需本地依赖,纯 Python 即可。 + +## 如何对 PDF 进行 OCR – 设置与授权 + +在调用任何 OCR 方法之前,你必须告诉 SDK 你的身份。Aspose 使用一个轻量级的许可证文件,你只需将其放在脚本可访问的位置。 + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*小技巧*:如果跳过授权步骤,SDK 仍然可以工作,但会在输出图像中嵌入一个小水印。生产环境下并不理想。 + +## 步骤 2:安装 Aspose OCR Cloud Python SDK + +打开终端并运行: + +```bash +pip install asposeocrcloud +``` + +该包会自动拉取所有必需的依赖(requests、pillow 等),你无需额外寻找任何东西。 + +## 步骤 3:创建 OCR 引擎并选择语言 + +引擎是整个操作的核心。你可以指定 Aspose 支持的任意语言;英文在大多数情况下都能工作。 + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +为什么要设置语言?因为 OCR 引擎会使用特定语言的词典来提升识别准确率。如果你要处理法语 PDF,只需将 `ENGLISH` 换成 `FRENCH` 即可。 + +## 步骤 4:指向你的多页 PDF + +为引擎提供待处理文件的完整路径。相对路径同样可以,只要它们相对于脚本的工作目录能够解析即可。 + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +确保文件可读;否则会抛出 `FileNotFoundError`。 + +## 步骤 5:运行 OCR – 你将得到一个结果列表 + +调用 `recognize_pdf` 会返回一个列表,列表中的每个元素对应源 PDF 的一页。 + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +每个 `OcrResult` 包含两个实用属性: + +* `text` – 页面对应的纯文本表示(非常适合 **提取 PDF 纯文本**) +* `image` – 渲染后页面的 Pillow `Image` 对象(完美用于 **将 PDF 页面转换为 PNG**) + +## 步骤 6:从 PDF 中提取文本并将页面转换为 PNG + +现在我们遍历结果,打印提取的文本,并保存每页的 PNG 版本。 + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### 预期的控制台输出 + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +你还会在 `YOUR_DIRECTORY` 中看到 `page_1.png`、`page_2.png` … 等文件。这些就是可以进一步用于下游图像处理流水线的栅格化页面图像。 + +## 步骤 7:保存 PDF 页面图像(可选后处理) + +如果你只需要图像而不需要文本,可以省略 `print(res.text)` 那一行。相反,如果你想把文本存入单独的 `.txt` 文件,只需添加一小段写入代码: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +这段小小的补充演示了在 **保存 PDF 页面图像** 的同时,也能轻松持久化提取的内容。 + +## 完整可运行示例 + +将所有内容整合在一起,下面是可以直接复制到 `ocr_pdf.py` 的完整脚本: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +使用以下命令运行: + +```bash +python ocr_pdf.py +``` + +你应该会在控制台看到每页文本的输出,同时生成一系列 PNG 文件。 + +## 接下来你应该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你在已有技巧的基础上进一步深入。每篇资源都提供了完整的可运行代码示例以及逐步解释,帮助你掌握更多 API 功能并在自己的项目中探索替代实现方案。 + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/chinese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..884850063 --- /dev/null +++ b/ocr/chinese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Python 对图像进行 OCR 预处理。学习使用 Otsu 方法二值化图像,如何校正扫描文档的倾斜,以及提升德文文本的 OCR + 准确率。 +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: zh +og_description: 如何在 Python 中对图像进行 OCR 预处理。本教程展示了使用 Otsu 方法二值化图像、如何校正扫描文档的倾斜,以及如何提升德语图像的 + OCR 准确率。 +og_title: 如何为OCR预处理图像——完整Python指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: 如何为 OCR 预处理图像——完整 Python 指南 +url: /zh/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何为 OCR 预处理图像 – 完整 Python 指南 + +有没有想过 **how to preprocess images for OCR**,让文本清晰可辨?你并非唯一。扫描文档——尤其是嘈杂的德文页面——对任何 OCR 引擎来说都是噩梦。好消息是?只需几个聪明的预处理步骤,就能把模糊、斑点的扫描件变成干净、机器可读的图像。 + +在本教程中,我们将通过一个实用示例演示使用 Python 的 **how to preprocess images for OCR**。你将学习 **binarize image using Otsu**、**how to deskew scanned documents**,以及整体上 **how to improve OCR accuracy**,当你需要 **extract text from German image** 文件时。没有废话,只有可直接复制粘贴的工作脚本。 + +## 你需要的准备 + +- **Python 3.9+**(任何近期版本均可) +- 一个提供 `OcrEngine` 类的 OCR 库——演示中我们假设使用通用的 `ocr` 包。使用 `pip install ocr-lib` 安装。 +- 一个嘈杂的德文扫描件(`noisy_german_scan.tif`),用于测试。 +- 对 Python 函数的基本了解(如果你写过 `def`,就足够了)。 + +> **技巧提示:** 如果你使用其他 OCR SDK(例如通过 `pytesseract` 的 Tesseract),概念保持不变——只需调整方法名称。 + +## 解决方案概览 + +1. **创建 OCR 引擎实例。** +2. **将识别语言设置为德语。** +3. **构建自定义预处理流水线**,包括去倾斜、去噪、二值化(Otsu)和对比度拉伸。 +4. **将流水线附加到引擎**,使每张图像自动经过处理。 +5. **运行 OCR** 对嘈杂的德文扫描件进行识别。 +6. **打印提取的文本** 以验证结果。 + +下面我们逐步拆解每一步,解释 **why** 它重要,并展示你需要的完整代码。 + +![如何为 OCR 预处理图像示例](image.png "如何为 OCR 预处理图像示例") + +## 步骤 1:创建 OCR 引擎实例 + +首先——没有引擎,什么也不会发生。`OcrEngine` 对象是协调后续所有处理的入口点。 + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Why this matters:* 初始化引擎会设置内部资源(如语言模型),并为后续附加自定义流水线提供干净的起点。 + +## 步骤 2:将识别语言设置为德语 + +OCR 的准确性高度依赖语言。告知引擎预期为德语后,会激活正确的字符集和语言模型。 + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +如果跳过此步骤,引擎可能默认使用英语,导致误识别变音符(ä, ö, ü)和 ß 字符——这是处理德文扫描件时常见的陷阱。 + +## 步骤 3:构建自定义预处理流水线 + +这是 **how to preprocess images for OCR** 的核心。我们将串联四个转换: + +| 转换 | 作用 | 帮助原因 | +|------|------|----------| +| **Deskew** | 将图像旋转回水平(最大 5°) | 扫描很少完全对齐;去倾斜可消除导致字符分割混乱的倾斜。 | +| **Denoise** | 降低随机斑点(强度 0.7) | 噪声会产生错误的边缘,OCR 引擎可能将其误识为字符。 | +| **Binarize (Otsu)** | 使用 Otsu 方法转换为黑白二值图 | 干净的二值图为引擎提供前景(文本)与背景之间的鲜明对比。 | +| **Contrast Stretch** | 扩展动态范围 | 提高细弱笔画的可读性,尤其是旧文档。 | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### 如何对扫描文档去倾斜 + +`deskew` 调用即是对 **how to deskew scanned documents** 的具体实现。内部通过 Hough 变换估计主文本行角度并将图像旋转回正。如果文档旋转超过 5°,可以提升 `max_angle`,但要注意过度旋转产生的伪影。 + +### 使用 Otsu 进行图像二值化 + +`binarize(method="otsu")` 这一行直接回答了 **binarize image using otsu** 的查询。Otsu 算法计算出最小化类内方差的阈值,非常适合具有双峰直方图(深色文本与浅色背景)的文档。 + +## 步骤 4:将流水线附加到引擎 + +现在我们指示 OCR 引擎对每个输入图像运行我们刚构建的流水线。 + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Why this matters:* 若不注册,引擎将直接处理原始扫描,忽略我们配置的所有清理步骤。此步骤通过一致地应用相同的预处理,确保 **how to improve OCR accuracy**。 + +## 步骤 5:从嘈杂的德文扫描件识别文本 + +是时候把所有内容组合起来了。我们向引擎提供嘈杂的德文图像,让它完成繁重的工作。 + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +如果你对性能感兴趣,可以对调用进行计时: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## 步骤 6:输出识别的文本 + +最后,我们打印提取的字符串。这是对 **extract text from german image** 的直接回答。 + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### 预期输出 + +假设示例扫描包含句子 “Die schnelle braune Füchsin springt über den faulen Hund.”,你应看到类似如下的输出: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +如果输出仍包含乱码,请考虑调整 `denoise` 强度或增加 `max_angle` 以进行去倾斜。 + +## 常见陷阱及解决方法 + +- **缺少语言模型:** 忘记调用 `set_recognition_language(Language.GERMAN)` 常导致缺失变音符。请再次检查该调用。 +- **去噪过度:** 强度高于 0.9 可能抹去细小笔画,尤其是旧字体。大多数情况下保持在 0.5‑0.7。 +- **文件格式错误:** 某些 OCR 引擎无法处理多页 TIFF。如果有多页文档,请先拆分为单页文件。 +- **流水线顺序:** 所示顺序(deskew → denoise → binarize → contrast)是有意为之。先二值化再去噪会固化噪声;请始终先去噪。 + +## 扩展流水线(下一步?) + +既然已经有了坚实的基线,你可能想要: + +- **添加形态学开运算** 来清除细小斑点(`.morph_open(kernel=3)`)。 +- **集成语言模型** 进行后处理校正(`ocr_engine.apply_spellcheck()`)。 +- **使用 `concurrent.futures` 并行批处理** 大规模数据集。 + +所有这些都是自然的扩展,在保持 **how to preprocess images for OCR** 核心思想的同时,进一步提升 **how to improve OCR accuracy**。 + +## 结论 + +我们已经完整介绍了 **how to preprocess images for OCR** 的全过程:创建引擎、设置德语、构建包含 **binarize image using Otsu**、**how to deskew scanned documents** 的流水线,最终以更高的置信度 **extract text from german image**。遵循上述六个步骤,你会看到识别质量显著提升——不再需要无尽的手动校正。 + +使用自己的扫描件运行脚本,尝试不同参数,让结果说话。对某个特定的预处理调整有疑问?留下评论,我们一起深入探讨。 + +祝编码愉快,愿你的 OCR 永远精准! + +## 接下来你应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题。每个资源都包含完整的可运行代码示例和逐步解释,帮助你掌握更多 API 功能并在项目中探索替代实现方案。 + +- [使用 Aspose.OCR 进行语言选择的 C# 提取图像文本](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [如何在 OCR 图像识别中设置阈值](/ocr/english/net/ocr-settings/set-threshold-value/) +- [如何 OCR 图像 – 在 OCR 图像识别中对图像执行 OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..d97034651 --- /dev/null +++ b/ocr/chinese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python 对 PNG 图像进行 OCR —— 学习如何从图像中提取文本,运行 Python OCR 示例,甚至轻松读取古希腊文本。 +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: zh +og_description: 在Python中解释OCR PNG图像。本指南展示了如何从图像中提取文本,运行Python OCR示例,并轻松阅读古希腊语。 +og_title: Python 中的 PNG 图像 OCR – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python 中的 PNG 图像 OCR – 完整逐步指南 +url: /zh/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中 OCR PNG 图像 – 完整分步指南 + +有没有想过如何直接在 Python 脚本中 **OCR PNG image** 文件?也许你有一整文件夹的扫描古籍手稿,需要 **extract text from image** 文件而不必手动逐字输入。好消息是,你不需要计算机视觉博士学位——只需几行代码和合适的库,就能在几秒钟内读取古希腊文。 + +在本教程中,我们将演示一个 **python OCR example**,它能够识别 PNG 中的文字,将语言设置为希腊文多音调(Greek polytonic),并打印结果。完成后,你将掌握如何 **recognize image text**、处理常见坑点,并能够将脚本扩展到其他语言或图像格式。 + +## 你将学到 + +- 安装并配置 Python OCR 库(pytesseract + Tesseract OCR) +- 创建 OCR 引擎实例并加载 PNG 文件 +- 将识别语言设置为希腊文多音调,以便 **read ancient greek** +- 输出识别后的文本并排查常见问题 +- 将脚本扩展为批量处理多个 PNG,或切换到其他语言 + +### 前置条件 + +| 要求 | 为什么重要 | +|------|------------| +| Python 3.8+ | 支持现代语法和类型提示 | +| `pytesseract` 包 | Tesseract 引擎的轻量包装器 | +| Tesseract OCR 二进制文件(≥ 5.0) | 实际执行 OCR 任务的核心引擎 | +| 希腊语语言数据(`grc.traineddata`) | 正确 **read ancient greek** 所必需 | +| 需要分析的 PNG 图像(例如 `ancient_greek.png`) | 本教程 **ocr png image** 示例的目标文件 | + +你可以使用以下命令安装 Python 端: + +```bash +pip install pytesseract Pillow +``` + +在 Ubuntu/macOS 上则需要安装引擎本身: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +别忘了下载希腊文多音调训练数据: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(路径可能不同;如有需要请调整 `TESSDATA_PREFIX`。)* + +--- + +## OCR PNG Image:创建引擎实例 + +我们首先需要一个与 Tesseract 通信的对象。在 `pytesseract` 中,引擎通过模块级函数访问,但为了清晰起见,我们将其封装在一个小类中。这与原始代码片段中的 “engine” 概念相呼应。 + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**为什么要封装?** +- 保持公共 API 与你最初的代码片段一致,迁移无痛。 +- 以后可以在不改动主流程的情况下加入日志或错误处理。 +- 展示良好的面向对象实践——高级开发者会欣赏。 + +--- + +## 从图像中提取文本:设置语言为希腊文多音调 + +有了引擎后,需要告诉它期待的语言。希腊文多音调使用的变音符号不在标准 “greek” 数据中,因此我们将 Tesseract 指向 `grc` 训练文件。 + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +如果你想在其他语言的 **extract text from image** 文件中使用,只需将 `"grc"` 替换为 `"eng"`(英语)、`"fra"`(法语)等。只要已安装对应语言包,这行代码即可通用。 + +--- + +## 识别图像文字:对 PNG 运行 OCR + +语言设定好后,我们将 PNG 传入引擎。原示例使用硬编码路径,这里改用 `Path` 对象,使代码更灵活。 + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**技巧与边缘情况** + +- **文件未找到** – 用 `try/except FileNotFoundError` 包裹调用,给出友好提示。 +- **低分辨率 PNG** – 在 OCR 前使用 Pillow 进行预处理(如缩放、二值化)。 +- **非希腊文文本** – Tesseract 仍会尝试解码,但准确率会大幅下降。请务必匹配语言。 + +--- + +## 输出识别后的文本 + +最后,打印结果。在实际项目中,你可能会将结果写入数据库、CSV,或进一步送入翻译流水线。 + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +当你对一张清晰的古希腊铭文扫描图运行脚本时,应该会看到类似下面的输出: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +如果输出乱码,请再次确认 **greek.traineddata** 文件位于正确目录,并且 PNG 没有过度噪声。 + +--- + +## 完整可运行示例(一步到位的脚本) + +下面是完整的、可直接运行的程序。保存为 `ocr_greek.py` 并执行 `python ocr_greek.py`。 + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**预期输出**(为简洁起见已截断): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +如果看到正确的希腊字符,恭喜你——已经成功在 Python 中完成一次 **ocr png image** 操作! + +--- + +## 常见问题与专业技巧 + +### 如何提升噪声 PNG 的识别准确率? + +- 将图像转为灰度:`img = img.convert('L')` +- 应用二值阈值:`img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- 使用 `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` 放大 + +这些步骤常能把 **recognize image text** 的噩梦转变为干净的结果。 + +### 能否一次处理整个 PNG 文件夹? + +完全可以。把 `recognize_image` 调用放进 `for` 循环,遍历 `Path.glob("*.png")`。将每个结果存入字典或写入 CSV,便于后续分析。 + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### 如果只想提取数字怎么办? + +向 `image_to_string` 传入自定义 **config** 字符串: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +这样就能 **extract text from image** 包含表格、序列号或时间戳的文件,仅保留数字部分。 + +### 如何获取置信度分数? + +使用 `pytesseract.image_to_data`,它会返回包含每个单词置信度的 TSV。你可以在组装最终字符串前过滤低置信度的词。 + +--- + +## 扩展本教程 + +掌握基础后,你可以进一步探索以下相关主题: + +- **使用多进程进行批量 OCR** – 加速大规模 PNG 语料库。 +- **OCR + NLP 混合流水线** – 自动将提取的古希腊文翻译为现代英语。 +- **替代引擎** – 尝试 `easyocr` 或基于 `opencv` 的方法,针对特定场景。 +- **云端 OCR 服务** – Google Vision、Azure Computer Vision 或 AWS Textract,实现无服务器扩展。 + +这些内容都建立在我们刚刚讲解的 **python ocr example** 基础上,帮助你更深入地探索。 + +--- + +## 结论 + +我们把一个简单的代码片段升级为在 Python 中完整、稳健的 **ocr png image** 工作流。通过创建 `OcrEngine`、设置希腊文多音调、读取 PNG 并打印结果,你现在已经掌握了 **extract text from image**、**recognize image text**,甚至可以 **read ancient greek**。 + +## 接下来该学习什么? + +以下教程与本指南紧密相关,帮助你进一步深化所学技术。每篇资源都提供完整可运行的代码示例和逐步解释,助你在项目中灵活运用 API 并探索替代实现方案。 + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/chinese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..37631ee2e --- /dev/null +++ b/ocr/chinese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR 教程,展示如何识别图像文字、进行高分辨率 OCR,并使用 GPU 加速的 OCR 提取西班牙语文本。 +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: zh +og_description: Python OCR 教程,带您逐步实现图像文字识别、高分辨率 OCR,以及使用 GPU 加速提取西班牙语文本。 +og_title: Python OCR 教程 – GPU 加速文本识别 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR 教程——使用 GPU 加速识别图像文字 +url: /zh/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR 教程 – 使用 GPU 加速识别图像文字 + +有没有想过如何在 Python 脚本中 **recognize image text** 而不需要花费数小时调参?你并不是唯一的。 在本 **python ocr tutorial** 中,我们将展示一种简洁、端到端的方法,从高分辨率图片中提取西班牙语文本,并加入 GPU 加速,使过程极速运行。 + +把它当作一次快速的咖啡休息演示,之后你可以将其扩展为生产级流水线。阅读完本指南后,你将拥有一个可运行的程序,能够执行 **high resolution OCR**,利用 CUDA 支持的 GPU,并输出所需的西班牙语字符。 + +## 你将学到的内容 + +- 如何安装并导入支持 GPU 加速的现代 OCR 库。 +- 如何创建 OCR 引擎实例并将其设置为西班牙语的 **recognize image text**。 +- 如何启用 **gpu accelerated OCR**,在高分辨率文件上实现巨大的速度提升。 +- 如何处理诸如缺少 CUDA 驱动或回退到 CPU 等边缘情况。 +- 在需要从噪声扫描中 **extract spanish text** 时提升准确性的技巧。 + +### 前置条件 + +- Python 3.9+(代码同样适用于 3.10 及更高版本)。 +- 兼容 CUDA 的 GPU(可选,但强烈推荐)。 +- 熟悉 pip 和虚拟环境的基本使用。 + +如果缺少上述任意项,教程仍可运行——只需跳过 GPU 步骤,库会自动回退到 CPU。 + +## Python OCR 教程:安装所需软件包 + +首先,我们需要一个可靠的 OCR 引擎。 本教程将使用开源的 **`easyocr`** 包,当检测到兼容设备时,它自带 GPU 支持。 + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** 如果你已经安装了 PyTorch,请确保它的版本与 CUDA 版本匹配(`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`)。版本不匹配是导致 “GPU not found” 错误的常见原因。 + +## 步骤 1:创建 OCR 引擎实例 + +现在我们启动引擎。EasyOCR 的主类为 `Reader`。构造函数接受语言代码列表;我们将传入西班牙语的 `"es"`。 + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* 通过提前声明语言,引擎只加载必要的神经网络权重,从而节省内存并加快推理——在后续处理 **high resolution OCR** 时尤为有用。 + +## 步骤 2:准备高分辨率图像 + +高分辨率图像为模型提供更多像素,通常会转化为更好的字符识别。假设你有一个名为 `high_res_spanish.png` 的文件,位于名为 `samples` 的文件夹中。 + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +如果没有现成的高分辨率样本,你可以从 Unsplash 下载免费图片,或使用 Pillow 生成合成图像。关键是保持 DPI 在 300 以上,以获得最佳效果。 + +## 步骤 3:启用 GPU 加速(可选但推荐) + +当你将 `gpu=True` 时,EasyOCR 已经会尝试使用 GPU。不过,验证设备是否真正被使用是个好习惯,尤其在多 GPU 环境下。 + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* 如果脚本悄悄回退到 CPU,你可能会疑惑为何原本 5 秒的操作突然变成 30 秒。此小检查使行为透明,并保持你的 **gpu accelerated OCR** 流程可预测。 + +## 步骤 4:执行高分辨率 OCR 并识别图像文字 + +现在是有趣的部分——实际读取文字。EasyOCR 的 `readtext` 方法返回一个元组列表,包含边界框、识别的字符串以及置信度分数。 + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +如果需要不带坐标的原始字符串,请设置 `detail=0`。对于大多数 **recognize image text** 场景,默认 (`detail=1`) 已提供足够的上下文以便后续处理。 + +## 步骤 5:提取西班牙语文本并清理输出 + +因为我们请求 EasyOCR 使用西班牙语,返回的字符串已经是该语言。不过,你可能仍想将它们拼接、去除空白或过滤低置信度的检测结果。 + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** 你可以降低阈值(但可能会产生噪声),或对图像进行预处理(提升对比度、二值化或去倾斜)。在处理扫描文档的 **high resolution OCR** 时,这些技巧很常见。 + +## 步骤 6:处理边缘情况和性能调优 + +即使是最佳训练的模型也会在某些场景中出现问题。下面提供几个可直接粘贴到脚本中的快速修复方案。 + +### 6.1 当没有 GPU 时的回退方案 + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 对超大图像进行下采样 + +如果你的图像大于 4000 × 4000 像素,可能会耗尽 GPU 内存。请在保持 DPI 的前提下按比例下采样: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +这些代码片段使脚本更加稳健,无论你是在工作站还是普通笔记本上运行。 + +## 完整可运行示例 + +将所有内容整合在一起,下面是完整脚本,你可以直接复制粘贴并立即运行: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**预期输出(示例):** + + + +## 接下来你应该学习什么? + +以下教程涵盖与本指南紧密相关的主题,基于所示技术进行扩展。每个资源都提供完整的可运行代码示例和逐步解释,帮助你掌握更多 API 功能,并在自己的项目中探索替代实现方案。 + +- [使用 Aspose OCR 从图像提取文本 – 步骤指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [使用 Aspose.OCR 按语言 OCR 图像文字的方法](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [在 Aspose.OCR 中识别页面矩形以进行 OCR 文本识别的方法](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/chinese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..5336e906b --- /dev/null +++ b/ocr/chinese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python OCR 引擎识别图像中的文字。学习如何配置 OCR 引擎 Python,并在几分钟内通过云处理提取图像文字。 +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: zh +og_description: 使用 Python OCR 引擎识别图像中的文本。本指南展示如何配置 Python OCR 引擎并高效地从图像中提取文本。 +og_title: 使用 Python 识别图像中的文字 – 完整设置教程 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 在 Python 中识别图像文字 – 完整 OCR 引擎设置指南 +url: /zh/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中从图像识别文本 – 完整设置教程 + +有没有想过只用几行 Python 代码就能 **从图像识别文本**?你并不孤单。无论是构建收据扫描器、文档数字化工具,还是简单的业余项目,提取图像中的文本都是一项回报快速的技能。 + +在本教程中,我们将完整演示整个流程——从 **configure OCR engine python** 风格的设置开始,经过云端认证,最后展示如何 **extract text from image** 并获得可靠结果。没有魔法,只有可以直接复制粘贴并立即运行的清晰步骤。 + +## 你将学到的内容 + +- 如何安装并导入所需的 OCR 库。 +- 用于 **configure OCR engine python** 进行云端处理的精确命令。 +- 一个完整、可运行的脚本,能够 **recognize text from image** 并打印输出。 +- 处理常见坑点的技巧,如缺少 API 密钥或不支持的图像格式。 +- 进阶思路,例如批量处理和本地回退。 + +### 前置条件 + +- 已在机器上安装 Python 3.8+。 +- 有网络连接(示例使用基于云的 OCR 服务)。 +- 来自 OCR 提供商的有效 API 密钥(后文会说明如何填入)。 + +如果你满足以上条件,下面开始——不废话,只提供实用指南。 + +--- + +## 步骤 1:安装 OCR 库并导入 + +在能够 **configure OCR engine python** 之前,需要先安装与云服务通信的库。这里我们使用一个虚构但具代表性的包 `ocrcloud`,请替换为你实际使用的包(例如 `easyocr`、`google-cloud-vision` 等)。 + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**为什么重要:** 导入类后,你才能使用 `use_cloud()`、`set_api_key()` 等方法。若不导入,脚本其余部分会抛出 `NameError`。 + +*小技巧:* 在 `requirements.txt` 中固定版本(`ocrcloud==2.1.0`),以避免后期意外的破坏性更新。 + +--- + +## 步骤 2:创建并 **configure OCR engine python** 为云模式 + +现在真正 **configure OCR engine python**。引擎默认在本地模式下启动;切换到云模式后,你可以将繁重的图像分析任务交给强大的服务器。 + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**解释:** +- `OcrEngine()` 创建一个全新的引擎对象——相当于你的空白画布。 +- `use_cloud(True)` 打开开关,指示引擎通过 HTTPS 将图像发送到云端,而不是在本地处理。这对复杂字体或低分辨率照片的高准确率至关重要。 + +--- + +## 步骤 3:使用云 API 密钥进行身份验证 + +大多数云 OCR 服务都需要 API 密钥。此步骤展示如何安全地注入凭证。 + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**安全提示:** 切勿在公开仓库中硬编码密钥。生产环境下应从环境变量读取: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## 步骤 4:**recognize text from image** – 发送远程图像进行处理 + +引擎配置完成后,终于可以 **recognize text from image**。`recognize_image()` 方法接受本地路径或 URL,返回包含提取文本的对象。 + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**底层发生了什么?** +图像字节被上传至提供商的端点,由深度学习模型处理后,纯文本结果被流式返回。如果图像过大,服务可能会自动降采样以加快处理速度。 + +--- + +## 步骤 5:输出 **extract text from image** 结果 + +OCR 服务完成工作后,我们只需打印文本。实际项目中,你可能会将其存入数据库或传递给其他函数。 + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**预期输出:**(示例) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +如果输出乱码,请确认图像清晰且已选择正确的语言模型(许多服务允许通过 `engine.set_language("en")` 指定语言)。 + +--- + +## 处理边缘情况与常见坑点 + +### 1. 缺失或无效的 API 密钥 +出现认证错误时,请检查: +- 密钥是否仍然有效且未过期。 +- 是否正确从环境变量读取。 +- 网络是否允许出站 HTTPS 流量。 + +### 2. 不支持的图像格式 +大多数 OCR API 支持 JPEG、PNG 和 PDF。使用 BMP 或 TIFF 可能会返回 “format not supported”。必要时可使用 Pillow 转换: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. 速率限制 +云服务通常对每分钟请求数有限制。若触发限制,可实现指数退避: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. 本地 OCR 回退 +如果云服务不可用,可以切回本地模式: + +```python +engine.use_cloud(False) # revert to local mode +``` + +拥有回退机制可以提升应用的韧性。 + +--- + +## 完整可运行示例 + +将所有步骤整合在一起,下面的脚本可以直接运行(只需替换占位符值)。 + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**运行方式:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +运行后,你应该在控制台看到提取的文本,证明已经成功 **recognize text from image** 并 **extract text from image**,且工作流已正确 **configure OCR engine python**。 + +--- + +## 结论 + +我们已经完整演示了一个端到端的流程,让你在 Python 中 **recognize text from image**——从库的安装、云服务认证到最终 **extract text from image** 的单函数调用。通过正确 **configure OCR engine python**,你既能获得灵活的云/本地切换,又能确保可靠的错误处理。 + +接下来可以尝试批量处理收据文件、加入语言检测,或实验 PDF 输入。一旦掌握基础,可能性无限。 + +祝编码愉快,欢迎在评论区提问——一起学习最棒! + +## 接下来你应该学习什么? + +以下教程涵盖与本指南紧密相关的主题,帮助你在已有技术之上进一步扩展。每篇资源都提供完整可运行的代码示例和逐步解释,助你掌握更多 API 功能并探索替代实现方式。 + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8fe1cdbd6 --- /dev/null +++ b/ocr/chinese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,335 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python 对图像进行 OCR 并查看置信度分数。了解如何过滤低置信度词汇、设置阈值以及处理边缘情况。 +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: zh +og_description: 在 Python 中对图像进行 OCR,检查置信度水平,并过滤低置信度的词。本教程将带您完成一个完整的可运行示例。 +og_title: 使用 Python 对图像进行 OCR – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: 使用 Python 对图像进行 OCR——完整的逐步指南 +url: /zh/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Python 对图像进行 OCR – 完整分步指南 + +是否曾经需要 **run OCR on image** 文件,却不确定如何提取可靠的文本?你并不孤单——很多开发者在提取的文字模糊、置信度分数难以理解时都会卡住。 + +在本指南中,我们将直接展示可运行的解决方案:你将看到如何对图像进行 OCR、读取整体置信度,并挑选出可能需要人工复核的低置信度词。阅读完毕后,你将拥有可复用的脚本,了解每行代码的意义,并学会为自己的项目调整置信度阈值。 + +## 本教程涵盖内容 + +我们将完整演示工作流——从加载图像到打印出置信度低于 80 % 的词汇报告。过程中我们会讨论: + +* 选择可靠的 OCR 引擎(我们使用 **EasyOCR**,一款流行的 Python OCR 库) +* 解读每个 OCR 结果返回的 `confidence` 属性 +* 使用自定义 **OCR confidence threshold** 过滤词汇 +* 将脚本扩展为批处理或使用 **pytesseract** 等其他引擎 + +无需任何 OCR 经验,只需具备基本的 Python 知识并拥有可用的运行环境(推荐 Python 3.9+)。 + +准备好把模糊的截图转换为干净、可搜索的文本了吗?让我们开始吧。 + +--- + +## ## How to Run OCR on Image with Python + +本教程的核心是一段三步代码片段,与你之前看到的代码结构相同。下面我们将逐行拆解,解释原因,并提供完整的可直接复制运行的脚本。 + +### 步骤 1:安装并导入 OCR 引擎 + +首先,确保 OCR 库已安装。**EasyOCR** 开箱即用,支持多语言,并为每个词提供置信度分数。 + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*为什么选 EasyOCR?* 它内置了经过多样化数据集训练的深度学习模型,通常比旧的 Tesseract 引擎在混合质量图像上得到更高的置信度。 + +> **小技巧:** 如果你运行在资源受限的环境(例如极小的 Docker 容器),`pytesseract` 可能更轻量,但会失去 EasyOCR 所提供的现代化准确性。 + +### 步骤 2:对图像执行 OCR + +现在我们真正 **run OCR on image**。原示例中的 `recognize_image` 方法被 EasyOCR 的 `readtext` 调用取代,返回 `(bbox, text, confidence)` 元组的列表。 + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +`ocr_results` 中的每个条目形如: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +第三个元素(示例中的 `0.92`)即置信度分数,取值范围为 0 到 1。 + +### 步骤 3:汇总整体置信度 + +不同于之前只打印单个 `confidence` 属性的代码片段,EasyOCR 为每个词提供置信度。我们通过求平均值来获得整体感受: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*为什么取平均?* 这能快速检查整体健康度——如果整体置信度低于 70 %,通常需要改进图像(如提升光照、预处理等)。 + +### 步骤 4:列出低置信度词汇 + +下面的代码直接实现了“列出置信度低于设定阈值的词”的需求。默认将 **OCR confidence threshold** 设为 0.80(80 %),你可以自行调整。 + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +循环会打印每个未达标的词及其置信度百分比。这正是原始 `for recognized_word in recognition_result.words` 循环的等价实现,只是适配了 EasyOCR 的输出格式。 + +--- + +## ## Understanding OCR Confidence Scores + +置信度并非神秘数字;它是模型对特定转录结果的自信程度估计。需要注意的要点如下: + +| 场景 | 典型置信度 | 处理建议 | +|-----------|-------------------|------------| +| 清晰、高分辨率扫描 | 0.95 – 1.00 | 无需额外操作 | +| 略有模糊或光照不均 | 0.80 – 0.94 | 考虑轻度预处理(提升对比度) | +| 噪声严重、文字倾斜 | < 0.70 | 进行图像预处理(去倾斜、去噪)或切换 OCR 引擎 | + +> **注意:** 某些语言(例如手写体)天然会得到较低分数,请相应调低阈值。 + +### 边缘情况与变体 + +1. **批量处理** – 若需 **run OCR on image** 多个文件,可将上述逻辑包装在遍历目录的循环中。 +2. **多语言支持** – 向 `easyocr.Reader` 传入 `['en', 'fr']` 等列表,引擎即可同时识别多种语言。 +3. **替代引擎** – 想尝试 **pytesseract**?将读取块替换为: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + 此时需要将字符级置信度聚合为词级置信度——工作量稍大但可实现。 + +4. **预处理技巧** – 使用 OpenCV 滤波(`cv2.threshold`, `cv2.GaussianBlur`)可提升噪声图像的置信度。 + +--- + +## ## Full, Ready‑to‑Run Script + +下面是完整的 Python 文件,直接复制到项目中即可使用。保存为 `ocr_report.py` 并运行 `python ocr_report.py`。请确保图像路径指向真实文件。 + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**预期输出**(数值会因图像而异): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +如果所有词的置信度均超过 80 %,你将看到友好的 “All words meet the confidence threshold.” 提示。 + +--- + +## ## Frequently Asked Questions (FAQ) + +**Q: 是否支持 PDF?** +A: 不能直接处理。请先使用 `pdf2image` 等工具将每页 PDF 转为图像(PNG/JPEG),再交给本脚本。 + +**Q: 我的置信度全部很低,怎么办?** +A: 尝试图像预处理:提升对比度、去除背景噪声或将图像旋转至水平基线。EasyOCR 还提供 `contrast_ths` 参数可调。 + +**Q: 能导出结果为 CSV 吗?** +A: 完全可以。在低置信度循环后,使用 `csv.DictWriter` 将 `ocr_results` 写入 CSV,每行包含 `text`、`confidence` 与边界框坐标。 + +**Q: 有 GPU 加速版本吗?** +A: EasyOCR 会在检测到兼容的 GPU 与已安装的 PyTorch 时自动使用 CUDA。运行前可通过 `torch.cuda.is_available()` 验证。 + +--- + +## Conclusion + +我们已经使用 Python **run OCR on image**,检查了整体置信度,并筛选出需要人工复核的低置信度词汇。 + +## What Should You Learn Next? + +以下教程与本指南紧密相关,帮助你进一步掌握 API 功能并探索其他实现方式: + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/czech/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..c70080503 --- /dev/null +++ b/ocr/czech/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extrahujte text z obrázku pomocí Python OCR během několika minut. Objevte + vícejazyčný OCR obrázků, automatické rozpoznávání jazyka OCR a jak přesně extrahovat + OCR text. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: cs +og_description: Rychle extrahujte text z obrázku pomocí Python OCR. Naučte se vícejazyčný + OCR obrázků, automatické rozpoznávání jazyka a jak krok za krokem extrahovat OCR + text. +og_title: Extrahování textu z obrázku pomocí Python OCR – kompletní průvodce +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Extrahování textu z obrázku pomocí Python OCR – Kompletní průvodce +url: /cs/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahování textu z obrázku pomocí Python OCR – Kompletní průvodce + +Už jste někdy potřebovali **extrahovat text z obrázku**, ale nebyli jste si jisti, která knihovna dokáže automaticky zpracovat více jazyků? Nejste v tom sami — vývojáři se neustále ptají, *jak extrahovat OCR text*, když pracují s mezinárodními dokumenty, účtenkami nebo naskenovanými letáky. V tomto tutoriálu projdeme praktickým příkladem v Pythonu, který nejen extrahuje text z obrázku, ale také **detekuje jazyk** za běhu, což dělá vícejazyčný OCR obrázku hračkou. + +Probereme vše od instalace OCR balíčku po povolení **auto detect language OCR**, spuštění enginu na ukázkovém obrázku a nakonec výpis jak detekovaného jazyka, tak extrahovaného řetězce. Na konci budete mít znovupoužitelný úryvek, který můžete vložit do libovolného projektu, ať už budujete překladatelský pipeline nebo službu pro ingestování dat. + +## Extrahování textu z obrázku – Nastavení prostředí + +Než se ponoříme do kódu, ujistěte se, že vaše pracovní stanice splňuje následující minimální požadavky: + +- Python 3.8 nebo novější (knihovna používá typové nápovědy, které starší verze ignorují) +- `pip` pro správu balíčků +- Soubor s obrázkem, který obsahuje text alespoň ve dvou různých jazycích (např. angličtina + španělština) + +Budete také potřebovat OCR knihovnu, která pohání tuto ukázku. Pro potřeby tohoto průvodce použijeme fiktivní balíček `ocr`, který napodobuje populární reálné nástroje jako Tesseract nebo EasyOCR, ale nabízí čisté Python API. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** Pokud narazíte na chyby oprávnění, přidejte před příkaz `python -m` nebo použijte virtuální prostředí — udrží vaše globální site‑packages přehledné. + +## Vytvoření instance OCR enginu + +Nyní, když je knihovna připravena, je první logickým krokem **vytvořit instanci OCR enginu**. Představte si engine jako chytrý skener, který můžete nakonfigurovat před tím, než mu předáte obrázky. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Proč instanciujeme engine samostatně místo volání statické metody? Objekt engine uchovává konfigurační stav (např. preference jazyků), který můžete znovu použít napříč mnoha obrázky, čímž ušetříte režii opětovné inicializace při každém volání. + +## Povolení Auto Detect Language OCR + +Většina OCR nástrojů vyžaduje zadání kódu jazyka — `eng` pro angličtinu, `spa` pro španělštinu a tak dále. Ruční hádání jazyka ruší smysl **vícejazyčného OCR obrázku**. Naštěstí balíček `ocr` nabízí režim *auto detect language OCR*, který prozkoumá obrázek a za scénou vybere nejlepší jazykový model. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Povolením **detect language OCR** tímto způsobem nebudete muset udržovat dlouhý seznam jazykových kódů. Engine se pokusí přiřadit skript, který vidí — latinka, cyrilice, han a podobně — a automaticky načte odpovídající model. + +## Provedení vícejazyčného OCR obrázku + +S připraveným enginem je čas skutečně **extrahovat text z obrázku**. Metoda `recognize_image` přijímá cestu k souboru a vrací objekt výsledku obsahující jak surový text, tak jazyk, který byl detekován. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Jestli se ptáte, *jak extrahovat OCR text* z PDF místo PNG, stejný engine nabízí `recognize_pdf` — stačí zaměnit název metody. Základní logika detekce zůstává stejná, takže máte k dispozici stejnou **auto detect language OCR** funkci. + +## Zobrazení detekovaného jazyka a extrahovaného textu + +Nakonec vypíšeme, co engine objevil. Objekt výsledku poskytuje `detected_language` (BCP‑47 tag jako `en` nebo `es`) a `text`, který obsahuje surový OCR výstup. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Spuštěním skriptu na našem ukázkovém obrázku byste měli získat něco podobného: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Všimněte si, že engine správně identifikoval angličtinu jako primární jazyk, ale zároveň zachytil i španělskou větu — právě to, co očekáváte od robustního **vícejazyčného OCR obrázku**. + +### Co když detekce selže? + +Někdy může OCR engine přejít na výchozí jazyk (obvykle angličtinu), pokud je obrázek rozmazaný nebo je skript příliš exotický. V takových případech můžete vynutit seznam jazyků: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Ale pamatujte, že vynucení jazyků ruší pohodlí **auto detect language OCR**, takže jej používejte jen tehdy, když máte známou podmnožinu jazyků. + +## Časté úskalí a jak spolehlivě extrahovat OCR text + +I při automatické detekci se můžete setkat s několika problémy: + +1. **Nízké rozlišení obrázků** — přesnost OCR dramaticky klesá pod 150 dpi. Zvětšete rozlišení nebo požádejte o sken ve vyšší kvalitě. +2. **Šum a kompresní artefakty** — před předáním obrázku engine použijte jednoduchý prahový filtr (`opencv` nebo `Pillow`). +3. **Smíšené skripty na jedné stránce** — některé enginy mají problémy se současnou latinkou a CJK znaky. Rozdělte stránku na regiony a spusťte samostatné rozpoznání, pokud je to potřeba. + +Řešením těchto problémů výrazně zlepšíte kvalitu procesu **extrahování textu z obrázku**, zejména při práci s reálnými, vícejazyčnými dokumenty. + +## Kompletní funkční příklad + +Níže je kompletní, připravený ke spuštění skript, který kombinuje všechny kroky, o kterých jsme mluvili. Uložte jej jako `multilingual_ocr.py` a spusťte z příkazové řádky. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Očekávaný výstup** (při předpokladu, že ukázkový obrázek obsahuje anglický a španělský text): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Klidně zaměňte `multilang_page.png` za libovolný obrázek, který obsahuje text v jiných jazycích — díky **auto detect language OCR** skript stále poskytne smysluplný jazykový tag a odpovídající text. + +![Příklad extrahování textu z obrázku](https://example.com/ocr-sample.png "Extrahování textu z obrázku") + +## Závěr + +Nyní přesně víte, **jak extrahovat OCR text** z obrázku, jak povolit **auto detect language OCR** a jak zvládat **vícejazyčné OCR obrázku** scénáře s minimálním množstvím kódu. Vytvořením instance OCR enginu, zapnutím automatické detekce jazyka a voláním `recognize_image` můžete spolehlivě získat jak identifikátor jazyka, tak surový text. + +Co dál? Zkuste předávat extrahované řetězce do překladatelského API, uložit je do prohledávatelné databáze nebo spojit více stránek do jednoho PDF reportu. Můžete také experimentovat s různými OCR backendy (Tesseract, EasyOCR, Google Vision) při zachování stejného vysoké úrovně workflow — díky konzistentnímu **detect language OCR** rozhraní. + +Pokud narazíte na nějaké nesrovnalosti, vraťte se k sekci „Časté úskalí“ nebo upravte předzpracování obrázku. Šťastné kódování a ať je váš další projekt plný správně detekovaného a perfektně extrahovaného textu! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/czech/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..7a499d1fa --- /dev/null +++ b/ocr/czech/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extrahujte text z obrázků a PDF pomocí Python OCR. Naučte se, jak rychle + převést naskenované dokumenty na text pomocí asynchronního dávkového rozpoznávání. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: cs +og_description: Extrahujte text z obrázků a PDF pomocí Pythonu. Tento krok‑za‑krokem + průvodce ukazuje, jak převést naskenované dokumenty na text pomocí asynchronního + OCR. +og_title: Extrahovat text z obrázků PDF – Python OCR tutoriál +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Extrahovat text z PDF obrázků – Python průvodce pro převod naskenovaných dokumentů + na text +url: /cs/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahování textu z PDF obrázků – Python průvodce převodem naskenovaných dokumentů na text + +Už jste někdy potřebovali **extrahovat text z PDF obrázků** bez strávení hodin přepisováním? V tomto průvodci vám ukážeme, jak **převést naskenované dokumenty na text** pomocí jednoduchého asynchronního OCR workflow v Pythonu. + +Pokud jste někdy zírali na hromadu naskenovaných PDF a pomysleli si: „Musí existovat rychlejší způsob“, jste na správném místě. Projdeme každý řádek kódu, vysvětlíme, proč je každá část důležitá, a dokonce se podíváme na několik okrajových případů, na které můžete narazit. + +## Co se naučíte + +- Jak spustit OCR engine a nastavit jazyk rozpoznávání. +- Mechaniku předávání smíšeného seznamu PNG a PDF souborů do dávkového rozpoznávače. +- Spuštění OCR úlohy asynchronně, aby vaše aplikace zůstala responzivní. +- Získání výsledků, přiřazení k jejich zdrojovým souborům a výpis čistého výstupu. + +**Prerequisites**: Python 3.8+, základní pochopení `asyncio` nebo `concurrent.futures` a OCR knihovnu, která poskytuje třídu `OcrEngine` podobnou té v příkladu (např. Aspose.OCR, obal Tesseractu nebo vlastní obal). Žádné těžké nastavení není potřeba — stačí nainstalovat knihovnu a můžete začít. + +![extrahování textu z PDF obrázků](https://example.com/placeholder.png "Screenshot of OCR output – extract text from images pdf") + +## Extrahování textu z PDF obrázků – Nastavení OCR engine + +První věc, kterou potřebujete, je instance OCR engine nakonfigurovaná pro jazyk vašich dokumentů. V našem případě použijeme francouzštinu, ale můžete ji nahradit libovolným podporovaným jazykem. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Why this matters**: Nastavení jazyka předem dramaticky zvyšuje přesnost. Engine používá jazykově specifické slovníky a modely znaků; předání špatného jazyka je častým zdrojem zkresleného výstupu. + +## Připravte seznam souborů – Obrázky a PDF dohromady + +Náš dávkový rozpoznávač zvládne jak rastrové obrázky (`.png`, `.jpg`), tak PDF kontejnery. Stačí předat obyčejný Python seznam cest k souborům. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: Udržujte seznam plochý; engine interně rozbalí každou stránku PDF na obrázky před rozpoznáním. Pokud máte tisíce souborů, zvažte rozdělení seznamu na menší dávky, aby nedošlo k výkyvům paměti. + +## Spuštění asynchronního dávkového rozpoznávání + +Místo blokování hlavního vlákna spustíme OCR úlohu na pozadí. Metoda vrací `Future`, který nakonec bude obsahovat seznam objektů `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**How it works**: Pod kapotou engine spouští thread pool (nebo asynchronní úlohu, podle implementace). To vám umožní pokračovat v jiných činnostech — např. aktualizovat UI, načítat další soubory nebo logovat průběh — zatímco těžká práce probíhá jinde. + +## Dělejte něco užitečného, zatímco OCR běží + +Častá chyba je sedět nečinně a v těsném cyklu dotazovat `future`. Místo toho můžete provádět jakoukoli nesouvisející práci. Pro demonstraci jen vypíšeme stavovou řádku. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Shromážděte výsledky po dokončení Future + +Až budete připraveni získat OCR výstup, použijte `as_completed` z `concurrent.futures`. Tento vzor funguje, ať máte jeden nebo více future. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**What you’ll see**: Každá cesta k souboru následovaná extrahovanou čistou textovou reprezentací. Pro PDF, `result.text` obsahuje konkatenovaný text ze všech stránek. + +### Očekávaný výstup (příklad) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Pokud si všimnete chybějících znaků, dvakrát zkontrolujte, že nastavený jazyk odpovídá jazyku dokumentu, a zvažte předzpracování obrázků (odklon, zvýšení kontrastu) před předáním engine. + +## Řešení okrajových případů a běžných úskalí + +| Situace | Co dělat | +|-----------|------------| +| **Smíšené jazyky** | Nejprve proveďte detekci jazyka, poté vytvořte samostatné enginy pro každý jazyk. | +| **Obrovské PDF (> 100 MB)** | Rozdělte PDF na jednotlivé stránky na disku (např. pomocí `PyPDF2`) a zpracovávejte je jako samostatné položky. | +| **Neslatinské skripty** | Ujistěte se, že OCR knihovna obsahuje požadovaný jazykový balíček; některé knihovny vyžadují stažení dodatečných datových souborů. | +| **Úzké místo výkonu** | Zvyšte velikost thread poolu (`engine.set_thread_pool_size(8)`) nebo přejděte na GPU‑akcelerovaný backend, pokud je k dispozici. | +| **Chybějící text v nízkokvalitních obrázcích** | Předzpracujte pomocí OpenCV: `cv2.resize`, `cv2.threshold` a `cv2.medianBlur` pro zlepšení čitelnosti. | + +## Kompletní funkční příklad (připravený ke kopírování) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Uložte tento soubor jako `extract_text_async.py`, nahraďte `YOUR_DIRECTORY` cestou k vašim souborům, nainstalujte OCR balíček (`pip install your-ocr-lib`) a spusťte `python extract_text_async.py`. V konzoli by se měl objevit výstup ilustrovaný výše. + +## Další kroky – Přesah základního extrahování + +- **Post‑processing**: Odstraňte nadbytečné mezery, normalizujte Unicode (`unicodedata.normalize`) nebo spusťte kontrolu pravopisu pro vyčištění OCR šumu. +- **Strukturovaný výstup**: Exportujte výsledky do CSV, JSON nebo přímo do databáze pro následné vyhledávání. +- **Paralelní dávky**: Pokud máte stovky souborů, spusťte více future a použijte frontu, aby CPU byla vytížená, aniž byste přetížili paměť. +- **Integrace s webovými frameworky**: Napojte tento skript na Flask nebo FastAPI endpoint a poskytujte OCR jako službu na vyžádání. + +--- + +### TL;DR + +Nyní víte, jak **extrahovat text z PDF obrázků** pomocí minimálního Python skriptu, který spouští OCR asynchronně, což vám umožní **převést naskenované dokumenty na text**, zatímco váš program zůstává responzivní. Pohrávejte si s nastavením jazyka, velikostí dávek a předzpracovacími triky, abyste získali co nejvyšší přesnost. + +Máte nějaký tip, který byste chtěli sdílet — třeba OCR na ručně psané poznámky nebo cloudovou službu? Zanechte komentář a šťastné kódování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s krok‑za‑krokem vysvětleními, aby vám pomohly zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Extrahování textu z obrázku pomocí Aspose OCR – krok za krokem průvodce](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrahování textu z obrázků pomocí OCR operace ve složkách](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extrahování textu z obrázků pomocí Aspose.OCR – povolené znaky](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/czech/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..747b080c6 --- /dev/null +++ b/ocr/czech/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Jak pomocí Pythonu provést OCR PDF, extrahovat text z PDF, převést text + naskenovaného PDF a změnit jazyk OCR během několika řádků kódu. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: cs +og_description: 'Jak provést OCR PDF pomocí Pythonu: praktický průvodce, který vám + ukáže, jak extrahovat text z PDF, převést text naskenovaného PDF a snadno změnit + jazyk OCR.' +og_title: Jak provést OCR PDF v Pythonu – Kompletní programovací tutoriál +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Jak provést OCR PDF v Pythonu – Kompletní krok za krokem průvodce +url: /cs/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak provést OCR PDF v Pythonu – Kompletní krok‑za‑krokem průvodce + +Už jste se někdy zamýšleli, **jak provést OCR PDF** soubory, aniž byste museli platit za drahé SaaS nástroje? Nejste v tom sami. Ať už digitalizujete staré knihy, získáváte data z faktur, nebo jen potřebujete prohledávat text ze skenovaného výkazu, zvládnutí OCR PDF v Pythonu vám může ušetřit hodiny ručního přepisování. + +V tomto tutoriálu projdeme stručný, funkční příklad, který **extrahuje text z PDF**, ukáže vám, jak **převést text skenovaného PDF** na editovatelné řetězce, a dokonce demonstruje, jak **změnit jazyk OCR**, pokud váš dokument není v angličtině. Na konci budete mít znovupoužitelný úryvek, který můžete vložit do libovolného projektu. + +## Požadavky a nastavení + +Než se pustíme do kódu, ujistěte se, že máte: + +- Python 3.8+ nainstalovaný (kód funguje na 3.9, 3.10 a novějších) +- Balíček `ocr`, který poskytuje třídu `OcrEngine` (nainstalujete ho pomocí `pip install ocr-lib` – nahraďte skutečným názvem balíčku, který používáte) +- PDF soubor, který chcete zpracovat; pro ukázku použijeme `high_res_book.pdf` umístěný ve složce `YOUR_DIRECTORY` + +Pokud používáte virtuální prostředí (vřele doporučeno), aktivujte ho nejprve: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Tip:** Ukládejte své PDF soubory do vyhrazené složky `data/`, abyste se později vyhnuli problémům s cestami. + +## Krok 1: Vytvoření instance OCR enginu (Jak provést OCR PDF – inicializace) + +První věc, kterou musíte udělat, když chcete **provést OCR na PDF** souborech, je vytvořit instanci enginu. Přemýšlejte o enginu jako o mozku, který přečte každou stránku, interpretuje glyfy a vrátí vám čistý text. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Proč je to důležité: bez enginu nemáte žádný kontext pro nastavení jazyka, možnosti renderování ani zpracování PDF. Objekt `OcrEngine` obsahuje všechna výchozí nastavení a umožňuje je později upravit. + +## Krok 2: Nastavení rozpoznávacího jazyka (Změna jazyka OCR) + +Většina OCR knihoven má jako výchozí jazyk angličtinu, ale co když je váš dokument ve francouzštině, němčině nebo dokonce v japonštině? Změna jazyka je tak jednoduchá jako zavolat `set_recognition_language`. Tím splníte požadavek **změnit jazyk OCR** a zajistíte vyšší přesnost. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Proč to můžete potřebovat:** Vícejazyčný archiv často obsahuje stránky v různých jazycích. Přepínání jazyků za běhu zabraňuje nesprávnému rozpoznání znaků jako “ß” nebo “ñ”. + +## Krok 3: Konfigurace možností renderování PDF (Efektivní převod skenovaného PDF na text) + +Při práci se skenovanými PDF má rozlišení a barevný režim zásadní vliv na kvalitu OCR. Renderování při 300 DPI v odstínech šedi je optimální pro většinu dokumentů – dostatečně detailní, ale zároveň šetří paměť. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Řetězené volání může vypadat sofistikovaně, ale jde jen o fluent API, které pokaždé vrací stejný objekt možností. Pokud potřebujete barvu (např. pro barevné diagramy), nahraďte `"grayscale"` za `"color"`. + +## Krok 4: Rozpoznání PDF a získání textu z první stránky (Extrahování textu z PDF) + +Nyní přichází jádro **jak provést OCR PDF**: předáte enginu cestu k souboru a získáte rozpoznaný text. Metoda vrací seznam výsledků po stránkách; každý výsledek obsahuje atribut `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Pokud potřebujete celý dokument, projděte `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Co když je PDF šifrované? + +Některá PDF jsou chráněna heslem. V takovém případě můžete heslo předat metodě `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Engine dešifruje za běhu před provedením OCR – žádné další kroky nejsou potřeba. + +## Krok 5: Post‑zpracování extrahovaného textu (Doladění extrahovaného textu z PDF) + +Surový výstup OCR často obsahuje zalomení řádků, nadbytečné mezery nebo občas špatně rozpoznané znaky. Rychlá čistící rutina připraví extrahovaný řetězec na další zpracování (indexování, ukládání do databáze atd.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Nyní můžete bezpečně **extrahovat text z PDF** a předat ho libovolnému NLP pipeline, vyhledávači nebo jednoduché operaci `open(...).write()`. + +## Bonus: Dávkové zpracování více PDF (Škálování OCR na PDF) + +Pokud máte složku plnou skenovaných PDF, zabalte logiku do smyčky: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Tento úryvek ukazuje, jak **provést OCR na PDF** souborech hromadně, což je častá potřeba u digitalizačních projektů. + +## Očekávaný výstup + +Spuštění jednostránkového příkladu (Krok 4) by mělo vypsat něco jako: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Pokud jste zpracovali více‑stránkovou knihu, konzole zobrazí vyčištěný text každé stránky a dávkový skript vytvoří soubor `.txt` vedle každého PDF. + +## Časté problémy a jak se jim vyhnout + +| Problém | Příznaky | Řešení | +|---------|----------|--------| +| PDF s nízkým rozlišením | Zkreslené znaky, chybějící slova | Zvyšte DPI (`set_dpi(400)` nebo vyšší) | +| Špatně nastavený jazyk | Mnoho neznámých symbolů, zejména s diakritikou | Použijte `engine.set_recognition_language(ocr.Language.FRENCH)` nebo příslušný enum | +| Velké PDF způsobuje chybu paměti | `MemoryError` nebo pád po několika stránkách | Zpracovávejte stránky po částech (`engine.recognize_pdf(..., max_pages=10)`) | +| Chybějící fonty v PDF | Prázdný výstup u některých stránek | Ujistěte se, že PDF skutečně obsahuje rastrové obrázky; některá PDF jsou jen vektorová a vyžadují jiný přístup | + +## Ilustrace + +Níže je rychlá vizualizace pracovního postupu. Alt text je úmyslně SEO‑přátelský. + +![diagram pracovního postupu OCR PDF ukazující inicializaci enginu, nastavení jazyka, možnosti renderování, rozpoznání a extrakci textu](/images/ocr-workflow.png) + +*Diagram není nutný pro spuštění kódu, ale pomáhá vizuálním typům pochopit, kde se který krok nachází.* + +## Závěr + +Probrali jsme **jak provést OCR PDF** soubory v Pythonu od začátku do konce: vytvoření OCR enginu, **změnu jazyka OCR**, nastavení renderování pro **převod skenovaného PDF na text** a nakonec **extrahování textu z PDF** pro další využití. Kompletní, spustitelný příklad je připraven k vložení do libovolného projektu a volitelný dávkový skript ukazuje, jak řešení škálovat. + +Dále můžete zkusit: + +- Přidat **provádění OCR na PDF** pro vícejazyčné archivy pomocí smyčky přes seznam jazyků. +- Integrovat extrahovaný text s Elasticsearch pro full‑textové vyhledávání. +- Použít OCR k vytvoření prohledávatelných PDF tím, že vložíte textovou vrstvu zpět do původního souboru (mnoho knihoven nabízí metodu `save_as_searchable_pdf`). + +Nebojte se experimentovat, ladit nastavení DPI nebo přejít na jiný OCR backend. Základy zůstávají stejné a nyní máte solidní základ, na kterém můžete stavět. + +Šťastné kódování a ať se vaše skenované dokumenty konečně stanou prohledávatelnými! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční kódové příklady s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vlastních projektech. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/czech/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..4dcab4176 --- /dev/null +++ b/ocr/czech/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-06 +description: Jak provést OCR PDF a vytvořit prohledávatelné PDF soubory z obrázků + pomocí Pythonu. Naučte se přidat prohledávatelný text a převést obrázek na PDF/A + během několika minut. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: cs +og_description: Jak provádět OCR PDF krok za krokem. Naučte se přidat prohledávatelný + text a převést obrázek na PDF/A pomocí jednoduchého Python skriptu. +og_title: Jak OCR PDF – rychlý průvodce tvorbou prohledávatelných PDF +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Jak provést OCR PDF v Pythonu – Vytvořit prohledávatelný PDF z obrázků +url: /cs/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak OCR PDF – Převést naskenované obrázky na prohledávatelné PDF + +Už jste se někdy zamysleli, **jak OCR PDF** soubory, když máte jen naskenovaný obrázek faktury nebo účtenky? Nejste v tom sami. V mnoha kancelářích přicházejí papírové dokumenty jako ploché PNG nebo JPEG a další krok – učinit obsah prohledávatelným – se zdá jako černá skříňka. + +Dobrá zpráva? Pouhých několik řádků Pythonu vám umožní **vytvořit prohledávatelné PDF** soubory, **přidat prohledávatelný text**, a dokonce **převést obrázek na PDF/A** pro dlouhodobé archivování. V tomto tutoriálu projdeme každý krok, vysvětlíme, proč je důležitý, a poskytneme vám připravený skript, který můžete vložit do jakéhokoli projektu. + +> **Pro tip:** Stejný přístup funguje pro vícestránkové skeny; stačí projít soubory ve smyčce a engine udělá těžkou práci. + +--- + +## Co budete potřebovat + +Než se pustíme dál, ujistěte se, že máte na svém počítači následující: + +| Požadavek | Proč je důležité | +|-------------|----------------| +| Python 3.9 nebo novější | Moderní syntaxe a lepší podpora knihoven | +| `pdfium`‑based OCR engine (např. `pdfocr` nebo komerční SDK) | Zvládá jak rozpoznávání obrazu, tak generování PDF/A | +| Obrázkový soubor (PNG, JPEG, TIFF), který chcete převést na prohledávatelné PDF | Zdroj textu | +| Zápisové oprávnění do výstupní složky | Aby skript mohl uložit nové PDF | + +Pokud jste ještě nenainstalovali OCR SDK, spusťte: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +A to je vše – žádné složité systémové závislosti, jen pip install. + +--- + +## Jak OCR PDF – Přehled + +Na vysoké úrovni proces sestává ze tří jednoduchých akcí: + +1. **Recognize** text uvnitř obrázku při zachování původní grafiky. +2. **Export** OCR výsledek spolu s původním obrázkem jako **searchable PDF/A** (archivně přátelský typ PDF). +3. **Validate** že výsledný soubor obsahuje výběrový, prohledávatelný text vrstvený nad původním obrázkem. + +Níže uvidíte každý krok v kódu, s vysvětlením *proč* za jednotlivými příkazy. + +## Krok 1: Rozpoznat text z obrázku + +Nejprve požádáme OCR engine, aby přečetl pixely a vrátil objekt výsledku, který obsahuje jak surový obrázek, tak extrahovaný text. Představte si to jako engine, který „čte“ fakturu za vás. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Proč je to důležité + +- **Preserving graphics** znamená, že vizuální rozvržení (tabulky, loga, razítka) zůstane přesně tak, jak jej zachytil skener. +- Objekt `result` obvykle obsahuje skrytou textovou vrstvu, kterou později vložíme do PDF. +- Použití `recognize_image` místo `recognize_pdf` eliminuje další krok konverze, což urychluje zpracování pro jednostránkové obrázky. + +#### Běžné varianty + +- Pokud máte **vícestránkový TIFF**, předávejte přímo cestu k souboru; většina engineů bude každou stránku považovat za samostatný obrázek. +- Pro PDF, které již obsahují obrázky, můžete zavolat `engine.recognize_pdf("file.pdf")` a tento krok úplně přeskočit. + +## Krok 2: Exportovat OCR výsledek jako prohledávatelné PDF/A + +Nyní vezmeme `result` z kroku 1 a řekneme engine, aby zapsal nový soubor. Klíčovým příznakem zde je *PDF/A* – verze PDF podle normy ISO určená pro dlouhodobé uchování. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Proč je to důležité + +- **Searchable PDF**: Výstupní soubor obsahuje skrytou, výběrovou textovou vrstvu. Nyní můžete v dokumentu použít Ctrl + F. +- **PDF/A compliance**: Některé organizace (právní, finanční) vyžadují PDF/A pro auditní stopy; tento krok automaticky splňuje toto pravidlo. +- Metoda také **přidává prohledávatelný text** bez zploštění obrázku, takže vizuální věrnost zůstává dokonalá. + +#### Okrajový případ: Potřebujete běžné PDF místo toho? + +Pokud vám PDF/A nevadí, nahraďte `save_as_pdfa` za `save_as_pdf`. Zbytek pracovního postupu zůstane stejný. + +## Krok 3: Ověřit prohledávatelné PDF + +Rychlá kontrola vám ušetří pozdější záhadné chyby. Otevřete vygenerovaný soubor v libovolném PDF prohlížeči, zkuste vybrat slovo a použijte funkci hledání. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Očekávaný výstup + +Po spuštění skriptu konzole vypíše: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Po otevření souboru byste měli vidět původní obrázek faktury s jemnou, neviditelnou textovou vrstvou. Zvýrazněte libovolné slovo a uvidíte, že je výběrové – **to je prohledávatelný text**, který jste právě přidali. + +## Přidání prohledávatelného textu do existujících PDF (Bonus) + +Někdy již máte PDF, ale potřebujete do něj **přidat prohledávatelný text**. Ten samý engine může překrýt OCR výsledky na existující PDF: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Zde `apply_to` sloučí skrytou vrstvu s původními stránkami, což vám umožní **vytvořit prohledávatelné PDF** bez opětovného skenování. + +## Běžné úskalí a tipy + +| Úskalí | Jak se mu vyhnout | +|---------|-----------------| +| **Nízké rozlišení zdrojových obrázků** (< 150 dpi) | Zvětšete nebo požádejte o sken s vyšším rozlišením; přesnost OCR dramaticky klesá pod 150 dpi. | +| **Chybějící jazyková data** | Nainstalujte příslušné jazykové balíčky pro váš OCR engine (`pip install pdfocr[eng,spa]`). | +| **Výstupní složka není zapisovatelná** | Spusťte skript s dostatečnými oprávněními nebo vyberte jiný adresář. | +| **Selhání validace PDF/A** | Ujistěte se, že nevkládáte nepodporované fonty nebo JavaScript; většina SDK automaticky tuto situaci řeší při použití `save_as_pdfa`. | + +## Kompletní skript – Jednosouborové řešení + +Níže je samostatný skript, který spojuje vše dohromady. Zkopírujte a vložte jej, nahraďte zástupné cesty a budete připraveni **převést obrázek na PDF/A** během několika sekund. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Co tento skript dělá:** +1. Načte OCR engine. +2. Načte vybraný obrázek a extrahuje text. +3. Zapíše **prohledávatelné PDF/A**, které můžete okamžitě distribuovat nebo archivovat. + +Neváhejte zabalit logiku `main` do funkce, která zpracuje celý adresář – stačí iterovat přes `os.listdir()` a opakovat tři kroky pro každý soubor. + +## Další kroky a související témata + +Nyní, když ovládáte **jak OCR PDF**, zvažte následující nápady: + +- **Dávkové zpracování:** Použijte `concurrent.futures` k OCR desítek faktur paralelně. +- **Vkládání metadat:** Přidejte data vytvoření nebo čísla faktur do metadat PDF pro snazší indexaci. +- **Hybridní PDF:** Kombinujte prohledávatelný text s vloženými originálními obrázky pro „digitální dvojče“ papírového dokumentu. +- **Alternativní výstupy:** Exportujte do **DOCX** nebo **HTML**, pokud downstream systémy potřebují editovatelné formáty. + +Každý z nich staví na základních konceptech, které jste se právě naučili – rozpoznat, exportovat, ověřit. + +## Shrnutí + +Stručně řečeno, nyní víte **jak OCR PDF** soubory tím, že jednoduchý obrázek převedete na **prohledávatelné PDF/A** pomocí pouhých tří řádků Pythonu. Skript provádí těžkou práci, zachovává původní grafiku a poskytuje vám dokument splňující standardy, který můžete prohledávat, archivovat nebo sdílet. + +Vyzkoušejte to na vlastních fakturách, účtenkách nebo naskenovaných smlouvách. Pokud narazíte na problémy, zanechte komentář níže nebo si prohlédněte oficiální dokumentaci SDK – obvykle obsahuje spoustu dalších příkladů. Šťastné programování a užívejte si nově získanou schopnost učinit jakýkoli obrázek okamžitě prohledávatelným! + +![Příklad OCR PDF ukazující původní obrázek a překrytí prohledávatelným PDF](placeholder.png "How to OCR PDF example") + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak OCR PDF v .NET s Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Rozpoznat text PDF – OCR operace s Aspose.OCR pro Java](/ocr/english/java/ocr-operations/) +- [Převod obrázků na PDF C# – Uložit vícestránkový OCR výsledek](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/czech/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..a6739c2da --- /dev/null +++ b/ocr/czech/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Jak provést OCR PDF pomocí Aspose OCR Cloud. Naučte se extrahovat text + z PDF, převést stránku PDF na PNG a uložit obrázky stránek PDF v Pythonu. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: cs +og_description: Jak provést OCR PDF pomocí Aspose OCR Cloud. Tento průvodce ukazuje, + jak extrahovat prostý text z PDF, převést stránku PDF na PNG a uložit obrázky stránek + PDF. +og_title: Jak provést OCR PDF pomocí Aspose OCR Cloud – krok za krokem +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Jak provést OCR PDF pomocí Aspose OCR Cloud – Kompletní průvodce +url: /cs/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak provést OCR PDF pomocí Aspose OCR Cloud – Kompletní průvodce + +Už jste se někdy ptali, **jak provést OCR PDF** soubory bez boje s těžkými desktopovými nástroji? Nejste sami – mnoho vývojářů narazí na tuto překážku, když potřebují rychlý, programový způsob, jak získat text ze skenovaných dokumentů. Dobrá zpráva? S Aspose OCR Cloud můžete **extrahovat text z PDF**, převést každou stránku na PNG a dokonce **uložit obrázky stránek PDF** pro pozdější použití, vše z přehledného Python skriptu. + +V tomto tutoriálu projdeme vše, co potřebujete vědět: od instalace SDK, licencování enginu a rozpoznávání vícestránkových PDF, po extrahování prostého textu, převod stránek na PNG a ukládání těchto obrázků na disk. Na konci budete mít znovupoužitelný úryvek, který můžete vložit do jakéhokoli projektu, který potřebuje funkce **jak provést OCR PDF**. + +## Co budete potřebovat + +- **Python 3.8+** (kód funguje také na 3.10 a novějších) +- Účet Aspose OCR Cloud – získáte soubor s licencí pro zkušební verzi (`Aspose.OCR.lic`) +- Balíček `asposeocrcloud` (`pip install asposeocrcloud`) +- Naskenovaný, vícestránkový PDF, který chcete zpracovat + +To je vše. Žádné další binární soubory, žádné nativní závislosti, jen čistý Python. + +## Jak provést OCR PDF – Nastavení a licence + +Než můžete volat jakékoli OCR metody, musíte SDK říct, kdo jste. Aspose používá lehký licenční soubor, který umístíte na místo přístupné vašemu skriptu. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Tip:* Pokud krok s licencí přeskočíte, SDK bude i nadále fungovat, ale do výstupních obrázků vloží malou vodoznak. Není to ideální pro produkci. + +## Krok 2: Instalace Aspose OCR Cloud Python SDK + +Otevřete terminál a spusťte: + +```bash +pip install asposeocrcloud +``` + +Balíček stáhne všechny potřebné závislosti (requests, pillow, atd.), takže nemusíte hledat nic dalšího. + +## Krok 3: Vytvoření OCR enginu a výběr jazyka + +Engine je srdcem operace. Můžete specifikovat libovolný jazyk podporovaný Aspose; angličtina funguje ve většině případů. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Proč nastavit jazyk? Protože OCR engine používá jazykově specifické slovníky ke zlepšení přesnosti. Pokud zpracováváte francouzské PDF, stačí vyměnit `ENGLISH` za `FRENCH`. + +## Krok 4: Odkaz na váš vícestránkový PDF + +Poskytněte engine úplnou cestu k souboru, který chcete zpracovat. Relativní cesty jsou v pořádku, pokud jsou vyhodnoceny z pracovního adresáře skriptu. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Ujistěte se, že soubor je čitelný; jinak uvidíte `FileNotFoundError`. + +## Krok 5: Spuštění OCR – Získáte seznam výsledků + +Volání `recognize_pdf` vrací seznam, kde každý prvek odpovídá jedné stránce zdrojového PDF. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Každý `OcrResult` obsahuje dvě užitečné vlastnosti: + +* `text` – prostý textový výstup stránky (skvělé pro **extrahovat prostý text pdf**) +* `image` – objekt Pillow `Image` vykreslené stránky (ideální pro **převést pdf stránku png**) + +## Krok 6: Extrahování textu z PDF a převod stránek na PNG + +Nyní projdeme výsledky, vytiskneme extrahovaný text a uložíme PNG verzi každé stránky. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Očekávaný výstup v konzoli + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Také najdete `page_1.png`, `page_2.png`, … v adresáři `YOUR_DIRECTORY`. Jedná se o rasterizované obrázky stránek, které můžete použít v následných pipelinech pro zpracování obrazu. + +## Krok 7: Uložení obrázků stránek PDF (volitelné zpracování po dokončení) + +Pokud potřebujete jen obrázky a ne text, můžete přeskočit řádek `print(res.text)`. Naopak, pokud chcete uložit text do samostatných souborů `.txt`, stačí přidat malý zápis: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Toto malé doplnění ukazuje, jak snadné je **uložit obrázky stránek PDF** a zároveň zachovat extrahovaný obsah. + +## Kompletní funkční příklad + +Spojením všeho dohromady, zde je kompletní skript, který můžete zkopírovat a vložit do `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Spusťte jej pomocí: + +```bash +python ocr_pdf.py +``` + +Měli byste vidět výpis v konzoli textu každé stránky a sérii PNG souborů + + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak provést OCR PDF v .NET s Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Rozpoznat text PDF – OCR operace s Aspose.OCR pro Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Převést obrázky na PDF C# – Uložit vícestránkový OCR výsledek](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/czech/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..e7596658e --- /dev/null +++ b/ocr/czech/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-06-06 +description: Jak předzpracovat obrázky pro OCR pomocí Pythonu. Naučte se binarizovat + obrázek pomocí Otsu, jak vyrovnat skenované dokumenty a zlepšit přesnost OCR pro + německý text. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: cs +og_description: Jak předzpracovat obrázky pro OCR v Pythonu. Tento tutoriál ukazuje, + jak binarizovat obrázek pomocí Otsu, jak vyrovnat skenované dokumenty a jak zlepšit + přesnost OCR pro německé obrázky. +og_title: Jak předzpracovat obrázky pro OCR – Kompletní průvodce v Pythonu +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Jak předzpracovat obrázky pro OCR – Kompletní průvodce v Pythonu +url: /cs/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak předzpracovat obrázky pro OCR – Kompletní průvodce v Pythonu + +Už jste se někdy zamýšleli **jak předzpracovat obrázky pro OCR**, aby text byl naprosto čitelný? Nejste jediní. Naskenované dokumenty — zejména špinavé německé stránky — mohou být noční můrou pro jakýkoli OCR engine. Dobrá zpráva? Několik chytrých kroků předzpracování může proměnit rozmazaný, posetý šmouhami sken na čistý, strojově čitelný obrázek. + +V tomto tutoriálu projdeme praktickým příkladem, který ukazuje **jak předzpracovat obrázky pro OCR** pomocí Pythonu. Naučíte se **binarizovat obrázek pomocí Otsu**, **jak narovnat (deskew) naskenované dokumenty** a celkově **jak zlepšit přesnost OCR**, když potřebujete **extrahovat text z německých obrázkových** souborů. Žádné zbytečnosti, jen funkční skript, který můžete dnes zkopírovat‑vložit. + +## Co budete potřebovat + +- **Python 3.9+** (jakákoli recentní verze) +- OCR knihovnu, která poskytuje třídu `OcrEngine` — pro ukázku předpokládáme obecný balíček `ocr`. Nainstalujte jej pomocí `pip install ocr-lib`. +- Špinavý německý sken (`noisy_german_scan.tif`), který chcete otestovat. +- Základní povědomí o Python funkcích (pokud už jste někdy použili `def`, jste v pohodě). + +> **Pro tip:** Pokud používáte jiný OCR SDK (např. Tesseract přes `pytesseract`), koncepty zůstávají stejné — stačí přizpůsobit názvy metod. + +## Přehled řešení + +1. **Vytvořit instanci OCR engine.** +2. **Nastavit jazyk rozpoznávání na němčinu.** +3. **Sestavit vlastní pipeline předzpracování**, která zahrnuje narovnání, odšumění, binarizaci (Otsu) a roztažení kontrastu. +4. **Připojit pipeline k enginu**, aby každá obrázek prošel automaticky. +5. **Spustit OCR** na špinavém německém skenu. +6. **Vytisknout extrahovaný text** pro ověření výsledku. + +Níže rozebíráme každý krok, vysvětlujeme **proč** je důležitý a ukazujeme přesný kód, který potřebujete. + +![how to preprocess images for OCR example](image.png "how to preprocess images for OCR example") + +## Krok 1: Vytvořit instanci OCR Engine + +Nejprve – bez engine se nic neděje. Objekt `OcrEngine` je vstupní bod, který koordinuje veškeré následné zpracování. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Proč je to důležité:* Inicializace engine nastaví interní zdroje (např. jazykové modely) a poskytne čistý základ, na který můžete později připojit vlastní pipeline. + +## Krok 2: Nastavit jazyk rozpoznávání na němčinu + +Přesnost OCR je silně závislá na jazyku. Když engine řeknete, že má očekávat němčinu, aktivujete správnou znakovou sadu a jazykový model. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Pokud tento krok přeskočíte, engine může výchozí nastavit angličtinu a špatně rozpoznávat umlauty (ä, ö, ü) a znak ß — časté úskalí při práci s německými skeny. + +## Krok 3: Sestavit vlastní pipeline předzpracování + +Toto je jádro **jak předzpracovat obrázky pro OCR**. Propojíme čtyři transformace: + +| Transformace | Co dělá | Proč pomáhá | +|--------------|---------|-------------| +| **Deskew** | Otáčí obrázek zpět do horizontální polohy (max 5°) | Skeny nejsou často dokonale zarovnané; narovnání odstraňuje sklon, který matí segmentaci znaků. | +| **Denoise** | Snižuje náhodné šmouhy (síla 0.7) | Šum vytváří falešné hrany, které OCR může zaměnit za znaky. | +| **Binarize (Otsu)** | Převádí na černobílý obraz pomocí Otsu metody | Čistý binární obrázek poskytuje ostrý kontrast mezi popředím (text) a pozadím. | +| **Contrast Stretch** | Rozšiřuje dynamický rozsah | Zlepšuje čitelnost slabých tahů, zejména u starých dokumentů. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Jak narovnat (Deskew) naskenované dokumenty + +Volání `deskew` výše je konkrétní odpovědí na **jak narovnat naskenované dokumenty**. Interně odhaduje dominantní úhel řádků textu pomocí Houghovy transformace a obrázek otočí zpět. Pokud jsou vaše dokumenty natočeny více než 5°, zvyšte `max_angle`, ale dejte pozor na artefakty při nadměrném otáčení. + +### Binarizovat obrázek pomocí Otsu + +Řádek `binarize(method="otsu")` přímo odpovídá dotazu **binarizovat obrázek pomocí otsu**. Otsu algoritmus vypočítá práh, který minimalizuje vnitřní varianci tříd, což je ideální pro dokumenty s bimodálními histogramy (tmavý text vs. světlé pozadí). + +## Krok 4: Připojit pipeline k enginu + +Nyní řekneme OCR engine, aby spouštěl každou příchozí obrázek přes pipeline, kterou jsme právě vytvořili. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Proč je to důležité:* Bez registrace by engine zpracovával surový sken a ignoroval veškeré čištění, které jsme nastavili. Tento krok zajišťuje **jak zlepšit přesnost OCR** aplikací stejného předzpracování konzistentně. + +## Krok 5: Rozpoznat text ze špinavého německého skenu + +Je čas dát vše dohromady. Předáme engine špinavý německý obrázek a necháme ho udělat těžkou práci. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Pokud vás zajímá výkon, můžete měřit dobu volání: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Krok 6: Vypsat rozpoznaný text + +Nakonec vytiskneme extrahovaný řetězec. To je přímá odpověď na **extrahovat text z německého obrázku**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Očekávaný výstup + +Předpokládejme, že ukázkový sken obsahuje větu „Die schnelle braune Füchsin springt über den faulen Hund.“; měli byste vidět něco jako: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Pokud výstup stále obsahuje poškozené znaky, zvažte úpravu síly `denoise` nebo zvýšení `max_angle` pro narovnání. + +## Časté problémy a jak je řešit + +- **Chybějící jazykový model:** Zapomenutí `set_recognition_language(Language.GERMAN)` často vede k chybějícím umlautům. Zkontrolujte volání. +- **Přehnané odšumění:** Síla nad 0.9 může vymazat tenké tahy, zejména ve starých fontách. Držte se 0.5‑0.7 pro většinu případů. +- **Nesprávný formát souboru:** Některé OCR enginy selžou na více‑stránkových TIFF souborech. Pokud máte více‑stránkový dokument, rozdělte jej na jednostránkové soubory. +- **Pořadí pipeline:** Ukázané pořadí (deskew → denoise → binarize → contrast) je záměrné. Binarizace před odšuměním může zachytit šum; vždy nejprve odšuměte. + +## Rozšíření pipeline (Co dál?) + +Nyní, když máte solidní základ, můžete chtít: + +- **Přidat morfologické otevírání** pro vyčištění drobných skvrn (`.morph_open(kernel=3)`). +- **Integrovat jazykový model** pro korekci po zpracování (`ocr_engine.apply_spellcheck()`). +- **Paralelizovat dávkové zpracování** velkých datasetů pomocí `concurrent.futures`. + +Všechny tyto možnosti jsou přirozenými rozšířeními, která zachovávají hlavní myšlenku **jak předzpracovat obrázky pro OCR** a zároveň dále zvyšují **jak zlepšit přesnost OCR**. + +## Závěr + +Prošli jsme **jak předzpracovat obrázky pro OCR** od začátku do konce: vytvořili engine, nastavili německý jazyk, postavili pipeline, která **binarizuje obrázek pomocí Otsu**, **jak narovnat naskenované dokumenty**, a nakonec **extrahuje text z německého obrázku** s vyšší důvěrou. Dodržením šesti výše uvedených kroků zaznamenáte výrazný nárůst kvality rozpoznání — už žádné nekonečné ruční opravy. + +Vyzkoušejte skript na vlastních skenech, pohrávejte si s parametry a nechte výsledky mluvit za vás. Máte otázky ohledně konkrétního vylepšení předzpracování? Zanechte komentář a ponoříme se do detailů společně. + +Šťastné kódování a ať je vaše OCR vždy přesné! + + +## Co se naučíte dál? + + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní přístupy ve vlastních projektech. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/czech/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..026067252 --- /dev/null +++ b/ocr/czech/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,320 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG obrázek s Pythonem – naučte se, jak extrahovat text z obrázku, + spustit příklad OCR v Pythonu a dokonce snadno číst starořecký text. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: cs +og_description: OCR PNG obrázek v Pythonu vysvětlen. Tento průvodce ukazuje, jak extrahovat + text z obrázku, spustit příklad OCR v Pythonu a snadno číst starou řečtinu. +og_title: OCR PNG obrázek v Pythonu – kompletní tutoriál +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR PNG obrázku v Pythonu – Kompletní krok‑za‑krokem průvodce +url: /cs/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG obrázek v Pythonu – Kompletní krok‑za‑krokem průvodce + +Už jste se někdy ptali, jak **OCR PNG image** soubory přímo ze skriptu v Pythonu? Možná máte složku plnou naskenovaných starověkých rukopisů a potřebujete **extract text from image** soubory, aniž byste je museli ručně přepisovat. Dobrou zprávou je, že nepotřebujete PhD v počítačovém vidění – stačí pár řádků kódu a správná knihovna a během několika sekund budete číst starověkou řečtinu. + +V tomto tutoriálu projdeme **python OCR example**, který rozpozná text z PNG, nastaví jazyk na řečtinu polytonickou a vytiskne výsledek. Na konci přesně budete vědět, jak **recognize image text**, jak řešit běžné problémy a jak přizpůsobit skript pro jiné jazyky nebo formáty obrázků. + +## Co se naučíte + +- Nainstalovat a nakonfigurovat Python OCR knihovnu (pytesseract + Tesseract OCR) +- Vytvořit instanci OCR enginu a načíst PNG soubor +- Nastavit rozpoznávací jazyk na řečtinu polytonickou, abyste mohli **read ancient greek** +- Vypsat rozpoznaný text a řešit typické problémy +- Rozšířit skript pro dávkové zpracování více PNG souborů nebo přepnout na jiný jazyk + +### Předpoklady + +| Požadavek | Proč je důležité | +|-------------|----------------| +| Python 3.8+ | Moderní syntaxe a typové nápovědy | +| `pytesseract` package | Lehký obal kolem Tesseract enginu | +| Tesseract OCR binaries (≥ 5.0) | Skutečný engine, který dělá těžkou práci | +| Greek language data (`grc.traineddata`) | Potřebné pro správné **read ancient greek** | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Naše cílová **ocr png image** ukázka | + +Můžete nainstalovat Python část pomocí: + +```bash +pip install pytesseract Pillow +``` + +A na Ubuntu/macOS přidáte samotný engine: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Nezapomeňte stáhnout trénovaná data pro řečtinu polytonickou: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Cesta se může lišit; v případě potřeby upravte `TESSDATA_PREFIX`.)* + +--- + +## OCR PNG obrázek: Vytvoření instance enginu + +První věc, kterou potřebujeme, je objekt, který komunikuje s Tesseract. V `pytesseract` je engine přístupný přes funkce na úrovni modulu, ale pro přehlednost jej zabalíme do malé třídy. To odráží koncept „engine“, který jste viděli v původním úryvku. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Proč to zabalit?** +- Udržuje veřejné API identické s úryvkem, se kterým jste začali, což usnadňuje migraci. +- Umožňuje později přidat logování nebo ošetření chyb, aniž byste zasahovali do hlavního toku. +- Demonstruje dobré OOP praktiky – něco, co oceňují zkušení vývojáři. + +## Extrahování textu z obrázku: Nastavení jazyka na řečtinu polytonickou + +Nyní, když máme engine, musíme mu říct, jaký jazyk očekávat. Řečtina polytonická používá diakritiku, která není zahrnuta ve standardních “greek” datech, takže nasměrujeme Tesseract na tréninkový soubor `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Pokud budete chtít **extract text from image** soubory v jiném jazyce, stačí nahradit `"grc"` za `"eng"` pro angličtinu, `"fra"` pro francouzštinu atd. Stejný řádek funguje pro jakýkoli nainstalovaný jazyk. + +## Rozpoznání textu z obrázku: Spuštění OCR na PNG + +Po nastavení jazyka předáme PNG engine. Původní příklad použil pevně zadanou cestu; uděláme to trochu flexibilnější pomocí objektů `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tipy a okrajové případy** + +- **File not found** – obalte volání do `try/except FileNotFoundError`, aby se zobrazila přátelská zpráva. +- **Low‑resolution PNG** – zvažte předzpracování (např. změna velikosti, binarizace) pomocí Pillow před OCR. +- **Non‑Greek text** – Tesseract se stále pokusí dekódovat, ale přesnost výrazně klesá. Vždy odpovídejte jazyku. + +## Výstup rozpoznaného textu + +Nakonec vytiskneme výsledek. Ve skutečném projektu můžete zapisovat do databáze, CSV nebo ho dokonce předat do překladového pipeline. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Když spustíte skript na čistém skenu starověké řecké nápisu, měli byste vidět něco jako: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Pokud výstup vypadá poškozeně, zkontrolujte, že soubor **greek.traineddata** je ve správné složce a že PNG není příliš šumivý. + +## Kompletní funkční příklad (všechny kroky v jednom skriptu) + +Níže je kompletní, připravený ke spuštění program. Uložte jej jako `ocr_greek.py` a spusťte `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Očekávaný výstup** (zkrácený pro stručnost): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Pokud vidíte správné řecké znaky, gratulujeme—úspěšně jste provedli operaci **ocr png image** v Pythonu! + +## Časté otázky a profesionální tipy + +### Jak zlepšit přesnost u šumivého PNG? + +- Převést obrázek na odstíny šedi: `img = img.convert('L')` +- Použít binární práh: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Zvětšit rozlišení pomocí `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Tyto kroky často promění **recognize image text** noční můru na čistý výsledek. + +### Můžu zpracovat celou složku PNG souborů? + +Ano. Zabalte volání `recognize_image` do `for` smyčky přes `Path.glob("*.png")`. Uložte každý výsledek do slovníku nebo jej zapište do CSV pro pozdější analýzu. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Co když potřebuji extrahovat jen čísla? + +Předávejte vlastní řetězec **config** funkci `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Tímto způsobem můžete **extract text from image** soubory, které obsahují tabulky, sériová čísla nebo časová razítka. + +### Existuje způsob, jak získat skóre důvěry? + +Ano—použijte `pytesseract.image_to_data`, který vrací TSV s důvěrou pro každé slovo. Můžete odfiltrovat tokeny s nízkou důvěrou před sestavením finálního řetězce. + +## Rozšíření tutoriálu + +Nyní, když ovládáte základy, zvažte prozkoumání těchto souvisejících témat: + +- **Batch OCR with multiprocessing** – urychlete zpracování velkých korpusů PNG souborů. +- **Hybrid OCR + NLP pipelines** – automaticky přeložte extrahovanou starověkou řečtinu do moderní angličtiny. +- **Alternative engines** – vyzkoušejte `easyocr` nebo metody založené na `opencv` pro specifické případy. +- **Cloud OCR services** – Google Vision, Azure Computer Vision nebo AWS Textract pro serverless škálování. + +Každý z nich staví na základním **python ocr example**, který jsme právě prošli, takže se budete cítit jistě při dalším prozkoumávání. + +## Závěr + +Vezmeme jednoduchý úryvek a proměnili jsme jej v robustní **ocr png image** workflow v Pythonu. Vytvořením `OcrEngine`, nastavením jazyka na řečtinu polytonickou, předáním PNG a vytištěním výsledku nyní víte, jak **extract text from image** soubory, **recognize image text**, a dokonce **read ancient greek**. + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Extrahovat text z obrázku pomocí Aspose OCR – krok‑za‑krokem průvodce](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Jak nastavit hodnotu prahu v OCR rozpoznávání obrázků](/ocr/english/net/ocr-settings/set-threshold-value/) +- [rozpoznat textový obrázek pomocí Aspose OCR pro více jazyků](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/czech/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..2fec6764c --- /dev/null +++ b/ocr/czech/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR tutoriál ukazující, jak rozpoznat text na obrázku, provést + OCR ve vysokém rozlišení a extrahovat španělský text pomocí GPU akcelerovaného OCR. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: cs +og_description: Python OCR tutoriál, který vás provede rozpoznáváním textu na obrázcích, + OCR ve vysokém rozlišení a extrakcí španělského textu s akcelerací GPU. +og_title: Python OCR tutoriál – GPU akcelerované rozpoznávání textu +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR tutoriál – Rozpoznání textu na obrázku s GPU akcelerací +url: /cs/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Rozpoznání textu na obrázku s akcelerací GPU + +Už jste se někdy zamysleli, jak **rozpoznat text na obrázku** v Python skriptu, aniž byste strávili hodiny laděním nastavení? Nejste v tom sami. V tomto **python ocr tutorial** vám ukážeme čistý, end‑to‑end způsob, jak extrahovat španělský text z vysoce rozlišeného obrázku, a přidáme akceleraci GPU, aby proces běžel bleskově rychle. + +Považujte to za rychlou ukázku během coffee‑breaku, kterou můžete později rozšířit na produkční pipeline. Na konci tohoto průvodce budete mít spustitelný program, který provádí **high resolution OCR**, využívá GPU s podporou CUDA a vypíše přesné španělské znaky, které potřebujete. + +## Co se naučíte + +- Jak nainstalovat a importovat moderní OCR knihovnu, která podporuje akceleraci GPU. +- Jak vytvořit instanci OCR enginu a nastavit ji na **rozpoznat text na obrázku** ve španělštině. +- Jak povolit **gpu accelerated OCR** pro masivní zrychlení při práci s vysokým rozlišením souborů. +- Jak řešit okrajové případy, jako jsou chybějící CUDA ovladače nebo přechod na CPU. +- Tipy pro zlepšení přesnosti, když potřebujete **extract spanish text** z špinavých skenů. + +### Požadavky + +- Python 3.9+ (kód funguje také na 3.10 a novějších). +- CUDA‑kompatibilní GPU (volitelné, ale vysoce doporučené). +- Základní znalost pip a virtuálních prostředí. + +Pokud vám něco z toho chybí, tutoriál stále funguje – stačí přeskočit krok s GPU a knihovna automaticky přejde na CPU. + +--- + +## Python OCR Tutorial: Instalace požadovaných balíčků + +Nejprve potřebujeme spolehlivý OCR engine. Pro tento tutoriál použijeme open‑source balíček **`easyocr`**, který má vestavěnou podporu GPU, pokud je detekováno kompatibilní zařízení. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Pokud již máte nainstalovaný PyTorch, ujistěte se, že odpovídá vaší verzi CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Nesoulad verzí je častým zdrojem chyb „GPU not found“. + +## Krok 1: Vytvoření instance OCR enginu + +Nyní spustíme engine. EasyOCR nazývá svou hlavní třídu `Reader`. Konstruktor přijímá seznam jazykových kódů; předáme `"es"` pro španělštinu. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Proč je to důležité:* Tím, že jazyk deklarujete předem, engine načte jen potřebné váhy neuronové sítě, což šetří paměť a urychluje inferenci – zvláště užitečné, když později pracujete s **high resolution OCR**. + +## Krok 2: Připravte vysoké rozlišení obrázku + +Obrázky s vysokým rozlišením poskytují modelu více pixelů k práci, což obvykle vede k lepšímu rozpoznání znaků. Předpokládejme, že máte soubor `high_res_spanish.png` ve složce `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Pokud nemáte po ruce vzorek s vysokým rozlišením, můžete si zdarma stáhnout jeden z Unsplash nebo vygenerovat syntetický obrázek pomocí Pillow. Klíčové je udržet DPI nad 300 pro nejlepší výsledky. + +## Krok 3: Povolení akcelerace GPU (volitelné, ale doporučené) + +EasyOCR se již snaží použít GPU, když nastavíte `gpu=True`. Přesto je dobré ověřit, že zařízení je skutečně používáno, zejména na systémech s více GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Proč to kontrolovat?* Pokud skript tiše přejde na CPU, můžete se divit, proč operace trvající 5 sekund najednou zabere 30 sekund. Tato malá kontrola zpřehlední chování a udrží vaši **gpu accelerated OCR** pipeline předvídatelnou. + +## Krok 4: Provedení High‑Resolution OCR a rozpoznání textu na obrázku + +Nyní zábavná část – skutečné čtení textu. Metoda `readtext` z EasyOCR vrací seznam n-tic obsahujících ohraničující box, rozpoznaný řetězec a skóre důvěry. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Pokud potřebujete surový řetězec bez souřadnic, nastavte `detail=0`. Pro většinu případů použití **recognize image text** je výchozí (`detail=1`) dostatečný kontext pro následné zpracování. + +## Krok 5: Extrahování španělského textu a vyčištění výstupu + +Protože jsme požádali EasyOCR o španělštinu, vrácené řetězce jsou již v tomto jazyce. Přesto můžete chtít je spojit, odstranit mezery nebo filtrovat detekce s nízkou důvěrou. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Co když je důvěra nízká?** Můžete buď snížit práh (s rizikem šumu) nebo předzpracovat obrázek (zvýšit kontrast, binarizovat nebo vyrovnat sklon). Tyto triky jsou běžné při práci s **high resolution OCR** na naskenovaných dokumentech. + +## Krok 6: Řešení okrajových případů a ladění výkonu + +I ty nejlepší natrénované modely narazí na několik scénářů. Níže jsou dva rychlé opravné kódy, které můžete vložit do skriptu. + +### 6.1 Návrat na CPU, když není k dispozici GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling velmi velkých obrázků + +Pokud je váš obrázek větší než 4000 × 4000 px, můžete vyčerpat GPU paměť. Down‑samplujte proporcionalně při zachování DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Tyto úryvky udržují skript robustní, ať už běžíte na pracovním stole nebo na skromném notebooku. + +--- + +## Kompletní funkční příklad + +Spojením všeho dohromady získáte kompletní skript, který můžete okamžitě zkopírovat a spustit: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Očekávaný výstup (příklad):** + + + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/czech/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..a7ecdb509 --- /dev/null +++ b/ocr/czech/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-06-06 +description: Rozpoznávejte text z obrázku pomocí OCR enginu v Pythonu. Naučte se, + jak nastavit OCR engine v Pythonu a extrahovat text z obrázku pomocí cloudového + zpracování během několika minut. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: cs +og_description: Rozpoznávejte text z obrázku pomocí OCR enginu v Pythonu. Tento průvodce + ukazuje, jak nastavit OCR engine v Pythonu a efektivně extrahovat text z obrázku. +og_title: Rozpoznání textu z obrázku v Pythonu – kompletní průvodce nastavením +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Rozpoznání textu z obrázku v Pythonu – Kompletní průvodce nastavením OCR enginu +url: /cs/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# rozpoznat text z obrázku v Pythonu – Kompletní nastavení tutoriálu + +Už jste se někdy zamýšleli, jak **rozpoznat text z obrázku** pomocí několika řádků Pythonu? Nejste sami. Ať už vytváříte skener účtenek, digitalizátor dokumentů nebo jednoduchý koníčkový projekt, schopnost extrahovat text z obrázku je dovednost, která se rychle vyplatí. + +V tomto tutoriálu projdeme celý proces – od nastavení ve stylu **configure OCR engine python**, přes autentizaci v cloudu, až po ukázku, jak **extrahovat text z obrázku** s spolehlivým výsledkem. Žádná magie, jen jasné kroky, které můžete dnes zkopírovat‑vložit a spustit. + +## Co se naučíte + +- Jak nainstalovat a importovat požadovanou OCR knihovnu. +- Přesné příkazy pro **configure OCR engine python** pro zpracování v cloudu. +- Kompletní, spustitelný skript, který **rozpozná text z obrázku** a vypíše výstup. +- Tipy pro řešení běžných problémů, jako chybějící API klíče nebo nepodporované formáty obrázků. +- Nápady na další úroveň, jako dávkové zpracování a lokální záložní řešení. + +### Požadavky + +- Python 3.8+ nainstalovaný na vašem počítači. +- Internetové připojení (příklad používá OCR službu založenou na cloudu). +- Platný API klíč od poskytovatele OCR (ukážeme si, kde jej vložit). + +Pokud je máte, pojďme na to – žádné zbytečnosti, jen praktický návod, který funguje. + +--- + +## Krok 1: Nainstalujte OCR knihovnu a importujte ji + +Než budete moci **configure OCR engine python**, potřebujete knihovnu, která komunikuje s cloudovou službou. V našem příkladu použijeme fiktivní, ale reprezentativní balíček nazvaný `ocrcloud`. Nahraďte jej skutečným balíčkem, který používáte (např. `easyocr`, `google-cloud-vision` atd.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Proč je to důležité:** Importování třídy vám poskytuje přístup k metodám jako `use_cloud()` a `set_api_key()`. Bez importu by zbytek skriptu vyvolal `NameError`. + +*Tip:* Uveďte verzi ve vašem `requirements.txt` (`ocrcloud==2.1.0`), abyste se později vyhnuli neočekávaným breaking changes. + +## Krok 2: Vytvořte a **configure OCR engine python** pro cloudový režim + +Nyní skutečně **configure OCR engine python**. Engine výchozí nastavený běží v lokálním režimu; přepnutím do cloudového režimu můžete přenést těžkou analýzu obrázků na výkonné servery. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Vysvětlení:** +- `OcrEngine()` vytvoří nový objekt engine – představte si ho jako prázdné plátno. +- `use_cloud(True)` přepne přepínač, který říká engine, aby posílal obrázky přes HTTPS místo lokálního zpracování. To je klíčové pro vysoce přesné výsledky u složitých fontů nebo nízkého rozlišení fotografií. + +## Krok 3: Autentizujte se pomocí vašeho cloudového API klíče + +Většina cloudových OCR služeb vyžaduje API klíč. Tento krok ukazuje, jak bezpečně vložit pověření. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Bezpečnostní poznámka:** Nikdy neukládejte klíč přímo v veřejném repozitáři. V produkci jej načtete z proměnné prostředí: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## Krok 4: **rozpoznat text z obrázku** – Odeslat vzdálený obrázek ke zpracování + +S nastaveným enginem můžeme konečně **rozpoznat text z obrázku**. Metoda `recognize_image()` přijímá cestu nebo URL a vrací objekt obsahující extrahovaný text. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Co se děje pod kapotou?** +Bajty obrázku jsou nahrány na koncový bod poskytovatele, zpracovány deep‑learning modelem a výsledek v podobě prostého textu je streamován zpět. Pokud je obrázek velký, služba jej může automaticky zmenšit pro zrychlení úlohy. + +## Krok 5: Výstup výsledku **extrahovat text z obrázku** + +Nyní, když OCR služba odvedla svou práci, jednoduše vytiskneme text. Ve skutečných aplikacích jej můžete uložit do databáze nebo předat další funkci. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Expected output:** (example) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Pokud výstup vypadá poškozeně, zkontrolujte, že je obrázek jasný a že jste vybrali správný jazykový model (mnoho služeb umožňuje nastavit `engine.set_language("en")`). + +## Řešení okrajových případů a běžných úskalí + +### 1. Chybějící nebo neplatný API klíč +Pokud vidíte chybu autentizace, ujistěte se: +- Klíč je aktivní a nevypršel. +- Je správně načítán z prostředí. +- Vaše síť povoluje odchozí HTTPS provoz. + +### 2. Nepodporované formáty obrázků +Většina OCR API akceptuje JPEG, PNG a PDF. Pokus o BMP nebo TIFF může vyvolat odpověď „formát není podporován“. Případně konvertujte pomocí Pillow, pokud je potřeba: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Limity rychlosti (Rate Limits) +Cloudové služby často omezují počet požadavků za minutu. Pokud limit dosáhnete, implementujte exponenciální back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Přepnutí na lokální OCR +Pokud je cloud nedostupný, můžete se přepnout zpět: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Mít záložní řešení udržuje vaši aplikaci odolnou. + +## Kompletní funkční příklad + +Spojením všeho dohromady zde máte skript, který můžete spustit hned teď (jen nahraďte placeholder hodnoty). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Run it:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Měli byste vidět extrahovaný text vytištěný v konzoli, což potvrzuje, že jste úspěšně **rozpoznali text z obrázku** a **extrahovali text z obrázku** pomocí správného **configure OCR engine python** workflow. + +## Závěr + +Právě jsme prošli kompletním, end‑to‑end procesem, který vám umožní **rozpoznat text z obrázku** v Pythonu, od instalace knihovny po autentizaci cloudové služby a nakonec **extrahovat text z obrázku** jedním voláním funkce. Správným **configure OCR engine python** získáte jak flexibilitu (cloud vs. lokální), tak spolehlivost (správné zpracování chyb). + +Co dál? Zkuste dávkové zpracování složky s účtenkami, přidejte detekci jazyka nebo experimentujte s PDF jako vstupem. Možnosti jsou neomezené, jakmile zvládnete základy. + +Šťastné kódování a neváhejte položit otázky v komentářích – nic nepřekoná společné učení! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/czech/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..acd868c9c --- /dev/null +++ b/ocr/czech/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Spusťte OCR na obrázku pomocí Pythonu a zobrazte skóre důvěryhodnosti. + Naučte se, jak filtrovat slova s nízkou důvěrou, nastavit prahy a řešit okrajové + případy. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: cs +og_description: Spusťte OCR na obrázku v Pythonu, zkontrolujte úrovně spolehlivosti + a odfiltrujte slova s nízkou spolehlivostí. Tento tutoriál vás provede kompletním, + spustitelným příkladem. +og_title: Spusťte OCR na obrázku pomocí Pythonu – Kompletní průvodce +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Spusťte OCR na obrázku pomocí Pythonu – Kompletní krok‑za‑krokem průvodce +url: /cs/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Spusťte OCR na obrázku pomocí Pythonu – Kompletní krok‑za‑krokem průvodce + +Už jste někdy potřebovali **spustit OCR na obrázku** soubory, ale nebyli jste si jisti, jak z nich získat spolehlivý text? Nejste sami – mnoho vývojářů narazilo na stejný problém, když extrahovaná slova vypadají nejistě a skóre důvěry je záhadou. + +V tomto průvodci se ponoříme přímo do fungujícího řešení: uvidíte, jak **spustit OCR na obrázku**, přečíst celkovou důvěru a vybrat slova s nízkou důvěrou, která mohou vyžadovat ruční kontrolu. Na konci budete mít znovupoužitelný skript, pochopíte, proč je každý řádek důležitý, a budete vědět, jak upravit prahovou hodnotu důvěry pro své vlastní projekty. + +## Co tento tutoriál pokrývá + +Provedeme vás celým pracovním postupem – od načtení obrázku po vytištění přehledné zprávy o slovech, která spadla pod 80 % hranici důvěry. Během toho si probereme: + +* Výběr spolehlivého OCR enginu (použijeme **EasyOCR**, populární Python OCR knihovnu) +* Interpretaci atributu `confidence`, který vrací každý OCR výsledek +* Filtrování slov pomocí vlastního **práhu důvěry OCR** +* Rozšíření skriptu pro dávkové zpracování nebo alternativní enginy jako **pytesseract** + +Předchozí zkušenost s OCR není vyžadována, stačí základní znalost Pythonu a funkční prostředí (doporučeno Python 3.9+). + +Připraveni proměnit rozmazané snímky obrazovky na čistý, prohledávatelný text? Pojďme na to. + +--- + +## ## Jak spustit OCR na obrázku pomocí Pythonu + +Jádrem tutoriálu je tříkrokový úryvek, který odráží kód, který jste již viděli. Níže rozložíme každý řádek, vysvětlíme proč, a poté vám poskytneme kompletní skript připravený ke kopírování a vložení. + +### Krok 1: Instalace a import OCR enginu + +Nejprve se ujistěte, že je OCR knihovna k dispozici. **EasyOCR** funguje ihned pro mnoho jazyků a poskytuje skóre důvěry pro každé slovo. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Proč EasyOCR?* Obsahuje model hlubokého učení, který byl trénován na různorodých datech, takže obvykle získáte vyšší hodnoty důvěry než u staršího enginu Tesseract, zejména u obrázků smíšené kvality. + +> **Tip:** Pokud pracujete v omezeném prostředí (např. malý Docker kontejner), `pytesseract` může být lehčí, ale ztratíte část moderní přesnosti, kterou EasyOCR poskytuje. + +### Krok 2: Spustit OCR na obrázku + +Nyní skutečně **spustíme OCR na obrázku**. Metoda `recognize_image` z původního příkladu je nahrazena voláním `readtext` z EasyOCR, které vrací seznam n-tic `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Každý záznam v `ocr_results` vypadá takto: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Třetí prvek (`0.92` v příkladu) je skóre důvěry v rozmezí 0 a 1. + +### Krok 3: Shrnutí celkové důvěry + +Na rozdíl od předchozího úryvku, který vytiskl jediný atribut `confidence`, EasyOCR poskytuje důvěru pro každé slovo. Pro získání celkového dojmu je zprůměrujeme: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Proč průměrovat?* Poskytuje rychlou kontrolu zdraví – pokud je celková důvěra pod, řekněme, 70 %, pravděpodobně budete muset vylepšit obrázek (lepší osvětlení, předzpracování atd.). + +### Krok 4: Seznam slov s nízkou důvěrou + +Nyní přichází část, která přímo odpovídá požadavku „seznam slov, jejichž důvěra je pod požadovaným prahem“. Výchozí **práh důvěry OCR** nastavíme na 0.80 (80 %), ale můžete jej upravit. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Smyčka vytiskne každé slovo, které neprošlo, spolu s procentuální důvěrou. Jedná se o přesný ekvivalent původní smyčky `for recognized_word in recognition_result.words`, ale nyní funguje s výstupním formátem EasyOCR. + +--- + +## ## Porozumění skóre důvěry OCR + +Důvěra není magické číslo; je to odhad modelu, jak si je jistý konkrétní transkripcí. Zde je několik věcí, na které je třeba pamatovat: + +| Situace | Typická důvěra | Co dělat | +|-----------|-------------------|------------| +| Čistý, vysoce rozlišený sken | 0.95 – 1.00 | Není potřeba žádná další práce | +| Mírné rozmazání nebo nerovnoměrné osvětlení | 0.80 – 0.94 | Zvažte mírné předzpracování (zvýšení kontrastu) | +| Silný šum, natočený text | < 0.70 | Použijte předzpracování obrazu (odklon, odstranění šumu) nebo přepněte na jiný OCR engine | + +> **Pozor:** Některé jazyky (např. kurzívní ruční psaní) přirozeně produkují nižší skóre. Přizpůsobte prahovou hodnotu podle toho. + +### Okrajové případy a varianty + +1. **Dávkové zpracování** – Pokud potřebujete **spustit OCR na obrázku** soubory hromadně, zabalte výše uvedenou logiku do smyčky, která prochází adresář. +2. **Více jazyků** – Předávejte seznam jako `['en', 'fr']` do `easyocr.Reader` a engine detekuje oba. +3. **Alternativní enginy** – Chcete vyzkoušet **pytesseract**? Nahraďte blok čtečky tímto: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Pak budete muset agregovat důvěry na úrovni znaků do důvěry na úrovni slov – trochu více práce, ale proveditelné. + +4. **Triky předzpracování** – Použití filtrů OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) může zvýšit důvěru u šumivých skenů. + +--- + +## ## Kompletní, připravený skript + +Níže je kompletní soubor Python, který můžete vložit do svého projektu. Uložte jej jako `ocr_report.py` a spusťte `python ocr_report.py`. Ujistěte se, že cesta k obrázku ukazuje na existující soubor. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Očekávaný výstup** (vaše čísla se mohou lišit): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Pokud každé slovo překročí 80 % práh, uvidíte přátelskou zprávu „All words meet the confidence threshold.“ místo toho. + +--- + +## ## Často kladené otázky (FAQ) + +**Q: Funguje to s PDF soubory?** +A: Ne přímo. Nejprve převěďte každou stránku PDF na obrázek (např. pomocí `pdf2image`) a poté vložte PNG/JPEG do skriptu. + +**Q: Moje čísla důvěry jsou všechna nízká – co mohu udělat?** +A: Zkuste předzpracování obrazu: zvýšte kontrast, odstraňte šum pozadí nebo otočte obrázek do vodorovné osy. EasyOCR také přijímá parametr `contrast_ths`, který můžete ladit. + +**Q: Můžu exportovat výsledky do CSV?** +A: Rozhodně. Po smyčce s nízkou důvěrou zapište `ocr_results` do `csv.DictWriter`, kde každý řádek obsahuje `text`, `confidence` a souřadnice ohraničujícího rámečku. + +**Q: Existuje verze akcelerovaná GPU?** +A: EasyOCR automaticky používá CUDA, pokud je nainstalován kompatibilní GPU a PyTorch. Ověřte pomocí `torch.cuda.is_available()` před spuštěním skriptu. + +--- + +## Závěr + +Právě jsme **spustili OCR na obrázku** pomocí Pythonu, prozkoumali celkovou důvěru a izolovali jakákoli slova s nízkou důvěrou, která potřebují + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou ovládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Jak nastavit hodnotu prahu v OCR rozpoznávání obrazu](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Jak použít Aspose OCR pro JSON výsledek v rozpoznávání obrazu](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extrahovat text z obrázku – optimalizace OCR s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/dutch/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..02256cbbc --- /dev/null +++ b/ocr/dutch/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Haal tekst uit een afbeelding met Python OCR in enkele minuten. Ontdek + meertalige afbeelding‑OCR, automatische taaldetectie‑OCR en hoe je OCR‑tekst nauwkeurig + kunt extraheren. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: nl +og_description: Haal snel tekst uit een afbeelding met Python OCR. Leer meertalige + afbeelding‑OCR, automatische taaldetectie en hoe je OCR‑tekst stap voor stap extraheert. +og_title: Tekst uit afbeelding halen met Python OCR – Complete gids +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Tekst extraheren uit afbeelding met Python OCR – Complete gids +url: /nl/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tekst uit afbeelding extraheren met Python OCR – Complete gids + +Heb je ooit **tekst uit een afbeelding** moeten extraheren, maar wist je niet welke bibliotheek meerdere talen automatisch aankon? Je bent niet de enige—ontwikkelaars vragen voortdurend *hoe OCR‑tekst te extraheren* bij internationale documenten, bonnetjes of gescande flyers. In deze tutorial lopen we een praktisch Python‑voorbeeld door dat niet alleen tekst uit een afbeelding haalt, maar ook **de taal detecteert** tijdens het proces, waardoor meertalige afbeelding‑OCR een fluitje van een cent wordt. + +We behandelen alles, van het installeren van het OCR‑pakket tot het inschakelen van **auto‑detect taal OCR**, het uitvoeren van de engine op een voorbeeldafbeelding, en uiteindelijk het afdrukken van zowel de gedetecteerde taal als de geëxtraheerde string. Aan het einde heb je een herbruikbare snippet die je in elk project kunt plaatsen, of je nu een vertaal‑pipeline bouwt of een data‑ingestieservice. + +## Tekst uit afbeelding extraheren – De omgeving instellen + +Voordat we in de code duiken, zorg ervoor dat je werkstation aan deze minimale vereisten voldoet: + +- Python 3.8 of nieuwer (de bibliotheek gebruikt type‑hints die oudere versies negeren) +- `pip` voor pakketbeheer +- Een afbeeldingsbestand dat tekst bevat in ten minste twee verschillende talen (bijv. Engels + Spaans) + +Je hebt ook de OCR‑bibliotheek nodig die deze demo aandrijft. Voor deze gids gebruiken we het fictieve `ocr`‑pakket, dat populaire real‑world tools zoals Tesseract of EasyOCR nabootst maar een nette Python‑API biedt. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** Als je permissiefouten tegenkomt, plaats dan `python -m` voor het commando of gebruik een virtuele omgeving—houdt je globale site‑packages netjes. + +## OCR‑engine‑instantie maken + +Nu de bibliotheek klaar is, is de eerste logische stap om **een OCR‑engine‑instantie te maken**. Beschouw de engine als een slimme scanner die je kunt configureren voordat je afbeeldingen erin stopt. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Waarom maken we de engine apart in plaats van een statische methode aan te roepen? Het engine‑object bewaart configuratiestatus (zoals taalvoorkeuren) die je mogelijk wilt hergebruiken over vele afbeeldingen, waardoor je de overhead van telkens opnieuw initialiseren bespaart. + +## Auto‑detect taal OCR inschakelen + +De meeste OCR‑tools vereisen dat je een taalcodes opgeeft—`eng` voor Engels, `spa` voor Spaans, enzovoort. Handmatig raden van de taal ondermijnt het doel van een **meertalige afbeelding‑OCR**‑workflow. Gelukkig biedt het `ocr`‑pakket een *auto‑detect taal OCR*‑modus die de afbeelding inspecteert en achter de schermen het beste taamodel selecteert. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Door **detect language OCR** op deze manier in te schakelen, hoef je geen lange lijst met taalcodes bij te houden. De engine probeert het script dat hij ziet te matchen—Latijn, Cyrillisch, Han, enz.—en laadt automatisch het juiste model. + +## Meertalige afbeelding‑OCR uitvoeren + +Met de engine klaar, is het tijd om daadwerkelijk **tekst uit afbeelding** te extraheren. De methode `recognize_image` accepteert een bestandspad en retourneert een result‑object dat zowel de ruwe tekst als de gedetecteerde taal bevat. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Als je je afvraagt *hoe OCR‑tekst te extraheren* uit een PDF in plaats van een PNG, biedt dezelfde engine `recognize_pdf`—vervang gewoon de methodenaam. De onderliggende detectielogica blijft identiek, zodat je profiteert van dezelfde **auto‑detect taal OCR**‑functie. + +## Gedetecteerde taal en geëxtraheerde tekst weergeven + +Tot slot geven we weer wat de engine heeft ontdekt. Het result‑object exposeert `detected_language` (een BCP‑47‑tag zoals `en` of `es`) en `text`, dat de ruwe OCR‑output bevat. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Het uitvoeren van het script op onze voorbeeldafbeelding zou iets vergelijkbaars moeten opleveren: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Let op hoe de engine correct Engels als primaire taal identificeerde, maar toch de Spaanse regel vastlegde—precies wat je verwacht van een robuuste **meertalige afbeelding‑OCR**‑oplossing. + +### Wat als detectie mislukt? + +Soms kan de OCR‑engine terugvallen op een standaardtaal (meestal Engels) als de afbeelding onscherp is of het script te exotisch. In die gevallen kun je een taallijst forceren: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Maar onthoud, het forceren van talen ondermijnt het gemak van **auto‑detect taal OCR**, dus gebruik het alleen wanneer je een bekende subset van talen hebt. + +## Veelvoorkomende valkuilen en hoe OCR‑tekst betrouwbaar te extraheren + +Zelfs met auto‑detectie kunnen een paar haperingen je tegenwerken: + +1. **Afbeeldingen met lage resolutie** – OCR‑nauwkeurigheid daalt scherp onder 150 dpi. Upscale of vraag een scan met hogere resolutie aan. +2. **Ruis en compressie‑artefacten** – Pas een eenvoudige drempel‑filter (`opencv` of `Pillow`) toe voordat je de afbeelding aan de engine geeft. +3. **Gemengde scripts op één pagina** – Sommige engines hebben moeite met gelijktijdig Latijnse en CJK‑tekens. Splits de pagina in regio’s en voer afzonderlijke herkenningen uit indien nodig. + +Het aanpakken van deze problemen verbetert de kwaliteit van het **extract text from image**‑proces drastisch, vooral bij real‑world, meertalige documenten. + +## Volledig werkend voorbeeld + +Hieronder staat het complete, kant‑klaar script dat alle besproken stappen combineert. Sla het op als `multilingual_ocr.py` en voer het uit vanaf de commandoregel. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Verwachte output** (ervan uitgaande dat de voorbeeldafbeelding Engels en Spaans bevat): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Voel je vrij om `multilang_page.png` te vervangen door elke afbeelding die tekst in andere talen bevat—dankzij **auto‑detect taal OCR** geeft het script je nog steeds een zinvolle taaltag en de bijbehorende tekst. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Conclusie + +Je weet nu precies **hoe OCR‑tekst te extraheren** uit een afbeelding, hoe je **auto‑detect taal OCR** inschakelt, en hoe je **meertalige afbeelding‑OCR**‑scenario's met minimale code afhandelt. Door een OCR‑engine‑instantie te maken, automatische taaldetectie aan te zetten en `recognize_image` aan te roepen, kun je betrouwbaar zowel de taalidentificatie als de ruwe tekst ophalen. + +Wat nu? Probeer de geëxtraheerde strings aan een vertaal‑API te voeren, sla ze op in een doorzoekbare database, of combineer meerdere pagina’s tot één PDF‑rapport. Je kunt ook experimenteren met verschillende OCR‑back‑ends (Tesseract, EasyOCR, Google Vision) terwijl je dezelfde high‑level workflow behoudt—dankzij de consistente **detect language OCR**‑interface. + +Als je tegen eigenaardigheden aanloopt, bekijk dan opnieuw de sectie “Veelvoorkomende valkuilen” of pas de beeld‑pre‑processing stappen aan. Veel plezier met coderen, en moge je volgende project vol zitten met correct‑gedetecteerde, perfect‑geëxtraheerde tekst! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat complete werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Afbeelding omzetten naar tekst – OCR uitvoeren op afbeelding vanuit URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Tekst uit afbeelding extraheren – OCR‑optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) +- [tekstafbeelding herkennen met Aspose OCR voor meerdere talen](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/dutch/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..86d15ca15 --- /dev/null +++ b/ocr/dutch/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Haal tekst uit afbeeldingen en pdf's met Python OCR. Leer hoe je gescande + documenten snel naar tekst kunt omzetten met asynchrone batchherkenning. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: nl +og_description: Tekst extraheren uit afbeeldingen en pdf's met Python. Deze stap‑voor‑stap + gids laat zien hoe je gescande documenten kunt omzetten naar tekst met async OCR. +og_title: Tekst uit PDF-afbeeldingen extraheren – Python OCR‑tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Tekst extraheren uit PDF‑afbeeldingen – Python‑gids voor het converteren van + gescande documenten naar tekst +url: /nl/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tekst extraheren uit afbeeldingen PDF – Python-gids om gescande documenten naar tekst te converteren + +Heb je ooit **tekst uit afbeeldingen pdf** moeten **extraheren** zonder uren te hoeven overtypen? In deze gids laten we je zien hoe je **gescande documenten naar tekst** kunt **converteren** met een eenvoudige asynchrone OCR-werkstroom in Python. + +Als je ooit naar een stapel gescande PDF's hebt gekeken en dacht: “Er moet toch een snellere manier zijn,” dan ben je op de juiste plek. We lopen elke regel code door, leggen uit waarom elk onderdeel belangrijk is, en behandelen zelfs een paar randgevallen die je kunt tegenkomen. + +## Wat je zult leren + +- Hoe je een OCR-engine opzet en de herkennings‑taal instelt. +- De werking van het voeden van een gemengde lijst van PNG's en PDF's aan een batch‑herkenner. +- Het asynchroon uitvoeren van de OCR-taak zodat je app responsief blijft. +- Het ophalen van de resultaten, koppelen aan hun bronbestanden, en het afdrukken van nette output. + +**Voorwaarden**: Python 3.8+, een basisbegrip van `asyncio` of `concurrent.futures`, en een OCR‑bibliotheek die een `OcrEngine`‑klasse exposeert die vergelijkbaar is met die in het voorbeeld (bijv. Aspose.OCR, Tesseract‑wrapper, of een aangepaste wrapper). Geen zware installatie vereist—installeer gewoon de bibliotheek en je bent klaar om te gaan. + +![tekst extraheren uit afbeeldingen pdf](https://example.com/placeholder.png "Schermafbeelding van OCR-uitvoer – tekst extraheren uit afbeeldingen pdf") + +## Tekst extraheren uit afbeeldingen PDF – OCR-engine instellen + +Het eerste wat je nodig hebt is een OCR‑engine‑instantie geconfigureerd voor de taal van je documenten. In ons geval gebruiken we Frans, maar je kunt dit vervangen door elke ondersteunde taal. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Waarom dit belangrijk is**: Het van tevoren instellen van de taal verbetert de nauwkeurigheid drastisch. De engine gebruikt taalspecifieke woordenboeken en tekenmodellen; het voeden van de verkeerde taal is een veelvoorkomende bron van onsamenhangende output. + +## Bestandslijst voorbereiden – Afbeeldingen en PDF's samen + +Onze batch‑herkenner kan zowel rasterafbeeldingen (`.png`, `.jpg`) als PDF‑containers verwerken. Geef gewoon een eenvoudige Python‑lijst met bestandspaden. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: Houd de lijst plat; de engine zal intern elke PDF‑pagina uitpakken naar afbeeldingen vóór herkenning. Als je duizenden bestanden hebt, overweeg dan de lijst op te splitsen in kleinere batches om geheugenpieken te voorkomen. + +## Asynchrone batch‑herkenning starten + +In plaats van de hoofdthread te blokkeren, starten we de OCR‑taak op de achtergrond. De methode retourneert een `Future` die uiteindelijk een lijst met `OcrResult`‑objecten bevat. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Hoe het werkt**: Intern spawnt de engine een thread‑pool (of een async‑taak, afhankelijk van de implementatie). Hierdoor kun je andere taken blijven uitvoeren—zoals een UI bijwerken, meer bestanden ophalen, of voortgang loggen—terwijl de zware verwerking elders plaatsvindt. + +## Doe iets nuttigs terwijl OCR draait + +Een veelgemaakte fout is om inactief te zitten en de future in een strakke lus te polleren. In plaats daarvan kun je willekeurig ander werk uitvoeren. Voor demonstratie zullen we gewoon een statusregel afdrukken. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Resultaten verzamelen zodra de Future voltooid is + +Wanneer je klaar bent om de OCR‑output te verzamelen, gebruik je `as_completed` van `concurrent.futures`. Dit patroon werkt of je nu één future of meerdere hebt. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Wat je zult zien**: Elk bestandspad gevolgd door de geëxtraheerde platte‑tekstrepresentatie. Voor PDF's bevat `result.text` de samengevoegde tekst van elke pagina. + +### Verwachte output (voorbeeld) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Als je ontbrekende tekens opmerkt, controleer dan of de ingestelde taal overeenkomt met de documenttaal, en overweeg de afbeeldingen vooraf te verwerken (kantelen corrigeren, contrast verhogen) voordat je ze aan de engine geeft. + +## Randgevallen en veelvoorkomende valkuilen + +| Situatie | Wat te doen | +|-----------|------------| +| **Gemengde talen** | Voer eerst een taal‑detectie‑pass uit, en instantiateer vervolgens aparte engines per taal. | +| **Grote PDF's (> 100 MB)** | Splits de PDF in afzonderlijke pagina's op schijf (bijv. met `PyPDF2`) en voer ze in als afzonderlijke items. | +| **Niet‑Latijnse scripts** | Zorg ervoor dat de OCR‑bibliotheek het benodigde taalpakket bevat; sommige bibliotheken vereisen dat je extra data‑bestanden downloadt. | +| **Prestatie‑knelpunt** | Verhoog de thread‑pool‑grootte (`engine.set_thread_pool_size(8)`) of schakel over naar een GPU‑versnelde backend indien beschikbaar. | +| **Ontbrekende tekst in lage‑resolutie‑afbeeldingen** | Pre‑process met OpenCV: `cv2.resize`, `cv2.threshold`, en `cv2.medianBlur` om de leesbaarheid te verbeteren. | + +## Volledig werkend voorbeeld (klaar om te kopiëren en plakken) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Sla dit op als `extract_text_async.py`, vervang `YOUR_DIRECTORY` door het pad naar je bestanden, installeer het OCR‑pakket (`pip install your-ocr-lib`), en voer `python extract_text_async.py` uit. Je zou de console‑output moeten zien die eerder werd geïllustreerd. + +## Volgende stappen – verder gaan dan basis‑extractie + +- **Post‑processing**: Verwijder extra witruimte, normaliseer Unicode (`unicodedata.normalize`), of voer een spell‑checker uit om OCR‑ruis op te schonen. +- **Gestructureerde output**: Exporteer resultaten naar CSV, JSON, of direct naar een database voor downstream zoeken. +- **Parallelle batches**: Als je honderden bestanden hebt, start dan meerdere futures en gebruik een wachtrij om de CPU bezig te houden zonder het geheugen te overbelasten. +- **Integreren met web‑frameworks**: Koppel dit script aan een Flask‑ of FastAPI‑endpoint om OCR on‑demand als service te bieden. + +--- + +### TL;DR + +Je weet nu hoe je **tekst uit afbeeldingen pdf** kunt **extraheren** met een minimale Python‑script die OCR asynchroon uitvoert, waardoor je **gescande documenten naar tekst** kunt **converteren** terwijl je programma responsief blijft. Experimenteer met de taalinstellingen, batch‑groottes en pre‑processing‑trucs om elke laatste teken‑nauwkeurigheid eruit te halen. + +Heb je een variant die je wilt delen—misschien OCR op handgeschreven notities of een cloud‑gebaseerde service? Laat een reactie achter, en happy coding! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Tekst extraheren uit afbeelding met Aspose OCR – Stapsgewijze gids](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Tekst extraheren uit afbeeldingen met OCR‑bewerking op mappen](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Tekst extraheren uit afbeeldingen met Aspose.OCR – Toegestane tekens](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e1d21b772 --- /dev/null +++ b/ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Hoe PDF's OCR'en met Python, tekst uit PDF extraheren, gescande PDF-tekst + converteren en OCR-taal wijzigen in slechts een paar regels code. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: nl +og_description: 'Hoe PDF OCR''en met Python: een praktische gids die laat zien hoe + je tekst uit PDF''s kunt extraheren, gescande PDF-tekst kunt converteren en moeiteloos + de OCR-taal kunt wijzigen.' +og_title: Hoe PDF OCR'en in Python – Volledige Programmeertutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Hoe PDF OCR'en in Python – Complete stap‑voor‑stap gids +url: /nl/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe PDF OCR'en in Python – Complete Stapsgewijze Gids + +Heb je je ooit afgevraagd **hoe je PDF's kunt OCR'en** zonder dure SaaS‑tools te betalen? Je bent niet de enige. Of je nu oude boeken digitaliseert, gegevens uit facturen haalt, of gewoon doorzoekbare tekst nodig hebt van een gescand rapport, het beheersen van PDF‑OCR in Python kan je uren handmatig kopiëren besparen. + +In deze tutorial lopen we een beknopt, werkend voorbeeld door dat **tekst uit PDF extraheert**, je laat zien hoe je **gescande PDF‑tekst** omzet in bewerkbare strings, en zelfs hoe je **OCR‑taal wijzigt** als je document niet in het Engels is. Aan het einde heb je een herbruikbare snippet die je in elk project kunt gebruiken. + +## Vereisten & Installatie + +Voordat we beginnen, zorg dat je het volgende hebt: + +- Python 3.8+ geïnstalleerd (de code werkt op 3.9, 3.10 en nieuwer) +- Het `ocr`‑pakket dat de `OcrEngine`‑klasse levert (installeer via `pip install ocr-lib` – vervang door de echte pakketnaam die je gebruikt) +- Een PDF‑bestand dat je wilt verwerken; voor de demo gebruiken we `high_res_book.pdf` in een map genaamd `YOUR_DIRECTORY` + +Als je een virtuele omgeving gebruikt (sterk aanbevolen), activeer deze dan eerst: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** Bewaar je PDF‑bestanden in een aparte `data/`‑directory om later pad‑gerelateerde problemen te vermijden. + +## Stap 1: Maak een OCR‑Engine‑instantie (Hoe PDF OCR – Initialisatie) + +Het allereerste wat je moet doen wanneer je **OCR op PDF**‑bestanden wilt uitvoeren, is de engine instantiëren. Beschouw de engine als het brein dat elke pagina leest, de glyphs interpreteert en je platte tekst teruggeeft. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Waarom dit belangrijk is: zonder een engine heb je geen context voor taalinstellingen, renderopties of PDF‑afhandeling. Het `OcrEngine`‑object bevat al die standaardwaarden en laat je ze later aanpassen. + +## Stap 2: Stel de Herkenningstaal In (OCR‑taal Wijzigen) + +De meeste OCR‑bibliotheken gebruiken standaard Engels, maar wat als je document in het Frans, Duits of zelfs Japans is? De taal wijzigen is zo simpel als het aanroepen van `set_recognition_language`. Dit voldoet aan de **change OCR language**‑vereiste en zorgt voor hogere nauwkeurigheid. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Waarom je dit nodig kunt hebben:** Een meertalige archief bevat vaak pagina’s met gemengde talen. Talen on‑the‑fly wisselen voorkomt mis‑herkenning van tekens zoals “ß” of “ñ”. + +## Stap 3: Configureer PDF‑Renderopties (Gescannde PDF‑tekst Effectief Converteren) + +Bij gescande PDF’s beïnvloeden resolutie en kleurmodus de OCR‑kwaliteit sterk. Renderen op 300 DPI in grijstinten is een goede balans voor de meeste documenten—hoog genoeg om details vast te leggen, maar laag genoeg om het geheugenverbruik redelijk te houden. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +De aaneengeschakelde aanroepen zien er misschien chic uit, maar het is gewoon een fluent API die telkens hetzelfde opties‑object teruggeeft. Als je kleur nodig hebt (bijv. voor gekleurde diagrammen), vervang dan `"grayscale"` door `"color"`. + +## Stap 4: Herken de PDF en Haal de Tekst van de Eerste Pagina Op (Tekst uit PDF Extracten) + +Nu volgt de kern van **hoe je PDF OCR't**: de engine een pad geven en de herkende tekst eruit halen. De methode retourneert een lijst met paginapresentaties; elke presentatie bevat een `text`‑attribuut. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Als je het volledige document nodig hebt, itereer dan over `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Wat Als de PDF Versleuteld Is? + +Sommige PDF’s zijn met een wachtwoord beveiligd. In dat geval kun je het wachtwoord doorgeven aan `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +De engine zal on‑the‑fly ontcijferen voordat OCR wordt uitgevoerd—geen extra stappen nodig. + +## Stap 5: Post‑Processing van de Geëxtraheerde Tekst (Fijn‑Afstellen van Extract Text from PDF) + +Ruwe OCR‑output bevat vaak regeleinden, extra spaties of af en toe verkeerd herkende tekens. Een snelle opschoonroutine maakt de geëxtraheerde string klaar voor downstream verwerking (zoekindexering, database‑opslag, enz.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Je kunt nu veilig **tekst uit PDF** extraheren en invoeren in elke NLP‑pipeline, zoekmachine of eenvoudige `open(...).write()`‑operatie. + +## Bonus: Batchverwerking van Meerdere PDF’s (OCR op PDF Schalen) + +Heb je een map vol gescande PDF’s, wikkel de logica dan in een lus: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Dit fragment laat zien hoe je **perform OCR on PDF**‑bestanden in bulk kunt uitvoeren, een veelvoorkomende behoefte bij digitaliseringsprojecten. + +## Verwachte Output + +Het uitvoeren van het één‑pagina‑voorbeeld (Stap 4) zou iets moeten afdrukken als: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Als je een meer‑pagina‑boek verwerkt, toont de console de opgeschoonde tekst van elke pagina, en laat het batch‑script een `.txt`‑bestand naast elke PDF achter. + +## Veelvoorkomende Valkuilen & Hoe Ze Te Vermijden + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| PDF met lage resolutie | Vervormde tekens, ontbrekende woorden | Verhoog DPI (`set_dpi(400)` of hoger) | +| Verkeerde taal ingesteld | Veel onbekende symbolen, vooral accenten | Gebruik `engine.set_recognition_language(ocr.Language.FRENCH)` of de juiste enum | +| Grote PDF veroorzaakt geheugenfout | `MemoryError` of crash na enkele pagina’s | Verwerk pagina’s in delen (`engine.recognize_pdf(..., max_pages=10)`) | +| Ontbrekende fonts in de PDF | Lege output voor bepaalde pagina’s | Zorg dat de PDF rasterafbeeldingen bevat; sommige PDF’s zijn alleen vector en vereisen andere handling | + +## Afbeeldingsillustratie + +Hieronder een snelle visualisatie van de workflow. De alt‑tekst is bewust SEO‑vriendelijk. + +![workflow diagram hoe PDF OCR te doen, toont engine‑initialisatie, taalinstelling, renderopties, herkenning en tekst‑extractie](/images/ocr-workflow.png) + +*Het diagram is niet vereist voor het uitvoeren van de code, maar helpt visuele leerlingen te zien waar elke stap in past.* + +## Conclusie + +We hebben **hoe je PDF OCR't** in Python van begin tot eind behandeld: een OCR‑engine maken, **OCR‑taal wijzigen**, renderen configureren om **gescande PDF‑tekst** te converteren, en uiteindelijk **tekst uit PDF** extraheren voor verder gebruik. Het complete, uitvoerbare voorbeeld staat klaar om in elk project te worden geplakt, en het optionele batch‑script laat zien hoe je de oplossing kunt opschalen. + +Vervolgens kun je overwegen: + +- **perform OCR on PDF** toe te voegen voor meertalige archieven door over een lijst met talen te itereren. +- De geëxtraheerde tekst te integreren met Elasticsearch voor full‑text zoeken. +- OCR te gebruiken om doorzoekbare PDF’s te maken door de tekstlaag terug in het originele bestand te embedden (veel bibliotheken bieden een `save_as_searchable_pdf`‑methode). + +Voel je vrij om te experimenteren, DPI‑instellingen aan te passen, of over te schakelen naar een andere OCR‑backend. De basisprincipes blijven hetzelfde, en je hebt nu een solide fundament om op voort te bouwen. + +Happy coding, en moge je gescande documenten eindelijk doorzoekbaar worden! + +## Wat Moet Je Hierna Leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat complete werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..16ebf75be --- /dev/null +++ b/ocr/dutch/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-06 +description: Hoe PDF's OCR'en en doorzoekbare PDF-bestanden maken van afbeeldingen + met Python. Leer doorzoekbare tekst toe te voegen en afbeeldingen naar PDF/A te + converteren in enkele minuten. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: nl +og_description: Hoe PDF stap‑voor‑stap OCR’en. Leer doorzoekbare tekst toe te voegen + en een afbeelding te converteren naar PDF/A met een eenvoudig Python‑script. +og_title: Hoe PDF OCR'en – Snelle gids voor het maken van doorzoekbare PDF's +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Hoe PDF OCR'en in Python – Maak een doorzoekbare PDF van afbeeldingen +url: /nl/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe PDF OCR'en – Scannen van Afbeeldingen omzetten naar Doorzoekbare PDF's + +Heb je je ooit afgevraagd **hoe je PDF's OCR't** wanneer je alleen een gescande afbeelding van een factuur of een bon hebt? Je bent niet de enige. In veel kantoren komt het binnenkomende papierwerk binnen als platte PNG's of JPEG's, en de volgende stap—die inhoud doorzoekbaar maken—voelt als een black‑box. + +Het goede nieuws? Met slechts een paar regels Python kun je **doorzoekbare PDF**-bestanden **aanmaken**, **doorzoekbare tekst toevoegen**, en zelfs **afbeelding naar PDF/A converteren** voor langdurige archivering. In deze tutorial lopen we elke stap door, leggen we uit waarom het belangrijk is, en geven we je een kant‑en‑klare script die je in elk project kunt gebruiken. + +> **Pro tip:** dezelfde aanpak werkt voor multi‑page scans; loop gewoon over de bestanden en de engine doet het zware werk. + +--- + +## Wat je nodig hebt + +Voordat we beginnen, zorg ervoor dat je het volgende op je machine hebt: + +| Vereiste | Waarom het belangrijk is | +|----------|--------------------------| +| Python 3.9 or newer | Moderne syntaxis en betere bibliotheekondersteuning | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Verwerkt zowel beeldherkenning als PDF/A-generatie | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | Een afbeeldingsbestand (PNG, JPEG, TIFF) dat je wilt omzetten naar een doorzoekbare PDF | +| Write permission to the output folder | Zodat het script de nieuwe PDF kan opslaan | + +Als je de OCR SDK nog niet hebt geïnstalleerd, voer dan uit: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Dat is alles—geen complexe systeemafhankelijkheden, alleen een pip‑installatie. + +## Hoe PDF OCR'en – Overzicht + +Op een hoog niveau bestaat het proces uit drie eenvoudige handelingen: + +1. **Herkennen** van de tekst in de afbeelding terwijl de originele grafische elementen behouden blijven. +2. **Exporteren** van het OCR-resultaat samen met de originele afbeelding als een **doorzoekbare PDF/A** (de archiefvriendelijke PDF‑variant). +3. **Valideren** dat het resulterende bestand selecteerbare, doorzoekbare tekst bevat die over de originele afbeelding is gelegd. + +Hieronder zie je elke stap in code, met uitleg over het *waarom* achter de commando's. + +## Stap 1: Tekst herkennen uit de afbeelding + +Eerst vragen we de OCR-engine om de pixels te lezen en een result-object terug te geven dat zowel de ruwe afbeelding als de geëxtraheerde tekst bevat. Beschouw het als de engine die de factuur voor je “leest”. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Waarom dit belangrijk is + +- **Grafische elementen behouden** betekent dat de visuele lay-out (tabellen, logo's, stempels) precies blijft zoals de scanner die heeft vastgelegd. +- Het `result`-object bevat doorgaans een verborgen tekstlaag die we later in de PDF zullen insluiten. +- Het gebruik van `recognize_image` in plaats van `recognize_pdf` vermijdt een extra conversiestap, wat de verwerking versnelt voor enkel‑pagina afbeeldingen. + +#### Veelvoorkomende variaties + +- Als je een **multi‑page TIFF** hebt, geef dan het bestandspad direct door; de meeste engines behandelen elke pagina als een aparte afbeelding. +- Voor PDF's die al afbeeldingen bevatten, kun je `engine.recognize_pdf("file.pdf")` aanroepen en deze stap volledig overslaan. + +## Stap 2: OCR-resultaat exporteren als doorzoekbare PDF/A + +Nu nemen we het `result` van stap 1 en vertellen we de engine een nieuw bestand te schrijven. De belangrijkste vlag hier is *PDF/A*—de ISO‑standaardversie van PDF ontworpen voor langdurige bewaring. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Waarom dit belangrijk is + +- **Doorzoekbare PDF**: Het uitvoerbestand bevat een verborgen, selecteerbare tekstlaag. Je kunt nu Ctrl + F gebruiken om door het document te zoeken. +- **PDF/A‑conformiteit**: Sommige organisaties (juridisch, financieel) vereisen PDF/A voor audittrails; deze stap voldoet automatisch aan die eis. +- De methode **voegt ook doorzoekbare tekst toe** zonder de afbeelding te flatten, zodat de visuele kwaliteit perfect blijft. + +#### Randgeval: Een gewone PDF in plaats van PDF/A nodig? + +Als je geen PDF/A nodig hebt, vervang dan `save_as_pdfa` door `save_as_pdf`. De rest van de workflow blijft hetzelfde. + +## Stap 3: De doorzoekbare PDF verifiëren + +Een snelle sanity‑check bespaart je later van mysterieuze bugs. Open het gegenereerde bestand in een PDF‑viewer, probeer een woord te selecteren en gebruik de zoekfunctie. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Verwachte output + +Wanneer je het script uitvoert, print de console: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Bij het openen van het bestand zie je de originele factuurafbeelding met een zwakke, onzichtbare tekstlaag. Markeer een woord en je merkt dat het selecteerbaar is—**dat is de doorzoekbare tekst** die je zojuist hebt toegevoegd. + +## Doorzoekbare tekst toevoegen aan bestaande PDF's (Bonus) + +Soms heb je al een PDF maar moet je er **doorzoekbare tekst** aan toevoegen. Dezelfde engine kan OCR-resultaten over een bestaande PDF leggen: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Hier voegt `apply_to` de verborgen laag samen met de originele pagina's, waardoor je **een doorzoekbare PDF** kunt maken zonder opnieuw te scannen. + +## Veelvoorkomende valkuilen en tips + +| Valkuil | Hoe te vermijden | +|---------|-----------------| +| **Lage resolutie bronafbeeldingen** (< 150 dpi) | Vergroot of vraag een scan met hogere resolutie aan; OCR‑nauwkeurigheid daalt drastisch onder 150 dpi. | +| **Missing language data** | Installeer de juiste taalpakketten voor je OCR-engine (`pip install pdfocr[eng,spa]`). | +| **Output folder not writable** | Voer het script uit met voldoende rechten of kies een andere map. | +| **PDF/A validation fails** | Zorg ervoor dat je geen niet‑ondersteunde lettertypen of JavaScript insluit; de meeste SDK's handelen dit automatisch af wanneer je `save_as_pdfa` gebruikt. | + +## Volledig script – Eén‑bestand oplossing + +Hieronder staat een zelf‑containend script dat alles samenbrengt. Kopieer‑en‑plak het, vervang de placeholder‑paden, en je bent klaar om **afbeelding naar PDF/A te converteren** in enkele seconden. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Wat dit script doet:** +1. Laadt de OCR-engine. +2. Leest de gekozen afbeelding en extraheert de tekst. +3. Schrijft een **doorzoekbare PDF/A** die je direct kunt distribueren of archiveren. + +Voel je vrij om de `main`‑logica in een functie te wikkelen die een hele map verwerkt—itereer gewoon over `os.listdir()` en herhaal de drie stappen voor elk bestand. + +## Volgende stappen & gerelateerde onderwerpen + +Nu je **hoe PDF OCR'en** onder de knie hebt, overweeg dan deze vervolgideeën: + +- **Batchverwerking:** Gebruik `concurrent.futures` om tientallen facturen parallel te OCR'en. +- **Metadata‑injectie:** Voeg aanmaakdatums of factuurnummers toe aan de PDF‑metadata voor eenvoudigere indexering. +- **Hybride PDF's:** Combineer doorzoekbare tekst met ingebedde originele afbeeldingen voor een “digitale tweeling” van het papieren document. +- **Alternatieve outputs:** Exporteer naar **DOCX** of **HTML** als downstream‑systemen bewerkbare formaten nodig hebben. + +Elk hiervan bouwt voort op de kernconcepten die je zojuist hebt geleerd—herkennen, exporteren, verifiëren. + +## Samenvatting + +Kort samengevat, je weet nu **hoe je PDF's OCR't** door een eenvoudige afbeelding om te zetten in een **doorzoekbare PDF/A** met slechts drie regels Python. Het script doet het zware werk, behoudt de originele grafische elementen, en levert een standaard‑conform document dat je kunt doorzoeken, archiveren of delen. + +Probeer het uit met je eigen facturen, bonnen of gescande contracten. Als je tegen problemen aanloopt, laat dan een reactie achter of bekijk de officiële documentatie van de SDK—die meestal vol staat met extra voorbeelden. Veel programmeerplezier, en geniet van de nieuwe mogelijkheid om elke afbeelding direct doorzoekbaar te maken! + +![Voorbeeld van OCR PDF die originele afbeelding en doorzoekbare PDF-overlay toont](placeholder.png "Voorbeeld van OCR PDF") + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat complete werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe PDF OCR'en in .NET met Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [PDF-tekst herkennen – OCR‑operaties met Aspose.OCR voor Java](/ocr/english/java/ocr-operations/) +- [Afbeeldingen naar PDF C# – Meerdere pagina's OCR‑resultaat opslaan](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/dutch/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..36de5c1d9 --- /dev/null +++ b/ocr/dutch/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-06-06 +description: Hoe PDF OCR'en met Aspose OCR Cloud. Leer tekst uit PDF te extraheren, + PDF-pagina's naar PNG te converteren en PDF-pagina‑afbeeldingen op te slaan in Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: nl +og_description: Hoe PDF OCR'en met Aspose OCR Cloud. Deze gids laat zien hoe je platte + tekst uit een PDF kunt extraheren, PDF‑pagina’s naar PNG kunt converteren en PDF‑pagina‑afbeeldingen + kunt opslaan. +og_title: Hoe PDF OCR'en met Aspose OCR Cloud – Stap voor stap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Hoe PDF OCR'en met Aspose OCR Cloud – Complete gids +url: /nl/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe PDF OCR'en met Aspose OCR Cloud – Complete Gids + +Heb je je ooit afgevraagd **hoe je PDF OCR't** zonder te worstelen met zware desktoptools? Je bent niet alleen—veel ontwikkelaars lopen tegen die muur aan wanneer ze een snelle, programmeerbare manier nodig hebben om tekst uit gescande documenten te halen. Het goede nieuws? Met Aspose OCR Cloud kun je **tekst uit PDF extraheren**, elke pagina omzetten naar een PNG, en zelfs **PDF-pagina‑afbeeldingen opslaan** voor later gebruik, allemaal vanuit een nette Python‑script. + +In deze tutorial lopen we alles door wat je moet weten: van het installeren van de SDK, het licentiëren van de engine, en het herkennen van multi‑page PDF's, tot het extraheren van platte tekst, het converteren van pagina's naar PNG, en het opslaan van die afbeeldingen op schijf. Aan het einde heb je een herbruikbare code‑fragment die je in elk project kunt plaatsen dat **hoe PDF OCR't** functionaliteit nodig heeft. + +## Wat je nodig hebt + +- **Python 3.8+** (de code werkt ook op 3.10 en nieuwer) +- Een Aspose OCR Cloud‑account – je krijgt een gratis proeflicentiebestand (`Aspose.OCR.lic`) +- Het `asposeocrcloud`‑pakket (`pip install asposeocrcloud`) +- Een gescande, multi‑page PDF die je wilt verwerken + +Dat is alles. Geen extra binaries, geen native afhankelijkheden, alleen pure Python. + +## Hoe PDF OCR't – Setup en Licentie + +Voordat je OCR‑methoden kunt aanroepen, moet je de SDK vertellen wie je bent. Aspose gebruikt een lichtgewicht licentiebestand dat je op een voor je script toegankelijke locatie plaatst. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* Als je de licentiestap overslaat, blijft de SDK werken maar voegt hij een klein watermerk toe aan de uitvoerafbeeldingen. Niet ideaal voor productie. + +## Stap 2: Installeer de Aspose OCR Cloud Python SDK + +Open een terminal en voer uit: + +```bash +pip install asposeocrcloud +``` + +Het pakket haalt alle benodigde afhankelijkheden binnen (requests, pillow, etc.) zodat je niets anders hoeft te zoeken. + +## Stap 3: Maak een OCR‑engine en kies een taal + +De engine is het hart van de operatie. Je kunt elke door Aspose ondersteunde taal opgeven; Engels werkt in de meeste gevallen. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Waarom de taal instellen? Omdat de OCR‑engine taalspecifieke woordenboeken gebruikt om de nauwkeurigheid te verbeteren. Als je Franse PDF's verwerkt, vervang dan gewoon `ENGLISH` door `FRENCH`. + +## Stap 4: Verwijs naar je multi‑page PDF + +Geef de engine het volledige pad naar het bestand dat je wilt verwerken. Relatieve paden zijn prima zolang ze resolven vanuit de werkmap van het script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Zorg ervoor dat het bestand leesbaar is; anders zie je een `FileNotFoundError`. + +## Stap 5: Voer OCR uit – je krijgt een lijst met resultaten + +Het aanroepen van `recognize_pdf` retourneert een lijst waarbij elk element overeenkomt met één pagina van de bron‑PDF. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Elke `OcrResult` bevat twee handige eigenschappen: + +* `text` – de platte‑tekst representatie van de pagina (ideaal voor **extract plain text pdf**) +* `image` – een Pillow `Image`‑object van de gerenderde pagina (perfect voor **convert pdf page png**) + +## Stap 6: Tekst extraheren uit PDF en pagina's converteren naar PNG + +Nu lopen we door de resultaten, printen we de geëxtraheerde tekst, en slaan we een PNG‑versie van elke pagina op. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Verwachte console‑output + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Je zult ook `page_1.png`, `page_2.png`, … vinden in `YOUR_DIRECTORY`. Dat zijn de gerasterde pagina‑afbeeldingen die je kunt gebruiken in downstream beeldverwerkings‑pijplijnen. + +## Stap 7: PDF‑pagina‑afbeeldingen opslaan (optionele post‑verwerking) + +Als je alleen de afbeeldingen nodig hebt en niet de tekst, kun je de regel `print(res.text)` overslaan. Omgekeerd, als je de tekst in afzonderlijke `.txt`‑bestanden wilt opslaan, voeg dan gewoon een klein schrijf‑statement toe: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Deze kleine toevoeging laat zien hoe eenvoudig het is om **PDF‑pagina‑afbeeldingen op te slaan** terwijl je ook de geëxtraheerde inhoud bewaart. + +## Volledig werkend voorbeeld + +Alles samenvoegend, hier is het volledige script dat je kunt kopiëren‑plakken in `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Voer het uit met: + +```bash +python ocr_pdf.py +``` + +Je zou de console‑dump van de tekst van elke pagina en een reeks PNG‑bestanden moeten zien + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/dutch/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..492cf8901 --- /dev/null +++ b/ocr/dutch/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-06-06 +description: Hoe afbeeldingen voor OCR te pre-processen met Python. Leer hoe je een + afbeelding binariseert met Otsu, hoe je gescande documenten rechtzet en de OCR-nauwkeurigheid + voor Duitse tekst verbetert. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: nl +og_description: Hoe afbeeldingen voor OCR in Python voor te bewerken. Deze tutorial + laat zien hoe je een afbeelding binariseert met Otsu, hoe je gescande documenten + rechtzet, en hoe je de OCR-nauwkeurigheid voor Duitse afbeeldingen verbetert. +og_title: Hoe afbeeldingen voor OCR te preprocessen – Complete Python-gids +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Hoe afbeeldingen voor OCR te preprocessen – Complete Python-gids +url: /nl/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe afbeeldingen voor OCR voor te bewerken – Complete Python-gids + +Heb je je ooit afgevraagd **hoe je afbeeldingen voor OCR moet voorbewerken** zodat de tekst kristalhelder uitkomt? Je bent niet de enige. Gescande documenten—vooral ruisende Duitse pagina’s—kunnen een nachtmerrie zijn voor elke OCR-engine. Het goede nieuws? Een paar slimme voorbewerkingsstappen kunnen een wazige, vlekkerige scan omtoveren tot een schone, machinaal leesbare afbeelding. + +In deze tutorial lopen we een praktisch voorbeeld door dat laat zien **hoe je afbeeldingen voor OCR moet voorbewerken** met Python. Je leert **afbeelding binariseren met Otsu**, **hoe je gescande documenten moet rechtzetten**, en in het algemeen **hoe je OCR-nauwkeurigheid kunt verbeteren** wanneer je **tekst wilt extraheren uit Duitse afbeelding**‑bestanden. Geen poespas, alleen een werkend script dat je vandaag nog kunt kopiëren‑plakken. + +## Wat je nodig hebt + +- **Python 3.9+** (elke recente versie werkt) +- Een OCR‑bibliotheek die een `OcrEngine`‑klasse exposeert – voor de demo gaan we uit van een generiek `ocr`‑pakket. Installeer het met `pip install ocr-lib`. +- Een ruisende Duitse scan (`noisy_german_scan.tif`) die je wilt testen. +- Een basisbegrip van Python‑functies (als je al een `def` hebt geschreven, ben je klaar). + +> **Pro tip:** Als je een andere OCR‑SDK gebruikt (bijv. Tesseract via `pytesseract`), blijven de concepten hetzelfde—pas alleen de methodenamen aan. + +## Overzicht van de oplossing + +1. **Maak een OCR‑engine‑instantie.** +2. **Stel de herkenningstaal in op Duits.** +3. **Bouw een aangepaste voorbewerkings‑pipeline** die rechtzetten, denoising, binariseren (Otsu) en contrast‑stretching omvat. +4. **Koppel de pipeline aan de engine** zodat elke afbeelding er automatisch doorheen gaat. +5. **Voer de OCR uit** op een ruisende Duitse scan. +6. **Print de geëxtraheerde tekst** om het resultaat te verifiëren. + +Hieronder splitsen we elke stap uit, leggen **waarom** het belangrijk is, en tonen de exacte code die je nodig hebt. + +![voorbeeld van hoe afbeeldingen voor OCR voor te bewerken](image.png "voorbeeld van hoe afbeeldingen voor OCR voor te bewerken") + +## Stap 1: Maak een OCR‑engine‑instantie + +Allereerst—zonder een engine gebeurt er niets. Het `OcrEngine`‑object is het toegangspunt dat alle latere verwerking coördineert. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Waarom dit belangrijk is:* Het initialiseren van de engine zet interne bronnen (zoals taalmodellen) klaar en geeft je een schone basis om later een aangepaste pipeline aan te koppelen. + +## Stap 2: Stel de herkenningstaal in op Duits + +OCR‑nauwkeurigheid is sterk afhankelijk van de taal. Door de engine te laten weten dat hij Duits moet verwachten, activeer je de juiste tekenset en het juiste taalmodel. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Als je dit overslaat, kan de engine standaard op Engels staan en umlauts (ä, ö, ü) en het ß‑teken verkeerd herkennen—veelvoorkomende valkuilen bij Duitse scans. + +## Stap 3: Bouw een aangepaste voorbewerkings‑pipeline + +Dit is de kern van **hoe je afbeeldingen voor OCR moet voorbewerken**. We schakelen vier transformaties aan: + +| Transformatie | Wat het doet | Waarom het helpt | +|----------------|--------------|------------------| +| **Deskew** | Roteert de afbeelding terug naar horizontaal (max 5°) | Scans zijn zelden perfect uitgelijnd; deskewing verwijdert de helling die karaktersegmentatie verstoort. | +| **Denoise** | Vermindert willekeurige vlekjes (sterkte 0.7) | Ruis creëert valse randen die de OCR-engine kan interpreteren als tekens. | +| **Binarize (Otsu)** | Converteert naar zwart‑wit met behulp van Otsu's methode | Een schone binaire afbeelding geeft de engine een scherp contrast tussen voorgrond (tekst) en achtergrond. | +| **Contrast Stretch** | Vergroot het dynamisch bereik | Verbeterde leesbaarheid van vage streken, vooral op oude documenten. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Hoe je gescande documenten moet rechtzetten + +De `deskew`‑aanroep hierboven is het concrete antwoord op **hoe je gescande documenten moet rechtzetten**. Intern schat hij de dominante tekstreekhoek via een Hough‑transformatie en roteert de afbeelding terug. Als je documenten meer dan 5° gedraaid zijn, verhoog dan `max_angle`, maar wees voorzichtig met over‑rotatie‑artefacten. + +### Afbeelding binariseren met Otsu + +De regel `binarize(method="otsu")` beantwoordt direct de vraag **binarize image using otsu**. Otsu's algoritme berekent een drempel die de intra‑klasse‑variantie minimaliseert, perfect voor documenten met bimodale histogrammen (donkere tekst vs. lichte achtergrond). + +## Stap 4: Koppel de pipeline aan de engine + +Nu vertellen we de OCR‑engine om elke binnenkomende afbeelding door de pipeline te laten gaan die we zojuist hebben gebouwd. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Waarom dit belangrijk is:* Zonder registratie zou de engine de ruwe scan verwerken, waarbij al het schoonmaken dat we hebben geconfigureerd wordt genegeerd. Deze stap zorgt ervoor dat **hoe je OCR‑nauwkeurigheid kunt verbeteren** door consequent dezelfde voorbewerking toe te passen. + +## Stap 5: Herken tekst uit een ruisende Duitse scan + +Tijd om alles samen te brengen. We voeren de engine een ruisende Duitse afbeelding in en laten hem het zware werk doen. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Als je nieuwsgierig bent naar de prestaties, kun je de aanroep timen: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Stap 6: Output de herkende tekst + +Tot slot printen we de geëxtraheerde string. Dit is het directe antwoord op **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Verwachte output + +Als de voorbeeldscan de zin “Die schnelle braune Füchsin springt über den faulen Hund.” bevat, zie je iets als: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Als de output nog steeds onleesbare tekens bevat, overweeg dan de `denoise`‑sterkte aan te passen of `max_angle` voor het rechtzetten te verhogen. + +## Veelvoorkomende valkuilen & hoe ze op te lossen + +- **Ontbrekend taalmodel:** Het vergeten van `set_recognition_language(Language.GERMAN)` leidt vaak tot ontbrekende umlauts. Controleer deze aanroep. +- **Over‑denoising:** Een sterkte boven 0.9 kan dunne streken wissen, vooral bij oudere lettertypen. Houd je aan 0.5‑0.7 voor de meeste gevallen. +- **Onjuist bestandsformaat:** Sommige OCR‑engines hebben moeite met multi‑page TIFF’s. Splits een meer‑pagina‑document eerst op in enkele pagina‑bestanden. +- **Volgorde van de pipeline:** De hier getoonde volgorde (deskew → denoise → binarize → contrast) is opzettelijk. Binariseren vóór denoising kan ruis vergrendelen; denoise altijd eerst. + +## De pipeline uitbreiden (Wat is de volgende stap?) + +Nu je een solide basis hebt, kun je overwegen om: + +- **Een morfologische opening** toe te voegen om kleine vlekjes te verwijderen (`.morph_open(kernel=3)`). +- **Een taalmodel** te integreren voor post‑processing correctie (`ocr_engine.apply_spellcheck()`). +- **Batch‑verwerking te paralleliseren** voor grote datasets met `concurrent.futures`. + +Al deze uitbreidingen behouden de kern van **hoe je afbeeldingen voor OCR moet voorbewerken** terwijl ze **hoe je OCR‑nauwkeurigheid kunt verbeteren** nog verder verhogen. + +## Conclusie + +We hebben net **hoe je afbeeldingen voor OCR moet voorbewerken** van begin tot eind behandeld: een engine maken, Duitse taal instellen, een pipeline bouwen die **afbeelding binariseren met Otsu**, **hoe je gescande documenten moet rechtzetten**, en uiteindelijk **tekst extraheren uit Duitse afbeelding** met hogere zekerheid. Door de zes stappen hierboven te volgen, zie je een merkbare sprong in herkenningskwaliteit—geen eindeloze handmatige correcties meer. + +Probeer het script met je eigen scans, experimenteer met de parameters, en laat de resultaten voor zich spreken. Vragen over een specifieke voorbewerkings‑tweak? Laat een reactie achter, dan duiken we samen dieper in. + +Happy coding, en moge je OCR altijd accuraat zijn! + + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..261ea31b7 --- /dev/null +++ b/ocr/dutch/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,336 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG-afbeelding met Python – leer hoe je tekst uit een afbeelding + kunt extraheren, een Python OCR‑voorbeeld kunt uitvoeren en zelfs gemakkelijk oude + Griekse tekst kunt lezen. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: nl +og_description: OCR PNG-afbeelding in Python uitgelegd. Deze gids laat zien hoe je + tekst uit een afbeelding kunt extraheren, een Python OCR-voorbeeld kunt uitvoeren + en gemakkelijk Oudgrieks kunt lezen. +og_title: OCR PNG-afbeelding in Python – Complete tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR PNG‑afbeelding in Python – Volledige stap‑voor‑stap gids +url: /nl/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG‑afbeelding in Python – Volledige stapsgewijze handleiding + +Heb je je ooit afgevraagd hoe je **OCR PNG‑afbeeldingen** rechtstreeks vanuit een Python‑script kunt uitvoeren? Misschien heb je een map vol met gescande oude manuscripten en moet je **tekst uit afbeelding**‑bestanden halen zonder alles handmatig te typen. Het goede nieuws is dat je geen doctoraat in computer‑vision nodig hebt—slechts een paar regels code en de juiste bibliotheek, en je leest oude Grieks in enkele seconden. + +In deze tutorial lopen we een **python OCR‑voorbeeld** door dat tekst herkent uit een PNG, de taal instelt op Grieks polytonisch, en het resultaat afdrukt. Aan het einde weet je precies hoe je **afbeeldingstekst herkent**, veelvoorkomende valkuilen aanpakt, en het script aanpast voor andere talen of afbeeldingsformaten. + +## Wat je zult leren + +- Een Python‑OCR‑bibliotheek installeren en configureren (pytesseract + Tesseract OCR) +- Een OCR‑engine‑instantie maken en een PNG‑bestand laden +- De herkenningstaal instellen op Grieks polytonisch zodat je **oud Grieks kunt lezen** +- De herkende tekst weergeven en typische problemen oplossen +- Het script uitbreiden om meerdere PNG’s in batch te verwerken of over te schakelen naar een andere taal + +### Vereisten + +| Vereiste | Waarom het belangrijk is | +|----------|--------------------------| +| Python 3.8+ | Moderne syntax en type‑hints | +| `pytesseract`‑package | Dunne wrapper rond de Tesseract‑engine | +| Tesseract OCR‑binaries (≥ 5.0) | De daadwerkelijke engine die het zware werk doet | +| Griekse taaldata (`grc.traineddata`) | Nodig om **oud Grieks correct te lezen** | +| Een PNG‑afbeelding die je wilt analyseren (bijv. `ancient_greek.png`) | Ons doel voor de **ocr png image**‑demo | + +Je kunt de Python‑kant installeren met: + +```bash +pip install pytesseract Pillow +``` + +En op Ubuntu/macOS voeg je de engine zelf toe: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Vergeet niet de Grieks‑polytonische trainingsdata te downloaden: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Pad kan verschillen; pas `TESSDATA_PREFIX` indien nodig aan.)* + +--- + +## OCR PNG‑afbeelding: maak de engine‑instantie + +Het eerste wat we nodig hebben is een object dat met Tesseract communiceert. In `pytesseract` wordt de engine benaderd via module‑niveau functies, maar voor de duidelijkheid wikkelen we het in een kleine klasse. Dit spiegelt het “engine”‑concept dat je in het oorspronkelijke fragment zag. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Waarom wikkelen?** +- Houdt de publieke API identiek aan het fragment waarmee je begon, waardoor migratie moeiteloos verloopt. +- Maakt het mogelijk om later logging of foutafhandeling toe te voegen zonder de hoofdlogica aan te passen. +- Demonstreert goede OOP‑praktijken—iets waar senior developers waardering voor hebben. + +--- + +## Tekst uit afbeelding halen: stel de taal in op Grieks polytonisch + +Nu we een engine hebben, moeten we aangeven welke taal we verwachten. Grieks polytonisch gebruikt diakritische tekens die niet gedekt worden door de standaard “greek” data, dus wijzen we Tesseract naar het `grc`‑trainedfile. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Wil je ooit **tekst uit afbeelding**‑bestanden in een andere taal extraheren, vervang dan `"grc"` door `"eng"` voor Engels, `"fra"` voor Frans, enzovoort. dezelfde regel werkt voor elke geïnstalleerde taal. + +--- + +## Afbeeldingstekst herkennen: voer de OCR uit op een PNG + +Met de taal ingesteld voeren we de PNG in de engine. Het oorspronkelijke voorbeeld gebruikte een hard‑coded pad; we maken het iets flexibeler door `Path`‑objecten te gebruiken. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tips & randgevallen** + +- **Bestand niet gevonden** – wikkel de aanroep in een `try/except FileNotFoundError` om een vriendelijke melding te geven. +- **Lage resolutie PNG** – overweeg pre‑processing (bijv. resizing, binarisatie) met Pillow vóór OCR. +- **Niet‑Griekse tekst** – Tesseract zal nog steeds proberen te decoderen, maar de nauwkeurigheid daalt sterk. Zorg altijd voor een passende taal. + +--- + +## De herkende tekst weergeven + +Tot slot drukken we het resultaat af. In een echt project schrijf je misschien naar een database, een CSV, of voed je het in een vertaal‑pipeline. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Wanneer je het script uitvoert tegen een duidelijke scan van een oude Griekse inscriptie, zou je iets moeten zien als: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Als de output er rommelig uitziet, controleer dan of het **greek.traineddata**‑bestand in de juiste map staat en of de PNG niet te ruisachtig is. + +--- + +## Volledig werkend voorbeeld (alle stappen in één script) + +Hieronder staat het complete, kant‑klaar script. Sla het op als `ocr_greek.py` en voer `python ocr_greek.py` uit. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Verwachte output** (ingekort voor de duidelijkheid): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Zie je de juiste Griekse tekens, gefeliciteerd—je hebt met succes een **ocr png image**‑operatie in Python uitgevoerd! + +--- + +## Veelgestelde vragen & pro‑tips + +### Hoe verbeter ik de nauwkeurigheid bij een ruisachtige PNG? + +- Converteer de afbeelding naar grijswaarden: `img = img.convert('L')` +- Pas een binaire drempel toe: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Schaal op met `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Deze stappen veranderen vaak een **recognize image text**‑nachtmerrie in een schoon resultaat. + +### Kan ik een hele map met PNG’s verwerken? + +Zeker. Wikkel de `recognize_image`‑aanroep in een `for`‑loop over `Path.glob("*.png")`. Sla elk resultaat op in een dictionary of schrijf naar een CSV voor latere analyse. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Wat als ik alleen cijfers wil extraheren? + +Geef een aangepaste **config**‑string mee aan `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Zo kun je **tekst uit afbeelding**‑bestanden die tabellen, serienummers of tijdstempels bevatten, extraheren. + +### Is er een manier om vertrouwensscores te krijgen? + +Ja—gebruik `pytesseract.image_to_data` dat een TSV met confidence per woord teruggeeft. Je kunt tokens met een lage confidence filteren voordat je de uiteindelijke string samenstelt. + +--- + +## De tutorial uitbreiden + +Nu je de basis onder de knie hebt, kun je de volgende gerelateerde onderwerpen verkennen: + +- **Batch‑OCR met multiprocessing** – versnel grote corpora van PNG’s. +- **Hybride OCR + NLP‑pipelines** – vertaal automatisch het geëxtraheerde oude Grieks naar modern Engels. +- **Alternatieve engines** – probeer `easyocr` of `opencv`‑gebaseerde methoden voor specifieke use‑cases. +- **Cloud‑OCR‑diensten** – Google Vision, Azure Computer Vision, of AWS Textract voor serverless scaling. + +Elk van deze bouwt voort op het kern‑**python ocr example** dat we net behandeld hebben, zodat je je comfortabel voelt om dieper te duiken. + +--- + +## Conclusie + +We hebben een simpel fragment omgevormd tot een robuuste **ocr png image**‑workflow in Python. Door een `OcrEngine` te maken, de taal in te stellen op Grieks polytonisch, een PNG te voeren en het resultaat af te drukken, weet je nu hoe je **tekst uit afbeelding**‑bestanden kunt **herkennen**, **afbeeldingstekst** kunt lezen, en zelfs **oud Grieks** kunt ontcijferen. + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementaties in je eigen projecten te verkennen. + +- [Tekst extraheren uit afbeelding met Aspose OCR – Stapsgewijze handleiding](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Hoe drempelwaarde instellen in OCR‑afbeeldingsherkenning](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Tekst herkennen in afbeelding met Aspose OCR voor meerdere talen](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/dutch/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..5e6972b0b --- /dev/null +++ b/ocr/dutch/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR-tutorial die laat zien hoe je afbeeldings­tekst herkent, OCR + met hoge resolutie uitvoert en Spaanse tekst extraheert met GPU-versnelde OCR. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: nl +og_description: Python OCR‑tutorial die je stap voor stap begeleidt bij het herkennen + van tekst in afbeeldingen, OCR met hoge resolutie en het extraheren van Spaanse + tekst met GPU‑versnelling. +og_title: Python OCR-tutorial – GPU-versnelde teksterkenning +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR‑tutorial – Herken afbeeldingstekst met GPU‑versnelling +url: /nl/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Herken afbeeldingstekst met GPU‑versnelling + +Heb je je ooit afgevraagd hoe je **afbeeldingstekst** kunt herkennen in een Python‑script zonder uren te besteden aan het afstellen van instellingen? Je bent niet de enige. In deze **python ocr tutorial** laten we je een schone, end‑to‑end manier zien om Spaanse tekst uit een hoge‑resolutie foto te extraheren, en we voegen GPU‑versnelling toe zodat het proces bliksemsnel verloopt. + +Beschouw het als een snelle koffiepauze‑demo die je later kunt uitbreiden tot een productie‑klare pipeline. Aan het einde van deze gids heb je een uitvoerbaar programma dat **high resolution OCR** uitvoert, een CUDA‑enabled GPU benut, en de exacte Spaanse tekens oplevert die je nodig hebt. + +## Wat je zult leren + +- Hoe je een moderne OCR‑bibliotheek installeert en importeert die GPU‑versnelling ondersteunt. +- Hoe je een OCR‑engine‑instantie maakt en instelt om **afbeeldingstekst** in het Spaans te **herkennen**. +- Hoe je **gpu accelerated OCR** inschakelt voor enorme snelheidswinst bij hoge‑resolutie bestanden. +- Hoe je edge‑cases afhandelt, zoals ontbrekende CUDA‑drivers of een fallback naar CPU. +- Tips om de nauwkeurigheid te verbeteren wanneer je **spanish text** moet **extraheren** uit ruisende scans. + +### Vereisten + +- Python 3.9+ (de code werkt ook op 3.10 en nieuwer). +- Een CUDA‑compatibele GPU (optioneel maar sterk aanbevolen). +- Basiskennis van pip en virtuele omgevingen. + +Als je een van deze mist, werkt de tutorial nog steeds — sla gewoon de GPU‑stap over en de bibliotheek valt automatisch terug op CPU. + +--- + +## Python OCR Tutorial: Installeer de vereiste pakketten + +Allereerst hebben we een degelijke OCR‑engine nodig. Voor deze tutorial gebruiken we het open‑source **`easyocr`**‑pakket, dat ingebouwde GPU‑ondersteuning biedt wanneer een compatibel apparaat wordt gedetecteerd. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Als je PyTorch al geïnstalleerd hebt, zorg er dan voor dat het overeenkomt met je CUDA‑versie (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Mismatchende versies zijn een veelvoorkomende oorzaak van “GPU not found”‑fouten. + +--- + +## Stap 1: Maak een OCR‑engine‑instantie + +Nu starten we de engine. EasyOCR noemt zijn hoofdklasse `Reader`. De constructor accepteert een lijst met taalcodes; we geven `"es"` op voor Spaans. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Waarom dit belangrijk is:* Door de taal vooraf te declareren laadt de engine alleen de benodigde neurale‑netwerk‑gewichten, wat geheugen bespaart en de inferentie versnelt — vooral handig wanneer je later werkt met **high resolution OCR**. + +--- + +## Stap 2: Bereid een hoge‑resolutie afbeelding voor + +Hoge‑resolutie afbeeldingen geven het model meer pixels om mee te werken, wat meestal resulteert in betere tekenherkenning. Laten we aannemen dat je een bestand hebt genaamd `high_res_spanish.png` in een map genaamd `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Als je geen hoge‑resolutie voorbeeld bij de hand hebt, kun je er gratis een downloaden van Unsplash of een synthetische afbeelding genereren met Pillow. Het belangrijkste is om de DPI boven de 300 te houden voor de beste resultaten. + +--- + +## Stap 3: Schakel GPU‑versnelling in (optioneel maar aanbevolen) + +EasyOCR probeert al de GPU te gebruiken wanneer je `gpu=True` instelt. Het is echter goed om te verifiëren dat het apparaat daadwerkelijk wordt gebruikt, vooral op systemen met meerdere GPU’s. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Waarom dit controleren?* Als het script stilletjes terugvalt op CPU, vraag je je misschien af waarom een bewerking van 5 seconden ineens 30 seconden duurt. Deze kleine controle maakt het gedrag transparant en houdt je **gpu accelerated OCR**‑pipeline voorspelbaar. + +--- + +## Stap 4: Voer high‑resolution OCR uit en herken afbeeldingstekst + +Nu het leuke deel — het daadwerkelijk lezen van de tekst. EasyOCR’s `readtext`‑methode retourneert een lijst van tuples met de begrenzings‑box, de herkende string en een confidence‑score. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Als je de ruwe string zonder coördinaten nodig hebt, stel `detail=0` in. Voor de meeste **recognize image text**‑use‑cases geeft de standaard (`detail=1`) je genoeg context om later post‑processing toe te passen. + +--- + +## Stap 5: Extraheer Spaanse tekst en maak de output schoon + +Omdat we EasyOCR om Spaans hebben gevraagd, zijn de geretourneerde strings al in die taal. Toch wil je ze misschien concatenëren, witruimte verwijderen of low‑confidence detecties filteren. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Wat als de confidence laag is?** Je kunt de drempel verlagen (met risico op ruis) of de afbeelding voorbewerken (contrast verhogen, binariseren of rechtzetten). Deze trucjes zijn gebruikelijk bij **high resolution OCR** op gescande documenten. + +--- + +## Stap 6: Edge‑cases en prestatie‑tweaks afhandelen + +Zelfs de best getrainde modellen struikelen over een paar scenario’s. Hieronder staan een paar snelle oplossingen die je in het script kunt plakken. + +### 6.1 Fallback wanneer er geen GPU aanwezig is + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling van zeer grote afbeeldingen + +Als je afbeelding groter is dan 4000 × 4000 px, kun je GPU‑geheugen tekortkomen. Down‑sample proportioneel terwijl je de DPI behoudt: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Deze snippets houden het script robuust, of je nu op een workstation of een bescheiden laptop werkt. + +--- + +## Volledig werkend voorbeeld + +Alles bij elkaar, hier is het complete script dat je direct kunt copy‑pasten en uitvoeren: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Verwachte output (voorbeeld):** + + + +## Wat kun je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/dutch/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..a94825d8d --- /dev/null +++ b/ocr/dutch/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-06 +description: herken tekst uit een afbeelding met Python OCR‑engine. Leer hoe je de + OCR‑engine in Python configureert en tekst uit een afbeelding haalt met cloudverwerking + in enkele minuten. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: nl +og_description: Herken tekst uit een afbeelding met de Python OCR‑engine. Deze gids + laat zien hoe je de OCR‑engine in Python configureert en efficiënt tekst uit een + afbeelding haalt. +og_title: Tekst herkennen uit afbeelding in Python – Complete installatiehandleiding +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: tekst herkennen uit afbeelding in Python – Volledige OCR‑engine installatiegids +url: /nl/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# recognize text from image in Python – Complete Setup Tutorial + +Heb je je ooit afgevraagd hoe je **tekst uit een afbeelding** kunt herkennen met slechts een paar regels Python? Je bent niet de enige. Of je nu een bon‑scanner, een documentdigitaliserer of een simpel hobbyproject bouwt, tekst uit een afbeelding kunnen extraheren is een vaardigheid die snel vruchten afwerpt. + +In deze tutorial lopen we het volledige proces door – beginnend met een **configure OCR engine python**‑achtige setup, via cloud‑authenticatie, tot het uiteindelijk **extraheren van tekst uit een afbeelding** met een betrouwbaar resultaat. Geen magie, alleen duidelijke stappen die je vandaag nog kunt copy‑pasten en uitvoeren. + +## What You’ll Learn + +- Hoe je de benodigde OCR‑bibliotheek installeert en importeert. +- De exacte commando’s om **configure OCR engine python** voor cloudverwerking in te stellen. +- Een complete, uitvoerbare script dat **recognize text from image** en de output afdrukt. +- Tips voor het omgaan met veelvoorkomende valkuilen zoals ontbrekende API‑sleutels of niet‑ondersteunde afbeeldingsformaten. +- Ideeën voor de volgende stap, zoals batchverwerking en een lokale fallback. + +### Prerequisites + +- Python 3.8+ geïnstalleerd op je machine. +- Een internetverbinding (het voorbeeld maakt gebruik van een cloud‑gebaseerde OCR‑service). +- Een geldige API‑sleutel van de OCR‑provider (je ziet later waar je deze moet invoegen). + +Als je dat allemaal hebt, duiken we erin – zonder poespas, alleen een praktische gids die werkt. + +--- + +## Step 1: Install the OCR Library and Import It + +Voordat je **configure OCR engine python** kunt uitvoeren, heb je de bibliotheek nodig die met de cloudservice communiceert. In ons voorbeeld gebruiken we een fictief maar representatief pakket genaamd `ocrcloud`. Vervang dit door het echte pakket dat jij gebruikt (bijv. `easyocr`, `google-cloud-vision`, etc.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Why this matters:** Importeren van de class geeft je toegang tot methoden zoals `use_cloud()` en `set_api_key()`. Zonder de import zou de rest van het script een `NameError` veroorzaken. + +*Pro tip:* Pin de versie in je `requirements.txt` (`ocrcloud==2.1.0`) om onverwachte breaking changes later te voorkomen. + +--- + +## Step 2: Create and **configure OCR engine python** for Cloud Mode + +Nu voeren we daadwerkelijk **configure OCR engine python** uit. De engine start standaard in lokale modus; overschakelen naar cloud‑modus laat je zware beeldanalyse uitbesteden aan krachtige servers. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explanation:** +- `OcrEngine()` maakt een nieuw engine‑object aan – zie het als een leeg canvas. +- `use_cloud(True)` zet een schakelaar om, waardoor de engine afbeeldingen via HTTPS verstuurt in plaats van ze lokaal te verwerken. Dit is cruciaal voor hoge nauwkeurigheid bij complexe lettertypen of lage‑resolutie foto’s. + +--- + +## Step 3: Authenticate with Your Cloud API Key + +De meeste cloud‑OCR‑services vereisen een API‑sleutel. Deze stap laat zien hoe je de credential veilig injecteert. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Security note:** Hard‑code de sleutel nooit in een openbaar repo. In productie haal je deze uit een omgevingsvariabele: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Step 4: **recognize text from image** – Send a Remote Image for Processing + +Met de engine geconfigureerd, kunnen we eindelijk **recognize text from image**. De methode `recognize_image()` accepteert een pad of URL en retourneert een object met de geëxtraheerde tekst. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**What happens under the hood?** +De afbeeldingsbytes worden geüpload naar het endpoint van de provider, verwerkt door een deep‑learning model, en de platte‑tekst wordt teruggestreamd. Als de afbeelding groot is, kan de service automatisch downscalen om het proces te versnellen. + +--- + +## Step 5: Output the **extract text from image** Result + +Nu de OCR‑service zijn werk heeft gedaan, printen we simpelweg de tekst. In echte toepassingen sla je deze misschien op in een database of geef je hem door aan een andere functie. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Expected output:** (example) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Als de output er rommelig uitziet, controleer dan of de afbeelding scherp is en of je het juiste taalmodel hebt geselecteerd (veel services laten je `engine.set_language("en")` specificeren). + +--- + +## Handling Edge Cases & Common Pitfalls + +### 1. Missing or Invalid API Key +Als je een authenticatiefout ziet, zorg dan dat: +- De sleutel actief is en niet verlopen. +- Hij correct uit de omgeving wordt gelezen. +- Je netwerk uitgaand HTTPS‑verkeer toestaat. + +### 2. Unsupported Image Formats +De meeste OCR‑API’s accepteren JPEG, PNG en PDF. Een BMP of TIFF kan een “format not supported”‑reactie veroorzaken. Converteer indien nodig met Pillow: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Rate Limits +Cloud‑services limiteren vaak het aantal verzoeken per minuut. Als je een limiet bereikt, implementeer dan exponential back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Fallback to Local OCR +Als de cloud down is, kun je terugschakelen: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Een fallback houdt je app veerkrachtig. + +--- + +## Full Working Example + +Alles bij elkaar, hier is een script dat je nu kunt draaien (vervang alleen de placeholder‑waarden). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Run it:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Je zou de geëxtraheerde tekst in de console moeten zien, wat bevestigt dat je succesvol **recognize text from image** en **extract text from image** hebt uitgevoerd met een goed geconfigureerde **configure OCR engine python** workflow. + +--- + +## Conclusion + +We hebben zojuist een compleet end‑to‑end proces doorlopen waarmee je **recognize text from image** in Python kunt uitvoeren, van het installeren van de bibliotheek tot het authenticeren bij een cloudservice en uiteindelijk **extract text from image** met één functieaanroep. Door **configure OCR engine python** op de juiste manier te doen, krijg je zowel flexibiliteit (cloud vs. lokaal) als betrouwbaarheid (goede foutafhandeling). + +Wat nu? Probeer een map met bonnen batch‑gewijs te verwerken, voeg taaldetectie toe, of experimenteer met PDF’s als invoer. De mogelijkheden zijn eindeloos zodra je de basis onder de knie hebt. + +Happy coding, and feel free to drop any questions in the comments—nothing beats learning together! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f2bb5c230 --- /dev/null +++ b/ocr/dutch/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,330 @@ +--- +category: general +date: 2026-06-06 +description: Voer OCR uit op een afbeelding met Python en bekijk de vertrouwensscores. + Leer hoe je woorden met een lage vertrouwensscore filtert, drempels instelt en randgevallen + afhandelt. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: nl +og_description: Voer OCR uit op een afbeelding in Python, controleer de vertrouwensniveaus + en filter woorden met een lage vertrouwensscore. Deze tutorial leidt je stap voor + stap door een volledig, uitvoerbaar voorbeeld. +og_title: OCR uitvoeren op afbeelding met Python – volledige gids +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Voer OCR uit op een afbeelding met Python – Complete stap‑voor‑stap gids +url: /nl/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR uitvoeren op afbeelding met Python – Complete stap‑voor‑stap gids + +Heb je ooit **OCR uitvoeren op afbeelding** bestanden nodig gehad, maar wist je niet hoe je er betrouwbare tekst uit kon halen? Je bent niet de enige—veel ontwikkelaars stuiten op hetzelfde probleem wanneer de geëxtraheerde woorden er wankel uitzien en de vertrouwensscore een mysterie is. + +In deze gids duiken we direct in een werkende oplossing: je ziet hoe je **OCR uitvoeren op afbeelding** doet, de algehele vertrouwensscore leest, en eventuele woorden met een lage vertrouwensscore eruit haalt die handmatige controle nodig hebben. Aan het einde heb je een herbruikbaar script, begrijp je waarom elke regel belangrijk is, en weet je hoe je de vertrouwensdrempel voor je eigen projecten kunt aanpassen. + +## Wat deze tutorial behandelt + +We lopen de volledige workflow door—van het laden van een afbeelding tot het afdrukken van een nette rapportage van woorden die onder een vertrouwenspercentage van 80 % vielen. Onderweg bespreken we: + +* Kiezen van een solide OCR-engine (we gebruiken **EasyOCR**, een populaire Python OCR-bibliotheek) +* Interpreteren van het `confidence`‑attribuut dat elk OCR-resultaat retourneert +* Filteren van woorden met een aangepaste **OCR confidence threshold** +* Het script uitbreiden voor batchverwerking of alternatieve engines zoals **pytesseract** + +Ervaring met OCR is niet vereist, alleen een basiskennis van Python en een werkende omgeving (Python 3.9+ aanbevolen). + +Klaar om vage screenshots om te zetten in schone, doorzoekbare tekst? Laten we beginnen. + +--- + +## ## Hoe OCR uitvoeren op afbeelding met Python + +Het hart van de tutorial is een drie‑stappen‑fragment dat de code die je al zag weerspiegelt. Hieronder splitsen we elke regel, leggen we het waarom uit, en geven we je een volledig, kant‑en‑klaar script. + +### Stap 1: Installeer en importeer de OCR-engine + +Zorg er eerst voor dat de OCR-bibliotheek beschikbaar is. **EasyOCR** werkt direct uit de doos voor veel talen en geeft je een vertrouwensscore per woord. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Waarom EasyOCR?* Het bevat een deep‑learning model dat getraind is op diverse datasets, waardoor je doorgaans hogere vertrouwenswaarden krijgt dan met de oudere Tesseract-engine, vooral bij afbeeldingen van gemengde kwaliteit. + +> **Pro tip:** Als je in een beperkte omgeving werkt (bijv. een kleine Docker‑container), kan `pytesseract` lichter zijn, maar verlies je een deel van de moderne nauwkeurigheid die EasyOCR biedt. + +### Stap 2: Voer OCR uit op de afbeelding + +Nu voeren we daadwerkelijk **OCR uitvoeren op afbeelding** uit. De `recognize_image`‑methode uit het oorspronkelijke voorbeeld wordt vervangen door EasyOCR’s `readtext`‑aanroep, die een lijst van `(bbox, text, confidence)`‑tuples retourneert. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Elke invoer in `ocr_results` ziet er als volgt uit: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Het derde element (`0.92` in het voorbeeld) is de vertrouwensscore, variërend van 0 tot 1. + +### Stap 3: Samenvatting van de algehele vertrouwensscore + +In tegenstelling tot het eerdere fragment dat één `confidence`‑attribuut afdrukte, geeft EasyOCR een vertrouwensscore per woord. Om een algemeen beeld te krijgen, nemen we hun gemiddelde: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Waarom gemiddeld?* Het geeft je een snelle gezondheidscheck—als de algehele vertrouwensscore onder, bijvoorbeeld, 70 % valt, moet je waarschijnlijk de afbeelding verbeteren (betere verlichting, voorbewerking, enz.). + +### Stap 4: Lijst met woorden met lage vertrouwensscore + +Nu volgt het deel dat direct antwoord geeft op de vereiste “lijst woorden waarvan de vertrouwensscore onder de gewenste drempel ligt”. We stellen standaard een **OCR confidence threshold** van 0.80 (80 %) in, maar je kunt deze aanpassen. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +De lus drukt elk woord af dat niet door de drempel kwam, samen met zijn percentage vertrouwensscore. Dit is de exacte analogie van de oorspronkelijke `for recognized_word in recognition_result.words`‑lus, maar werkt nu met het outputformaat van EasyOCR. + +## ## Begrijpen van OCR‑vertrouwensscores + +Vertrouwen is geen magisch getal; het is de schatting van het model hoe zeker het is van een bepaalde transcriptie. Hier zijn een paar zaken om in gedachten te houden: + +| Situatie | Typische vertrouwensscore | Wat te doen | +|-----------|-------------------|------------| +| Duidelijke, hoge‑resolutie scan | 0.95 – 1.00 | Geen extra werk nodig | +| Lichte onscherpte of ongelijke verlichting | 0.80 – 0.94 | Overweeg lichte voorbewerking (contrastverhoging) | +| Zware ruis, gedraaide tekst | < 0.70 | Pas beeldvoorbewerking toe (ontkanten, ruisverwijdering) of schakel over naar een andere OCR-engine | + +> **Let op:** Sommige talen (bijv. cursieve handschrift) leveren van nature lagere scores op. Pas de drempel dienovereenkomstig aan. + +### Randgevallen & Variaties + +1. **Batchverwerking** – Als je **OCR uitvoeren op afbeelding** bestanden in bulk moet uitvoeren, wikkel dan de bovenstaande logica in een lus die over een map iterereert. +2. **Meerdere talen** – Geef een lijst zoals `['en', 'fr']` door aan `easyocr.Reader` en de engine detecteert beide. +3. **Alternatieve engines** – Wil je **pytesseract** proberen? Vervang het lezer‑blok door: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Je moet dan per‑karakter vertrouwensscores aggregeren tot per‑woord waarden—een beetje extra werk maar haalbaar. +4. **Voorbewerkings‑trucs** – Het toepassen van OpenCV-filters (`cv2.threshold`, `cv2.GaussianBlur`) kan de vertrouwensscore voor ruisende scans verhogen. + +## ## Volledig, kant‑klaar script + +Hieronder staat het volledige Python‑bestand dat je in je project kunt plaatsen. Sla het op als `ocr_report.py` en voer `python ocr_report.py` uit. Zorg ervoor dat het afbeeldingspad naar een bestaand bestand wijst. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Verwachte output** (je cijfers zullen variëren): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Als elk woord de 80 % drempel haalt, zie je in plaats daarvan het vriendelijke bericht “All words meet the confidence threshold.”. + +## ## Veelgestelde vragen (FAQ) + +**Q: Werkt dit met PDF’s?** +A: Niet direct. Converteer elke PDF‑pagina eerst naar een afbeelding (bijv. met `pdf2image`) en voer vervolgens de PNG/JPEG in het script. + +**Q: Mijn vertrouwenscijfers zijn allemaal laag—wat kan ik doen?** +A: Probeer beeldvoorbewerking: verhoog het contrast, verwijder achtergrondruis, of roteer de afbeelding naar een horizontale basislijn. EasyOCR accepteert ook een `contrast_ths`‑parameter die je kunt aanpassen. + +**Q: Kan ik de resultaten exporteren naar CSV?** +A: Zeker. Na de low‑confidence‑lus schrijf je `ocr_results` naar een `csv.DictWriter` waarbij elke rij `text`, `confidence` en de coördinaten van de begrenzings‑box bevat. + +**Q: Is er een GPU‑versnelde versie?** +A: EasyOCR gebruikt automatisch CUDA als er een compatibele GPU en PyTorch geïnstalleerd zijn. Controleer met `torch.cuda.is_available()` voordat je het script uitvoert. + +## Conclusie + +We hebben net **OCR uitvoeren op afbeelding** gedaan met Python, de algehele vertrouwensscore geïnspecteerd, en eventuele woorden met lage vertrouwensscore geïsoleerd die een + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe drempelwaarde in OCR‑beeldherkenning instellen](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Hoe Aspose OCR gebruiken voor JSON‑resultaat in beeldherkenning](/ocr/english/net/text-recognition/get-result-as-json/) +- [Tekst extraheren uit afbeelding – OCR‑optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/english/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..bb8d29089 --- /dev/null +++ b/ocr/english/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: en +og_description: Extract text from image with Python OCR quickly. Learn multilingual + image OCR, auto detect language OCR, and how to extract OCR text step by step. +og_title: Extract Text from Image Using Python OCR – Complete Guide +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Extract Text from Image Using Python OCR – Complete Guide +url: /python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Image Using Python OCR – Complete Guide + +Ever needed to **extract text from image** but weren’t sure which library could handle multiple languages automatically? You’re not alone—developers constantly ask *how to extract OCR text* when dealing with international documents, receipts, or scanned flyers. In this tutorial we’ll walk through a practical Python example that not only extracts text from an image but also **detects the language** on the fly, making multilingual image OCR a breeze. + +We’ll cover everything from installing the OCR package to enabling **auto detect language OCR**, running the engine on a sample picture, and finally printing both the detected language and the extracted string. By the end you’ll have a reusable snippet you can drop into any project, whether you’re building a translation pipeline or a data‑ingestion service. + +## Extract Text from Image – Setting Up the Environment + +Before we dive into code, make sure your workstation meets these minimal requirements: + +- Python 3.8 or newer (the library uses type hints that older versions ignore) +- `pip` for package management +- An image file that contains text in at least two different languages (e.g., English + Spanish) + +You’ll also need the OCR library that powers this demo. For the sake of this guide we’ll use the fictional `ocr` package, which mirrors popular real‑world tools like Tesseract or EasyOCR but offers a clean Python API. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** If you run into permission errors, prepend the command with `python -m` or use a virtual environment—keeps your global site‑packages tidy. + +## Create OCR Engine Instance + +Now that the library is ready, the first logical step is to **create an OCR engine instance**. Think of the engine as a smart scanner that you can configure before feeding it images. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Why do we instantiate the engine separately instead of calling a static method? The engine object holds configuration state (like language preferences) that you might want to reuse across many images, saving you the overhead of re‑initializing it each time. + +## Enable Auto Detect Language OCR + +Most OCR tools require you to specify a language code—`eng` for English, `spa` for Spanish, and so on. Manually guessing the language defeats the purpose of a **multilingual image OCR** workflow. Luckily, the `ocr` package offers an *auto detect language OCR* mode that inspects the image and selects the best language model behind the scenes. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Enabling **detect language OCR** this way means you won’t have to maintain a long list of language codes. The engine will try to match the script it sees—Latin, Cyrillic, Han, etc.—and load the appropriate model automatically. + +## Perform Multilingual Image OCR + +With the engine primed, it’s time to actually **extract text from image**. The method `recognize_image` accepts a file path and returns a result object containing both the raw text and the language that was detected. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +If you’re wondering *how to extract OCR text* from a PDF instead of a PNG, the same engine offers `recognize_pdf`—just swap the method name. The underlying detection logic stays identical, so you benefit from the same **auto detect language OCR** feature. + +## Display Detected Language and Extracted Text + +Finally, we output what the engine discovered. The result object exposes `detected_language` (a BCP‑47 tag like `en` or `es`) and `text`, which holds the raw OCR output. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Running the script on our sample image should produce something similar to: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Notice how the engine correctly identified English as the primary language, yet still captured the Spanish line—exactly what you expect from a robust **multilingual image OCR** solution. + +### What If Detection Fails? + +Sometimes the OCR engine might fall back to a default language (usually English) if the image is blurry or the script is too exotic. In those cases you can force a language list: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +But remember, forcing languages defeats the convenience of **auto detect language OCR**, so use it only when you have a known subset of languages. + +## Common Pitfalls and How to Extract OCR Text Reliably + +Even with auto‑detection, a few hiccups can trip you up: + +1. **Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale or request a higher‑resolution scan. +2. **Noise and compression artifacts** – Apply a simple threshold filter (`opencv` or `Pillow`) before feeding the image to the engine. +3. **Mixed scripts on one page** – Some engines struggle with simultaneous Latin and CJK characters. Split the page into regions and run separate recognitions if needed. + +Addressing these issues dramatically improves the quality of the **extract text from image** process, especially when dealing with real‑world, multilingual documents. + +## Full Working Example + +Below is the complete, ready‑to‑run script that combines all the steps we discussed. Save it as `multilingual_ocr.py` and execute it from the command line. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Expected output** (assuming the sample image contains English and Spanish text): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Feel free to replace `multilang_page.png` with any picture that contains text in other languages—thanks to **auto detect language OCR**, the script will still give you a sensible language tag and the corresponding text. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Conclusion + +You now know exactly **how to extract OCR text** from an image, how to enable **auto detect language OCR**, and how to handle **multilingual image OCR** scenarios with minimal code. By creating an OCR engine instance, turning on automatic language detection, and calling `recognize_image`, you can reliably pull out both the language identifier and the raw text. + +What’s next? Try feeding the extracted strings into a translation API, store them in a searchable database, or combine multiple pages into a single PDF report. You could also experiment with different OCR back‑ends (Tesseract, EasyOCR, Google Vision) while keeping the same high‑level workflow—thanks to the consistent **detect language OCR** interface. + +If you run into any quirks, revisit the “Common Pitfalls” section or tweak the image preprocessing steps. Happy coding, and may your next project be full of correctly‑detected, perfectly‑extracted text! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/english/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..5635c875d --- /dev/null +++ b/ocr/english/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-06-06 +description: Extract text from images pdf using Python OCR. Learn how to convert scanned + documents to text quickly with async batch recognition. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: en +og_description: Extract text from images pdf with Python. This step‑by‑step guide + shows how to convert scanned documents to text using async OCR. +og_title: Extract Text from Images PDF – Python OCR Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Extract Text from Images PDF – Python Guide to Convert Scanned Documents to + Text +url: /python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Images PDF – Python Guide to Convert Scanned Documents to Text + +Ever needed to **extract text from images pdf** without spending hours re‑typing? In this guide we'll show you how to **convert scanned documents to text** using a simple asynchronous OCR workflow in Python. + +If you’ve ever stared at a stack of scanned PDFs and thought, “There’s got to be a faster way,” you’re in the right place. We'll walk through every line of code, explain why each piece matters, and even cover a few edge cases you might run into. + +## What You’ll Learn + +- How to spin up an OCR engine and set the recognition language. +- The mechanics of feeding a mixed list of PNGs and PDFs into a batch recognizer. +- Running the OCR job asynchronously so your app stays responsive. +- Pulling the results back, pairing them with their source files, and printing clean output. + +**Prerequisites**: Python 3.8+, a basic understanding of `asyncio` or `concurrent.futures`, and an OCR library that exposes an `OcrEngine` class similar to the one in the example (e.g., Aspose.OCR, Tesseract wrapper, or a custom wrapper). No heavy setup required—just install the library and you’re good to go. + +![extract text from images pdf](https://example.com/placeholder.png "Screenshot of OCR output – extract text from images pdf") + +## Extract Text from Images PDF – Setting Up the OCR Engine + +The first thing you need is an OCR engine instance configured for the language of your documents. In our case we’ll use French, but you can swap it out for any supported language. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Why this matters**: Setting the language up front dramatically improves accuracy. The engine uses language‑specific dictionaries and character models; feeding it the wrong language is a common source of garbled output. + +## Prepare the File List – Images and PDFs Together + +Our batch recognizer can handle both raster images (`.png`, `.jpg`) and PDF containers. Just feed a plain Python list of file paths. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: Keep the list flat; the engine will internally unpack each PDF page into images before recognition. If you have thousands of files, consider chunking the list into smaller batches to avoid memory spikes. + +## Kick Off Asynchronous Batch Recognition + +Instead of blocking the main thread, we launch the OCR job in the background. The method returns a `Future` that will eventually hold a list of `OcrResult` objects. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**How it works**: Under the hood the engine spawns a thread pool (or an async task, depending on the implementation). This lets you continue doing other work—like updating a UI, fetching more files, or logging progress—while the heavy lifting happens elsewhere. + +## Do Something Useful While OCR Runs + +A common mistake is to sit idle and poll the future in a tight loop. Instead, you can perform any unrelated work. For demonstration, we’ll just print a status line. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Gather Results Once the Future Completes + +When you’re ready to collect the OCR output, use `as_completed` from `concurrent.futures`. This pattern works whether you have one future or many. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**What you’ll see**: Each file path followed by the extracted plain‑text representation. For PDFs, `result.text` contains the concatenated text of every page. + +### Expected Output (example) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +If you notice missing characters, double‑check that the language you set matches the document language, and consider pre‑processing the images (deskew, increase contrast) before feeding them to the engine. + +## Handling Edge Cases and Common Pitfalls + +| Situation | What to Do | +|-----------|------------| +| **Mixed languages** | Run a language‑detection pass first, then instantiate separate engines per language. | +| **Huge PDFs (> 100 MB)** | Split the PDF into individual pages on disk (e.g., using `PyPDF2`) and feed them as separate entries. | +| **Non‑Latin scripts** | Ensure the OCR library includes the required language pack; some libraries need you to download additional data files. | +| **Performance bottleneck** | Increase the thread pool size (`engine.set_thread_pool_size(8)`) or switch to a GPU‑accelerated backend if available. | +| **Missing text in low‑resolution images** | Pre‑process with OpenCV: `cv2.resize`, `cv2.threshold`, and `cv2.medianBlur` to improve readability. | + +## Full Working Example (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Save this as `extract_text_async.py`, replace `YOUR_DIRECTORY` with the path to your files, install the OCR package (`pip install your-ocr-lib`), and run `python extract_text_async.py`. You should see the console output illustrated earlier. + +## Next Steps – Going Beyond Basic Extraction + +- **Post‑processing**: Strip extra whitespace, normalize Unicode (`unicodedata.normalize`), or run a spell‑checker to clean up OCR noise. +- **Structured output**: Export results to CSV, JSON, or directly into a database for downstream search. +- **Parallel batches**: If you have hundreds of files, spin up multiple futures and use a queue to keep the CPU busy without overwhelming memory. +- **Integrate with web frameworks**: Hook this script into a Flask or FastAPI endpoint to provide on‑demand OCR as a service. + +--- + +### TL;DR + +You now know how to **extract text from images pdf** with a minimal Python script that runs OCR asynchronously, letting you **convert scanned documents to text** while your program stays responsive. Play with the language settings, batch sizes, and pre‑processing tricks to squeeze out every last character accuracy. + +Got a twist you’d like to share—maybe OCR on handwritten notes or a cloud‑based service? Drop a comment, and happy coding! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Images Using Aspose.OCR – Allowed Characters](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/english/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..af2d216fb --- /dev/null +++ b/ocr/english/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: How to OCR PDF using Python, extract text from PDF, convert scanned PDF + text, and change OCR language in just a few lines of code. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: en +og_description: 'How to OCR PDF with Python: a practical guide that shows you how + to extract text from PDF, convert scanned PDF text, and change OCR language effortlessly.' +og_title: How to OCR PDF in Python – Full Programming Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: How to OCR PDF in Python – Complete Step‑by‑Step Guide +url: /python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to OCR PDF in Python – Complete Step‑by‑Step Guide + +Ever wondered **how to OCR PDF** files without paying for pricey SaaS tools? You're not the only one. Whether you're digitizing old books, pulling data from invoices, or just need searchable text from a scanned report, mastering PDF OCR in Python can save you hours of manual copying. + +In this tutorial we'll walk through a concise, working example that **extracts text from PDF**, shows you how to **convert scanned PDF text** into editable strings, and even demonstrates how to **change OCR language** if your document isn’t in English. By the end you’ll have a reusable snippet that you can drop into any project. + +## Prerequisites & Setup + +Before we dive in, make sure you have: + +- Python 3.8+ installed (the code works on 3.9, 3.10, and newer) +- The `ocr` package that provides the `OcrEngine` class (you can install it via `pip install ocr-lib` – replace with the real package name you use) +- A PDF file you want to process; for the demo we’ll use `high_res_book.pdf` placed in a folder called `YOUR_DIRECTORY` + +If you’re using a virtual environment (highly recommended), activate it first: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** Keep your PDF files under a dedicated `data/` directory to avoid path‑related headaches later. + +## Step 1: Create an OCR Engine Instance (How to OCR PDF – Initialization) + +The very first thing you need to do when you want to **perform OCR on PDF** files is instantiate the engine. Think of the engine as the brain that will read each page, interpret the glyphs, and hand you back plain text. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Why this matters: without an engine you have no context for language settings, rendering options, or PDF handling. The `OcrEngine` object holds all those defaults and lets you tweak them later. + +## Step 2: Set the Recognition Language (Change OCR Language) + +Most OCR libraries default to English, but what if your document is in French, German, or even Japanese? Changing the language is as simple as calling `set_recognition_language`. This satisfies the **change OCR language** requirement and ensures higher accuracy. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Why you might need this:** A multilingual archive often contains mixed‑language pages. Switching languages on the fly prevents mis‑recognition of characters like “ß” or “ñ”. + +## Step 3: Configure PDF Rendering Options (Convert Scanned PDF Text Effectively) + +When dealing with scanned PDFs, resolution and color mode dramatically affect OCR quality. Rendering at 300 DPI in grayscale is a sweet spot for most documents—high enough to capture detail but low enough to keep memory usage reasonable. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +The chained calls might look fancy, but they’re just a fluent API that returns the same options object each time. If you need color (e.g., for colored diagrams), replace `"grayscale"` with `"color"`. + +## Step 4: Recognize the PDF and Grab the First Page Text (Extract Text from PDF) + +Now comes the core of **how to OCR PDF**: handing the engine a file path and pulling out the recognized text. The method returns a list of page results; each result contains a `text` attribute. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +If you need the whole document, iterate over `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### What If the PDF Is Encrypted? + +Some PDFs come password‑protected. In that case you can pass the password to `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +The engine will decrypt on the fly before performing OCR—no extra steps required. + +## Step 5: Post‑Processing the Extracted Text (Fine‑Tuning Extract Text from PDF) + +Raw OCR output often contains line breaks, extra spaces, or occasional mis‑recognized characters. A quick clean‑up routine makes the extracted string ready for downstream processing (search indexing, database storage, etc.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +You can now safely **extract text from PDF** and feed it into any NLP pipeline, search engine, or simple `open(...).write()` operation. + +## Bonus: Batch Processing Multiple PDFs (Scaling Perform OCR on PDF) + +If you have a folder full of scanned PDFs, wrap the logic in a loop: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +This snippet shows how to **perform OCR on PDF** files in bulk, a common need for digitization projects. + +## Expected Output + +Running the single‑page example (Step 4) should print something like: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +If you processed a multi‑page book, the console will display each page’s cleaned text, and the batch script will leave a `.txt` file beside every PDF. + +## Common Pitfalls & How to Avoid Them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Low‑resolution source PDF | Garbled characters, missing words | Increase DPI (`set_dpi(400)` or higher) | +| Wrong language set | Many unknown symbols, especially accented characters | Use `engine.set_recognition_language(ocr.Language.FRENCH)` or the appropriate enum | +| Large PDF causing memory error | `MemoryError` or crash after a few pages | Process pages in chunks (`engine.recognize_pdf(..., max_pages=10)`) | +| Missing fonts in the PDF | Blank output for certain pages | Ensure the PDF actually contains raster images; some PDFs are vector‑only and need different handling | + +## Image Illustration + +Below is a quick visual of the workflow. The alt text is deliberately SEO‑friendly. + +![how to ocr pdf workflow diagram showing engine initialization, language setting, rendering options, recognition, and text extraction](/images/ocr-workflow.png) + +*The diagram isn’t required for the code to run, but it helps visual learners see where each step fits.* + +## Conclusion + +We’ve covered **how to OCR PDF** files in Python from start to finish: creating an OCR engine, **changing OCR language**, configuring rendering to **convert scanned PDF text**, and finally **extracting text from PDF** for further use. The complete, runnable example is ready to drop into any project, and the optional batch script shows you how to scale the solution. + +Next, you might want to explore: + +- Adding **perform OCR on PDF** for multilingual archives by looping over a language list. +- Integrating the extracted text with Elasticsearch for full‑text search. +- Using OCR to create searchable PDFs by embedding the text layer back into the original file (many libraries expose a `save_as_searchable_pdf` method). + +Feel free to experiment, tweak DPI settings, or switch to a different OCR backend. The fundamentals stay the same, and you now have a solid foundation to build on. + +Happy coding, and may your scanned documents finally become searchable! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/english/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..f2f6d0c31 --- /dev/null +++ b/ocr/english/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-06 +description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: en +og_description: How to OCR PDF step‑by‑step. Learn to add searchable text and convert + image to PDF/A using a simple Python script. +og_title: How to OCR PDF – Quick Guide to Create Searchable PDFs +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: How to OCR PDF in Python – Create Searchable PDF from Images +url: /python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to OCR PDF – Turn Scanned Images into Searchable PDFs + +Ever wondered **how to OCR PDF** files when all you have is a scanned image of an invoice or a receipt? You’re not the only one. In many offices the incoming paperwork arrives as flat PNGs or JPEGs, and the next step—making that content searchable—feels like a black‑box. + +The good news? With just a few lines of Python you can **create searchable PDF** files, **add searchable text**, and even **convert image to PDF/A** for long‑term archiving. In this tutorial we’ll walk through each step, explain why it matters, and give you a ready‑to‑run script that you can drop into any project. + +> **Pro tip:** The same approach works for multi‑page scans; just loop over the files and the engine does the heavy lifting. + +--- + +## What You’ll Need + +Before we dive in, make sure you have the following on your machine: + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9 or newer | Modern syntax and better library support | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Handles both image recognition and PDF/A generation | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | The source of the text | +| Write permission to the output folder | So the script can save the new PDF | + +If you haven’t installed the OCR SDK yet, run: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +That’s it—no complex system dependencies, just a pip install. + +--- + +## How to OCR PDF – Overview + +At a high level the process consists of three simple actions: + +1. **Recognize** the text inside the image while preserving the original graphics. +2. **Export** the OCR result together with the original image as a **searchable PDF/A** (the archival‑friendly PDF flavour). +3. **Validate** that the resulting file contains selectable, searchable text layered over the original picture. + +Below you’ll see each step in code, with explanations of the *why* behind the commands. + +--- + +## Step 1: Recognize Text from the Image + +First we ask the OCR engine to read the pixels and return a result object that holds both the raw image and the extracted text. Think of it as the engine “reading” the invoice for you. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Why this matters + +- **Preserving graphics** means the visual layout (tables, logos, stamps) stays exactly as the scanner captured it. +- The `result` object typically contains a hidden text layer that we’ll later embed into the PDF. +- Using `recognize_image` instead of `recognize_pdf` avoids an extra conversion step, which speeds up processing for single‑page images. + +#### Common variations + +- If you have a **multi‑page TIFF**, pass the file path directly; most engines will treat each page as a separate image. +- For PDFs that already contain images, you can call `engine.recognize_pdf("file.pdf")` and skip this step entirely. + +--- + +## Step 2: Export OCR Result as Searchable PDF/A + +Now we take the `result` from step 1 and tell the engine to write a new file. The key flag here is *PDF/A*—the ISO‑standard version of PDF designed for long‑term preservation. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Why this matters + +- **Searchable PDF**: The output file contains a hidden, selectable text layer. You can now Ctrl + F through the document. +- **PDF/A compliance**: Some organizations (legal, finance) require PDF/A for audit trails; this step satisfies that rule automatically. +- The method also **adds searchable text** without flattening the image, so the visual fidelity stays perfect. + +#### Edge case: Need a regular PDF instead? + +If you don’t care about PDF/A, replace `save_as_pdfa` with `save_as_pdf`. The rest of the workflow stays the same. + +--- + +## Step 3: Verify the Searchable PDF + +A quick sanity check saves you from mysterious bugs later. Open the generated file in any PDF viewer, try selecting a word, and use the search function. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Expected output + +When you run the script, the console prints: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Opening the file, you should see the original invoice image with a faint, invisible text layer. Highlight any word and you’ll notice it’s selectable—**that’s the searchable text** you just added. + +--- + +## Adding Searchable Text to Existing PDFs (Bonus) + +Sometimes you already have a PDF but need to **add searchable text** to it. The same engine can overlay OCR results onto an existing PDF: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Here `apply_to` merges the hidden layer with the original pages, letting you **create searchable PDF** without re‑scanning. + +--- + +## Common Pitfalls and Tips + +| Pitfall | How to avoid it | +|---------|-----------------| +| **Low‑resolution source images** (< 150 dpi) | Upscale or request a higher‑resolution scan; OCR accuracy drops dramatically below 150 dpi. | +| **Missing language data** | Install the appropriate language packs for your OCR engine (`pip install pdfocr[eng,spa]`). | +| **Output folder not writable** | Run the script with sufficient permissions or choose a different directory. | +| **PDF/A validation fails** | Ensure you’re not embedding unsupported fonts or JavaScript; most SDKs handle this automatically when you use `save_as_pdfa`. | + +--- + +## Full Script – One‑File Solution + +Below is a self‑contained script that ties everything together. Copy‑paste it, replace the placeholder paths, and you’re ready to **convert image to PDF/A** in seconds. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**What this script does:** +1. Loads the OCR engine. +2. Reads the chosen image and extracts the text. +3. Writes a **searchable PDF/A** that you can immediately distribute or archive. + +Feel free to wrap the `main` logic in a function that processes a whole folder—just iterate over `os.listdir()` and repeat the three steps for each file. + +--- + +## Next Steps & Related Topics + +Now that you’ve mastered **how to OCR PDF**, consider exploring these follow‑up ideas: + +- **Batch processing:** Use `concurrent.futures` to OCR dozens of invoices in parallel. +- **Metadata injection:** Add creation dates or invoice numbers to the PDF metadata for easier indexing. +- **Hybrid PDFs:** Combine searchable text with embedded original images for a “digital twin” of the paper document. +- **Alternative outputs:** Export to **DOCX** or **HTML** if downstream systems need editable formats. + +Each of these builds on the core concepts you just learned—recognize, export, verify. + +--- + +## Wrap‑Up + +In a nutshell, you now know **how to OCR PDF** files by turning a simple image into a **searchable PDF/A** with just three lines of Python. The script handles the heavy lifting, preserves the original graphics, and gives you a standards‑compliant document that you can search, archive, or share. + +Give it a spin with your own invoices, receipts, or scanned contracts. If you hit any snags, drop a comment below or check the SDK’s official docs—they’re usually packed with extra examples. Happy coding, and enjoy the newfound ability to make any image instantly searchable! + +![How to OCR PDF example showing original image and searchable PDF overlay](placeholder.png "How to OCR PDF example") + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/english/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..7d3849ecb --- /dev/null +++ b/ocr/english/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: en +og_description: How to OCR PDF with Aspose OCR Cloud. This guide shows how to extract + plain text PDF, convert PDF page PNG, and save PDF page images. +og_title: How to OCR PDF with Aspose OCR Cloud – Step-by-Step +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: How to OCR PDF with Aspose OCR Cloud – Complete Guide +url: /python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to OCR PDF with Aspose OCR Cloud – Complete Guide + +Ever wondered **how to OCR PDF** files without wrestling with heavyweight desktop tools? You’re not alone—many developers hit that wall when they need a quick, programmatic way to pull text out of scanned documents. The good news? With Aspose OCR Cloud you can **extract text from PDF**, turn each page into a PNG, and even **save PDF page images** for later use, all from a tidy Python script. + +In this tutorial we’ll walk through everything you need to know: from installing the SDK, licensing the engine, and recognizing multi‑page PDFs, to extracting plain text, converting pages to PNG, and persisting those images on disk. By the end you’ll have a reusable snippet you can drop into any project that needs **how to OCR PDF** capabilities. + +## What You’ll Need + +- **Python 3.8+** (the code works on 3.10 and newer as well) +- An Aspose OCR Cloud account – you’ll get a free trial license file (`Aspose.OCR.lic`) +- The `asposeocrcloud` package (`pip install asposeocrcloud`) +- A scanned, multi‑page PDF you want to process + +That’s it. No extra binaries, no native dependencies, just pure Python. + +## How to OCR PDF – Setup and License + +Before you can call any OCR methods, you have to tell the SDK who you are. Aspose uses a lightweight license file that you place somewhere accessible to your script. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* If you skip the license step, the SDK will still work but will embed a small watermark in the output images. Not ideal for production. + +## Step 2: Install the Aspose OCR Cloud Python SDK + +Open a terminal and run: + +```bash +pip install asposeocrcloud +``` + +The package pulls in all required dependencies (requests, pillow, etc.) so you don’t have to hunt down anything else. + +## Step 3: Create an OCR Engine and Choose a Language + +The engine is the heart of the operation. You can specify any language supported by Aspose; English works for most cases. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Why set the language? Because the OCR engine uses language‑specific dictionaries to improve accuracy. If you’re processing French PDFs, just swap `ENGLISH` for `FRENCH`. + +## Step 4: Point to Your Multi‑Page PDF + +Give the engine the full path to the file you want to process. Relative paths are fine as long as they resolve from the script’s working directory. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Make sure the file is readable; otherwise you’ll see a `FileNotFoundError`. + +## Step 5: Run OCR – You Get a List of Results + +Calling `recognize_pdf` returns a list where each element corresponds to one page of the source PDF. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Each `OcrResult` contains two handy properties: + +* `text` – the plain‑text representation of the page (great for **extract plain text pdf**) +* `image` – a Pillow `Image` object of the rendered page (perfect for **convert pdf page png**) + +## Step 6: Extract Text from PDF and Convert Pages to PNG + +Now we loop through the results, print the extracted text, and save a PNG version of every page. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Expected Console Output + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +You’ll also find `page_1.png`, `page_2.png`, … floating in `YOUR_DIRECTORY`. Those are the rasterized page images you can feed into downstream image‑processing pipelines. + +## Step 7: Save PDF Page Images (Optional Post‑Processing) + +If you only need the images and not the text, you can skip the `print(res.text)` line. Conversely, if you want to store the text in separate `.txt` files, just add a tiny write‑out: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +This small addition demonstrates how easy it is to **save PDF page images** while also persisting the extracted content. + +## Full Working Example + +Putting everything together, here’s the complete script you can copy‑paste into `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Run it with: + +```bash +python ocr_pdf.py +``` + +You should see the console dump of each page’s text and a series of PNG files + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/english/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..7f9e8ce35 --- /dev/null +++ b/ocr/english/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-06-06 +description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: en +og_description: How to preprocess images for OCR in Python. This tutorial shows binarize + image using Otsu, how to deskew scanned documents, and how to improve OCR accuracy + for German images. +og_title: How to Preprocess Images for OCR – Complete Python Guide +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: How to Preprocess Images for OCR – Complete Python Guide +url: /python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Preprocess Images for OCR – Complete Python Guide + +Ever wondered **how to preprocess images for OCR** so that the text comes out crystal‑clear? You’re not the only one. Scanned documents—especially noisy German pages—can be a nightmare for any OCR engine. The good news? A few smart preprocessing steps can turn a blurry, speckled scan into a clean, machine‑readable image. + +In this tutorial we’ll walk through a practical example that shows **how to preprocess images for OCR** using Python. You’ll learn to **binarize image using Otsu**, **how to deskew scanned documents**, and overall **how to improve OCR accuracy** when you need to **extract text from German image** files. No fluff, just a working script you can copy‑paste today. + +## What You’ll Need + +- **Python 3.9+** (any recent version works) +- An OCR library that exposes an `OcrEngine` class – for the demo we’ll assume a generic `ocr` package. Install it with `pip install ocr-lib`. +- A noisy German scan (`noisy_german_scan.tif`) you want to test against. +- A basic understanding of Python functions (if you’ve written a `def` before, you’re good). + +> **Pro tip:** If you’re using a different OCR SDK (e.g., Tesseract via `pytesseract`), the concepts stay the same—just adapt the method names. + +## Overview of the Solution + +1. **Create an OCR engine instance.** +2. **Set the recognition language to German.** +3. **Build a custom preprocessing pipeline** that includes deskewing, denoising, binarization (Otsu), and contrast stretching. +4. **Attach the pipeline to the engine** so every image passes through it automatically. +5. **Run the OCR** on a noisy German scan. +6. **Print the extracted text** to verify the result. + +Below we break each step down, explain **why** it matters, and show the exact code you need. + +![how to preprocess images for OCR example](image.png "how to preprocess images for OCR example") + +## Step 1: Create an OCR Engine Instance + +First things first—without an engine, nothing happens. The `OcrEngine` object is the entry point that coordinates all later processing. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Why this matters:* Initializing the engine sets up internal resources (like language models) and gives you a clean slate to attach a custom pipeline later. + +## Step 2: Set the Recognition Language to German + +OCR accuracy is heavily language‑dependent. By telling the engine to expect German, you activate the right character set and language model. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +If you skip this, the engine might default to English, mis‑recognizing umlauts (ä, ö, ü) and the ß character—common pitfalls when dealing with German scans. + +## Step 3: Build a Custom Preprocessing Pipeline + +This is the heart of **how to preprocess images for OCR**. We’ll chain four transformations: + +| Transformation | What it does | Why it helps | +|----------------|--------------|--------------| +| **Deskew** | Rotates the image back to horizontal (max 5°) | Scans are rarely perfectly aligned; deskewing removes slant that confuses character segmentation. | +| **Denoise** | Reduces random speckles (strength 0.7) | Noise creates false edges that the OCR engine may interpret as characters. | +| **Binarize (Otsu)** | Converts to black‑and‑white using Otsu’s method | A clean binary image gives the engine a sharp contrast between foreground (text) and background. | +| **Contrast Stretch** | Expands the dynamic range | Improves readability of faint strokes, especially on old documents. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### How to Deskew Scanned Documents + +The `deskew` call above is the concrete answer to **how to deskew scanned documents**. Internally it estimates the dominant text line angle via Hough transform and rotates the image back. If your documents are rotated more than 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + +### Binarize Image Using Otsu + +The `binarize(method="otsu")` line directly answers the query **binarize image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class variance, which is perfect for documents with bimodal histograms (dark text vs. light background). + +## Step 4: Attach the Pipeline to the Engine + +Now we tell the OCR engine to run every incoming image through the pipeline we just built. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Why this matters:* Without registering, the engine would process the raw scan, ignoring all the cleaning we just configured. This step ensures **how to improve OCR accuracy** by applying the same preprocessing consistently. + +## Step 5: Recognize Text from a Noisy German Scan + +Time to put everything together. We feed the engine a noisy German image and let it do the heavy lifting. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +If you’re curious about performance, you can time the call: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Step 6: Output the Recognized Text + +Finally, we print the extracted string. This is the direct answer to **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Expected Output + +Assuming the sample scan contains the sentence “Die schnelle braune Füchsin springt über den faulen Hund.” you should see something like: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +If the output still contains garbled characters, consider tweaking the `denoise` strength or increasing the `max_angle` for deskewing. + +## Common Pitfalls & How to Tackle Them + +- **Missing language model:** Forgetting `set_recognition_language(Language.GERMAN)` often results in missing umlauts. Double‑check the call. +- **Over‑denoising:** A strength above 0.9 can erase thin strokes, especially in older fonts. Stick to 0.5‑0.7 for most cases. +- **Incorrect file format:** Some OCR engines choke on multi‑page TIFFs. If you have a multi‑page document, split it into single‑page files first. +- **Pipeline order:** The order shown (deskew → denoise → binarize → contrast) is intentional. Binarizing before denoising can lock in noise; always denoise first. + +## Extending the Pipeline (What’s Next?) + +Now that you have a solid baseline, you might want to: + +- **Add a morphological opening** to clean tiny blobs (`.morph_open(kernel=3)`). +- **Integrate a language model** for post‑processing correction (`ocr_engine.apply_spellcheck()`). +- **Parallelize batch processing** for large datasets using `concurrent.futures`. + +All of these are natural extensions that keep the core idea of **how to preprocess images for OCR** intact while boosting **how to improve OCR accuracy** even further. + +## Conclusion + +We’ve just covered **how to preprocess images for OCR** from start to finish: create an engine, set German language, build a pipeline that **binarize image using Otsu**, **how to deskew scanned documents**, and finally **extract text from german image** with higher confidence. By following the six steps above you’ll see a noticeable jump in recognition quality—no more endless manual corrections. + +Give the script a spin with your own scans, experiment with the parameters, and let the results speak for themselves. Got questions about a particular preprocessing tweak? Drop a comment, and we’ll dive deeper together. + +Happy coding, and may your OCR be ever accurate! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/english/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..4bb1c8b91 --- /dev/null +++ b/ocr/english/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,336 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: en +og_description: OCR PNG image in Python explained. This guide shows how to extract + text from image, run a python OCR example and read ancient greek with ease. +og_title: OCR PNG Image in Python – Complete Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR PNG Image in Python – Full Step‑by‑Step Guide +url: /python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image in Python – Full Step‑by‑Step Guide + +Ever wondered how to **OCR PNG image** files straight from a Python script? Maybe you have a folder full of scanned ancient manuscripts and you need to **extract text from image** files without manually typing everything. The good news is you don’t need a PhD in computer vision—just a few lines of code and the right library, and you’ll be reading ancient greek in seconds. + +In this tutorial we’ll walk through a **python OCR example** that recognises text from a PNG, sets the language to Greek polytonic, and prints the result. By the end you’ll know exactly how to **recognize image text**, handle common pitfalls, and adapt the script for other languages or image formats. + +## What You’ll Learn + +- Install and configure a Python OCR library (pytesseract + Tesseract OCR) +- Create an OCR engine instance and load a PNG file +- Set the recognition language to Greek polytonic so you can **read ancient greek** +- Output the recognised text and troubleshoot typical issues +- Extend the script to batch‑process multiple PNGs or switch to another language + +### Prerequisites + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | Modern syntax and type hints | +| `pytesseract` package | Thin wrapper around the Tesseract engine | +| Tesseract OCR binaries (≥ 5.0) | The actual engine that does the heavy lifting | +| Greek language data (`grc.traineddata`) | Needed for **read ancient greek** correctly | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Our target for the **ocr png image** demo | + +You can install the Python side with: + +```bash +pip install pytesseract Pillow +``` + +And on Ubuntu/macOS you’d add the engine itself: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Don’t forget to download the Greek polytonic trained data: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Path may differ; adjust `TESSDATA_PREFIX` if needed.)* + +--- + +## OCR PNG Image: Create the Engine Instance + +The first thing we need is an object that talks to Tesseract. In `pytesseract` the engine is accessed through module‑level functions, but for clarity we’ll wrap it in a tiny class. This mirrors the “engine” concept you saw in the original snippet. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Why wrap it?** +- Keeps the public API identical to the snippet you started with, making migration painless. +- Allows us to add logging or error handling later without touching the main flow. +- Demonstrates good OOP practice—something senior developers appreciate. + +--- + +## Extract Text from Image: Set the Language to Greek Polytonic + +Now that we have an engine, we need to tell it which language to expect. Greek polytonic uses diacritics that aren’t covered by the standard “greek” data, so we point Tesseract at the `grc` trainedfile. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +If you ever want to **extract text from image** files in another language, just replace `"grc"` with `"eng"` for English, `"fra"` for French, etc. The same line works for any language you have installed. + +--- + +## Recognize Image Text: Run the OCR on a PNG + +With the language set, we feed the PNG into the engine. The original example used a hard‑coded path; we’ll make it a little more flexible by using `Path` objects. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tips & Edge Cases** + +- **File not found** – wrap the call in a `try/except FileNotFoundError` to give a friendly message. +- **Low‑resolution PNG** – consider pre‑processing (e.g., resizing, binarization) with Pillow before OCR. +- **Non‑Greek text** – Tesseract will still try to decode, but accuracy drops sharply. Always match the language. + +--- + +## Output the Recognized Text + +Finally, we print the result. In a real project you might write to a database, a CSV, or even feed it into a translation pipeline. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +When you run the script against a clear scan of an ancient Greek inscription, you should see something like: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +If the output looks garbled, double‑check that the **greek.traineddata** file is in the right folder and that the PNG isn’t too noisy. + +--- + +## Full Working Example (All Steps in One Script) + +Below is the complete, ready‑to‑run program. Save it as `ocr_greek.py` and execute `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Expected output** (truncated for brevity): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +If you see the proper Greek characters, congratulations—you’ve successfully performed an **ocr png image** operation in Python! + +--- + +## Common Questions & Pro Tips + +### How do I improve accuracy on a noisy PNG? + +- Convert the image to grayscale: `img = img.convert('L')` +- Apply a binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +These steps often turn a **recognize image text** nightmare into a clean result. + +### Can I process a whole folder of PNGs? + +Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. Store each result in a dictionary or write to a CSV for later analysis. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### What if I need to extract numbers only? + +Pass a custom **config** string to `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +That way you can **extract text from image** files that contain tables, serial numbers, or timestamps. + +### Is there a way to get confidence scores? + +Yes—use `pytesseract.image_to_data` which returns a TSV with confidence per word. You can filter out low‑confidence tokens before assembling the final string. + +--- + +## Extending the Tutorial + +Now that you’ve mastered the basics, consider exploring these related topics: + +- **Batch OCR with multiprocessing** – speed up large corpora of PNGs. +- **Hybrid OCR + NLP pipelines** – automatically translate the extracted ancient Greek into modern English. +- **Alternative engines** – try `easyocr` or `opencv`‑based methods for specific use‑cases. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, or AWS Textract for serverless scaling. + +Each of these builds on the core **python ocr example** we just covered, so you’ll feel comfortable diving deeper. + +--- + +## Conclusion + +We’ve taken a simple snippet and turned it into a robust **ocr png image** workflow in Python. By creating an `OcrEngine`, setting the language to Greek polytonic, feeding a PNG, and printing the result, you now know how to **extract text from image** files, **recognize image text**, and even **read ancient greek + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/english/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..ca58426e8 --- /dev/null +++ b/ocr/english/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: en +og_description: Python OCR tutorial that walks you through recognizing image text, + high resolution OCR, and extracting Spanish text with GPU acceleration. +og_title: Python OCR Tutorial – GPU Accelerated Text Recognition +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR Tutorial – Recognize Image Text with GPU Acceleration +url: /python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Recognize Image Text with GPU Acceleration + +Ever wondered how to **recognize image text** in a Python script without spending hours tweaking settings? You're not the only one. In this **python ocr tutorial** we’ll show you a clean, end‑to‑end way to extract Spanish text from a high‑resolution picture, and we’ll throw GPU acceleration into the mix so the process runs lightning‑fast. + +Think of it as a quick coffee‑break demo that you can expand into a production‑grade pipeline later. By the end of this guide you’ll have a runnable program that performs **high resolution OCR**, leverages a CUDA‑enabled GPU, and spits out the exact Spanish characters you need. + +## What You’ll Learn + +- How to install and import a modern OCR library that supports GPU acceleration. +- How to create an OCR engine instance and set it to **recognize image text** in Spanish. +- How to enable **gpu accelerated OCR** for massive speed gains on high‑resolution files. +- How to handle edge cases such as missing CUDA drivers or fallback to CPU. +- Tips for improving accuracy when you need to **extract spanish text** from noisy scans. + +### Prerequisites + +- Python 3.9+ (the code works on 3.10 and newer as well). +- A CUDA‑compatible GPU (optional but highly recommended). +- Basic familiarity with pip and virtual environments. + +If you’re missing any of these, the tutorial still works—just skip the GPU step and the library will fall back to CPU automatically. + +--- + +## Python OCR Tutorial: Install the Required Packages + +First things first, we need a solid OCR engine. For this tutorial we’ll use the open‑source **`easyocr`** package, which ships with built‑in GPU support when a compatible device is detected. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** If you already have PyTorch installed, make sure it matches your CUDA version (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Mismatched versions are a common source of “GPU not found” errors. + +--- + +## Step 1: Create an OCR Engine Instance + +Now we spin up the engine. EasyOCR calls its main class `Reader`. The constructor accepts a list of language codes; we’ll pass `"es"` for Spanish. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* By declaring the language up front, the engine loads only the necessary neural network weights, which saves memory and speeds up inference—especially useful when you’re dealing with **high resolution OCR** later on. + +--- + +## Step 2: Prepare a High‑Resolution Image + +High‑resolution images give the model more pixels to work with, which usually translates into better character recognition. Let’s assume you have a file called `high_res_spanish.png` sitting in a folder named `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +If you don’t have a high‑resolution sample handy, you can download a free one from Unsplash or generate a synthetic image with Pillow. The key is to keep the DPI above 300 for the best results. + +--- + +## Step 3: Enable GPU Acceleration (Optional but Recommended) + +EasyOCR already tries to use the GPU when you set `gpu=True`. However, it’s good practice to verify that the device is actually being used, especially on multi‑GPU rigs. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* If the script silently falls back to CPU, you might wonder why a 5‑second operation suddenly takes 30 seconds. This small check makes the behavior transparent and keeps your **gpu accelerated OCR** pipeline predictable. + +--- + +## Step 4: Perform High‑Resolution OCR and Recognize Image Text + +Now the fun part—actually reading the text. EasyOCR’s `readtext` method returns a list of tuples containing the bounding box, the recognized string, and a confidence score. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +If you need the raw string without coordinates, set `detail=0`. For most **recognize image text** use‑cases, the default (`detail=1`) gives you enough context to post‑process later. + +--- + +## Step 5: Extract Spanish Text and Clean the Output + +Because we asked EasyOCR for Spanish, the returned strings are already in that language. Still, you might want to concatenate them, strip whitespace, or filter out low‑confidence detections. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** You can either lower the threshold (risking noise) or pre‑process the image (increase contrast, binarize, or deskew). Those tricks are common when dealing with **high resolution OCR** on scanned documents. + +--- + +## Step 6: Handling Edge Cases and Performance Tweaks + +Even the best‑trained models stumble on a few scenarios. Below are a couple of quick fixes you can paste into the script. + +### 6.1 Fallback When No GPU Is Present + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling Very Large Images + +If your image is larger than 4000 × 4000 px, you might run out of GPU memory. Down‑sample proportionally while preserving DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +These snippets keep the script robust, whether you’re running on a workstation or a modest laptop. + +--- + +## Full Working Example + +Putting it all together, here’s the complete script you can copy‑paste and run immediately: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Expected output (example):** + +``` +✅ CUDA device detected: NVIDIA GeForce RTX 3080 + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/english/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..712329b0b --- /dev/null +++ b/ocr/english/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-06 +description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: en +og_description: recognize text from image with Python OCR engine. This guide shows + how to configure OCR engine python and extract text from image efficiently. +og_title: recognize text from image in Python – Complete Setup Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: recognize text from image in Python – Full OCR Engine Setup Guide +url: /python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# recognize text from image in Python – Complete Setup Tutorial + +Ever wondered how to **recognize text from image** using just a few lines of Python? You're not alone. Whether you're building a receipt‑scanner, a document digitizer, or a simple hobby project, being able to extract text from image is a skill that pays off quickly. + +In this tutorial we’ll walk through the whole process—starting from **configure OCR engine python** style setup, moving through cloud authentication, and finally showing you how to **extract text from image** with a reliable result. No magic, just clear steps you can copy‑paste and run today. + +## What You’ll Learn + +- How to install and import the required OCR library. +- The exact commands to **configure OCR engine python** for cloud processing. +- A complete, runnable script that **recognize text from image** and prints the output. +- Tips for handling common pitfalls like missing API keys or unsupported image formats. +- Next‑level ideas such as batch processing and local fallback. + +### Prerequisites + +- Python 3.8+ installed on your machine. +- An internet connection (the example uses a cloud‑based OCR service). +- A valid API key from the OCR provider (you’ll see where to plug it in). + +If you’ve got those, let’s dive in—no fluff, just a practical guide that works. + +--- + +## Step 1: Install the OCR Library and Import It + +Before you can **configure OCR engine python**, you need the library that talks to the cloud service. In our example we’ll use a fictional but representative package called `ocrcloud`. Replace it with the real package you’re using (e.g., `easyocr`, `google-cloud-vision`, etc.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Why this matters:** Importing the class gives you access to methods like `use_cloud()` and `set_api_key()`. Without the import, the rest of the script would raise a `NameError`. + +*Pro tip:* Pin the version in your `requirements.txt` (`ocrcloud==2.1.0`) to avoid unexpected breaking changes later. + +--- + +## Step 2: Create and **configure OCR engine python** for Cloud Mode + +Now we actually **configure OCR engine python**. The engine starts in local mode by default; switching to cloud mode lets you offload heavy image analysis to powerful servers. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explanation:** +- `OcrEngine()` creates a fresh engine object—think of it as your blank canvas. +- `use_cloud(True)` flips a switch, telling the engine to send images over HTTPS instead of processing them locally. This is crucial for high‑accuracy results on complex fonts or low‑resolution photos. + +--- + +## Step 3: Authenticate with Your Cloud API Key + +Most cloud OCR services require an API key. This step shows how to safely inject the credential. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Security note:** Never hard‑code the key in a public repo. In production you’d pull it from an environment variable: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Step 4: **recognize text from image** – Send a Remote Image for Processing + +With the engine configured, we can finally **recognize text from image**. The method `recognize_image()` takes a path or URL and returns an object containing the extracted text. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**What happens under the hood?** +The image bytes are uploaded to the provider’s endpoint, processed by a deep‑learning model, and the plain‑text result is streamed back. If the image is large, the service may automatically downscale to speed up the job. + +--- + +## Step 5: Output the **extract text from image** Result + +Now that the OCR service has done its job, we simply print the text. In real applications you might store it in a database or pass it to another function. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Expected output:** (example) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +If the output looks garbled, double‑check that the image is clear and that you’ve selected the correct language model (many services let you specify `engine.set_language("en")`). + +--- + +## Handling Edge Cases & Common Pitfalls + +### 1. Missing or Invalid API Key +If you see an authentication error, make sure: +- The key is active and not expired. +- It’s being read from the environment correctly. +- Your network allows outbound HTTPS traffic. + +### 2. Unsupported Image Formats +Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger a “format not supported” response. Convert with Pillow if needed: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Rate Limits +Cloud services often cap requests per minute. If you hit a limit, implement exponential back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Fallback to Local OCR +If the cloud is down, you can switch back: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Having a fallback keeps your app resilient. + +--- + +## Full Working Example + +Putting it all together, here’s a script you can run right now (just replace the placeholder values). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Run it:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +You should see the extracted text printed to the console, confirming that you’ve successfully **recognize text from image** and **extract text from image** using a properly **configure OCR engine python** workflow. + +--- + +## Conclusion + +We’ve just walked through a complete, end‑to‑end process that lets you **recognize text from image** in Python, from installing the library to authenticating a cloud service and finally **extract text from image** with a single function call. By **configure OCR engine python** the right way, you gain both flexibility (cloud vs. local) and reliability (proper error handling). + +What’s next? Try batching a folder of receipts, add language detection, or experiment with PDFs as input. The sky’s the limit once you’ve mastered the basics. + +Happy coding, and feel free to drop any questions in the comments—nothing beats learning together! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/english/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f290c87f5 --- /dev/null +++ b/ocr/english/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Run OCR on image using Python and see confidence scores. Learn how to + filter low‑confidence words, set thresholds, and handle edge cases. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: en +og_description: Run OCR on image in Python, inspect confidence levels, and filter + low‑confidence words. This tutorial walks you through a complete, runnable example. +og_title: Run OCR on Image with Python – Full Guide +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Run OCR on Image with Python – Complete Step‑by‑Step Guide +url: /python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Run OCR on Image with Python – Complete Step‑by‑Step Guide + +Ever needed to **run OCR on image** files but weren’t sure how to get reliable text out of them? You’re not alone—many developers hit the same wall when the extracted words look shaky and the confidence score is a mystery. + +In this guide we’ll dive straight into a working solution: you’ll see how to run OCR on image, read the overall confidence, and pull out any low‑confidence words that might need manual review. By the end you’ll have a reusable script, understand why each line matters, and know how to tweak the confidence threshold for your own projects. + +## What This Tutorial Covers + +We’ll walk through the entire workflow—from loading an image to printing a tidy report of words that fell below an 80 % confidence mark. Along the way we’ll discuss: + +* Choosing a solid OCR engine (we’ll use **EasyOCR**, a popular Python OCR library) +* Interpreting the `confidence` attribute that every OCR result returns +* Filtering words with a custom **OCR confidence threshold** +* Extending the script for batch processing or alternative engines like **pytesseract** + +No prior OCR experience is required, just a basic familiarity with Python and a working environment (Python 3.9+ recommended). + +Ready to turn blurry screenshots into clean, searchable text? Let’s get started. + +--- + +## ## How to Run OCR on Image with Python + +The heart of the tutorial is a three‑step snippet that mirrors the code you already saw. Below we’ll break each line apart, explain the why, and then give you a full, copy‑and‑paste‑ready script. + +### Step 1: Install and Import the OCR Engine + +First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box for many languages and gives you a confidence score per word. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Why EasyOCR?* It bundles a deep‑learning model that’s been trained on diverse datasets, so you typically get higher confidence values than the older Tesseract engine, especially on mixed‑quality images. + +> **Pro tip:** If you’re on a constrained environment (e.g., a tiny Docker container), `pytesseract` might be lighter, but you’ll lose some of the modern accuracy EasyOCR provides. + +### Step 2: Run OCR on the Image + +Now we actually **run OCR on image**. The `recognize_image` method from the original example is replaced with EasyOCR’s `readtext` call, which returns a list of `(bbox, text, confidence)` tuples. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Each entry in `ocr_results` looks like: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +The third element (`0.92` in the example) is the confidence score ranging from 0 to 1. + +### Step 3: Summarize Overall Confidence + +Unlike the earlier snippet that printed a single `confidence` attribute, EasyOCR gives a confidence per word. To get an overall sense, we’ll average them: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Why average?* It gives you a quick health check—if the overall confidence is below, say, 70 %, you probably need to improve the image (better lighting, preprocessing, etc.). + +### Step 4: List Low‑Confidence Words + +Now comes the part that directly answers the “list words whose confidence is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** of 0.80 (80 %) by default, but you can adjust it. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +The loop prints each word that didn’t make the cut, together with its percentage confidence. This is the exact analogue of the original `for recognized_word in recognition_result.words` loop, but now works with EasyOCR’s output format. + +--- + +## ## Understanding OCR Confidence Scores + +Confidence isn’t a magic number; it’s the model’s estimate of how sure it is about a particular transcription. Here are a few things to keep in mind: + +| Situation | Typical Confidence | What to Do | +|-----------|-------------------|------------| +| Clear, high‑resolution scan | 0.95 – 1.00 | No extra work needed | +| Slight blur or uneven lighting | 0.80 – 0.94 | Consider slight preprocessing (contrast boost) | +| Heavy noise, rotated text | < 0.70 | Apply image preprocessing (deskew, denoise) or switch to a different OCR engine | + +> **Watch out:** Some languages (e.g., cursive handwriting) naturally produce lower scores. Adjust the threshold accordingly. + +### Edge Cases & Variations + +1. **Batch Processing** – If you need to **run OCR on image** files in bulk, wrap the above logic in a loop that iterates over a directory. +2. **Multiple Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine will detect both. +3. **Alternative Engines** – Want to try **pytesseract**? Replace the reader block with: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + You’ll then need to aggregate per‑character confidences into per‑word values—a bit more work but doable. + +4. **Pre‑processing Tricks** – Applying OpenCV filters (`cv2.threshold`, `cv2.GaussianBlur`) can boost confidence for noisy scans. + +--- + +## ## Full, Ready‑to‑Run Script + +Below is the complete Python file you can drop into your project. Save it as `ocr_report.py` and run `python ocr_report.py`. Make sure the image path points to a real file. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Expected output** (your numbers will vary): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +If every word clears the 80 % bar you’ll see the friendly “All words meet the confidence threshold.” message instead. + +--- + +## ## Frequently Asked Questions (FAQ) + +**Q: Does this work with PDFs?** +A: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) and then feed the PNG/JPEG into the script. + +**Q: My confidence numbers are all low—what can I do?** +A: Try image preprocessing: increase contrast, remove background noise, or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` parameter you can tweak. + +**Q: Can I export the results to CSV?** +A: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` where each row contains `text`, `confidence`, and bounding‑box coordinates. + +**Q: Is there a GPU‑accelerated version?** +A: EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. Verify with `torch.cuda.is_available()` before running the script. + +--- + +## Conclusion + +We’ve just **run OCR on image** using Python, inspected the overall confidence, and isolated any low‑confidence words that need a + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/french/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..e8fe1d485 --- /dev/null +++ b/ocr/french/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extrayez du texte d’une image avec Python OCR en quelques minutes. Découvrez + l’OCR d’images multilingues, la détection automatique de la langue OCR et comment + extraire le texte OCR avec précision. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: fr +og_description: Extrayez du texte d’une image avec Python OCR rapidement. Apprenez + l’OCR d’images multilingues, la détection automatique de la langue en OCR, et comment + extraire le texte OCR étape par étape. +og_title: Extraire du texte d’une image avec OCR Python – Guide complet +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Extraire le texte d’une image avec OCR Python – Guide complet +url: /fr/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraire du texte d'une image avec Python OCR – Guide complet + +Vous avez déjà eu besoin d'**extraire du texte d'une image** sans savoir quelle bibliothèque pouvait gérer automatiquement plusieurs langues ? Vous n'êtes pas seul — les développeurs demandent constamment *comment extraire du texte OCR* lorsqu'ils traitent des documents internationaux, des reçus ou des flyers numérisés. Dans ce tutoriel, nous parcourrons un exemple pratique en Python qui non seulement extrait le texte d'une image mais **détecte également la langue** à la volée, rendant l'OCR d'images multilingues un jeu d'enfant. + +Nous couvrirons tout, de l'installation du package OCR à l'activation de **l'OCR de détection automatique de langue**, en passant par l'exécution du moteur sur une image d'exemple, puis l'affichage à la fois de la langue détectée et de la chaîne extraite. À la fin, vous disposerez d'un extrait réutilisable que vous pourrez intégrer à n'importe quel projet, que vous construisiez un pipeline de traduction ou un service d'ingestion de données. + +## Extraire du texte d'une image – Configuration de l'environnement + +Avant de plonger dans le code, assurez‑vous que votre poste de travail répond à ces exigences minimales : + +- Python 3.8 ou plus récent (la bibliothèque utilise des annotations de type que les versions antérieures ignorent) +- `pip` pour la gestion des paquets +- Un fichier image contenant du texte dans au moins deux langues différentes (par ex. anglais + espagnol) + +Vous aurez également besoin de la bibliothèque OCR qui alimente cette démonstration. Pour les besoins de ce guide, nous utiliserons le package fictif `ocr`, qui reflète des outils réels populaires comme Tesseract ou EasyOCR tout en offrant une API Python propre. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Astuce :** Si vous rencontrez des erreurs de permission, préfixez la commande avec `python -m` ou utilisez un environnement virtuel — cela garde vos site‑packages globaux bien rangés. + +## Créer une instance du moteur OCR + +Maintenant que la bibliothèque est prête, la première étape logique est de **créer une instance du moteur OCR**. Pensez au moteur comme à un scanner intelligent que vous pouvez configurer avant de lui fournir des images. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Pourquoi instancier le moteur séparément au lieu d'appeler une méthode statique ? L'objet moteur conserve l'état de configuration (comme les préférences de langue) que vous pourriez vouloir réutiliser sur de nombreuses images, vous évitant ainsi le surcoût de le réinitialiser à chaque fois. + +## Activer l'OCR de détection automatique de langue + +La plupart des outils OCR vous obligent à spécifier un code de langue — `eng` pour l'anglais, `spa` pour l'espagnol, etc. Deviner manuellement la langue annule l'intérêt d'un flux de travail **OCR d'image multilingue**. Heureusement, le package `ocr` propose un mode *auto detect language OCR* qui inspecte l'image et sélectionne le meilleur modèle linguistique en coulisses. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Activer **detect language OCR** de cette façon signifie que vous n'aurez plus à maintenir une longue liste de codes de langue. Le moteur essaiera de faire correspondre le script qu'il voit — latin, cyrillique, han, etc.—et chargera automatiquement le modèle approprié. + +## Effectuer un OCR d'image multilingue + +Avec le moteur prêt, il est temps d'**extraire du texte d'une image**. La méthode `recognize_image` accepte un chemin de fichier et renvoie un objet résultat contenant à la fois le texte brut et la langue qui a été détectée. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Si vous vous demandez *comment extraire du texte OCR* d'un PDF au lieu d'un PNG, le même moteur propose `recognize_pdf`—il suffit de remplacer le nom de la méthode. La logique de détection sous‑jacente reste identique, vous bénéficiant ainsi de la même fonctionnalité **auto detect language OCR**. + +## Afficher la langue détectée et le texte extrait + +Enfin, nous affichons ce que le moteur a découvert. L'objet résultat expose `detected_language` (une balise BCP‑47 comme `en` ou `es`) et `text`, qui contient la sortie brute de l'OCR. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Exécuter le script sur notre image d'exemple devrait produire quelque chose de similaire à : + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Remarquez comment le moteur a correctement identifié l'anglais comme langue principale, tout en capturant la ligne en espagnol—exactement ce que l’on attend d’une solution **OCR d'image multilingue** robuste. + +### Et si la détection échoue ? + +Parfois, le moteur OCR peut revenir à une langue par défaut (généralement l'anglais) si l'image est floue ou si le script est trop exotique. Dans ces cas, vous pouvez forcer une liste de langues : + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Mais rappelez‑vous, forcer les langues annule la commodité de **auto detect language OCR**, donc utilisez‑le uniquement lorsque vous connaissez un sous‑ensemble de langues. + +## Pièges courants et comment extraire du texte OCR de façon fiable + +Même avec la détection automatique, quelques obstacles peuvent vous surprendre : + +1. **Images à basse résolution** – La précision de l'OCR chute brutalement sous 150 dpi. Agrandissez ou demandez un scan à plus haute résolution. +2. **Bruit et artefacts de compression** – Appliquez un filtre de seuillage simple (`opencv` ou `Pillow`) avant d'alimenter l'image au moteur. +3. **Scripts mixtes sur une même page** – Certains moteurs peinent avec des caractères latins et CJK simultanés. Divisez la page en régions et lancez des reconnaissances séparées si nécessaire. + +Traiter ces problèmes améliore considérablement la qualité du processus **extract text from image**, surtout lorsqu'il s'agit de documents multilingues du monde réel. + +## Exemple complet fonctionnel + +Voici le script complet, prêt à être exécuté, qui combine toutes les étapes abordées. Enregistrez‑le sous le nom `multilingual_ocr.py` et lancez‑le depuis la ligne de commande. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Sortie attendue** (en supposant que l'image d'exemple contienne du texte en anglais et en espagnol) : + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +N'hésitez pas à remplacer `multilang_page.png` par n'importe quelle image contenant du texte dans d'autres langues — grâce à **auto detect language OCR**, le script vous fournira toujours une balise de langue sensée et le texte correspondant. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Conclusion + +Vous savez maintenant exactement **comment extraire du texte OCR** d'une image, comment activer **auto detect language OCR**, et comment gérer les scénarios **OCR d'image multilingue** avec un minimum de code. En créant une instance du moteur OCR, en activant la détection automatique de langue, et en appelant `recognize_image`, vous pouvez extraire de façon fiable à la fois l'identifiant de langue et le texte brut. + +Et après ? Essayez d'alimenter les chaînes extraites dans une API de traduction, stockez‑les dans une base de données consultable, ou combinez plusieurs pages en un seul rapport PDF. Vous pouvez également expérimenter avec différents back‑ends OCR (Tesseract, EasyOCR, Google Vision) tout en conservant le même flux de travail de haut niveau—grâce à l'interface cohérente **detect language OCR**. + +Si vous rencontrez des particularités, revenez à la section « Pièges courants » ou ajustez les étapes de pré‑traitement d'image. Bon codage, et que votre prochain projet regorge de texte correctement détecté et parfaitement extrait ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et à explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/french/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..d7c2ee1b6 --- /dev/null +++ b/ocr/french/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extraire du texte d’images PDF à l’aide de Python OCR. Apprenez comment + convertir rapidement des documents numérisés en texte avec une reconnaissance par + lots asynchrone. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: fr +og_description: Extraire du texte d'images PDF avec Python. Ce guide étape par étape + montre comment convertir des documents numérisés en texte en utilisant l'OCR asynchrone. +og_title: Extraire du texte d'images PDF – Tutoriel OCR Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Extraire le texte des images PDF – Guide Python pour convertir les documents + numérisés en texte +url: /fr/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraire du texte à partir d'images PDF – Guide Python pour convertir des documents numérisés en texte + +Vous avez déjà eu besoin d'**extraire du texte à partir d'images pdf** sans passer des heures à retaper ? Dans ce guide, nous vous montrerons comment **convertir des documents numérisés en texte** en utilisant un flux de travail OCR asynchrone simple en Python. + +Si vous avez déjà contemplé une pile de PDF numérisés en vous disant « Il doit bien y avoir une façon plus rapide », vous êtes au bon endroit. Nous passerons en revue chaque ligne de code, expliquerons pourquoi chaque élément est important, et couvrirons même quelques cas limites que vous pourriez rencontrer. + +## Ce que vous apprendrez + +- Comment démarrer un moteur OCR et définir la langue de reconnaissance. +- Le fonctionnement de l'alimentation d'une liste mixte de PNG et PDF dans un reconnaisseur par lots. +- Exécuter la tâche OCR de manière asynchrone afin que votre application reste réactive. +- Récupérer les résultats, les associer à leurs fichiers sources et afficher une sortie propre. + +**Prérequis** : Python 3.8+, une compréhension de base de `asyncio` ou `concurrent.futures`, et une bibliothèque OCR qui expose une classe `OcrEngine` similaire à celle de l'exemple (par ex., Aspose.OCR, wrapper Tesseract, ou un wrapper personnalisé). Aucun réglage lourd requis — installez simplement la bibliothèque et vous êtes prêt à partir. + +![extraire du texte à partir d'images pdf](https://example.com/placeholder.png "Capture d'écran de la sortie OCR – extraire du texte à partir d'images pdf") + +## Extraire du texte à partir d'images PDF – Configurer le moteur OCR + +La première chose dont vous avez besoin est une instance de moteur OCR configurée pour la langue de vos documents. Dans notre cas, nous utiliserons le français, mais vous pouvez le remplacer par n'importe quelle langue prise en charge. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Pourquoi c’est important** : Définir la langue dès le départ améliore considérablement la précision. Le moteur utilise des dictionnaires et des modèles de caractères spécifiques à chaque langue ; le fournir avec la mauvaise langue est une source fréquente de sortie brouillée. + +## Préparer la liste de fichiers – Images et PDF ensemble + +Notre reconnaisseur par lots peut gérer à la fois les images raster (`.png`, `.jpg`) et les conteneurs PDF. Il suffit de fournir une simple liste Python de chemins de fichiers. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Astuce** : Gardez la liste plate ; le moteur décompressera chaque page PDF en images en interne avant la reconnaissance. Si vous avez des milliers de fichiers, envisagez de découper la liste en lots plus petits afin d'éviter des pics de mémoire. + +## Lancer la reconnaissance par lots asynchrone + +Au lieu de bloquer le thread principal, nous lançons la tâche OCR en arrière‑plan. La méthode renvoie un `Future` qui contiendra finalement une liste d'objets `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Comment ça fonctionne** : En coulisses, le moteur crée un pool de threads (ou une tâche async, selon l'implémentation). Cela vous permet de continuer d'autres travaux — comme mettre à jour une UI, récupérer davantage de fichiers, ou journaliser la progression — pendant que le traitement lourd s'effectue ailleurs. + +## Faire quelque chose d’utile pendant que l’OCR s’exécute + +Une erreur courante consiste à rester inactif et à interroger le futur dans une boucle serrée. À la place, vous pouvez effectuer n'importe quel travail non lié. Pour la démonstration, nous nous contenterons d'imprimer une ligne d'état. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Rassembler les résultats une fois le futur terminé + +Lorsque vous êtes prêt à collecter la sortie OCR, utilisez `as_completed` de `concurrent.futures`. Ce modèle fonctionne que vous ayez un futur ou plusieurs. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Ce que vous verrez** : Chaque chemin de fichier suivi de la représentation texte brute extraite. Pour les PDF, `result.text` contient le texte concaténé de chaque page. + +### Sortie attendue (exemple) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Si vous remarquez des caractères manquants, revérifiez que la langue que vous avez définie correspond à la langue du document, et envisagez de pré‑traiter les images (redressement, augmentation du contraste) avant de les fournir au moteur. + +## Gestion des cas limites et des pièges courants + +| Situation | Que faire | +|-----------|-----------| +| **Langues mixtes** | Effectuer d'abord une passe de détection de langue, puis instancier des moteurs séparés par langue. | +| **PDF volumineux (> 100 Mo)** | Diviser le PDF en pages individuelles sur le disque (par ex., avec `PyPDF2`) et les fournir comme entrées séparées. | +| **Scripts non latins** | S'assurer que la bibliothèque OCR inclut le pack de langue requis ; certaines bibliothèques exigent le téléchargement de fichiers de données supplémentaires. | +| **Goulot d'étranglement de performance** | Augmenter la taille du pool de threads (`engine.set_thread_pool_size(8)`) ou passer à un backend accéléré GPU si disponible. | +| **Texte manquant dans les images basse résolution** | Pré‑traiter avec OpenCV : `cv2.resize`, `cv2.threshold` et `cv2.medianBlur` pour améliorer la lisibilité. | + +## Exemple complet fonctionnel (prêt à copier‑coller) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Enregistrez ceci sous `extract_text_async.py`, remplacez `YOUR_DIRECTORY` par le chemin vers vos fichiers, installez le paquet OCR (`pip install your-ocr-lib`), puis exécutez `python extract_text_async.py`. Vous devriez voir la sortie console illustrée précédemment. + +## Prochaines étapes – Aller au‑delà de l’extraction basique + +- **Post‑traitement** : Supprimer les espaces superflus, normaliser l'Unicode (`unicodedata.normalize`), ou exécuter un correcteur orthographique pour nettoyer le bruit OCR. +- **Sortie structurée** : Exporter les résultats vers CSV, JSON, ou directement dans une base de données pour la recherche en aval. +- **Lots parallèles** : Si vous avez des centaines de fichiers, lancez plusieurs futures et utilisez une file d'attente pour garder le CPU occupé sans saturer la mémoire. +- **Intégration avec des frameworks web** : Connecter ce script à un endpoint Flask ou FastAPI pour fournir un OCR à la demande en tant que service. + +--- + +### TL;DR + +Vous savez maintenant comment **extraire du texte à partir d'images pdf** avec un script Python minimal qui exécute l'OCR de façon asynchrone, vous permettant de **convertir des documents numérisés en texte** tout en gardant votre programme réactif. Expérimentez avec les paramètres de langue, les tailles de lots et les astuces de pré‑traitement pour obtenir la meilleure précision possible. + +Vous avez une variante à partager — peut‑être l’OCR sur des notes manuscrites ou un service cloud ? Laissez un commentaire, et bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extraire du texte à partir d'une image avec Aspose OCR – Guide étape par étape](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extraire du texte à partir d'images en utilisant l'opération OCR sur des dossiers](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extraire du texte à partir d'images en utilisant Aspose.OCR – Caractères autorisés](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/french/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..586500020 --- /dev/null +++ b/ocr/french/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: Comment faire de l'OCR sur un PDF avec Python, extraire le texte d'un + PDF, convertir le texte d'un PDF numérisé et changer la langue de l'OCR en quelques + lignes de code seulement. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: fr +og_description: 'Comment faire de l''OCR sur un PDF avec Python : un guide pratique + qui vous montre comment extraire du texte d’un PDF, convertir le texte d’un PDF + scanné et changer la langue de l’OCR sans effort.' +og_title: Comment faire de l'OCR d'un PDF en Python – Tutoriel complet de programmation +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Comment faire de l’OCR d’un PDF en Python – Guide complet étape par étape +url: /fr/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment faire de l'OCR sur un PDF en Python – Guide complet étape par étape + +Vous vous êtes déjà demandé **comment faire de l'OCR sur un PDF** sans payer pour des outils SaaS coûteux ? Vous n'êtes pas le seul. Que vous numérisiez de vieux livres, extrayiez des données de factures, ou que vous ayez simplement besoin d'un texte consultable à partir d'un rapport numérisé, maîtriser l'OCR de PDF en Python peut vous faire gagner des heures de copie manuelle. + +Dans ce tutoriel, nous parcourrons un exemple concis et fonctionnel qui **extrait du texte d'un PDF**, vous montre comment **convertir le texte d'un PDF numérisé** en chaînes éditables, et même comment **changer la langue de l'OCR** si votre document n’est pas en anglais. À la fin, vous disposerez d’un extrait réutilisable que vous pourrez intégrer à n’importe quel projet. + +## Prérequis et configuration + +Avant de plonger, assurez‑vous d’avoir : + +- Python 3.8+ installé (le code fonctionne sur 3.9, 3.10 et versions ultérieures) +- Le package `ocr` qui fournit la classe `OcrEngine` (vous pouvez l’installer via `pip install ocr-lib` – remplacez par le vrai nom du package que vous utilisez) +- Un fichier PDF que vous souhaitez traiter ; pour la démonstration nous utiliserons `high_res_book.pdf` placé dans un dossier appelé `YOUR_DIRECTORY` + +If you’re using a virtual environment (highly recommended), activate it first: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Astuce :** Conservez vos fichiers PDF dans un répertoire dédié `data/` afin d’éviter des problèmes de chemins plus tard. + +## Étape 1 : Créer une instance du moteur OCR (Comment faire de l'OCR sur un PDF – Initialisation) + +La toute première chose à faire lorsque vous souhaitez **effectuer de l'OCR sur des PDF** est d’instancier le moteur. Pensez au moteur comme le cerveau qui lira chaque page, interprétera les glyphes et vous rendra du texte brut. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Pourquoi c’est important : sans moteur, vous n’avez aucun contexte pour les paramètres de langue, les options de rendu ou la gestion du PDF. L’objet `OcrEngine` contient toutes ces valeurs par défaut et vous permet de les ajuster ultérieurement. + +## Étape 2 : Définir la langue de reconnaissance (Changer la langue de l'OCR) + +La plupart des bibliothèques OCR utilisent l'anglais par défaut, mais que faire si votre document est en français, allemand ou même japonais ? Changer la langue est aussi simple que d’appeler `set_recognition_language`. Cela répond à l’exigence de **changer la langue de l'OCR** et garantit une meilleure précision. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Pourquoi vous pourriez en avoir besoin :** Une archive multilingue contient souvent des pages à langues mixtes. Changer de langue à la volée évite la mauvaise reconnaissance de caractères comme “ß” ou “ñ”. + +## Étape 3 : Configurer les options de rendu du PDF (Convertir efficacement le texte d’un PDF numérisé) + +Lorsqu’on travaille avec des PDF numérisés, la résolution et le mode couleur influencent fortement la qualité de l’OCR. Un rendu à 300 DPI en niveaux de gris est un bon compromis pour la plupart des documents — assez élevé pour capturer les détails, mais suffisamment bas pour garder une utilisation de mémoire raisonnable. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Les appels en chaîne peuvent sembler sophistiqués, mais ils ne sont qu’une API fluide qui renvoie le même objet d’options à chaque fois. Si vous avez besoin de couleur (par ex., pour des diagrammes en couleur), remplacez `"grayscale"` par `"color"`. + +## Étape 4 : Reconnaître le PDF et récupérer le texte de la première page (Extraire du texte d’un PDF) + +Voici le cœur du **comment faire de l'OCR sur un PDF** : fournir au moteur le chemin du fichier et extraire le texte reconnu. La méthode renvoie une liste de résultats de pages ; chaque résultat possède un attribut `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Si vous avez besoin du document complet, itérez sur `results` : + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Et si le PDF est chiffré ? + +Certains PDF sont protégés par mot de passe. Dans ce cas, vous pouvez transmettre le mot de passe à `recognize_pdf` : + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Le moteur déchiffrera à la volée avant d’effectuer l’OCR—aucune étape supplémentaire n’est nécessaire. + +## Étape 5 : Post‑traitement du texte extrait (Affiner l’extraction du texte d’un PDF) + +La sortie brute de l’OCR contient souvent des sauts de ligne, des espaces superflus ou des caractères mal reconnus. Une routine de nettoyage rapide rend la chaîne extraite prête pour le traitement en aval (indexation de recherche, stockage en base de données, etc.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Vous pouvez maintenant **extraire du texte d’un PDF** en toute sécurité et l’alimenter dans n’importe quel pipeline NLP, moteur de recherche ou opération simple `open(...).write()`. + +## Bonus : Traitement par lots de plusieurs PDF (Faire de l'OCR sur des PDF à grande échelle) + +Si vous avez un dossier rempli de PDF numérisés, encapsulez la logique dans une boucle : + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Cet extrait montre comment **effectuer de l'OCR sur des PDF** en masse, un besoin fréquent pour les projets de numérisation. + +## Résultat attendu + +L’exécution de l’exemple d’une seule page (Étape 4) devrait afficher quelque chose comme : + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Si vous avez traité un livre multi‑pages, la console affichera le texte nettoyé de chaque page, et le script de traitement par lots laissera un fichier `.txt` à côté de chaque PDF. + +## Problèmes courants et comment les éviter + +| Problème | Symptômes | Solution | +|----------|-----------|----------| +| PDF source à basse résolution | Caractères brouillés, mots manquants | Augmenter le DPI (`set_dpi(400)` ou plus) | +| Mauvaise langue définie | De nombreux symboles inconnus, surtout les caractères accentués | Utiliser `engine.set_recognition_language(ocr.Language.FRENCH)` ou l’énumération appropriée | +| Grand PDF provoquant une erreur de mémoire | `MemoryError` ou plantage après quelques pages | Traiter les pages par lots (`engine.recognize_pdf(..., max_pages=10)`) | +| Polices manquantes dans le PDF | Sortie vide pour certaines pages | Vérifier que le PDF contient réellement des images raster ; certains PDF sont uniquement vectoriels et nécessitent une prise en charge différente | + +## Illustration d’image + +Voici une illustration rapide du flux de travail. Le texte alternatif est délibérément optimisé pour le SEO. + +![diagramme du flux de travail de comment faire de l'ocr pdf montrant l'initialisation du moteur, le réglage de la langue, les options de rendu, la reconnaissance et l'extraction du texte](/images/ocr-workflow.png) + +*Le diagramme n’est pas requis pour que le code fonctionne, mais il aide les apprenants visuels à voir où chaque étape s’insère.* + +## Conclusion + +Nous avons couvert **comment faire de l'OCR sur des PDF** en Python du début à la fin : création d’un moteur OCR, **changement de la langue de l'OCR**, configuration du rendu pour **convertir le texte d’un PDF numérisé**, et enfin **extraction du texte d’un PDF** pour une utilisation ultérieure. L’exemple complet et exécutable est prêt à être intégré à n’importe quel projet, et le script de traitement par lots optionnel vous montre comment mettre l’application à l’échelle. + +Ensuite, vous pourriez explorer : + +- Ajouter **perform OCR on PDF** pour les archives multilingues en parcourant une liste de langues. +- Intégrer le texte extrait avec Elasticsearch pour la recherche en texte intégral. +- Utiliser l’OCR pour créer des PDF consultables en incorporant la couche de texte dans le fichier original (de nombreuses bibliothèques exposent une méthode `save_as_searchable_pdf`). + +N’hésitez pas à expérimenter, ajuster les paramètres DPI, ou passer à un autre moteur OCR. Les principes restent les mêmes, et vous disposez désormais d’une base solide sur laquelle construire. + +Bon codage, et que vos documents numérisés deviennent enfin consultables ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/french/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..9cdb44b80 --- /dev/null +++ b/ocr/french/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-06 +description: Comment faire de l’OCR sur un PDF et créer des fichiers PDF recherchables + à partir d’images avec Python. Apprenez à ajouter du texte recherchable et à convertir + une image en PDF/A en quelques minutes. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: fr +og_description: Comment faire de l’OCR sur un PDF étape par étape. Apprenez à ajouter + du texte recherchable et à convertir une image en PDF/A à l’aide d’un script Python + simple. +og_title: Comment faire de l'OCR d'un PDF – Guide rapide pour créer des PDF recherchables +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Comment faire de l'OCR d'un PDF en Python – Créer un PDF consultable à partir + d'images +url: /fr/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment OCR un PDF – Transformer des images numérisées en PDF recherchables + +Vous vous êtes déjà demandé **comment OCR un PDF** lorsqu’il ne vous reste qu’une image numérisée d’une facture ou d’un reçu ? Vous n’êtes pas le seul. Dans de nombreux bureaux, les documents entrants arrivent sous forme de PNG ou JPEG plats, et l’étape suivante—rendre ce contenu interrogeable—semble être une boîte noire. + +La bonne nouvelle ? En quelques lignes de Python, vous pouvez **créer des PDF recherchables**, **ajouter du texte interrogeable**, et même **convertir une image en PDF/A** pour l’archivage à long terme. Dans ce tutoriel, nous parcourrons chaque étape, expliquerons pourquoi elle est importante, et vous fournirons un script prêt à l’emploi que vous pourrez intégrer à n’importe quel projet. + +> **Astuce :** La même approche fonctionne pour les numérisations multi‑pages ; il suffit de boucler sur les fichiers et le moteur se charge du travail lourd. + +--- + +## Ce dont vous avez besoin + +Avant de commencer, assurez‑vous d’avoir les éléments suivants sur votre machine : + +| Exigence | Pourquoi c’est important | +|----------|---------------------------| +| Python 3.9 ou plus récent | Syntaxe moderne et meilleure prise en charge des bibliothèques | +| Moteur OCR basé sur `pdfium` (par ex., `pdfocr` ou un SDK commercial) | Gère à la fois la reconnaissance d’image et la génération de PDF/A | +| Un fichier image (PNG, JPEG, TIFF) que vous souhaitez transformer en PDF recherché | La source du texte | +| Permission d’écriture sur le dossier de sortie | Pour que le script puisse enregistrer le nouveau PDF | + +Si vous n’avez pas encore installé le SDK OCR, exécutez : + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +C’est tout — aucune dépendance système complexe, juste un `pip install`. + +--- + +## Comment OCR un PDF – Vue d’ensemble + +À haut niveau, le processus se compose de trois actions simples : + +1. **Reconnaître** le texte présent dans l’image tout en conservant les graphiques d’origine. +2. **Exporter** le résultat OCR avec l’image originale sous forme de **PDF/A recherché** (la variante PDF adaptée à l’archivage). +3. **Valider** que le fichier résultant contient du texte sélectionnable, superposé à l’image d’origine. + +Vous verrez ci‑dessous chaque étape en code, avec les explications du *pourquoi* derrière les commandes. + +--- + +## Étape 1 : Reconnaître le texte à partir de l’image + +Dans un premier temps, nous demandons au moteur OCR de lire les pixels et de renvoyer un objet résultat contenant à la fois l’image brute et le texte extrait. Pensez‑y comme le moteur « lisant » la facture pour vous. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Pourquoi c’est important + +- **Conserver les graphiques** signifie que la mise en page visuelle (tableaux, logos, tampons) reste exactement telle que le scanner l’a capturée. +- L’objet `result` contient généralement une couche de texte cachée que nous intégrerons plus tard dans le PDF. +- Utiliser `recognize_image` au lieu de `recognize_pdf` évite une étape de conversion supplémentaire, ce qui accélère le traitement des images mono‑page. + +#### Variantes courantes + +- Si vous avez un **TIFF multi‑pages**, passez le chemin du fichier directement ; la plupart des moteurs traiteront chaque page comme une image séparée. +- Pour les PDF contenant déjà des images, vous pouvez appeler `engine.recognize_pdf("file.pdf")` et ignorer complètement cette étape. + +--- + +## Étape 2 : Exporter le résultat OCR en PDF/A recherché + +Nous prenons maintenant le `result` de l’étape 1 et demandons au moteur d’écrire un nouveau fichier. Le drapeau clé ici est *PDF/A* — la version normalisée ISO du PDF conçue pour la préservation à long terme. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Pourquoi c’est important + +- **PDF recherché** : Le fichier de sortie contient une couche de texte cachée et sélectionnable. Vous pouvez maintenant faire Ctrl + F dans le document. +- **Conformité PDF/A** : Certaines organisations (juridiques, financières) exigent le PDF/A pour les archives ; cette étape satisfait automatiquement cette contrainte. +- La méthode **ajoute du texte recherché** sans aplatir l’image, de sorte que la fidélité visuelle reste parfaite. + +#### Cas particulier : besoin d’un PDF standard ? + +Si le PDF/A ne vous intéresse pas, remplacez `save_as_pdfa` par `save_as_pdf`. Le reste du flux de travail reste identique. + +--- + +## Étape 3 : Vérifier le PDF recherché + +Une vérification rapide vous évite des bugs mystérieux plus tard. Ouvrez le fichier généré dans n’importe quel lecteur PDF, essayez de sélectionner un mot, et utilisez la fonction de recherche. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Résultat attendu + +Lorsque vous exécutez le script, la console affiche : + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +En ouvrant le fichier, vous devez voir l’image originale de la facture avec une fine couche de texte invisible. Sélectionnez n’importe quel mot ; il sera sélectionnable—**c’est le texte recherché** que vous venez d’ajouter. + +--- + +## Ajouter du texte recherché à des PDF existants (Bonus) + +Parfois, vous avez déjà un PDF mais devez **ajouter du texte recherché**. Le même moteur peut superposer les résultats OCR sur un PDF existant : + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Ici, `apply_to` fusionne la couche cachée avec les pages originales, vous permettant de **créer un PDF recherché** sans rescanner. + +--- + +## Pièges courants et astuces + +| Piège | Comment l’éviter | +|-------|-------------------| +| **Images sources à basse résolution** (< 150 dpi) | Agrandir ou demander un scan à plus haute résolution ; la précision de l’OCR chute fortement en dessous de 150 dpi. | +| **Données linguistiques manquantes** | Installez les packs de langues appropriés pour votre moteur OCR (`pip install pdfocr[eng,spa]`). | +| **Dossier de sortie non inscriptible** | Exécutez le script avec les permissions suffisantes ou choisissez un autre répertoire. | +| **Échec de validation PDF/A** | Assurez‑vous de ne pas incorporer de polices ou de JavaScript non supportés ; la plupart des SDK gèrent cela automatiquement avec `save_as_pdfa`. | + +--- + +## Script complet – Solution en un seul fichier + +Voici un script autonome qui réunit tous les éléments. Copiez‑collez‑le, remplacez les chemins factices, et vous êtes prêt à **convertir une image en PDF/A** en quelques secondes. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Ce que fait ce script :** +1. Charge le moteur OCR. +2. Lit l’image choisie et extrait le texte. +3. Écrit un **PDF/A recherché** que vous pouvez immédiatement distribuer ou archiver. + +N’hésitez pas à encapsuler la logique `main` dans une fonction qui traite un dossier complet — il suffit d’itérer sur `os.listdir()` et de répéter les trois étapes pour chaque fichier. + +--- + +## Prochaines étapes & sujets connexes + +Maintenant que vous avez maîtrisé **comment OCR un PDF**, explorez ces idées complémentaires : + +- **Traitement par lots** : utilisez `concurrent.futures` pour OCRiser des dizaines de factures en parallèle. +- **Injection de métadonnées** : ajoutez des dates de création ou des numéros de facture aux métadonnées du PDF pour faciliter l’indexation. +- **PDF hybrides** : combinez texte recherché et images intégrées pour créer un « jumeau numérique » du document papier. +- **Sorties alternatives** : exportez vers **DOCX** ou **HTML** si les systèmes en aval nécessitent des formats éditables. + +Chacune de ces options s’appuie sur les concepts de base que vous venez d’apprendre — reconnaître, exporter, vérifier. + +--- + +## Conclusion + +En résumé, vous savez maintenant **comment OCR un PDF** en transformant une simple image en **PDF/A recherché** avec seulement trois lignes de Python. Le script se charge du travail lourd, préserve les graphiques d’origine, et vous fournit un document conforme aux normes que vous pouvez rechercher, archiver ou partager. + +Testez-le avec vos propres factures, reçus ou contrats numérisés. Si vous rencontrez des difficultés, laissez un commentaire ci‑dessous ou consultez la documentation officielle du SDK — elle regorge généralement d’exemples supplémentaires. Bon codage, et profitez de votre nouvelle capacité à rendre n’importe quelle image instantanément interrogeable ! + +![Exemple de comment OCR un PDF montrant l’image originale et la superposition du PDF recherché](placeholder.png "Exemple de comment OCR un PDF montrant l’image originale et la superposition du PDF recherché") + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et à explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment OCR un PDF en .NET avec Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Reconnaître le texte d’un PDF – Opérations OCR avec Aspose.OCR pour Java](/ocr/english/java/ocr-operations/) +- [Convertir des images en PDF C# – Enregistrer le résultat OCR multi‑pages](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/french/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..c740a09dc --- /dev/null +++ b/ocr/french/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Comment effectuer la reconnaissance OCR d’un PDF avec Aspose OCR Cloud. + Apprenez à extraire le texte d’un PDF, convertir une page PDF en PNG et enregistrer + les images des pages PDF en Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: fr +og_description: Comment OCR un PDF avec Aspose OCR Cloud. Ce guide montre comment + extraire le texte brut d’un PDF, convertir une page PDF en PNG et enregistrer les + images des pages du PDF. +og_title: Comment faire de l'OCR d'un PDF avec Aspose OCR Cloud – Étape par étape +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Comment OCR un PDF avec Aspose OCR Cloud – Guide complet +url: /fr/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment faire de l'OCR de PDF avec Aspose OCR Cloud – Guide complet + +Vous vous êtes déjà demandé **comment faire de l'OCR de PDF** sans vous battre avec des outils de bureau lourds ? Vous n'êtes pas seul—de nombreux développeurs rencontrent ce problème lorsqu'ils ont besoin d'une méthode rapide et programmatique pour extraire le texte de documents numérisés. La bonne nouvelle ? Avec Aspose OCR Cloud, vous pouvez **extraire du texte d'un PDF**, transformer chaque page en PNG, et même **enregistrer les images des pages PDF** pour une utilisation ultérieure, le tout depuis un script Python propre. + +Dans ce tutoriel, nous passerons en revue tout ce que vous devez savoir : de l'installation du SDK, à la licence du moteur, en passant par la reconnaissance de PDF multi‑pages, jusqu'à l'extraction de texte brut, la conversion des pages en PNG et la persistance de ces images sur le disque. À la fin, vous disposerez d'un extrait réutilisable que vous pourrez intégrer à n'importe quel projet nécessitant des capacités **comment faire de l'OCR de PDF**. + +## Ce dont vous avez besoin + +- **Python 3.8+** (le code fonctionne également sur 3.10 et versions ultérieures) +- Un compte Aspose OCR Cloud – vous recevrez un fichier de licence d'essai gratuit (`Aspose.OCR.lic`) +- Le package `asposeocrcloud` (`pip install asposeocrcloud`) +- Un PDF numérisé, multi‑pages que vous souhaitez traiter + +C’est tout. Aucun binaire supplémentaire, aucune dépendance native, juste du Python pur. + +## Comment faire de l'OCR de PDF – Configuration et licence + +Avant de pouvoir appeler des méthodes OCR, vous devez indiquer au SDK qui vous êtes. Aspose utilise un fichier de licence léger que vous placez à un endroit accessible à votre script. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Astuce :* Si vous sautez l'étape de licence, le SDK fonctionnera toujours mais ajoutera un petit filigrane aux images de sortie. Ce n’est pas idéal pour la production. + +## Étape 2 : Installer le SDK Python Aspose OCR Cloud + +Ouvrez un terminal et exécutez : + +```bash +pip install asposeocrcloud +``` + +Le package récupère toutes les dépendances requises (requests, pillow, etc.) afin que vous n'ayez rien d'autre à chercher. + +## Étape 3 : Créer un moteur OCR et choisir une langue + +Le moteur est le cœur de l'opération. Vous pouvez spécifier n'importe quelle langue prise en charge par Aspose ; l'anglais fonctionne dans la plupart des cas. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Pourquoi définir la langue ? Parce que le moteur OCR utilise des dictionnaires spécifiques à chaque langue pour améliorer la précision. Si vous traitez des PDF en français, remplacez simplement `ENGLISH` par `FRENCH`. + +## Étape 4 : Pointer vers votre PDF multi‑pages + +Fournissez au moteur le chemin complet du fichier que vous souhaitez traiter. Les chemins relatifs sont acceptables tant qu'ils se résolvent depuis le répertoire de travail du script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Assurez‑vous que le fichier est lisible ; sinon vous verrez une `FileNotFoundError`. + +## Étape 5 : Exécuter l'OCR – Vous obtenez une liste de résultats + +Appeler `recognize_pdf` renvoie une liste où chaque élément correspond à une page du PDF source. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Chaque `OcrResult` contient deux propriétés pratiques : + +* `text` – la représentation en texte brut de la page (idéal pour **extract plain text pdf**) +* `image` – un objet `Image` de Pillow de la page rendue (parfait pour **convert pdf page png**) + +## Étape 6 : Extraire le texte du PDF et convertir les pages en PNG + +Nous parcourons maintenant les résultats, affichons le texte extrait et enregistrons une version PNG de chaque page. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Sortie console attendue + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Vous trouverez également `page_1.png`, `page_2.png`, … dans `YOUR_DIRECTORY`. Ce sont les images rasterisées des pages que vous pouvez injecter dans des pipelines de traitement d'image en aval. + +## Étape 7 : Enregistrer les images des pages PDF (post‑traitement optionnel) + +Si vous n’avez besoin que des images et pas du texte, vous pouvez ignorer la ligne `print(res.text)`. Inversement, si vous souhaitez stocker le texte dans des fichiers `.txt` séparés, ajoutez simplement une petite écriture : + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Cette petite addition montre à quel point il est facile de **save PDF page images** tout en conservant le contenu extrait. + +## Exemple complet fonctionnel + +En rassemblant tous les éléments, voici le script complet que vous pouvez copier‑coller dans `ocr_pdf.py` : + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Exécutez‑le avec : + +```bash +python ocr_pdf.py +``` + +Vous devriez voir l’affichage console du texte de chaque page ainsi qu’une série de fichiers PNG + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Comment faire de l'OCR de PDF en .NET avec Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Reconnaître le texte PDF – Opérations OCR avec Aspose.OCR pour Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convertir des images en PDF C# – Enregistrer le résultat OCR multi‑pages](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/french/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..39ef5cfd4 --- /dev/null +++ b/ocr/french/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Comment prétraiter les images pour l’OCR avec Python. Apprenez à binariser + une image avec la méthode d’Otsu, à redresser les documents numérisés et à améliorer + la précision de l’OCR pour le texte allemand. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: fr +og_description: Comment prétraiter les images pour l'OCR en Python. Ce tutoriel montre + comment binariser une image avec Otsu, comment redresser les documents numérisés, + et comment améliorer la précision de l'OCR pour les images en allemand. +og_title: Comment prétraiter les images pour l'OCR – Guide complet en Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Comment prétraiter les images pour l'OCR – Guide complet en Python +url: /fr/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment prétraiter les images pour l'OCR – Guide complet Python + +Vous vous êtes déjà demandé **comment prétraiter les images pour l'OCR** afin que le texte soit parfaitement lisible ? Vous n'êtes pas le seul. Les documents numérisés—en particulier les pages allemandes bruyantes—peuvent être un cauchemar pour n'importe quel moteur OCR. Bonne nouvelle ? Quelques étapes de prétraitement intelligentes peuvent transformer un scan flou et granuleux en une image propre et lisible par machine. + +Dans ce tutoriel, nous parcourrons un exemple pratique qui montre **comment prétraiter les images pour l'OCR** avec Python. Vous apprendrez à **binariser une image avec Otsu**, **comment redresser les documents numérisés**, et globalement **comment améliorer la précision de l'OCR** lorsque vous devez **extraire du texte d'images allemandes**. Pas de fioritures, juste un script fonctionnel que vous pouvez copier‑coller dès aujourd'hui. + +## Ce dont vous avez besoin + +- **Python 3.9+** (toute version récente fonctionne) +- Une bibliothèque OCR qui expose une classe `OcrEngine` — pour la démo, nous supposerons un paquet générique `ocr`. Installez‑le avec `pip install ocr-lib`. +- Un scan allemand bruyant (`noisy_german_scan.tif`) que vous voulez tester. +- Une compréhension de base des fonctions Python (si vous avez déjà écrit un `def`, vous êtes prêt). + +> **Astuce :** Si vous utilisez un SDK OCR différent (par ex. : Tesseract via `pytesseract`), les concepts restent les mêmes — adaptez simplement les noms de méthodes. + +## Vue d'ensemble de la solution + +1. **Créer une instance du moteur OCR.** +2. **Définir la langue de reconnaissance sur l'allemand.** +3. **Construire un pipeline de prétraitement personnalisé** incluant le redressement, le débruitage, la binarisation (Otsu) et l'étirement du contraste. +4. **Attacher le pipeline au moteur** afin que chaque image le traverse automatiquement. +5. **Exécuter l'OCR** sur un scan allemand bruyant. +6. **Afficher le texte extrait** pour vérifier le résultat. + +Ci‑dessous, nous détaillons chaque étape, expliquons **pourquoi** c’est important, et montrons le code exact dont vous avez besoin. + +![exemple de prétraitement d'images pour OCR](image.png "exemple de prétraitement d'images pour OCR") + +## Étape 1 : Créer une instance du moteur OCR + +Tout d'abord—sans moteur, rien ne se passe. L'objet `OcrEngine` est le point d'entrée qui coordonne tout le traitement ultérieur. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Pourquoi c’est important :* L'initialisation du moteur configure les ressources internes (comme les modèles de langue) et vous donne une base propre pour y attacher un pipeline personnalisé plus tard. + +## Étape 2 : Définir la langue de reconnaissance sur l'allemand + +La précision de l'OCR dépend fortement de la langue. En indiquant au moteur d’attendre de l'allemand, vous activez le bon jeu de caractères et le modèle linguistique approprié. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Si vous omettez cela, le moteur pourrait se rabattre sur l'anglais, mal reconnaître les umlauts (ä, ö, ü) et le caractère ß — des écueils fréquents avec les scans allemands. + +## Étape 3 : Construire un pipeline de prétraitement personnalisé + +C’est le cœur de **comment prétraiter les images pour l'OCR**. Nous chaînons quatre transformations : + +| Transformation | Ce que cela fait | Pourquoi c’est utile | +|----------------|-------------------|----------------------| +| **Deskew** | Fait pivoter l'image pour la rendre horizontale (max 5°) | Les scans ne sont jamais parfaitement alignés ; le redressement élimine l’inclinaison qui perturbe la segmentation des caractères. | +| **Denoise** | Réduit les taches aléatoires (intensité 0,7) | Le bruit crée de fausses bordures que le moteur OCR peut interpréter comme des caractères. | +| **Binarize (Otsu)** | Convertit en noir et blanc à l’aide de la méthode d’Otsu | Une image binaire propre offre un contraste net entre le texte (premier plan) et l’arrière‑plan. | +| **Contrast Stretch** | Étend la gamme dynamique | Améliore la lisibilité des traits faibles, surtout sur les documents anciens. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Comment redresser les documents numérisés + +L’appel `deskew` ci‑dessus répond concrètement à **comment redresser les documents numérisés**. En interne, il estime l’angle dominant des lignes de texte via la transformée de Hough et fait pivoter l’image en sens inverse. Si vos documents sont tournés de plus de 5°, augmentez `max_angle`, mais attention aux artefacts de sur‑rotation. + +### Binariser l'image avec Otsu + +La ligne `binarize(method="otsu")` répond directement à la requête **binariser une image avec otsu**. L’algorithme d’Otsu calcule un seuil qui minimise la variance intra‑classe, idéal pour les documents avec des histogrammes bimodaux (texte sombre vs. fond clair). + +## Étape 4 : Attacher le pipeline au moteur + +Nous indiquons maintenant au moteur OCR d’exécuter chaque image entrante à travers le pipeline que nous venons de créer. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Pourquoi c’est important :* Sans enregistrement, le moteur traiterait le scan brut, ignorant tout le nettoyage que nous venons de configurer. Cette étape garantit **comment améliorer la précision de l'OCR** en appliquant le même prétraitement de façon cohérente. + +## Étape 5 : Reconnaître le texte d'un scan allemand bruyant + +Il est temps de tout assembler. Nous fournissons au moteur une image allemande bruyante et laissons le moteur faire le travail lourd. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Si vous êtes curieux de la performance, vous pouvez chronométrer l’appel : + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Étape 6 : Afficher le texte reconnu + +Enfin, nous imprimons la chaîne extraite. C’est la réponse directe à **extraire du texte d'une image allemande**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Résultat attendu + +En supposant que le scan d’exemple contienne la phrase « Die schnelle braune Füchsin springt über den faulen Hund. », vous devriez obtenir quelque chose comme : + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Si la sortie contient encore des caractères illisibles, envisagez d’ajuster l’intensité du `denoise` ou d’augmenter `max_angle` pour le redressement. + +## Pièges courants et comment les surmonter + +- **Modèle de langue manquant :** Oublier `set_recognition_language(Language.GERMAN)` entraîne souvent l’absence d’umlauts. Vérifiez bien cet appel. +- **Sur‑débruitage :** Une intensité supérieure à 0,9 peut effacer les traits fins, surtout dans les polices anciennes. Restez entre 0,5 et 0,7 dans la plupart des cas. +- **Format de fichier incorrect :** Certains moteurs OCR peinent avec les TIFF multi‑pages. Si vous avez un document multi‑pages, découpez‑le en fichiers d’une page chacun d’abord. +- **Ordre du pipeline :** L’ordre présenté (deskew → denoise → binarize → contrast) est intentionnel. Binariser avant de débruiter peut figer le bruit ; débruitez toujours en premier. + +## Extension du pipeline (et après ?) + +Maintenant que vous avez une base solide, vous pourriez vouloir : + +- **Ajouter une ouverture morphologique** pour nettoyer les petites taches (`.morph_open(kernel=3)`). +- **Intégrer un modèle linguistique** pour la correction post‑traitement (`ocr_engine.apply_spellcheck()`). +- **Paralléliser le traitement par lots** pour de grands ensembles de données en utilisant `concurrent.futures`. + +Toutes ces extensions conservent l’idée centrale de **comment prétraiter les images pour l'OCR** tout en boostant **comment améliorer la précision de l'OCR** davantage. + +## Conclusion + +Nous venons de couvrir **comment prétraiter les images pour l'OCR** de bout en bout : créer un moteur, définir la langue allemande, construire un pipeline qui **binarise une image avec Otsu**, **comment redresser les documents numérisés**, et enfin **extraire du texte d'une image allemande** avec plus de confiance. En suivant les six étapes ci‑dessus, vous constaterez une nette amélioration de la qualité de reconnaissance—plus besoin de corrections manuelles interminables. + +Testez le script avec vos propres scans, jouez avec les paramètres, et laissez les résultats parler d’eux-mêmes. Vous avez des questions sur un réglage de prétraitement particulier ? Laissez un commentaire, et nous approfondirons ensemble. + +Bon codage, et que votre OCR soit toujours précis ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extraire le texte d'image C# avec sélection de langue en utilisant Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Comment définir la valeur de seuil dans la reconnaissance d'image OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Comment OCR une image – Effectuer l'OCR sur une image dans la reconnaissance d'image OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/french/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..d137674c7 --- /dev/null +++ b/ocr/french/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,320 @@ +--- +category: general +date: 2026-06-06 +description: OCR d'image PNG avec Python – apprenez comment extraire du texte d'une + image, exécuter un exemple d'OCR en Python et même lire facilement du texte grec + ancien. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: fr +og_description: OCR d'image PNG en Python expliqué. Ce guide montre comment extraire + du texte d’une image, exécuter un exemple d’OCR en Python et lire le grec ancien + facilement. +og_title: OCR d'image PNG en Python – Tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR d'image PNG en Python – Guide complet étape par étape +url: /fr/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR d'image PNG en Python – Guide complet étape par étape + +Vous êtes‑vous déjà demandé comment **OCR PNG image** des fichiers directement depuis un script Python ? Peut‑être avez‑vous un dossier rempli de manuscrits anciens numérisés et vous devez **extract text from image** sans taper tout manuellement. La bonne nouvelle, c’est que vous n’avez pas besoin d’un doctorat en vision par ordinateur—juste quelques lignes de code et la bonne bibliothèque, et vous lirez du grec ancien en quelques secondes. + +Dans ce tutoriel, nous parcourrons un **python OCR example** qui reconnaît le texte d’un PNG, définit la langue en grec polytonique, et affiche le résultat. À la fin, vous saurez exactement comment **recognize image text**, gérer les pièges courants, et adapter le script à d’autres langues ou formats d’image. + +## Ce que vous apprendrez + +- Installer et configurer une bibliothèque OCR Python (pytesseract + Tesseract OCR) +- Créer une instance du moteur OCR et charger un fichier PNG +- Définir la langue de reconnaissance en grec polytonique afin de pouvoir **read ancient greek** +- Produire le texte reconnu et dépanner les problèmes typiques +- Étendre le script pour traiter par lots plusieurs PNG ou passer à une autre langue + +### Prérequis + +| Exigence | Pourquoi c’est important | +|----------|---------------------------| +| Python 3.8+ | Syntaxe moderne et annotations de type | +| `pytesseract` package | Petit wrapper autour du moteur Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Le moteur réel qui effectue le travail lourd | +| Greek language data (`grc.traineddata`) | Nécessaire pour **read ancient greek** correctement | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Notre cible pour la démonstration **ocr png image** | + +Vous pouvez installer la partie Python avec : + +```bash +pip install pytesseract Pillow +``` + +Et sur Ubuntu/macOS, vous ajouteriez le moteur lui‑même : + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +N’oubliez pas de télécharger les données d’entraînement grec polytonique : + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Le chemin peut différer ; ajustez `TESSDATA_PREFIX` si nécessaire.)* + +## OCR PNG Image : Créer l’instance du moteur + +La première chose dont nous avons besoin est un objet qui communique avec Tesseract. Dans `pytesseract`, le moteur est accessible via des fonctions au niveau du module, mais pour plus de clarté nous l’envelopperons dans une petite classe. Cela reflète le concept de « engine » que vous avez vu dans l’extrait original. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Pourquoi l’envelopper ?** +- Conserve l’API publique identique à l’extrait avec lequel vous avez commencé, rendant la migration indolore. +- Nous permet d’ajouter de la journalisation ou de la gestion d’erreurs plus tard sans toucher au flux principal. +- Démonstre une bonne pratique OOP—quelque chose que les développeurs seniors apprécient. + +## Extraire le texte d’une image : définir la langue en grec polytonique + +Maintenant que nous avons un moteur, nous devons lui indiquer quelle langue attendre. Le grec polytonique utilise des diacritiques qui ne sont pas couverts par les données « greek » standard, nous pointons donc Tesseract vers le fichier d’entraînement `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Si vous souhaitez un jour **extract text from image** dans une autre langue, remplacez simplement `"grc"` par `"eng"` pour l’anglais, `"fra"` pour le français, etc. La même ligne fonctionne pour toute langue que vous avez installée. + +## Reconnaître le texte d’une image : exécuter l’OCR sur un PNG + +Avec la langue définie, nous injectons le PNG dans le moteur. L’exemple original utilisait un chemin codé en dur ; nous le rendrons un peu plus flexible en utilisant des objets `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Conseils & cas limites** + +- **File not found** – encapsulez l’appel dans un `try/except FileNotFoundError` pour fournir un message convivial. +- **Low‑resolution PNG** – envisagez un pré‑traitement (par ex., redimensionnement, binarisation) avec Pillow avant l’OCR. +- **Non‑Greek text** – Tesseract essaiera toujours de décoder, mais la précision chute fortement. Assurez‑vous toujours que la langue correspond. + +## Sortir le texte reconnu + +Enfin, nous affichons le résultat. Dans un projet réel, vous pourriez écrire dans une base de données, un CSV, ou même l’alimenter dans un pipeline de traduction. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Lorsque vous exécutez le script sur une numérisation claire d’une inscription grecque ancienne, vous devriez voir quelque chose comme : + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Si la sortie apparaît brouillée, vérifiez que le fichier **greek.traineddata** se trouve dans le bon dossier et que le PNG n’est pas trop bruyant. + +## Exemple complet fonctionnel (Toutes les étapes dans un seul script) + +Ci‑dessous se trouve le programme complet, prêt à être exécuté. Enregistrez‑le sous le nom `ocr_greek.py` et lancez `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Sortie attendue** (troncature pour la brièveté) : + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Si vous voyez les caractères grecs corrects, félicitations — vous avez réussi à effectuer une opération **ocr png image** en Python ! + +## Questions fréquentes & astuces pro + +### Comment améliorer la précision sur un PNG bruyant ? + +- Convertir l’image en niveaux de gris : `img = img.convert('L')` +- Appliquer un seuil binaire : `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Agrandir avec `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Ces étapes transforment souvent un cauchemar de **recognize image text** en un résultat propre. + +### Puis‑je traiter un dossier complet de PNG ? + +Absolument. Enveloppez l’appel `recognize_image` dans une boucle `for` sur `Path.glob("*.png")`. Stockez chaque résultat dans un dictionnaire ou écrivez‑le dans un CSV pour une analyse ultérieure. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Et si je dois extraire uniquement les nombres ? + +Passez une chaîne **config** personnalisée à `image_to_string` : + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +De cette façon vous pouvez **extract text from image** des fichiers contenant des tableaux, numéros de série ou horodatages. + +### Existe‑t‑il un moyen d’obtenir des scores de confiance ? + +Oui—utilisez `pytesseract.image_to_data` qui renvoie un TSV avec la confiance par mot. Vous pouvez filtrer les tokens à faible confiance avant d’assembler la chaîne finale. + +## Étendre le tutoriel + +Maintenant que vous avez maîtrisé les bases, envisagez d’explorer ces sujets connexes : + +- **Batch OCR with multiprocessing** – accélérer le traitement de grands corpus de PNG. +- **Hybrid OCR + NLP pipelines** – traduire automatiquement le grec ancien extrait en anglais moderne. +- **Alternative engines** – essayer `easyocr` ou des méthodes basées sur `opencv` pour des cas d’utilisation spécifiques. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, ou AWS Textract pour une mise à l’échelle sans serveur. + +Chacun de ces éléments s’appuie sur le **python ocr example** de base que nous venons de couvrir, vous permettant de plonger plus profondément en toute confiance. + +## Conclusion + +Nous avons pris un extrait simple et l’avons transformé en un flux de travail robuste **ocr png image** en Python. En créant un `OcrEngine`, en définissant la langue en grec polytonique, en injectant un PNG et en affichant le résultat, vous savez maintenant comment **extract text from image** des fichiers, **recognize image text**, et même **read ancient greek**. + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extraire du texte d’une image avec Aspose OCR – Guide étape par étape](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Comment définir la valeur du seuil dans la reconnaissance d’image OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [reconnaître le texte d’une image avec Aspose OCR pour plusieurs langues](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/french/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..1cb032971 --- /dev/null +++ b/ocr/french/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-06 +description: Tutoriel OCR en Python montrant comment reconnaître le texte d’une image, + réaliser une OCR haute résolution et extraire du texte espagnol à l’aide d’une OCR + accélérée par GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: fr +og_description: Tutoriel Python OCR qui vous guide à travers la reconnaissance de + texte d'image, l'OCR haute résolution et l'extraction de texte espagnol avec accélération + GPU. +og_title: Tutoriel OCR Python – Reconnaissance de texte accélérée par GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Tutoriel OCR Python – Reconnaître le texte d'image avec accélération GPU +url: /fr/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutoriel OCR Python – Reconnaître le texte d’une image avec accélération GPU + +Vous êtes-vous déjà demandé comment **reconnaître le texte d’une image** dans un script Python sans passer des heures à ajuster les paramètres ? Vous n’êtes pas seul. Dans ce **tutoriel OCR python** nous allons vous montrer une méthode propre, de bout en bout, pour extraire du texte espagnol d’une image haute résolution, et nous y ajouterons l’accélération GPU afin que le processus soit ultra‑rapide. + +Considérez cela comme une petite démonstration à la pause café que vous pourrez développer plus tard en un pipeline de production. À la fin de ce guide, vous disposerez d’un programme exécutable qui effectue de **l’OCR haute résolution**, exploite un GPU compatible CUDA, et renvoie exactement les caractères espagnols dont vous avez besoin. + +## Ce que vous allez apprendre + +- Comment installer et importer une bibliothèque OCR moderne qui supporte l’accélération GPU. +- Comment créer une instance du moteur OCR et la configurer pour **reconnaître le texte d’une image** en espagnol. +- Comment activer **l’OCR accéléré par GPU** pour obtenir des gains de vitesse massifs sur des fichiers haute résolution. +- Comment gérer les cas limites tels que l’absence de pilotes CUDA ou le basculement vers le CPU. +- Astuces pour améliorer la précision lorsque vous devez **extraire du texte espagnol** à partir de scans bruyants. + +### Prérequis + +- Python 3.9+ (le code fonctionne également sur 3.10 et versions supérieures). +- Un GPU compatible CUDA (optionnel mais fortement recommandé). +- Familiarité de base avec pip et les environnements virtuels. + +Si l’un de ces éléments vous manque, le tutoriel fonctionne toujours — il suffit de sauter l’étape GPU et la bibliothèque reviendra automatiquement au CPU. + +--- + +## Tutoriel OCR Python : Installation des paquets requis + +Tout d’abord, il nous faut un moteur OCR fiable. Pour ce tutoriel, nous utiliserons le package open‑source **`easyocr`**, qui intègre le support GPU dès qu’un dispositif compatible est détecté. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Astuce :** Si vous avez déjà installé PyTorch, assurez‑vous qu’il correspond à votre version CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Des versions incompatibles sont une cause fréquente d’erreurs « GPU non trouvé ». + +--- + +## Étape 1 : Créer une instance du moteur OCR + +Nous lançons maintenant le moteur. EasyOCR appelle sa classe principale `Reader`. Le constructeur accepte une liste de codes de langue ; nous passerons `"es"` pour l’espagnol. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Pourquoi c’est important :* En déclarant la langue dès le départ, le moteur ne charge que les poids de réseau neuronal nécessaires, ce qui économise de la mémoire et accélère l’inférence — particulièrement utile lorsque vous traitez de **l’OCR haute résolution** plus tard. + +--- + +## Étape 2 : Préparer une image haute résolution + +Les images haute résolution offrent au modèle davantage de pixels, ce qui se traduit généralement par une meilleure reconnaissance des caractères. Supposons que vous disposiez d’un fichier nommé `high_res_spanish.png` placé dans un dossier appelé `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Si vous n’avez pas d’échantillon haute résolution sous la main, vous pouvez en télécharger un gratuitement sur Unsplash ou générer une image synthétique avec Pillow. L’important est de garder le DPI au‑dessus de 300 pour obtenir les meilleurs résultats. + +--- + +## Étape 3 : Activer l’accélération GPU (Optionnel mais recommandé) + +EasyOCR tente déjà d’utiliser le GPU dès que vous définissez `gpu=True`. Cependant, il est judicieux de vérifier que le dispositif est réellement utilisé, surtout sur des stations à plusieurs GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Pourquoi vérifier ?* Si le script bascule silencieusement vers le CPU, vous vous demanderez pourquoi une opération de 5 secondes prend soudainement 30 secondes. Cette petite vérification rend le comportement transparent et maintient votre pipeline **OCR accéléré par GPU** prévisible. + +--- + +## Étape 4 : Effectuer l’OCR haute résolution et reconnaître le texte d’image + +Place maintenant la partie amusante — la lecture du texte. La méthode `readtext` d’EasyOCR renvoie une liste de tuples contenant la boîte englobante, la chaîne reconnue et un score de confiance. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Si vous avez besoin de la chaîne brute sans coordonnées, définissez `detail=0`. Pour la plupart des cas d’utilisation de **reconnaître le texte d’image**, la valeur par défaut (`detail=1`) vous fournit suffisamment de contexte pour un post‑traitement ultérieur. + +--- + +## Étape 5 : Extraire le texte espagnol et nettoyer la sortie + +Comme nous avons demandé à EasyOCR de travailler en espagnol, les chaînes retournées le sont déjà. Vous pouvez néanmoins les concaténer, supprimer les espaces superflus ou filtrer les détections à faible confiance. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Et si la confiance est basse ?** Vous pouvez soit abaisser le seuil (au risque d’introduire du bruit) soit pré‑traiter l’image (augmenter le contraste, binariser ou redresser). Ces astuces sont courantes lorsqu’on traite de **l’OCR haute résolution** sur des documents numérisés. + +--- + +## Étape 6 : Gestion des cas limites et ajustements de performance + +Même les modèles les mieux entraînés rencontrent quelques scénarios difficiles. Voici deux correctifs rapides que vous pouvez coller dans votre script. + +### 6.1 Basculement lorsqu’aucun GPU n’est présent + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Réduction d’échantillonnage d’images très grandes + +Si votre image dépasse 4000 × 4000 px, vous risquez d’épuiser la mémoire du GPU. Réduisez‑la proportionnellement tout en conservant le DPI : + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Ces extraits rendent le script robuste, que vous l’exécutiez sur une station de travail ou sur un ordinateur portable modeste. + +--- + +## Exemple complet fonctionnel + +En rassemblant tous les morceaux, voici le script complet que vous pouvez copier‑coller et exécuter immédiatement : + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Sortie attendue (exemple) :** + + + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités d’API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extraire du texte d’une image avec Aspose OCR – Guide pas à pas](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Comment faire de l’OCR de texte d’image avec langue en utilisant Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Comment reconnaître les rectangles de page pour la reconnaissance de texte OCR dans Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/french/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..7cafc4c17 --- /dev/null +++ b/ocr/french/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-06 +description: Reconnaître le texte d’une image en utilisant le moteur OCR Python. Apprenez + comment configurer le moteur OCR Python et extraire le texte d’une image avec le + traitement cloud en quelques minutes. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: fr +og_description: Reconnaître le texte d’une image avec le moteur OCR Python. Ce guide + montre comment configurer le moteur OCR Python et extraire le texte d’une image + efficacement. +og_title: Reconnaître du texte à partir d'une image en Python – Tutoriel complet d'installation +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Reconnaître du texte à partir d'une image en Python – Guide complet d'installation + du moteur OCR +url: /fr/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconnaître du texte à partir d'une image en Python – Tutoriel complet d'installation + +Vous êtes-vous déjà demandé comment **reconnaître du texte à partir d'une image** en quelques lignes de Python ? Vous n'êtes pas seul. Que vous construisiez un scanner de reçus, un numériseur de documents ou un simple projet de loisir, pouvoir extraire du texte d'une image est une compétence qui rapporte rapidement. + +Dans ce tutoriel, nous parcourrons l’ensemble du processus — en commençant par la configuration du **configure OCR engine python**, en passant par l’authentification cloud, et en terminant par la façon d’**extract text from image** avec un résultat fiable. Pas de magie, seulement des étapes claires que vous pouvez copier‑coller et exécuter dès aujourd’hui. + +## Ce que vous allez apprendre + +- Comment installer et importer la bibliothèque OCR requise. +- Les commandes exactes pour **configure OCR engine python** pour le traitement cloud. +- Un script complet, exécutable, qui **recognize text from image** et affiche le résultat. +- Des astuces pour gérer les pièges courants comme les clés API manquantes ou les formats d’image non pris en charge. +- Des idées de niveau supérieur telles que le traitement par lots et le repli local. + +### Prérequis + +- Python 3.8+ installé sur votre machine. +- Une connexion Internet (l’exemple utilise un service OCR basé sur le cloud). +- Une clé API valide du fournisseur OCR (vous verrez où l’insérer). + +Si vous avez tout cela, plongeons‑y—pas de blabla, juste un guide pratique qui fonctionne. + +--- + +## Étape 1 : Installer la bibliothèque OCR et l’importer + +Avant de pouvoir **configure OCR engine python**, vous avez besoin de la bibliothèque qui communique avec le service cloud. Dans notre exemple, nous utiliserons un paquet fictif mais représentatif appelé `ocrcloud`. Remplacez‑le par le vrai paquet que vous utilisez (par ex. `easyocr`, `google-cloud-vision`, etc.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Pourquoi c’est important :** L’import de la classe vous donne accès à des méthodes comme `use_cloud()` et `set_api_key()`. Sans cet import, le reste du script lèverait une `NameError`. + +*Astuce :* Verrouillez la version dans votre `requirements.txt` (`ocrcloud==2.1.0`) pour éviter des changements incompatibles plus tard. + +--- + +## Étape 2 : Créer et **configure OCR engine python** pour le mode Cloud + +Nous allons maintenant réellement **configure OCR engine python**. Le moteur démarre en mode local par défaut ; le passer en mode cloud vous permet de déléguer l’analyse lourde d’images à des serveurs puissants. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explication :** +- `OcrEngine()` crée un nouvel objet moteur — pensez‑y comme votre toile vierge. +- `use_cloud(True)` bascule un commutateur, indiquant au moteur d’envoyer les images via HTTPS au lieu de les traiter localement. C’est crucial pour obtenir des résultats haute précision sur des polices complexes ou des photos basse résolution. + +--- + +## Étape 3 : Authentifier avec votre clé API cloud + +La plupart des services OCR cloud exigent une clé API. Cette étape montre comment injecter la crédential de façon sécurisée. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Note de sécurité :** Ne jamais coder en dur la clé dans un dépôt public. En production, vous la récupérez depuis une variable d’environnement : + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Étape 4 : **recognize text from image** – Envoyer une image distante pour le traitement + +Avec le moteur configuré, nous pouvons enfin **recognize text from image**. La méthode `recognize_image()` accepte un chemin ou une URL et renvoie un objet contenant le texte extrait. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Que se passe‑t‑il en coulisses ?** +Les octets de l’image sont téléchargés vers le point d’accès du fournisseur, traités par un modèle d’apprentissage profond, et le texte brut est renvoyé en flux. Si l’image est volumineuse, le service peut automatiquement la réduire pour accélérer le travail. + +--- + +## Étape 5 : Afficher le résultat de **extract text from image** + +Maintenant que le service OCR a fait son travail, nous affichons simplement le texte. Dans des applications réelles, vous pourriez le stocker dans une base de données ou le transmettre à une autre fonction. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Sortie attendue :** (exemple) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Si la sortie apparaît brouillée, vérifiez que l’image est nette et que vous avez sélectionné le bon modèle de langue (de nombreux services permettent de spécifier `engine.set_language("en")`). + +--- + +## Gestion des cas limites & pièges courants + +### 1. Clé API manquante ou invalide +Si vous obtenez une erreur d’authentification, assurez‑vous : +- Que la clé est active et non expirée. +- Qu’elle est correctement lue depuis l’environnement. +- Que votre réseau autorise le trafic HTTPS sortant. + +### 2. Formats d’image non pris en charge +La plupart des API OCR acceptent JPEG, PNG et PDF. Tenter un BMP ou TIFF peut déclencher une réponse « format non supporté ». Convertissez avec Pillow si besoin : + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Limites de débit +Les services cloud limitent souvent le nombre de requêtes par minute. Si vous atteignez cette limite, implémentez un back‑off exponentiel : + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Repli vers OCR local +Si le cloud est indisponible, vous pouvez revenir en arrière : + +```python +engine.use_cloud(False) # revert to local mode +``` + +Avoir un repli rend votre application résiliente. + +--- + +## Exemple complet fonctionnel + +En rassemblant le tout, voici un script que vous pouvez exécuter immédiatement (remplacez simplement les valeurs factices). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Exécutez‑le :** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Vous devriez voir le texte extrait affiché dans la console, confirmant que vous avez bien **recognize text from image** et **extract text from image** en suivant un workflow **configure OCR engine python** correctement configuré. + +--- + +## Conclusion + +Nous venons de parcourir un processus complet, de bout en bout, qui vous permet de **recognize text from image** en Python, depuis l’installation de la bibliothèque jusqu’à l’authentification d’un service cloud et enfin **extract text from image** avec un appel de fonction unique. En **configure OCR engine python** de la bonne façon, vous gagnez à la fois flexibilité (cloud vs. local) et fiabilité (gestion correcte des erreurs). + +Et après ? Essayez le traitement par lots d’un dossier de reçus, ajoutez la détection de langue, ou expérimentez avec des PDF en entrée. Le ciel est la limite une fois que vous avez maîtrisé les bases. + +Bon codage, et n’hésitez pas à poser vos questions dans les commentaires — rien ne vaut l’apprentissage collectif ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/french/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ac8477a47 --- /dev/null +++ b/ocr/french/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Exécutez la reconnaissance optique de caractères (OCR) sur une image + avec Python et consultez les scores de confiance. Apprenez à filtrer les mots à + faible confiance, à définir des seuils et à gérer les cas limites. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: fr +og_description: Exécutez la reconnaissance optique de caractères (OCR) sur une image + en Python, inspectez les niveaux de confiance et filtrez les mots à faible confiance. + Ce tutoriel vous guide à travers un exemple complet et exécutable. +og_title: Exécuter l'OCR sur une image avec Python – Guide complet +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Exécuter l'OCR sur une image avec Python – Guide complet étape par étape +url: /fr/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exécuter l'OCR sur une image avec Python – Guide complet étape par étape + +Vous avez déjà eu besoin d'**exécuter l'OCR sur une image** mais vous ne saviez pas comment obtenir un texte fiable à partir de celle‑ci ? Vous n'êtes pas seul·e — de nombreux développeurs rencontrent le même problème lorsque les mots extraits semblent incertains et que le score de confiance reste un mystère. + +Dans ce guide, nous plongerons directement dans une solution fonctionnelle : vous verrez comment exécuter l'OCR sur image, lire la confiance globale, et extraire les mots à faible confiance qui pourraient nécessiter une révision manuelle. À la fin, vous disposerez d’un script réutilisable, comprendrez pourquoi chaque ligne compte, et saurez comment ajuster le seuil de confiance pour vos propres projets. + +## Ce que couvre ce tutoriel + +Nous parcourrons l’ensemble du flux de travail — du chargement d’une image à l’impression d’un rapport propre des mots dont la confiance est inférieure à 80 % . En chemin, nous aborderons : + +* Le choix d’un moteur OCR solide (nous utiliserons **EasyOCR**, une bibliothèque OCR Python populaire) +* L’interprétation de l’attribut `confidence` que chaque résultat OCR renvoie +* Le filtrage des mots avec un **seuil de confiance OCR** personnalisé +* L’extension du script pour le traitement par lots ou des moteurs alternatifs comme **pytesseract** + +Aucune expérience préalable en OCR n’est requise, juste une familiarité de base avec Python et un environnement de travail (Python 3.9+ recommandé). + +Prêt·e à transformer des captures d’écran floues en texte propre et interrogeable ? C’est parti. + +--- + +## ## Comment exécuter l'OCR sur une image avec Python + +Le cœur du tutoriel est un extrait en trois étapes qui reflète le code que vous avez déjà vu. Ci‑dessous, nous décortiquons chaque ligne, expliquons le pourquoi, puis vous fournissons un script complet, prêt à copier‑coller. + +### Étape 1 : Installer et importer le moteur OCR + +Tout d’abord, assurez‑vous que la bibliothèque OCR est disponible. **EasyOCR** fonctionne immédiatement pour de nombreuses langues et vous fournit un score de confiance par mot. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Why EasyOCR?* It bundles a deep‑learning model that’s been trained on diverse datasets, so you typically get higher confidence values than the older Tesseract engine, especially on mixed‑quality images. + +> **Astuce pro :** Si vous êtes dans un environnement contraint (par ex. un petit conteneur Docker), `pytesseract` peut être plus léger, mais vous perdrez une partie de la précision moderne offerte par EasyOCR. + +### Étape 2 : Exécuter l'OCR sur l'image + +Nous allons maintenant **exécuter l'OCR sur image**. La méthode `recognize_image` de l’exemple original est remplacée par l’appel `readtext` d’EasyOCR, qui renvoie une liste de tuples `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Chaque entrée de `ocr_results` ressemble à : + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Le troisième élément (`0.92` dans l’exemple) est le score de confiance, compris entre 0 et 1. + +### Étape 3 : Résumer la confiance globale + +Contrairement à l’extrait précédent qui affichait un seul attribut `confidence`, EasyOCR fournit une confiance par mot. Pour obtenir une idée globale, nous allons les moyenner : + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Why average?* It gives you a quick health check—if the overall confidence is below, say, 70 %, you probably need to improve the image (better lighting, preprocessing, etc.). + +### Étape 4 : Lister les mots à faible confiance + +Voici la partie qui répond directement à la demande « lister les mots dont la confiance est inférieure au seuil souhaité ». Nous fixons par défaut un **seuil de confiance OCR** de 0,80 (80 %), mais vous pouvez l’ajuster. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +La boucle imprime chaque mot qui n’a pas atteint le seuil, accompagné de son pourcentage de confiance. C’est l’analogue exact de la boucle originale `for recognized_word in recognition_result.words`, mais adaptée au format de sortie d’EasyOCR. + +--- + +## ## Comprendre les scores de confiance OCR + +La confiance n’est pas un nombre magique ; c’est l’estimation du modèle quant à la certitude de chaque transcription. Gardez à l’esprit les points suivants : + +| Situation | Confiance typique | À faire | +|-----------|-------------------|----------| +| Numérisation claire et haute résolution | 0,95 – 1,00 | Aucun travail supplémentaire nécessaire | +| Légère flou ou éclairage inégal | 0,80 – 0,94 | Envisager un pré‑traitement léger (augmentation du contraste) | +| Bruit important, texte tourné | < 0,70 | Appliquer un pré‑traitement (deskew, débruitage) ou changer de moteur OCR | + +> **Attention :** Certaines langues (par ex. l’écriture cursive) produisent naturellement des scores plus bas. Ajustez le seuil en conséquence. + +### Cas limites et variations + +1. **Traitement par lots** – Si vous devez **exécuter l'OCR sur image** en masse, encapsulez la logique ci‑dessus dans une boucle qui parcourt un répertoire. +2. **Multiples langues** – Passez une liste comme `['en', 'fr']` à `easyocr.Reader` et le moteur détectera les deux. +3. **Moteurs alternatifs** – Vous voulez essayer **pytesseract** ? Remplacez le bloc lecteur par : + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Vous devrez alors agréger les confiances caractère par caractère en confiances par mot — un peu plus de travail mais faisable. + +4. **Astuces de pré‑traitement** – L’application de filtres OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) peut augmenter la confiance pour les scans bruyants. + +--- + +## ## Script complet, prêt à l'emploi + +Voici le fichier Python complet que vous pouvez déposer dans votre projet. Enregistrez‑le sous le nom `ocr_report.py` et lancez `python ocr_report.py`. Assurez‑vous que le chemin de l’image pointe vers un fichier réel. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Résultat attendu** (vos chiffres varieront) : + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Si chaque mot dépasse la barre des 80 %, vous verrez le message amical « Tous les mots respectent le seuil de confiance. » à la place. + +--- + +## ## Questions fréquentes (FAQ) + +**Q : Cette méthode fonctionne‑t‑elle avec les PDF ?** +R : Pas directement. Convertissez chaque page PDF en image d’abord (par ex. avec `pdf2image`) puis alimentez le script avec le PNG/JPEG. + +**Q : Mes scores de confiance sont tous bas—que puis‑je faire ?** +R : Essayez le pré‑traitement : augmentez le contraste, éliminez le bruit de fond, ou pivotez l’image pour la mettre à l’horizontale. EasyOCR accepte également un paramètre `contrast_ths` que vous pouvez ajuster. + +**Q : Puis‑je exporter les résultats en CSV ?** +R : Absolument. Après la boucle des mots à faible confiance, écrivez `ocr_results` dans un `csv.DictWriter` où chaque ligne contient `text`, `confidence` et les coordonnées de la boîte englobante. + +**Q : Existe‑t‑il une version accélérée par GPU ?** +R : EasyOCR utilise automatiquement CUDA si un GPU compatible et PyTorch sont installés. Vérifiez avec `torch.cuda.is_available()` avant d’exécuter le script. + +--- + +## Conclusion + +Nous venons d’**exécuter l'OCR sur image** avec Python, d’inspecter la confiance globale, et d’isoler les mots à faible confiance qui nécessitent une révision manuelle. + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants abordent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment définir la valeur du seuil dans la reconnaissance d'image OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Comment utiliser Aspose OCR pour obtenir un résultat JSON dans la reconnaissance d'image](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extraire du texte d'une image – Optimisation OCR avec Aspose.OCR pour .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/german/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..18a7d03e0 --- /dev/null +++ b/ocr/german/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-06-06 +description: Extrahiere Text aus Bildern mit Python‑OCR in wenigen Minuten. Entdecke + mehrsprachige Bild‑OCR, automatische Spracherkennung und wie man OCR‑Text präzise + extrahiert. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: de +og_description: Extrahiere Text aus Bildern schnell mit Python OCR. Lerne mehrsprachige + Bild‑OCR, automatische Spracherkennung und wie man OCR‑Text Schritt für Schritt + extrahiert. +og_title: Text aus Bild mit Python OCR extrahieren – Komplettanleitung +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Text aus Bild mit Python OCR extrahieren – Komplettanleitung +url: /de/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bild mit Python OCR extrahieren – Komplettanleitung + +Haben Sie jemals **Text aus Bild extrahieren** müssen, waren sich aber nicht sicher, welche Bibliothek mehrere Sprachen automatisch verarbeiten kann? Sie sind nicht allein – Entwickler fragen ständig *wie man OCR‑Text extrahiert*, wenn sie mit internationalen Dokumenten, Quittungen oder gescannten Flyern arbeiten. In diesem Tutorial führen wir Sie durch ein praktisches Python‑Beispiel, das nicht nur Text aus einem Bild extrahiert, sondern auch **die Sprache** on the fly erkennt, sodass mehrsprachiges Bild‑OCR zum Kinderspiel wird. + +Wir decken alles ab, vom Installieren des OCR‑Pakets über das Aktivieren von **auto detect language OCR**, bis hin zum Ausführen der Engine an einem Beispielbild und dem anschließenden Ausgeben sowohl der erkannten Sprache als auch des extrahierten Strings. Am Ende haben Sie einen wiederverwendbaren Code‑Snippet, den Sie in jedes Projekt einbinden können – egal, ob Sie eine Übersetzungspipeline oder einen Daten‑Ingest‑Service bauen. + +## Text aus Bild extrahieren – Umgebung einrichten + +Bevor wir in den Code eintauchen, stellen Sie sicher, dass Ihr Arbeitsplatz diese Minimalanforderungen erfüllt: + +- Python 3.8 oder neuer (die Bibliothek nutzt Typ‑Hints, die ältere Versionen ignorieren) +- `pip` für das Paket‑Management +- Eine Bilddatei, die Text in mindestens zwei verschiedenen Sprachen enthält (z. B. Englisch + Spanisch) + +Sie benötigen außerdem die OCR‑Bibliothek, die dieses Demo‑Beispiel antreibt. Für diese Anleitung verwenden wir das fiktive `ocr`‑Paket, das populäre reale Tools wie Tesseract oder EasyOCR widerspiegelt, aber eine saubere Python‑API bietet. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro‑Tipp:** Wenn Sie auf Berechtigungsfehler stoßen, stellen Sie dem Befehl `python -m` voran oder nutzen Sie eine virtuelle Umgebung – das hält Ihre globalen site‑packages sauber. + +## OCR‑Engine‑Instanz erstellen + +Jetzt, wo die Bibliothek bereit ist, ist der erste logische Schritt, **eine OCR‑Engine‑Instanz zu erstellen**. Denken Sie an die Engine als einen intelligenten Scanner, den Sie konfigurieren können, bevor Sie ihm Bilder zufüttern. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Warum instanziieren wir die Engine separat, anstatt eine statische Methode aufzurufen? Das Engine‑Objekt hält Konfigurationszustände (wie Spracheinstellungen), die Sie über viele Bilder hinweg wiederverwenden können, wodurch Sie den Overhead einer erneuten Initialisierung jedes Mal vermeiden. + +## Auto Detect Language OCR aktivieren + +Die meisten OCR‑Tools verlangen, dass Sie einen Sprachcode angeben – `eng` für Englisch, `spa` für Spanisch usw. Das manuelle Raten der Sprache widerspricht dem Zweck eines **mehrsprachigen Bild‑OCR**‑Workflows. Glücklicherweise bietet das `ocr`‑Paket einen *auto detect language OCR*‑Modus, der das Bild analysiert und im Hintergrund das beste Sprachmodell auswählt. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Durch das Aktivieren von **detect language OCR** auf diese Weise müssen Sie keine lange Liste von Sprachcodes pflegen. Die Engine versucht, das erkannte Schriftsystem – Lateinisch, Kyrillisch, Han usw. – zuzuordnen und lädt das passende Modell automatisch. + +## Mehrsprachiges Bild‑OCR ausführen + +Mit der vorbereiteten Engine ist es Zeit, tatsächlich **Text aus Bild zu extrahieren**. Die Methode `recognize_image` akzeptiert einen Dateipfad und liefert ein Ergebnis‑Objekt, das sowohl den Rohtext als auch die erkannte Sprache enthält. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Falls Sie sich fragen, *wie man OCR‑Text aus einem PDF* statt einer PNG extrahiert, bietet dieselbe Engine `recognize_pdf` – einfach den Methodennamen austauschen. Die zugrunde liegende Erkennungslogik bleibt identisch, sodass Sie vom gleichen **auto detect language OCR**‑Feature profitieren. + +## Erkannte Sprache und extrahierten Text anzeigen + +Abschließend geben wir aus, was die Engine herausgefunden hat. Das Ergebnis‑Objekt stellt `detected_language` (ein BCP‑47‑Tag wie `en` oder `es`) und `text` bereit, das den rohen OCR‑Output enthält. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Das Ausführen des Skripts mit unserem Beispielbild sollte etwa Folgendes erzeugen: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Beachten Sie, wie die Engine Englisch korrekt als Hauptsprache identifiziert, aber dennoch die spanische Zeile erfasst – genau das, was Sie von einer robusten **mehrsprachigen Bild‑OCR**‑Lösung erwarten. + +### Was passiert, wenn die Erkennung fehlschlägt? + +Manchmal fällt die OCR‑Engine auf eine Standardsprache (meist Englisch) zurück, wenn das Bild unscharf ist oder das Schriftsystem zu exotisch ist. In solchen Fällen können Sie eine Sprachliste erzwingen: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Denken Sie jedoch daran, dass das Erzwingen von Sprachen den Komfort von **auto detect language OCR** untergräbt, also verwenden Sie es nur, wenn Sie eine bekannte Teilmenge von Sprachen haben. + +## Häufige Stolperfallen und zuverlässiges Extrahieren von OCR‑Text + +Selbst mit automatischer Erkennung können einige Hürden auftreten: + +1. **Niedrigauflösende Bilder** – Die OCR‑Genauigkeit sinkt stark unter 150 dpi. Upscaling oder ein Scan mit höherer Auflösung hilft. +2. **Rauschen und Kompressionsartefakte** – Wenden Sie vor dem Einspeisen des Bildes in die Engine einen einfachen Schwellenwert‑Filter (`opencv` oder `Pillow`) an. +3. **Gemischte Schriftsysteme auf einer Seite** – Einige Engines kämpfen mit gleichzeitigen Latein‑ und CJK‑Zeichen. Teilen Sie die Seite in Regionen auf und führen Sie bei Bedarf separate Erkennungen durch. + +Die Behebung dieser Probleme verbessert die Qualität des **extract text from image**‑Prozesses erheblich, besonders bei realen, mehrsprachigen Dokumenten. + +## Vollständiges, funktionierendes Beispiel + +Unten finden Sie das komplette, sofort ausführbare Skript, das alle besprochenen Schritte kombiniert. Speichern Sie es als `multilingual_ocr.py` und führen Sie es über die Kommandozeile aus. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Erwartete Ausgabe** (unter der Annahme, dass das Beispielbild englischen und spanischen Text enthält): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Ersetzen Sie `multilang_page.png` gern durch ein beliebiges Bild, das Text in anderen Sprachen enthält – dank **auto detect language OCR** liefert das Skript weiterhin einen sinnvollen Sprach‑Tag und den zugehörigen Text. + +![Beispiel für Textauszug aus Bild](https://example.com/ocr-sample.png "Text aus Bild extrahieren") + +## Fazit + +Sie wissen jetzt genau, **wie man OCR‑Text aus einem Bild extrahiert**, wie man **auto detect language OCR** aktiviert und wie man **mehrsprachige Bild‑OCR**‑Szenarien mit minimalem Code handhabt. Durch das Erstellen einer OCR‑Engine‑Instanz, das Einschalten der automatischen Spracherkennung und das Aufrufen von `recognize_image` können Sie zuverlässig sowohl den Sprach‑Identifier als auch den Rohtext erhalten. + +Was kommt als Nächstes? Füttern Sie die extrahierten Strings in eine Übersetzungs‑API, speichern Sie sie in einer durchsuchbaren Datenbank oder kombinieren Sie mehrere Seiten zu einem einzigen PDF‑Report. Sie können auch mit verschiedenen OCR‑Back‑ends (Tesseract, EasyOCR, Google Vision) experimentieren, während Sie denselben hohen‑level‑Workflow beibehalten – dank der konsistenten **detect language OCR**‑Schnittstelle. + +Wenn Sie auf Eigenheiten stoßen, werfen Sie einen Blick zurück auf den Abschnitt „Häufige Stolperfallen“ oder passen Sie die Bild‑Vorverarbeitungsschritte an. Viel Spaß beim Coden, und möge Ihr nächstes Projekt voller korrekt erkannter, perfekt extrahierter Texte sein! + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, damit Sie weitere API‑Features meistern und alternative Implementierungsansätze in Ihren eigenen Projekten erkunden können. + +- [Bild in Text umwandeln – OCR auf Bild von URL ausführen](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Text aus Bild extrahieren – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Textbild mit Aspose OCR für mehrere Sprachen erkennen](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/german/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..a07758a02 --- /dev/null +++ b/ocr/german/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Extrahiere Text aus Bild‑PDFs mit Python OCR. Lerne, wie du gescannte + Dokumente schnell in Text umwandeln kannst, mit asynchroner Batch‑Erkennung. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: de +og_description: Extrahiere Text aus Bild‑PDFs mit Python. Diese Schritt‑für‑Schritt-Anleitung + zeigt, wie man gescannte Dokumente mit asynchroner OCR in Text umwandelt. +og_title: Text aus Bild‑PDFs extrahieren – Python OCR‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Text aus Bild‑PDFs extrahieren – Python‑Leitfaden zum Konvertieren gescannter + Dokumente in Text +url: /de/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bild‑PDFs extrahieren – Python‑Leitfaden zum Konvertieren gescannter Dokumente in Text + +Haben Sie jemals **Text aus Bild‑PDFs extrahieren** müssen, ohne stundenlang abzutippen? In diesem Leitfaden zeigen wir Ihnen, wie Sie **gescannte Dokumente in Text konvertieren** können, indem Sie einen einfachen asynchronen OCR‑Workflow in Python verwenden. + +Wenn Sie jemals auf einen Stapel gescannter PDFs gestarrt haben und dachten: „Da muss es doch einen schnelleren Weg geben“, dann sind Sie hier genau richtig. Wir gehen jede Codezeile durch, erklären, warum jedes Teil wichtig ist, und behandeln sogar einige Randfälle, auf die Sie stoßen könnten. + +## Was Sie lernen werden + +- Wie man eine OCR‑Engine startet und die Erkennungssprache festlegt. +- Die Funktionsweise, eine gemischte Liste aus PNGs und PDFs an einen Batch‑Recognizer zu übergeben. +- Wie man den OCR‑Job asynchron ausführt, damit Ihre Anwendung reaktionsfähig bleibt. +- Wie man die Ergebnisse abruft, sie den Quelldateien zuordnet und eine saubere Ausgabe druckt. + +**Voraussetzungen**: Python 3.8+, ein grundlegendes Verständnis von `asyncio` oder `concurrent.futures` und eine OCR‑Bibliothek, die eine `OcrEngine`‑Klasse ähnlich der im Beispiel bereitstellt (z. B. Aspose.OCR, Tesseract‑Wrapper oder ein benutzerdefinierter Wrapper). Keine aufwändige Einrichtung nötig – einfach die Bibliothek installieren und Sie können loslegen. + +![Text aus Bild‑PDFs extrahieren](https://example.com/placeholder.png "Screenshot der OCR‑Ausgabe – Text aus Bild‑PDFs extrahieren") + +## Text aus Bild‑PDFs extrahieren – Einrichtung der OCR‑Engine + +Das Erste, was Sie benötigen, ist eine OCR‑Engine‑Instanz, die für die Sprache Ihrer Dokumente konfiguriert ist. In unserem Fall verwenden wir Französisch, aber Sie können sie durch jede unterstützte Sprache ersetzen. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Warum das wichtig ist**: Die Festlegung der Sprache im Voraus verbessert die Genauigkeit erheblich. Die Engine nutzt sprachspezifische Wörterbücher und Zeichenmodelle; die falsche Sprache zu verwenden ist eine häufige Ursache für fehlerhafte Ausgaben. + +## Dateiliste vorbereiten – Bilder und PDFs zusammen + +Unser Batch‑Recognizer kann sowohl Rasterbilder (`.png`, `.jpg`) als auch PDF‑Container verarbeiten. Geben Sie einfach eine einfache Python‑Liste von Dateipfaden ein. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tipp**: Halten Sie die Liste flach; die Engine wird intern jede PDF‑Seite in Bilder entpacken, bevor sie erkannt wird. Wenn Sie tausende Dateien haben, sollten Sie die Liste in kleinere Batches aufteilen, um Speicher‑Spitzen zu vermeiden. + +## Asynchrone Batch‑Erkennung starten + +Anstatt den Haupt‑Thread zu blockieren, starten wir den OCR‑Job im Hintergrund. Die Methode gibt ein `Future` zurück, das schließlich eine Liste von `OcrResult`‑Objekten enthält. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Wie es funktioniert**: Unter der Haube startet die Engine einen Thread‑Pool (oder eine async‑Aufgabe, je nach Implementierung). Das ermöglicht Ihnen, andere Arbeiten fortzusetzen – z. B. eine UI zu aktualisieren, weitere Dateien zu holen oder den Fortschritt zu protokollieren – während die schwere Arbeit im Hintergrund läuft. + +## Etwas Nützliches tun, während OCR läuft + +Ein häufiger Fehler ist, untätig zu warten und das Future in einer engen Schleife abzufragen. Stattdessen können Sie beliebige andere Arbeiten ausführen. Zur Demonstration geben wir einfach eine Statuszeile aus. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Ergebnisse sammeln, sobald das Future abgeschlossen ist + +Wenn Sie bereit sind, die OCR‑Ausgabe zu sammeln, verwenden Sie `as_completed` aus `concurrent.futures`. Dieses Muster funktioniert sowohl bei einem einzelnen Future als auch bei vielen. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Was Sie sehen werden**: Jeder Dateipfad gefolgt von der extrahierten Klartext‑Darstellung. Für PDFs enthält `result.text` den zusammengefügten Text aller Seiten. + +### Erwartete Ausgabe (Beispiel) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Falls Sie fehlende Zeichen bemerken, prüfen Sie, ob die eingestellte Sprache mit der Dokumentensprache übereinstimmt, und erwägen Sie, die Bilder vorzuverarbeiten (Entzerrung, Kontrast erhöhen), bevor Sie sie an die Engine übergeben. + +## Umgang mit Randfällen und häufigen Stolperfallen + +| Situation | Vorgehensweise | +|-----------|----------------| +| **Gemischte Sprachen** | Führen Sie zuerst einen Sprach‑Erkennungsschritt durch und erstellen Sie dann separate Engines pro Sprache. | +| **Große PDFs (> 100 MB)** | Teilen Sie das PDF in einzelne Seiten auf der Festplatte (z. B. mit `PyPDF2`) und geben Sie sie als separate Einträge ein. | +| **Nicht‑lateinische Schriften** | Stellen Sie sicher, dass die OCR‑Bibliothek das benötigte Sprachpaket enthält; einige Bibliotheken erfordern das Herunterladen zusätzlicher Datendateien. | +| **Leistungsengpass** | Erhöhen Sie die Thread‑Pool‑Größe (`engine.set_thread_pool_size(8)`) oder wechseln Sie zu einem GPU‑beschleunigten Backend, falls verfügbar. | +| **Fehlender Text in niedrigauflösenden Bildern** | Vorverarbeiten mit OpenCV: `cv2.resize`, `cv2.threshold` und `cv2.medianBlur`, um die Lesbarkeit zu verbessern. | + +## Vollständiges funktionierendes Beispiel (Copy‑Paste‑bereit) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Speichern Sie dies als `extract_text_async.py`, ersetzen Sie `YOUR_DIRECTORY` durch den Pfad zu Ihren Dateien, installieren Sie das OCR‑Paket (`pip install your-ocr-lib`) und führen Sie `python extract_text_async.py` aus. Sie sollten die zuvor gezeigte Konsolenausgabe sehen. + +## Nächste Schritte – über die Grundextraktion hinaus + +- **Nachbearbeitung**: Entfernen Sie überflüssige Leerzeichen, normalisieren Sie Unicode (`unicodedata.normalize`) oder führen Sie eine Rechtschreibprüfung durch, um OCR‑Rauschen zu bereinigen. +- **Strukturierte Ausgabe**: Exportieren Sie die Ergebnisse nach CSV, JSON oder direkt in eine Datenbank für nachgelagerte Suche. +- **Parallele Batches**: Wenn Sie Hunderte von Dateien haben, starten Sie mehrere Futures und verwenden Sie eine Warteschlange, um die CPU auszulasten, ohne den Speicher zu überlasten. +- **Integration in Web‑Frameworks**: Binden Sie dieses Skript in einen Flask‑ oder FastAPI‑Endpoint ein, um OCR‑On‑Demand als Service bereitzustellen. + +--- + +### TL;DR + +Sie wissen jetzt, wie man **Text aus Bild‑PDFs extrahiert** mit einem minimalen Python‑Skript, das OCR asynchron ausführt, sodass Sie **gescannte Dokumente in Text konvertieren** können, während Ihr Programm reaktionsfähig bleibt. Experimentieren Sie mit den Spracheinstellungen, Batch‑Größen und Vorverarbeitungstricks, um jede noch so kleine Zeichen‑Genauigkeit herauszuholen. + +Haben Sie eine Variante, die Sie teilen möchten – vielleicht OCR für handgeschriebene Notizen oder einen cloud‑basierten Dienst? Hinterlassen Sie einen Kommentar und viel Spaß beim Coden! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Text aus Bild mit Aspose OCR extrahieren – Schritt‑für‑Schritt‑Leitfaden](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Text aus Bildern mit OCR‑Operation in Ordnern extrahieren](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Text aus Bildern mit Aspose.OCR extrahieren – Erlaubte Zeichen](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/german/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8b55fa922 --- /dev/null +++ b/ocr/german/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Wie man PDFs mit Python OCR verarbeitet, Text aus PDFs extrahiert, gescannten + PDF‑Text konvertiert und die OCR‑Sprache in nur wenigen Zeilen Code ändert. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: de +og_description: 'Wie man PDFs mit Python OCRt: ein praktischer Leitfaden, der zeigt, + wie man Text aus PDFs extrahiert, gescannte PDF‑Texte konvertiert und die OCR‑Sprache + mühelos ändert.' +og_title: Wie man PDFs in Python OCRt – Vollständiges Programmier‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Wie man PDFs in Python OCRt – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man PDF in Python OCR‑t – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie sich jemals gefragt, **wie man PDF** Dateien OCR‑t, ohne teure SaaS‑Tools zu bezahlen? Sie sind nicht allein. Egal, ob Sie alte Bücher digitalisieren, Daten aus Rechnungen extrahieren oder einfach durchsuchbaren Text aus einem gescannten Bericht benötigen, das Beherrschen von PDF‑OCR in Python kann Ihnen Stunden manueller Kopierarbeit ersparen. + +In diesem Tutorial führen wir Sie durch ein kompaktes, funktionierendes Beispiel, das **Text aus PDF extrahiert**, Ihnen zeigt, wie Sie **gescannte PDF‑Texte** in editierbare Strings umwandeln, und sogar demonstriert, wie Sie **die OCR‑Sprache ändern** können, wenn Ihr Dokument nicht auf Englisch ist. Am Ende haben Sie ein wiederverwendbares Snippet, das Sie in jedes Projekt einbinden können. + +## Voraussetzungen & Einrichtung + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes haben: + +- Python 3.8+ installiert (der Code funktioniert mit 3.9, 3.10 und neueren Versionen) +- Das `ocr`‑Paket, das die Klasse `OcrEngine` bereitstellt (Sie können es über `pip install ocr-lib` installieren – ersetzen Sie den Namen durch das reale Paket, das Sie verwenden) +- Eine PDF‑Datei, die Sie verarbeiten möchten; für die Demo verwenden wir `high_res_book.pdf`, abgelegt in einem Ordner namens `YOUR_DIRECTORY` + +Wenn Sie eine virtuelle Umgebung verwenden (dringend empfohlen), aktivieren Sie sie zuerst: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro Tipp:** Legen Sie Ihre PDF‑Dateien in einem eigenen `data/`‑Verzeichnis ab, um später Pfad‑bezogene Probleme zu vermeiden. + +## Schritt 1: Erstellen einer OCR‑Engine‑Instanz (Wie man PDF OCR‑t – Initialisierung) + +Der allererste Schritt, wenn Sie **OCR auf PDF**‑Dateien ausführen möchten, besteht darin, die Engine zu instanziieren. Denken Sie an die Engine als das Gehirn, das jede Seite liest, die Glyphen interpretiert und Ihnen reinen Text zurückgibt. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Warum das wichtig ist: Ohne eine Engine haben Sie keinen Kontext für Spracheinstellungen, Rendering‑Optionen oder PDF‑Verarbeitung. Das `OcrEngine`‑Objekt enthält all diese Vorgaben und lässt Sie später Feinjustierungen vornehmen. + +## Schritt 2: Erkennen der Sprache festlegen (OCR‑Sprache ändern) + +Die meisten OCR‑Bibliotheken verwenden standardmäßig Englisch, aber was, wenn Ihr Dokument auf Französisch, Deutsch oder sogar Japanisch ist? Die Sprache zu ändern ist so einfach wie ein Aufruf von `set_recognition_language`. Das erfüllt die Anforderung **change OCR language** und sorgt für höhere Genauigkeit. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Warum Sie das benötigen könnten:** Ein mehrsprachiges Archiv enthält häufig gemischte Sprachseiten. Das Umschalten der Sprache on‑the‑fly verhindert Fehlinterpretationen von Zeichen wie „ß“ oder „ñ“. + +## Schritt 3: PDF‑Render‑Optionen konfigurieren (gescannte PDF‑Texte effektiv konvertieren) + +Bei gescannten PDFs beeinflussen Auflösung und Farbraum die OCR‑Qualität stark. Das Rendern mit 300 DPI in Graustufen ist für die meisten Dokumente ein guter Kompromiss – hoch genug, um Details zu erfassen, aber niedrig genug, um den Speicherverbrauch im Rahmen zu halten. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Die verketteten Aufrufe sehen vielleicht fancy aus, sind aber nur eine fluente API, die jedes Mal dasselbe Options‑Objekt zurückgibt. Wenn Sie Farbe benötigen (z. B. für farbige Diagramme), ersetzen Sie `"grayscale"` durch `"color"`. + +## Schritt 4: PDF erkennen und Text der ersten Seite extrahieren (Text aus PDF extrahieren) + +Jetzt kommt der Kern von **how to OCR PDF**: Der Engine einen Dateipfad übergeben und den erkannten Text herausziehen. Die Methode liefert eine Liste von Seitenergebnissen; jedes Ergebnis enthält ein `text`‑Attribut. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Wenn Sie das gesamte Dokument benötigen, iterieren Sie über `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Was tun, wenn das PDF verschlüsselt ist? + +Einige PDFs sind passwortgeschützt. In diesem Fall können Sie das Passwort an `recognize_pdf` übergeben: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Die Engine entschlüsselt on‑the‑fly, bevor sie das OCR ausführt – keine zusätzlichen Schritte nötig. + +## Schritt 5: Nachbearbeitung des extrahierten Textes (Feinabstimmung des Textes aus PDF) + +Roh‑OCR‑Ausgaben enthalten häufig Zeilenumbrüche, überflüssige Leerzeichen oder gelegentlich falsch erkannte Zeichen. Eine schnelle Aufräum‑Routine macht den extrahierten String bereit für nachgelagerte Verarbeitung (Suchindizierung, Datenbankspeicherung usw.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Sie können nun sicher **text from PDF** extrahieren und in jede NLP‑Pipeline, Suchmaschine oder einfache `open(...).write()`‑Operation einspeisen. + +## Bonus: Stapelverarbeitung mehrerer PDFs (Skalierung von OCR auf PDF) + +Wenn Sie einen Ordner voller gescannter PDFs haben, verpacken Sie die Logik in einer Schleife: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Dieses Snippet zeigt, wie Sie **perform OCR on PDF**‑Dateien in großen Mengen verarbeiten – ein häufiger Bedarf bei Digitalisierungsprojekten. + +## Erwartete Ausgabe + +Das Ausführen des Ein‑Seiten‑Beispiels (Schritt 4) sollte etwa Folgendes ausgeben: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Wenn Sie ein mehrseitiges Buch verarbeitet haben, zeigt die Konsole den bereinigten Text jeder Seite, und das Batch‑Skript legt neben jeder PDF eine `.txt`‑Datei an. + +## Häufige Fallstricke & wie man sie vermeidet + +| Problem | Symptome | Lösung | +|-------|----------|-----| +| Low‑resolution source PDF | Verzerrte Zeichen, fehlende Wörter | DPI erhöhen (`set_dpi(400)` oder höher) | +| Wrong language set | Viele unbekannte Symbole, besonders bei Akzentzeichen | `engine.set_recognition_language(ocr.Language.FRENCH)` oder das passende Enum verwenden | +| Large PDF causing memory error | `MemoryError` oder Absturz nach einigen Seiten | Seiten in Chunks verarbeiten (`engine.recognize_pdf(..., max_pages=10)`) | +| Missing fonts in the PDF | Leere Ausgabe für bestimmte Seiten | Sicherstellen, dass das PDF tatsächlich Rasterbilder enthält; manche PDFs sind nur Vektor‑ und benötigen andere Handhabung | + +## Bildillustration + +Unten sehen Sie eine schnelle Visualisierung des Workflows. Der Alt‑Text ist bewusst SEO‑freundlich. + +![how to ocr pdf workflow diagram showing engine initialization, language setting, rendering options, recognition, and text extraction](/images/ocr-workflow.png) + +*Das Diagramm ist nicht erforderlich, damit der Code läuft, hilft aber visuellen Lernenden zu verstehen, wo jeder Schritt einzuordnen ist.* + +## Fazit + +Wir haben **how to OCR PDF**‑Dateien in Python von Anfang bis Ende behandelt: Erstellung einer OCR‑Engine, **changing OCR language**, Konfiguration des Renderings zum **convert scanned PDF text** und schließlich **extracting text from PDF** für die weitere Nutzung. Das komplette, ausführbare Beispiel kann in jedes Projekt übernommen werden, und das optionale Batch‑Skript zeigt, wie Sie die Lösung skalieren. + +Als Nächstes könnten Sie folgendes erkunden: + +- Hinzufügen von **perform OCR on PDF** für mehrsprachige Archive, indem Sie über eine Sprachliste iterieren. +- Integration des extrahierten Textes in Elasticsearch für Volltextsuche. +- Nutzung von OCR, um durchsuchbare PDFs zu erstellen, indem Sie die Textebene wieder in die Originaldatei einbetten (viele Bibliotheken bieten eine `save_as_searchable_pdf`‑Methode). + +Fühlen Sie sich frei zu experimentieren, DPI‑Einstellungen zu justieren oder zu einem anderen OCR‑Backend zu wechseln. Die Grundlagen bleiben gleich, und Sie haben nun ein solides Fundament, auf dem Sie aufbauen können. + +Viel Spaß beim Coden, und mögen Ihre gescannten Dokumente endlich durchsuchbar werden! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält komplette, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Features zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/german/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..7282c3165 --- /dev/null +++ b/ocr/german/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-06 +description: Wie man PDFs OCRt und durchsuchbare PDF-Dateien aus Bildern mit Python + erstellt. Lernen Sie, durchsuchbaren Text hinzuzufügen und Bilder in PDF/A in wenigen + Minuten zu konvertieren. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: de +og_description: Wie man PDF Schritt für Schritt OCRt. Lernen Sie, durchsuchbaren Text + hinzuzufügen und Bilder mit einem einfachen Python‑Skript in PDF/A zu konvertieren. +og_title: Wie man PDFs OCRt – Schnellleitfaden zur Erstellung durchsuchbarer PDFs +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Wie man PDFs in Python OCRt – Durchsuchbare PDFs aus Bildern erstellen +url: /de/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man PDF OCR‑t – Gescannte Bilder in durchsuchbare PDFs umwandelt + +Haben Sie sich schon einmal gefragt, **wie man PDF OCR‑t**, wenn Sie nur ein gescanntes Bild einer Rechnung oder eines Belegs haben? Sie sind nicht allein. In vielen Büros kommen eingehende Unterlagen als flache PNG‑ oder JPEG‑Dateien, und der nächste Schritt – diese Inhalte durchsuchbar zu machen – fühlt sich wie eine Black‑Box an. + +Die gute Nachricht? Mit nur wenigen Zeilen Python können Sie **durchsuchbare PDF**‑Dateien **erstellen**, **durchsuchbaren Text hinzufügen** und sogar **Bild zu PDF/A konvertieren** für die Langzeitarchivierung. In diesem Tutorial gehen wir jeden Schritt durch, erklären, warum er wichtig ist, und geben Ihnen ein sofort einsatzbereites Skript, das Sie in jedes Projekt einbinden können. + +> **Pro‑Tipp:** Der gleiche Ansatz funktioniert für mehrseitige Scans; einfach über die Dateien iterieren und die Engine erledigt den Rest. + +--- + +## Was Sie benötigen + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes auf Ihrem Rechner haben: + +| Anforderung | Warum es wichtig ist | +|-------------|----------------------| +| Python 3.9 oder neuer | Moderne Syntax und bessere Bibliotheksunterstützung | +| `pdfium`‑basierte OCR‑Engine (z. B. `pdfocr` oder ein kommerzielles SDK) | Handhabt sowohl Bild‑Erkennung als auch PDF/A‑Erstellung | +| Eine Bilddatei (PNG, JPEG, TIFF), die Sie in ein durchsuchbares PDF umwandeln möchten | Die Quelle des Textes | +| Schreibrechte für den Zielordner | Damit das Skript das neue PDF speichern kann | + +Falls Sie das OCR‑SDK noch nicht installiert haben, führen Sie aus: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Das war’s – keine komplexen Systemabhängigkeiten, nur ein pip‑Install. + +--- + +## Wie man PDF OCR‑t – Überblick + +Auf hoher Ebene besteht der Prozess aus drei einfachen Aktionen: + +1. **Erkennen** des Textes im Bild, während die ursprüngliche Grafik erhalten bleibt. +2. **Exportieren** des OCR‑Ergebnisses zusammen mit dem Originalbild als **durchsuchbares PDF/A** (die archivfreundliche PDF‑Variante). +3. **Validieren**, dass die resultierende Datei auswählbaren, durchsuchbaren Text über dem Originalbild enthält. + +Im Folgenden sehen Sie jeden Schritt im Code, mit Erklärungen zum *Warum* hinter den Befehlen. + +--- + +## Schritt 1: Text aus dem Bild erkennen + +Zuerst lassen wir die OCR‑Engine die Pixel lesen und ein Ergebnis‑Objekt zurückgeben, das sowohl das Rohbild als auch den extrahierten Text enthält. Denken Sie daran, dass die Engine das Dokument für Sie „liest“. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Warum das wichtig ist + +- **Grafiken erhalten** bedeutet, dass das visuelle Layout (Tabellen, Logos, Stempel) exakt so bleibt, wie der Scanner es erfasst hat. +- Das `result`‑Objekt enthält typischerweise eine versteckte Textebene, die wir später in das PDF einbetten. +- Die Verwendung von `recognize_image` statt `recognize_pdf` vermeidet einen zusätzlichen Konvertierungsschritt, was die Verarbeitung von Einzelseiten‑Bildern beschleunigt. + +#### Häufige Varianten + +- Wenn Sie ein **mehrseitiges TIFF** haben, übergeben Sie den Dateipfad direkt; die meisten Engines behandeln jede Seite als separates Bild. +- Für PDFs, die bereits Bilder enthalten, können Sie `engine.recognize_pdf("file.pdf")` aufrufen und diesen Schritt komplett überspringen. + +--- + +## Schritt 2: OCR‑Ergebnis als durchsuchbares PDF/A exportieren + +Jetzt nehmen wir das `result` aus Schritt 1 und lassen die Engine eine neue Datei schreiben. Das Schlüssel‑Flag hier ist *PDF/A* – die ISO‑Standard‑Version von PDF, die für die Langzeit‑Aufbewahrung konzipiert ist. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Warum das wichtig ist + +- **Durchsuchbares PDF**: Die Ausgabedatei enthält eine versteckte, auswählbare Textebene. Sie können jetzt mit Strg + F das Dokument durchsuchen. +- **PDF/A‑Konformität**: Einige Organisationen (Recht, Finanzen) verlangen PDF/A für Prüfpfade; dieser Schritt erfüllt diese Anforderung automatisch. +- Die Methode **fügt durchsuchbaren Text hinzu**, ohne das Bild zu flatten, sodass die visuelle Treue perfekt bleibt. + +#### Sonderfall: Stattdessen ein normales PDF? + +Wenn Ihnen PDF/A egal ist, ersetzen Sie `save_as_pdfa` durch `save_as_pdf`. Der Rest des Workflows bleibt unverändert. + +--- + +## Schritt 3: Das durchsuchbare PDF überprüfen + +Ein kurzer Plausibilitäts‑Check erspart Ihnen später mysteriöse Fehler. Öffnen Sie die erzeugte Datei in einem beliebigen PDF‑Viewer, versuchen Sie ein Wort zu markieren und nutzen Sie die Suchfunktion. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Erwartete Ausgabe + +Wenn Sie das Skript ausführen, gibt die Konsole Folgendes aus: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Beim Öffnen der Datei sollten Sie das Original‑Rechnungsbild mit einer schwachen, unsichtbaren Textebene sehen. Markieren Sie ein beliebiges Wort – es ist auswählbar – **das ist der durchsuchbare Text**, den Sie gerade hinzugefügt haben. + +--- + +## Durchsuchbaren Text zu bestehenden PDFs hinzufügen (Bonus) + +Manchmal haben Sie bereits ein PDF, dem Sie **durchsuchbaren Text** hinzufügen müssen. Die gleiche Engine kann OCR‑Ergebnisse über ein bestehendes PDF legen: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Hier kombiniert `apply_to` die versteckte Ebene mit den Originalseiten, sodass Sie **durchsuchbare PDFs** erstellen können, ohne erneut zu scannen. + +--- + +## Häufige Stolperfallen und Tipps + +| Stolperfalle | Wie man sie vermeidet | +|--------------|----------------------| +| **Niedrigauflösende Quellbilder** (< 150 dpi) | Hochskalieren oder um einen Scan mit höherer Auflösung bitten; die OCR‑Genauigkeit sinkt dramatisch unter 150 dpi. | +| **Fehlende Sprachdaten** | Installieren Sie die passenden Sprachpakete für Ihre OCR‑Engine (`pip install pdfocr[eng,spa]`). | +| **Ausgabeordner nicht beschreibbar** | Skript mit ausreichenden Rechten ausführen oder ein anderes Verzeichnis wählen. | +| **PDF/A‑Validierung schlägt fehl** | Stellen Sie sicher, dass Sie keine nicht unterstützten Schriften oder JavaScript einbetten; die meisten SDKs erledigen das automatisch, wenn Sie `save_as_pdfa` verwenden. | + +--- + +## Komplettes Skript – Ein‑Datei‑Lösung + +Unten finden Sie ein eigenständiges Skript, das alles zusammenführt. Kopieren‑Sie es, ersetzen Sie die Platzhalter‑Pfade, und Sie können **Bild zu PDF/A** in Sekundenschnelle konvertieren. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Was dieses Skript macht:** +1. Lädt die OCR‑Engine. +2. Liest das ausgewählte Bild und extrahiert den Text. +3. Schreibt ein **durchsuchbares PDF/A**, das Sie sofort verteilen oder archivieren können. + +Sie können die `main`‑Logik leicht in eine Funktion verpacken, die einen ganzen Ordner verarbeitet – einfach über `os.listdir()` iterieren und die drei Schritte für jede Datei wiederholen. + +--- + +## Nächste Schritte & verwandte Themen + +Jetzt, wo Sie **wie man PDF OCR‑t** beherrschen, können Sie folgende weiterführende Ideen erkunden: + +- **Batch‑Verarbeitung:** Nutzen Sie `concurrent.futures`, um Dutzende Rechnungen parallel zu OCR‑en. +- **Metadaten‑Injection:** Fügen Sie Erstellungsdaten oder Rechnungsnummern zu den PDF‑Metadaten hinzu, um die Indexierung zu erleichtern. +- **Hybrid‑PDFs:** Kombinieren Sie durchsuchbaren Text mit eingebetteten Originalbildern für einen „digitalen Zwilling“ des Papierdokuments. +- **Alternative Ausgaben:** Exportieren Sie nach **DOCX** oder **HTML**, wenn nachgelagerte Systeme editierbare Formate benötigen. + +Jeder dieser Punkte baut auf den Kernkonzepten auf, die Sie gerade gelernt haben – erkennen, exportieren, verifizieren. + +--- + +## Fazit + +Kurz gesagt, Sie wissen jetzt **wie man PDF OCR‑t**, indem Sie ein einfaches Bild mit nur drei Zeilen Python in ein **durchsuchbares PDF/A** verwandeln. Das Skript übernimmt die schwere Arbeit, bewahrt die Originalgrafiken und liefert ein normkonformes Dokument, das Sie durchsuchen, archivieren oder teilen können. + +Probieren Sie es mit Ihren eigenen Rechnungen, Belegen oder gescannten Verträgen aus. Wenn Sie auf Probleme stoßen, hinterlassen Sie einen Kommentar unten oder schauen Sie in die offizielle Dokumentation des SDK – dort finden Sie meist weitere Beispiele. Viel Spaß beim Coden und genießen Sie die neue Möglichkeit, jedes Bild sofort durchsuchbar zu machen! + +![How to OCR PDF example showing original image and searchable PDF overlay](placeholder.png "How to OCR PDF example") + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, damit Sie weitere API‑Funktionen meistern und alternative Implementierungsansätze in Ihren eigenen Projekten erkunden können. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/german/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..5989791d6 --- /dev/null +++ b/ocr/german/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-06-06 +description: Wie man PDFs mit Aspose OCR Cloud OCR verarbeitet. Erfahren Sie, wie + Sie Text aus PDFs extrahieren, PDF‑Seiten in PNG konvertieren und PDF‑Seitenbilder + in Python speichern. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: de +og_description: Wie man PDFs mit Aspose OCR Cloud OCRt. Dieser Leitfaden zeigt, wie + man reinen Text aus PDFs extrahiert, PDF‑Seiten in PNG konvertiert und PDF‑Seitenbilder + speichert. +og_title: Wie man PDF mit Aspose OCR Cloud OCRt – Schritt für Schritt +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Wie man PDFs mit Aspose OCR Cloud OCRt – vollständige Anleitung +url: /de/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man PDF mit Aspose OCR Cloud OCR macht – Vollständige Anleitung + +Haben Sie sich jemals gefragt, **wie man PDF**‑Dateien OCR‑t, ohne schwere Desktop‑Tools zu verwenden? Sie sind nicht allein – vielen Entwicklern stößt man an diese Grenze, wenn sie eine schnelle, programmatische Möglichkeit benötigen, Text aus gescannten Dokumenten zu extrahieren. Die gute Nachricht? Mit Aspose OCR Cloud können Sie **Text aus PDF** extrahieren, jede Seite in ein PNG umwandeln und sogar **PDF‑Seitenbilder** für die spätere Verwendung speichern – alles aus einem übersichtlichen Python‑Skript. + +In diesem Tutorial gehen wir Schritt für Schritt durch alles, was Sie wissen müssen: von der Installation des SDK, über die Lizenzierung der Engine, bis hin zur Erkennung von mehrseitigen PDFs, dem Extrahieren von Klartext, dem Konvertieren von Seiten zu PNG und dem Persistieren dieser Bilder auf der Festplatte. Am Ende haben Sie einen wiederverwendbaren Code‑Snippet, den Sie in jedes Projekt einbinden können, das **wie man PDF OCR‑t**‑Funktionen benötigt. + +## Was Sie benötigen + +- **Python 3.8+** (der Code funktioniert auch mit 3.10 und neuer) +- Ein Aspose OCR Cloud‑Konto – Sie erhalten eine kostenlose Test‑Lizenzdatei (`Aspose.OCR.lic`) +- Das Paket `asposeocrcloud` (`pip install asposeocrcloud`) +- Ein gescanntes, mehrseitiges PDF, das Sie verarbeiten möchten + +Das ist alles. Keine zusätzlichen Binärdateien, keine nativen Abhängigkeiten, nur reines Python. + +## Wie man PDF OCR‑t – Einrichtung und Lizenz + +Bevor Sie irgendeine OCR‑Methode aufrufen können, müssen Sie dem SDK mitteilen, wer Sie sind. Aspose verwendet eine leichte Lizenzdatei, die Sie an einem für Ihr Skript zugänglichen Ort ablegen. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro‑Tipp:* Wenn Sie den Lizenzschritt überspringen, funktioniert das SDK weiterhin, fügt jedoch ein kleines Wasserzeichen in die Ausgabebilder ein. Für die Produktion nicht ideal. + +## Schritt 2: Installieren des Aspose OCR Cloud Python SDK + +Öffnen Sie ein Terminal und führen Sie aus: + +```bash +pip install asposeocrcloud +``` + +Das Paket zieht alle erforderlichen Abhängigkeiten (requests, pillow usw.) nach, sodass Sie nichts Weiteres suchen müssen. + +## Schritt 3: Erstellen einer OCR‑Engine und Auswahl einer Sprache + +Die Engine ist das Herzstück der Operation. Sie können jede von Aspose unterstützte Sprache angeben; Englisch funktioniert in den meisten Fällen. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Warum die Sprache setzen? Weil die OCR‑Engine sprachspezifische Wörterbücher nutzt, um die Genauigkeit zu verbessern. Wenn Sie französische PDFs verarbeiten, ersetzen Sie einfach `ENGLISH` durch `FRENCH`. + +## Schritt 4: Verweisen Sie auf Ihr mehrseitiges PDF + +Geben Sie der Engine den vollständigen Pfad zu der Datei, die Sie verarbeiten möchten. Relative Pfade sind in Ordnung, solange sie vom Arbeitsverzeichnis des Skripts aus aufgelöst werden können. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Stellen Sie sicher, dass die Datei lesbar ist; andernfalls erhalten Sie einen `FileNotFoundError`. + +## Schritt 5: OCR ausführen – Sie erhalten eine Ergebnisliste + +Der Aufruf von `recognize_pdf` liefert eine Liste, wobei jedes Element einer Seite des Quell‑PDF entspricht. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Jedes `OcrResult` enthält zwei praktische Eigenschaften: + +* `text` – die Klartext‑Darstellung der Seite (ideal für **extract plain text pdf**) +* `image` – ein Pillow‑`Image`‑Objekt der gerenderten Seite (perfekt für **convert pdf page png**) + +## Schritt 6: Text aus PDF extrahieren und Seiten zu PNG konvertieren + +Jetzt durchlaufen wir die Ergebnisse, geben den extrahierten Text aus und speichern eine PNG‑Version jeder Seite. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Erwartete Konsolenausgabe + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Sie finden außerdem `page_1.png`, `page_2.png`, … im Verzeichnis `YOUR_DIRECTORY`. Das sind die gerasterten Seitenbilder, die Sie in nachgelagerte Bild‑Verarbeitungspipelines einspeisen können. + +## Schritt 7: PDF‑Seitenbilder speichern (optionale Nachbearbeitung) + +Wenn Sie nur die Bilder und nicht den Text benötigen, können Sie die Zeile `print(res.text)` weglassen. Wenn Sie hingegen den Text in separate `.txt`‑Dateien speichern möchten, fügen Sie einfach einen kleinen Schreibvorgang hinzu: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Diese kleine Ergänzung zeigt, wie einfach es ist, **PDF‑Seitenbilder** zu **speichern**, während gleichzeitig der extrahierte Inhalt persistiert wird. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengeführt, hier das komplette Skript, das Sie in `ocr_pdf.py` kopieren‑und‑einfügen können: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Führen Sie es aus mit: + +```bash +python ocr_pdf.py +``` + +Sie sollten die Konsolenausgabe jedes Seiten‑Texts sowie eine Reihe von PNG‑Dateien sehen. + + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/german/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..533b63d2e --- /dev/null +++ b/ocr/german/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Wie man Bilder für OCR mit Python vorverarbeitet. Lernen Sie, wie man + ein Bild mit Otsu binarisiert, gescannte Dokumente entneigt und die OCR‑Genauigkeit + für deutschen Text verbessert. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: de +og_description: Wie man Bilder für OCR in Python vorverarbeitet. Dieses Tutorial zeigt, + wie man Bilder mit Otsu binarisiert, gescannte Dokumente entneigt und die OCR‑Genauigkeit + für deutsche Bilder verbessert. +og_title: Wie man Bilder für OCR vorverarbeitet – Vollständiger Python-Leitfaden +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Wie man Bilder für OCR vorverarbeitet – Vollständiger Python‑Leitfaden +url: /de/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Bilder für OCR vorverarbeitet – Vollständiger Python‑Leitfaden + +Haben Sie sich jemals gefragt **wie man Bilder für OCR vorverarbeitet**, damit der Text kristallklar herauskommt? Sie sind nicht allein. Gescannte Dokumente – besonders verrauschte deutsche Seiten – können für jede OCR‑Engine ein Albtraum sein. Die gute Nachricht? Ein paar clevere Vorverarbeitungsschritte können einen unscharfen, gesprenkelten Scan in ein sauberes, maschinenlesbares Bild verwandeln. + +In diesem Tutorial führen wir Sie durch ein praktisches Beispiel, das **zeigt, wie man Bilder für OCR vorverarbeitet** mit Python. Sie lernen, **ein Bild mit Otsu zu binarisieren**, **wie man gescannte Dokumente entzerrt**, und insgesamt **wie man die OCR‑Genauigkeit verbessert**, wenn Sie **Text aus deutschen Bilddateien extrahieren** müssen. Kein Schnickschnack, nur ein funktionierendes Skript, das Sie noch heute kopieren‑und‑einfügen können. + +## Was Sie benötigen + +- **Python 3.9+** (jede aktuelle Version funktioniert) +- Eine OCR‑Bibliothek, die eine `OcrEngine`‑Klasse bereitstellt – für das Demo gehen wir von einem generischen `ocr`‑Paket aus. Installieren Sie es mit `pip install ocr-lib`. +- Ein verrauschter deutscher Scan (`noisy_german_scan.tif`), den Sie testen möchten. +- Grundlegendes Verständnis von Python‑Funktionen (wenn Sie schon einmal ein `def` geschrieben haben, sind Sie bereit). + +> **Pro‑Tipp:** Wenn Sie ein anderes OCR‑SDK verwenden (z. B. Tesseract via `pytesseract`), bleiben die Konzepte gleich – passen Sie nur die Methodennamen an. + +## Überblick über die Lösung + +1. **Eine OCR‑Engine‑Instanz erstellen.** +2. **Die Erkennungssprache auf Deutsch setzen.** +3. **Eine benutzerdefinierte Vorverarbeitungspipeline bauen**, die Entzerren, Entrauschen, Binarisierung (Otsu) und Kontraststreckung umfasst. +4. **Die Pipeline an die Engine anhängen**, sodass jedes Bild automatisch durch sie läuft. +5. **Die OCR** auf einem verrauschten deutschen Scan ausführen. +6. **Den extrahierten Text ausgeben**, um das Ergebnis zu prüfen. + +Im Folgenden zerlegen wir jeden Schritt, erklären **warum** er wichtig ist und zeigen den genauen Code, den Sie benötigen. + +![wie man Bilder für OCR vorverarbeitet Beispiel](image.png "wie man Bilder für OCR vorverarbeitet Beispiel") + +## Schritt 1: OCR‑Engine‑Instanz erstellen + +Zuerst einmal – ohne Engine passiert nichts. Das `OcrEngine`‑Objekt ist der Einstiegspunkt, der alle nachfolgenden Verarbeitungsschritte koordiniert. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Warum das wichtig ist:* Das Initialisieren der Engine richtet interne Ressourcen (wie Sprachmodelle) ein und gibt Ihnen eine saubere Basis, um später eine eigene Pipeline anzuhängen. + +## Schritt 2: Erkennungs­sprache auf Deutsch setzen + +Die OCR‑Genauigkeit ist stark sprachabhängig. Wenn Sie der Engine mitteilen, dass Deutsch erwartet wird, aktivieren Sie den richtigen Zeichensatz und das passende Sprachmodell. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Wenn Sie das überspringen, könnte die Engine standardmäßig Englisch verwenden und Umlaute (ä, ö, ü) sowie das ß‑Zeichen falsch erkennen – ein häufiger Stolperstein bei deutschen Scans. + +## Schritt 3: Benutzerdefinierte Vorverarbeitungspipeline erstellen + +Dies ist das Herzstück von **wie man Bilder für OCR vorverarbeitet**. Wir verketten vier Transformationen: + +| Transformation | Was es macht | Warum es hilft | +|----------------|--------------|----------------| +| **Deskew** | Dreht das Bild wieder horizontal (max 5°) | Scans sind selten perfekt ausgerichtet; das Entzerren entfernt die Schräglage, die die Zeichensegmentierung verwirrt. | +| **Denoise** | Reduziert zufällige Punkte (Stärke 0.7) | Rauschen erzeugt falsche Kanten, die die OCR‑Engine als Zeichen interpretieren könnte. | +| **Binarize (Otsu)** | Wandelt mit Otsus Methode in Schwarz‑Weiß um | Ein sauberes Binärbild liefert der Engine einen starken Kontrast zwischen Vordergrund (Text) und Hintergrund. | +| **Contrast Stretch** | Erweitert den Dynamikbereich | Verbessert die Lesbarkeit schwacher Striche, besonders bei alten Dokumenten. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Wie man gescannte Dokumente entzerrt + +Der Aufruf `deskew` oben ist die konkrete Antwort auf **wie man gescannte Dokumente entzerrt**. Intern schätzt er den dominanten Textzeilenwinkel mittels Hough‑Transformation und rotiert das Bild zurück. Wenn Ihre Dokumente um mehr als 5° gedreht sind, erhöhen Sie `max_angle`, achten Sie jedoch auf mögliche Über‑Rotationsartefakte. + +### Bild mit Otsu binarisieren + +Die Zeile `binarize(method="otsu")` beantwortet direkt die Frage **binarize image using otsu**. Otsus Algorithmus berechnet einen Schwellenwert, der die intra‑Klassen‑Varianz minimiert – ideal für Dokumente mit bimodalen Histogrammen (dunkler Text vs. heller Hintergrund). + +## Schritt 4: Pipeline an die Engine anhängen + +Jetzt weisen wir die OCR‑Engine an, jedes eingehende Bild durch die gerade erstellte Pipeline zu schicken. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Warum das wichtig ist:* Ohne Registrierung würde die Engine den Rohscan verarbeiten und all die von uns konfigurierten Bereinigungen ignorieren. Dieser Schritt stellt sicher, dass **wie man die OCR‑Genauigkeit verbessert**, indem dieselbe Vorverarbeitung konsequent angewendet wird. + +## Schritt 5: Text aus einem verrauschten deutschen Scan erkennen + +Jetzt wird alles zusammengeführt. Wir geben der Engine ein verrauschtes deutsches Bild und lassen sie die schwere Arbeit erledigen. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Wenn Sie an der Performance interessiert sind, können Sie den Aufruf zeitlich messen: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Schritt 6: Erkannten Text ausgeben + +Abschließend drucken wir die extrahierte Zeichenkette. Das ist die direkte Antwort auf **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Erwartete Ausgabe + +Angenommen, der Beispiel‑Scan enthält den Satz „Die schnelle braune Füchsin springt über den faulen Hund.“ sollten Sie etwa Folgendes sehen: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Wenn die Ausgabe noch verzerrte Zeichen enthält, überlegen Sie, die `denoise`‑Stärke anzupassen oder den `max_angle` für das Entzerren zu erhöhen. + +## Häufige Fallstricke & wie man sie behebt + +- **Fehlendes Sprachmodell:** Das Vergessen von `set_recognition_language(Language.GERMAN)` führt häufig zu fehlenden Umlauten. Prüfen Sie den Aufruf doppelt. +- **Über‑Entrauschen:** Eine Stärke über 0.9 kann dünne Striche, besonders in älteren Schriften, löschen. Bleiben Sie bei 0.5‑0.7 für die meisten Fälle. +- **Falsches Dateiformat:** Einige OCR‑Engines kommen mit mehrseitigen TIFFs nicht klar. Wenn Sie ein mehrseitiges Dokument haben, teilen Sie es zuerst in Einzelseiten‑Dateien auf. +- **Reihenfolge der Pipeline:** Die gezeigte Reihenfolge (Entzerren → Entrauschen → Binarisieren → Kontrast) ist bewusst gewählt. Binarisieren vor dem Entrauschen kann das Rauschen festsetzen; immer zuerst entrauschen. + +## Pipeline erweitern (Was kommt als Nächstes?) + +Jetzt, wo Sie eine solide Basis haben, könnten Sie Folgendes hinzufügen: + +- **Ein morphologisches Öffnen** einbauen, um kleine Flecken zu säubern (`.morph_open(kernel=3)`). +- **Ein Sprachmodell integrieren** für die Nachbearbeitungskorrektur (`ocr_engine.apply_spellcheck()`). +- **Batch‑Verarbeitung parallelisieren** für große Datensätze mittels `concurrent.futures`. + +All das sind natürliche Erweiterungen, die die Kernidee von **wie man Bilder für OCR vorverarbeitet** beibehalten und gleichzeitig **wie man die OCR‑Genauigkeit verbessert** weiter steigern. + +## Fazit + +Wir haben gerade **wie man Bilder für OCR vorverarbeitet** von Anfang bis Ende behandelt: Engine erstellen, deutsche Sprache setzen, eine Pipeline bauen, die **Bild mit Otsu binarisiert**, **wie man gescannte Dokumente entzerrt**, und schließlich **Text aus deutschem Bild extrahiert** mit höherer Zuverlässigkeit. Wenn Sie die sechs Schritte oben befolgen, werden Sie einen spürbaren Sprung in der Erkennungsqualität sehen – keine endlosen manuellen Korrekturen mehr. + +Probieren Sie das Skript mit Ihren eigenen Scans aus, experimentieren Sie mit den Parametern und lassen Sie die Ergebnisse für sich sprechen. Haben Sie Fragen zu einer bestimmten Vorverarbeitungs‑Optimierung? Hinterlassen Sie einen Kommentar, und wir tauchen gemeinsam tiefer ein. + +Viel Spaß beim Coden, und möge Ihre OCR stets präzise sein! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Bildtext in C# extrahieren mit Sprachauswahl mittels Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Wie man Schwellenwert im OCR‑Bilderkennung festlegt](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Wie man ein Bild OCR‑t – OCR auf Bild ausführen in OCR‑Bilderkennung](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/german/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..6eb3bac1f --- /dev/null +++ b/ocr/german/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG‑Bild mit Python – lernen Sie, wie man Text aus einem Bild extrahiert, + ein Python‑OCR‑Beispiel ausführt und sogar antiken griechischen Text leicht liest. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: de +og_description: OCR-PNG-Bild in Python erklärt. Dieser Leitfaden zeigt, wie man Text + aus einem Bild extrahiert, ein Python-OCR-Beispiel ausführt und antikes Griechisch + mühelos liest. +og_title: OCR PNG‑Bild in Python – Vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR‑PNG‑Bild in Python – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Bild in Python – Vollständige Schritt‑für‑Schritt-Anleitung + +Haben Sie sich jemals gefragt, wie man **OCR PNG image** Dateien direkt aus einem Python‑Skript heraus verarbeitet? Vielleicht haben Sie einen Ordner voller gescannter antiker Manuskripte und müssen **extract text from image** Dateien extrahieren, ohne alles von Hand abzutippen. Die gute Nachricht: Sie benötigen keinen Doktortitel in Computer Vision – nur ein paar Zeilen Code und die richtige Bibliothek, und Sie können antikes Griechisch in Sekunden lesen. + +In diesem Tutorial gehen wir ein **python OCR example** durch, das Text aus einer PNG erkennt, die Sprache auf Griechisch polytonisch setzt und das Ergebnis ausgibt. Am Ende wissen Sie genau, wie man **recognize image text** durchführt, gängige Fallstricke behandelt und das Skript für andere Sprachen oder Bildformate anpasst. + +## Was Sie lernen werden + +- Installieren und konfigurieren Sie eine Python OCR‑Bibliothek (pytesseract + Tesseract OCR) +- Erstellen Sie eine OCR‑Engine‑Instanz und laden Sie eine PNG‑Datei +- Setzen Sie die Erkennungssprache auf Griechisch polytonisch, damit Sie **read ancient greek** können +- Geben Sie den erkannten Text aus und beheben Sie typische Probleme +- Erweitern Sie das Skript, um mehrere PNGs stapelweise zu verarbeiten oder zu einer anderen Sprache zu wechseln + +### Voraussetzungen + +| Anforderung | Warum es wichtig ist | +|-------------|----------------------| +| Python 3.8+ | Moderne Syntax und Typ‑Hinweise | +| `pytesseract`‑Paket | Dünner Wrapper um die Tesseract‑Engine | +| Tesseract OCR‑Binärdateien (≥ 5.0) | Die eigentliche Engine, die die schwere Arbeit leistet | +| Griechische Sprachdaten (`grc.traineddata`) | Benötigt, um **read ancient greek** korrekt zu lesen | +| Ein PNG‑Bild, das Sie analysieren möchten (z. B. `ancient_greek.png`) | Unser Ziel für die **ocr png image** Demo | + +Sie können die Python‑Seite installieren mit: + +```bash +pip install pytesseract Pillow +``` + +Und unter Ubuntu/macOS würden Sie die Engine selbst hinzufügen: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Vergessen Sie nicht, die griechischen polytonischen Trainingsdaten herunterzuladen: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Der Pfad kann abweichen; passen Sie `TESSDATA_PREFIX` bei Bedarf an.)* + +## OCR PNG Bild: Engine‑Instanz erstellen + +Das erste, was wir benötigen, ist ein Objekt, das mit Tesseract kommuniziert. In `pytesseract` wird die Engine über Funktionen auf Modulebene angesprochen, aber zur Klarheit verpacken wir sie in einer kleinen Klasse. Das spiegelt das „engine“-Konzept wider, das Sie im ursprünglichen Snippet gesehen haben. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Warum ein Wrapper?** +- Behält die öffentliche API identisch zum Ausgangssnippet bei, wodurch die Migration problemlos verläuft. +- Ermöglicht es uns, später Logging oder Fehlerbehandlung hinzuzufügen, ohne den Hauptablauf zu berühren. +- Demonstriert gute OOP‑Praxis – etwas, das erfahrene Entwickler zu schätzen wissen. + +## Text aus Bild extrahieren: Sprache auf Griechisch polytonisch setzen + +Jetzt, da wir eine Engine haben, müssen wir ihr mitteilen, welche Sprache erwartet wird. Griechisch polytonisch verwendet Diakritika, die in den Standard‑„greek“-Daten nicht enthalten sind, daher verweisen wir Tesseract auf die `grc`‑Trainingsdatei. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Wenn Sie jemals **extract text from image** Dateien in einer anderen Sprache extrahieren möchten, ersetzen Sie einfach `"grc"` durch `"eng"` für Englisch, `"fra"` für Französisch usw. Die gleiche Zeile funktioniert für jede installierte Sprache. + +## Bildtext erkennen: OCR auf einer PNG ausführen + +Mit der eingestellten Sprache übergeben wir die PNG an die Engine. Das ursprüngliche Beispiel verwendete einen fest codierten Pfad; wir machen es etwas flexibler, indem wir `Path`‑Objekte verwenden. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tipps & Sonderfälle** + +- **File not found** – wickeln Sie den Aufruf in ein `try/except FileNotFoundError`, um eine freundliche Meldung auszugeben. +- **Low‑resolution PNG** – erwägen Sie eine Vorverarbeitung (z. B. Skalierung, Binarisierung) mit Pillow vor dem OCR. +- **Non‑Greek text** – Tesseract wird weiterhin versuchen zu dekodieren, aber die Genauigkeit sinkt stark. Stimmen Sie immer die Sprache ab. + +## Erkannten Text ausgeben + +Schließlich geben wir das Ergebnis aus. In einem echten Projekt könnten Sie es in eine Datenbank, eine CSV‑Datei schreiben oder sogar in eine Übersetzungspipeline einspeisen. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Wenn Sie das Skript gegen einen klaren Scan einer antiken griechischen Inschrift ausführen, sollten Sie etwas Ähnliches sehen: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Wenn die Ausgabe unleserlich aussieht, überprüfen Sie, ob die **greek.traineddata**‑Datei im richtigen Ordner liegt und das PNG nicht zu verrauscht ist. + +## Vollständiges funktionierendes Beispiel (Alle Schritte in einem Skript) + +Unten finden Sie das vollständige, sofort ausführbare Programm. Speichern Sie es als `ocr_greek.py` und führen Sie `python ocr_greek.py` aus. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Erwartete Ausgabe** (gekürzt für die Kürze): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Wenn Sie die korrekten griechischen Zeichen sehen, herzlichen Glückwunsch – Sie haben erfolgreich eine **ocr png image**‑Operation in Python durchgeführt! + +## Häufige Fragen & Profi‑Tipps + +### Wie verbessere ich die Genauigkeit bei einem verrauschten PNG? + +- Konvertieren Sie das Bild in Graustufen: `img = img.convert('L')` +- Wenden Sie einen binären Schwellenwert an: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Skalieren Sie hoch mit `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Diese Schritte verwandeln oft ein **recognize image text**‑Alptraum in ein sauberes Ergebnis. + +### Kann ich einen ganzen Ordner von PNGs verarbeiten? + +Absolut. Verpacken Sie den Aufruf von `recognize_image` in eine `for`‑Schleife über `Path.glob("*.png")`. Speichern Sie jedes Ergebnis in einem Wörterbuch oder schreiben Sie es in eine CSV für spätere Analysen. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Was, wenn ich nur Zahlen extrahieren muss? + +Geben Sie einen benutzerdefinierten **config**‑String an `image_to_string` weiter: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Auf diese Weise können Sie **extract text from image** Dateien extrahieren, die Tabellen, Seriennummern oder Zeitstempel enthalten. + +### Gibt es eine Möglichkeit, Vertrauenswerte zu erhalten? + +Ja – verwenden Sie `pytesseract.image_to_data`, das ein TSV mit dem Vertrauenswert pro Wort zurückgibt. Sie können Tokens mit niedrigem Vertrauenswert herausfiltern, bevor Sie den endgültigen String zusammenstellen. + +## Das Tutorial erweitern + +Jetzt, da Sie die Grundlagen beherrscht haben, sollten Sie diese verwandten Themen erkunden: + +- **Batch OCR with multiprocessing** – beschleunigt große Korpora von PNGs. +- **Hybrid OCR + NLP pipelines** – übersetzt automatisch das extrahierte antike Griechisch in modernes Englisch. +- **Alternative engines** – probieren Sie `easyocr` oder `opencv`‑basierte Methoden für spezifische Anwendungsfälle. +- **Cloud OCR services** – Google Vision, Azure Computer Vision oder AWS Textract für serverloses Skalieren. + +Jedes dieser Themen baut auf dem Kern‑**python ocr example** auf, das wir gerade behandelt haben, sodass Sie sich beim tieferen Eintauchen wohlfühlen. + +## Fazit + +Wir haben ein einfaches Snippet genommen und in einen robusten **ocr png image**‑Workflow in Python verwandelt. Durch das Erstellen einer `OcrEngine`, das Setzen der Sprache auf Griechisch polytonisch, das Einspeisen einer PNG und das Ausgeben des Ergebnisses wissen Sie jetzt, wie man **extract text from image** Dateien, **recognize image text** und sogar **read ancient greek** verarbeitet. + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Text aus Bild mit Aspose OCR extrahieren – Schritt‑für‑Schritt‑Anleitung](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Wie man den Schwellenwert in OCR‑Bilderkennung einstellt](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Textbild mit Aspose OCR für mehrere Sprachen erkennen](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/german/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..025f6c443 --- /dev/null +++ b/ocr/german/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-06 +description: Python-OCR-Tutorial, das zeigt, wie man Bildtext erkennt, hochauflösende + OCR durchführt und spanischen Text mit GPU‑beschleunigter OCR extrahiert. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: de +og_description: Python-OCR-Tutorial, das Sie durch die Erkennung von Bildtext, hochauflösende + OCR und das Extrahieren spanischen Textes mit GPU‑Beschleunigung führt. +og_title: Python‑OCR‑Tutorial – GPU‑beschleunigte Texterkennung +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR‑Tutorial – Bildtext mit GPU‑Beschleunigung erkennen +url: /de/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Bildtext mit GPU‑Beschleunigung erkennen + +Haben Sie sich jemals gefragt, wie man **Bildtext** in einem Python‑Skript erkennt, ohne Stunden damit zu verbringen, Einstellungen zu optimieren? Sie sind nicht allein. In diesem **python ocr tutorial** zeigen wir Ihnen einen sauberen, End‑to‑End‑Ansatz, um spanischen Text aus einem hochauflösenden Bild zu extrahieren, und wir fügen GPU‑Beschleunigung hinzu, damit der Vorgang blitzschnell läuft. + +Betrachten Sie es als eine schnelle Kaffeepausen‑Demo, die Sie später zu einer produktionsreifen Pipeline ausbauen können. Am Ende dieses Leitfadens haben Sie ein ausführbares Programm, das **high resolution OCR** durchführt, eine CUDA‑fähige GPU nutzt und die genauen spanischen Zeichen ausgibt, die Sie benötigen. + +## Was Sie lernen werden + +- Wie man eine moderne OCR‑Bibliothek installiert und importiert, die GPU‑Beschleunigung unterstützt. +- Wie man eine OCR‑Engine‑Instanz erstellt und sie auf **recognize image text** in Spanisch einstellt. +- Wie man **gpu accelerated OCR** aktiviert, um massive Geschwindigkeitsgewinne bei hochauflösenden Dateien zu erzielen. +- Wie man Randfälle wie fehlende CUDA‑Treiber oder das Zurückfallen auf die CPU behandelt. +- Tipps zur Verbesserung der Genauigkeit, wenn Sie **extract spanish text** aus verrauschten Scans extrahieren müssen. + +### Voraussetzungen + +- Python 3.9+ (der Code funktioniert auch mit 3.10 und neuer). +- Eine CUDA‑kompatible GPU (optional, aber sehr empfehlenswert). +- Grundlegende Kenntnisse mit pip und virtuellen Umgebungen. + +Wenn Ihnen etwas davon fehlt, funktioniert das Tutorial trotzdem – überspringen Sie einfach den GPU‑Schritt und die Bibliothek fällt automatisch auf die CPU zurück. + +--- + +## Python OCR Tutorial: Erforderliche Pakete installieren + +Zuerst benötigen wir eine zuverlässige OCR‑Engine. Für dieses Tutorial verwenden wir das Open‑Source‑Paket **`easyocr`**, das integrierte GPU‑Unterstützung bietet, wenn ein kompatibles Gerät erkannt wird. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Wenn Sie bereits PyTorch installiert haben, stellen Sie sicher, dass es zu Ihrer CUDA‑Version passt (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Nicht übereinstimmende Versionen sind eine häufige Ursache für „GPU not found“-Fehler. + +## Schritt 1: Eine OCR‑Engine‑Instanz erstellen + +Jetzt starten wir die Engine. EasyOCR nennt seine Hauptklasse `Reader`. Der Konstruktor akzeptiert eine Liste von Sprachcodes; wir übergeben `"es"` für Spanisch. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Warum das wichtig ist:* Durch die vorherige Angabe der Sprache lädt die Engine nur die notwendigen neuronalen Netzwerkgewichte, was Speicher spart und die Inferenz beschleunigt – besonders nützlich, wenn Sie später mit **high resolution OCR** arbeiten. + +## Schritt 2: Ein hochauflösendes Bild vorbereiten + +Hochauflösende Bilder liefern dem Modell mehr Pixel zum Arbeiten, was in der Regel zu einer besseren Zeichenerkennung führt. Nehmen wir an, Sie haben eine Datei namens `high_res_spanish.png` in einem Ordner namens `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Falls Sie kein hochauflösendes Beispiel zur Hand haben, können Sie ein kostenloses von Unsplash herunterladen oder ein synthetisches Bild mit Pillow erzeugen. Wichtig ist, die DPI über 300 zu halten, um die besten Ergebnisse zu erzielen. + +## Schritt 3: GPU‑Beschleunigung aktivieren (optional aber empfohlen) + +EasyOCR versucht bereits, die GPU zu nutzen, wenn Sie `gpu=True` setzen. Es ist jedoch gute Praxis, zu überprüfen, ob das Gerät tatsächlich verwendet wird, besonders bei Multi‑GPU‑Setups. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Warum das prüfen?* Wenn das Skript stillschweigend auf die CPU zurückfällt, fragen Sie sich vielleicht, warum ein 5‑Sekunden‑Vorgang plötzlich 30 Sekunden dauert. Diese kleine Prüfung macht das Verhalten transparent und hält Ihre **gpu accelerated OCR**‑Pipeline vorhersehbar. + +## Schritt 4: Hochauflösendes OCR durchführen und Bildtext erkennen + +Jetzt der spaßige Teil – das eigentliche Lesen des Textes. Die `readtext`‑Methode von EasyOCR gibt eine Liste von Tupeln zurück, die das Begrenzungsfeld, die erkannte Zeichenkette und einen Vertrauenswert enthalten. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Wenn Sie die Rohzeichenkette ohne Koordinaten benötigen, setzen Sie `detail=0`. Für die meisten **recognize image text**‑Anwendungsfälle liefert der Standard (`detail=1`) genügend Kontext für die nachträgliche Verarbeitung. + +## Schritt 5: Spanischen Text extrahieren und die Ausgabe bereinigen + +Da wir EasyOCR nach Spanisch gefragt haben, sind die zurückgegebenen Zeichenketten bereits in dieser Sprache. Dennoch möchten Sie sie vielleicht zusammenfügen, Leerzeichen entfernen oder Erkennungen mit niedriger Sicherheit herausfiltern. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Was, wenn die Sicherheit niedrig ist?** Sie können entweder die Schwelle senken (was Rauschen riskieren kann) oder das Bild vorverarbeiten (Kontrast erhöhen, binarisieren oder deskew). Diese Tricks sind üblich, wenn man mit **high resolution OCR** bei gescannten Dokumenten arbeitet. + +## Schritt 6: Randfälle behandeln und Leistungsoptimierungen + +Selbst die besttrainierten Modelle stolpern über einige Szenarien. Im Folgenden finden Sie ein paar schnelle Lösungen, die Sie in das Skript einfügen können. + +### 6.1 Fallback, wenn keine GPU vorhanden ist + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Herunterskalieren sehr großer Bilder + +Wenn Ihr Bild größer als 4000 × 4000 px ist, könnte Ihnen der GPU‑Speicher ausgehen. Skalieren Sie proportional herunter, während Sie die DPI beibehalten: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Diese Snippets halten das Skript robust, egal ob Sie auf einer Workstation oder einem bescheidenen Laptop arbeiten. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengeführt, hier das komplette Skript, das Sie sofort kopieren‑einfügen und ausführen können: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Erwartete Ausgabe (Beispiel):** + + + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Text aus Bild mit Aspose OCR extrahieren – Schritt‑für‑Schritt‑Anleitung](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Wie man Bildtext mit Sprache mittels Aspose.OCR OCR‑t](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Wie man Seitenrechtecke für OCR‑Texterkennung in Aspose.OCR erkennt](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/german/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..56d8721d1 --- /dev/null +++ b/ocr/german/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-06-06 +description: Texterkennung aus Bildern mit der Python-OCR-Engine. Lernen Sie, wie + Sie die OCR-Engine in Python konfigurieren und Text aus Bildern mit Cloud‑Verarbeitung + in wenigen Minuten extrahieren. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: de +og_description: Erkenne Text aus Bildern mit der Python-OCR-Engine. Dieser Leitfaden + zeigt, wie man die OCR-Engine in Python konfiguriert und Text effizient aus Bildern + extrahiert. +og_title: Text aus Bild in Python erkennen – Komplettes Setup‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Text aus Bild in Python erkennen – Vollständiger Leitfaden zur Einrichtung + einer OCR-Engine +url: /de/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Texterkennung aus Bild in Python – Komplettes Setup‑Tutorial + +Haben Sie sich jemals gefragt, wie man **recognize text from image** mit nur wenigen Zeilen Python erkennt? Sie sind nicht allein. Egal, ob Sie einen Beleg‑Scanner, einen Dokumenten‑Digitalisierer oder ein einfaches Hobby‑Projekt bauen, die Fähigkeit, Text aus Bild zu extrahieren, zahlt sich schnell aus. + +In diesem Tutorial führen wir Sie durch den gesamten Prozess – beginnend mit einem **configure OCR engine python**‑artigen Setup, über die Cloud‑Authentifizierung bis hin zur Demonstration, wie Sie **extract text from image** mit zuverlässigem Ergebnis erhalten. Kein Zauber, nur klare Schritte, die Sie heute copy‑paste‑en und ausführen können. + +## Was Sie lernen werden + +- Wie man die erforderliche OCR‑Bibliothek installiert und importiert. +- Die genauen Befehle, um **configure OCR engine python** für die Cloud‑Verarbeitung zu nutzen. +- Ein vollständiges, ausführbares Skript, das **recognize text from image** ausführt und die Ausgabe druckt. +- Tipps zum Umgang mit häufigen Stolperfallen wie fehlenden API‑Schlüsseln oder nicht unterstützten Bildformaten. +- Ideen der nächsten Ebene wie Batch‑Verarbeitung und lokaler Fallback. + +### Voraussetzungen + +- Python 3.8+ auf Ihrem Rechner installiert. +- Eine Internetverbindung (das Beispiel verwendet einen cloud‑basierten OCR‑Dienst). +- Ein gültiger API‑Schlüssel vom OCR‑Anbieter (Sie sehen, wo Sie ihn einfügen). + +Wenn Sie das haben, lassen Sie uns loslegen – ohne Schnickschnack, nur ein praktischer Leitfaden, der funktioniert. + +--- + +## Schritt 1: Installieren Sie die OCR‑Bibliothek und importieren Sie sie + +Bevor Sie **configure OCR engine python** können, benötigen Sie die Bibliothek, die mit dem Cloud‑Dienst kommuniziert. In unserem Beispiel verwenden wir ein fiktives, aber repräsentatives Paket namens `ocrcloud`. Ersetzen Sie es durch das echte Paket, das Sie verwenden (z. B. `easyocr`, `google-cloud-vision` usw.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Why this matters:** Das Importieren der Klasse gibt Ihnen Zugriff auf Methoden wie `use_cloud()` und `set_api_key()`. Ohne den Import würde der Rest des Skripts einen `NameError` auslösen. + +*Pro tip:* Pin die Version in Ihrer `requirements.txt` (`ocrcloud==2.1.0`), um später unerwartete Breaking Changes zu vermeiden. + +## Schritt 2: Erstellen Sie und **configure OCR engine python** für den Cloud‑Modus + +Jetzt konfigurieren wir tatsächlich **configure OCR engine python**. Die Engine startet standardmäßig im lokalen Modus; das Umschalten auf den Cloud‑Modus ermöglicht es Ihnen, schwere Bildanalysen an leistungsstarke Server auszulagern. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explanation:** +- `OcrEngine()` erstellt ein frisches Engine‑Objekt – denken Sie an eine leere Leinwand. +- `use_cloud(True)` schaltet einen Schalter um, der der Engine sagt, Bilder über HTTPS zu senden statt sie lokal zu verarbeiten. Das ist entscheidend für hochgenaue Ergebnisse bei komplexen Schriften oder niedrig aufgelösten Fotos. + +## Schritt 3: Authentifizieren Sie sich mit Ihrem Cloud‑API‑Schlüssel + +Die meisten Cloud‑OCR‑Dienste benötigen einen API‑Schlüssel. Dieser Schritt zeigt, wie Sie das Credential sicher einbinden. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Security note:** Nie den Schlüssel in einem öffentlichen Repository hard‑coden. In der Produktion würden Sie ihn aus einer Umgebungsvariable auslesen: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## Schritt 4: **recognize text from image** – Senden Sie ein Remote‑Bild zur Verarbeitung + +Mit der konfigurierten Engine können wir endlich **recognize text from image**. Die Methode `recognize_image()` nimmt einen Pfad oder eine URL entgegen und gibt ein Objekt zurück, das den extrahierten Text enthält. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**What happens under the hood?** +Die Bildbytes werden zum Endpunkt des Anbieters hochgeladen, von einem Deep‑Learning‑Modell verarbeitet und das Klartext‑Ergebnis wird zurückgestreamt. Ist das Bild groß, kann der Service automatisch herunter skalieren, um den Job zu beschleunigen. + +## Schritt 5: Ausgabe des **extract text from image**‑Ergebnisses + +Jetzt, wo der OCR‑Dienst seine Arbeit erledigt hat, drucken wir einfach den Text. In realen Anwendungen könnten Sie ihn in einer Datenbank speichern oder an eine andere Funktion weitergeben. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Expected output:** (Beispiel) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Wenn die Ausgabe wirr aussieht, prüfen Sie, ob das Bild klar ist und Sie das richtige Sprachmodell ausgewählt haben (viele Dienste erlauben `engine.set_language("en")`). + +## Umgang mit Randfällen & häufigen Stolperfallen + +### 1. Fehlender oder ungültiger API‑Schlüssel +Wenn Sie einen Authentifizierungsfehler sehen, stellen Sie sicher: +- Der Schlüssel ist aktiv und nicht abgelaufen. +- Er wird korrekt aus der Umgebung gelesen. +- Ihr Netzwerk erlaubt ausgehenden HTTPS‑Traffic. + +### 2. Nicht unterstützte Bildformate +Die meisten OCR‑APIs akzeptieren JPEG, PNG und PDF. Der Versuch, ein BMP oder TIFF zu verwenden, kann eine „format not supported“-Antwort auslösen. Konvertieren Sie bei Bedarf mit Pillow: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Rate Limits +Cloud‑Dienste begrenzen häufig Anfragen pro Minute. Wenn Sie ein Limit erreichen, implementieren Sie exponentielles Back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Rückgriff auf lokale OCR +Falls die Cloud ausfällt, können Sie zurückschalten: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Ein Fallback erhöht die Resilienz Ihrer Anwendung. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengeführt, hier ein Skript, das Sie jetzt ausführen können (einfach die Platzhalterwerte ersetzen). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Run it:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Sie sollten den extrahierten Text in der Konsole sehen, was bestätigt, dass Sie erfolgreich **recognize text from image** und **extract text from image** mit einem korrekt **configure OCR engine python**‑Workflow durchgeführt haben. + +## Fazit + +Wir haben gerade einen kompletten End‑to‑End‑Prozess durchlaufen, der Ihnen ermöglicht, **recognize text from image** in Python zu nutzen, von der Installation der Bibliothek über die Authentifizierung bei einem Cloud‑Dienst bis hin zum **extract text from image** mit einem einzigen Funktionsaufruf. Durch das richtige **configure OCR engine python** erhalten Sie sowohl Flexibilität (Cloud vs. lokal) als auch Zuverlässigkeit (korrekte Fehlerbehandlung). + +Was kommt als Nächstes? Versuchen Sie, einen Ordner mit Belegen stapelweise zu verarbeiten, fügen Sie Spracherkennung hinzu oder experimentieren Sie mit PDFs als Eingabe. Der Himmel ist die Grenze, sobald Sie die Grundlagen beherrschen. + +Viel Spaß beim Coden, und stellen Sie gern Fragen in den Kommentaren – nichts schlägt das gemeinsame Lernen! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Text aus Bild extrahieren mit Aspose OCR – Schritt‑für‑Schritt‑Anleitung](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Text aus Bild extrahieren – Zeile erkennen mit Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Wie man Text aus Bild extrahiert, indem man Rechtecke in OCR vorbereitet](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/german/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..b18ee1a2d --- /dev/null +++ b/ocr/german/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-06-06 +description: Führen Sie OCR auf einem Bild mit Python aus und sehen Sie sich die Vertrauenswerte + an. Lernen Sie, wie Sie Wörter mit geringem Vertrauen filtern, Schwellenwerte festlegen + und Sonderfälle behandeln. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: de +og_description: Führen Sie OCR auf einem Bild in Python aus, prüfen Sie die Vertrauenswerte + und filtern Sie Wörter mit niedriger Sicherheit. Dieses Tutorial führt Sie durch + ein vollständiges, ausführbares Beispiel. +og_title: OCR auf Bild mit Python ausführen – Vollständige Anleitung +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: OCR auf Bild mit Python ausführen – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR auf Bildern mit Python ausführen – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie schon einmal **OCR auf Bild**‑Dateien ausführen müssen, waren sich aber nicht sicher, wie Sie zuverlässigen Text daraus erhalten? Sie sind nicht allein – vielen Entwicklern geht es genauso, wenn die extrahierten Wörter wackelig aussehen und der Vertrauenswert ein Rätsel bleibt. + +In diesem Leitfaden gehen wir direkt zu einer funktionierenden Lösung: Sie sehen, wie man OCR auf Bild ausführt, das Gesamtergebnis‑Vertrauen ausliest und Wörter mit geringem Vertrauen herausfiltert, die einer manuellen Überprüfung bedürfen. Am Ende haben Sie ein wiederverwendbares Skript, verstehen, warum jede Zeile wichtig ist, und wissen, wie Sie den Vertrauens‑Schwellenwert für Ihre eigenen Projekte anpassen können. + +## Was dieses Tutorial behandelt + +Wir gehen den gesamten Workflow durch – vom Laden eines Bildes bis zum Ausgeben eines übersichtlichen Berichts über Wörter, die unter einer Vertrauensmarke von 80 % liegen. Dabei besprechen wir: + +* Auswahl einer soliden OCR‑Engine (wir verwenden **EasyOCR**, eine beliebte Python‑OCR‑Bibliothek) +* Interpretation des `confidence`‑Attributs, das jedes OCR‑Ergebnis zurückgibt +* Filtern von Wörtern mit einem benutzerdefinierten **OCR‑Vertrauens‑Schwellenwert** +* Erweiterung des Skripts für Batch‑Verarbeitung oder alternative Engines wie **pytesseract** + +Vorkenntnisse in OCR sind nicht nötig, nur Grundkenntnisse in Python und eine funktionierende Umgebung (Python 3.9+ empfohlen). + +Bereit, verschwommene Screenshots in sauberen, durchsuchbaren Text zu verwandeln? Dann legen wir los. + +--- + +## ## Wie man OCR auf Bild mit Python ausführt + +Der Kern des Tutorials ist ein dreischrittiger Code‑Abschnitt, der dem bereits gezeigten Code entspricht. Im Folgenden zerlegen wir jede Zeile, erklären das Warum und geben Ihnen anschließend ein vollständiges, copy‑and‑paste‑fertiges Skript. + +### Schritt 1: OCR‑Engine installieren und importieren + +Stellen Sie zuerst sicher, dass die OCR‑Bibliothek verfügbar ist. **EasyOCR** funktioniert out‑of‑the‑box für viele Sprachen und liefert einen Vertrauenswert pro Wort. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Warum EasyOCR?* Es bündelt ein Deep‑Learning‑Modell, das auf diversen Datensätzen trainiert wurde, sodass Sie typischerweise höhere Vertrauenswerte erhalten als mit der älteren Tesseract‑Engine, besonders bei Bildern gemischter Qualität. + +> **Pro‑Tipp:** Wenn Sie in einer eingeschränkten Umgebung arbeiten (z. B. ein kleiner Docker‑Container), könnte `pytesseract` leichter sein, allerdings verlieren Sie dabei etwas von der modernen Genauigkeit, die EasyOCR bietet. + +### Schritt 2: OCR auf das Bild anwenden + +Jetzt führen wir tatsächlich **OCR auf Bild** aus. Die `recognize_image`‑Methode aus dem ursprünglichen Beispiel wird durch den EasyOCR‑Aufruf `readtext` ersetzt, der eine Liste von `(bbox, text, confidence)`‑Tupeln zurückgibt. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Jeder Eintrag in `ocr_results` sieht folgendermaßen aus: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Das dritte Element (`0.92` im Beispiel) ist der Vertrauenswert im Bereich von 0 bis 1. + +### Schritt 3: Gesamtes Vertrauen zusammenfassen + +Im Gegensatz zum vorherigen Snippet, das ein einzelnes `confidence`‑Attribut ausgab, liefert EasyOCR ein Vertrauen pro Wort. Um einen Gesamteindruck zu bekommen, mitteln wir diese Werte: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Warum mitteln?* Es gibt Ihnen einen schnellen Gesundheits‑Check – liegt das Gesamtergebnis unter etwa 70 %, sollten Sie das Bild verbessern (bessere Beleuchtung, Vorverarbeitung usw.). + +### Schritt 4: Wörter mit geringem Vertrauen auflisten + +Jetzt kommt der Teil, der direkt die Anforderung „Liste Wörter, deren Vertrauen unter dem gewünschten Schwellenwert liegt“ erfüllt. Wir setzen standardmäßig einen **OCR‑Vertrauens‑Schwellenwert** von 0.80 (80 %) und können ihn bei Bedarf anpassen. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Die Schleife gibt jedes Wort aus, das den Cut‑off nicht erreicht hat, zusammen mit seinem prozentualen Vertrauenswert. Das ist das exakte Gegenstück zur ursprünglichen `for recognized_word in recognition_result.words`‑Schleife, funktioniert aber mit dem Ausgabeformat von EasyOCR. + +--- + +## ## Verständnis von OCR‑Vertrauens‑Scores + +Vertrauen ist keine magische Zahl; es ist die Schätzung des Modells, wie sicher es sich bei einer bestimmten Transkription ist. Beachten Sie Folgendes: + +| Situation | Typisches Vertrauen | Was zu tun ist | +|-----------|-------------------|------------| +| Klarer, hochauflösender Scan | 0.95 – 1.00 | Keine zusätzlichen Schritte nötig | +| Leichte Unschärfe oder ungleichmäßige Beleuchtung | 0.80 – 0.94 | Leichte Vorverarbeitung (Kontrast erhöhen) | +| Starke Geräusche, gedrehter Text | < 0.70 | Bildvorverarbeitung (Deskew, Denoise) oder andere OCR‑Engine verwenden | + +> **Achtung:** Einige Sprachen (z. B. kursive Handschrift) erzeugen naturgemäß niedrigere Werte. Passen Sie den Schwellenwert entsprechend an. + +### Randfälle & Varianten + +1. **Batch‑Verarbeitung** – Wenn Sie **OCR auf Bild**‑Dateien in großen Mengen ausführen müssen, verpacken Sie die obige Logik in eine Schleife, die ein Verzeichnis durchläuft. +2. **Mehrere Sprachen** – Übergeben Sie eine Liste wie `['en', 'fr']` an `easyocr.Reader` und die Engine erkennt beide. +3. **Alternative Engines** – Möchten Sie **pytesseract** testen? Ersetzen Sie den Reader‑Block durch: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Anschließend müssen Sie die Vertrauenswerte pro Zeichen zu Wort‑Vertrauenswerten aggregieren – etwas mehr Aufwand, aber machbar. + +4. **Vorverarbeitungs‑Tricks** – Das Anwenden von OpenCV‑Filtern (`cv2.threshold`, `cv2.GaussianBlur`) kann das Vertrauen bei verrauschten Scans erhöhen. + +--- + +## ## Vollständiges, sofort ausführbares Skript + +Unten finden Sie die komplette Python‑Datei, die Sie in Ihr Projekt einbinden können. Speichern Sie sie als `ocr_report.py` und führen Sie `python ocr_report.py` aus. Achten Sie darauf, dass der Bildpfad auf eine reale Datei zeigt. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Erwartete Ausgabe** (Ihre Zahlen werden abweichen): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Wenn jedes Wort die 80 %-Marke überschreitet, sehen Sie stattdessen die freundliche Meldung „All words meet the confidence threshold.“. + +--- + +## ## Häufig gestellte Fragen (FAQ) + +**F: Funktioniert das mit PDFs?** +A: Nicht direkt. Konvertieren Sie jede PDF‑Seite zuerst in ein Bild (z. B. mit `pdf2image`) und übergeben Sie dann das PNG/JPEG an das Skript. + +**F: Meine Vertrauenszahlen sind alle niedrig – was kann ich tun?** +A: Probieren Sie Bildvorverarbeitung: Kontrast erhöhen, Hintergrundrauschen entfernen oder das Bild horizontal ausrichten. EasyOCR akzeptiert außerdem einen Parameter `contrast_ths`, den Sie anpassen können. + +**F: Kann ich die Ergebnisse als CSV exportieren?** +A: Auf jeden Fall. Schreiben Sie nach der Low‑Confidence‑Schleife `ocr_results` mit einem `csv.DictWriter`, wobei jede Zeile `text`, `confidence` und die Bounding‑Box‑Koordinaten enthält. + +**F: Gibt es eine GPU‑beschleunigte Version?** +A: EasyOCR nutzt automatisch CUDA, wenn eine kompatible GPU und PyTorch installiert sind. Prüfen Sie mit `torch.cuda.is_available()` vor dem Skriptlauf. + +--- + +## Fazit + +Wir haben gerade **OCR auf Bild** mit Python ausgeführt, das Gesamtergebnis‑Vertrauen geprüft und Wörter mit geringem Vertrauen isoliert, die einer manuellen Nachbearbeitung bedürfen. + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/greek/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..b7fd1e417 --- /dev/null +++ b/ocr/greek/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Εξάγετε κείμενο από εικόνα με Python OCR σε λίγα λεπτά. Ανακαλύψτε πολυγλωσσικό + OCR εικόνας, αυτόματη ανίχνευση γλώσσας OCR και πώς να εξάγετε κείμενο OCR με ακρίβεια. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: el +og_description: Εξάγετε κείμενο από εικόνα με Python OCR γρήγορα. Μάθετε πολυγλωσσικό + OCR εικόνας, αυτόματη ανίχνευση γλώσσας OCR και πώς να εξάγετε κείμενο OCR βήμα + προς βήμα. +og_title: Εξαγωγή κειμένου από εικόνα χρησιμοποιώντας Python OCR – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Απόσπαση κειμένου από εικόνα με Python OCR – Πλήρης οδηγός +url: /el/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εξαγωγή Κειμένου από Εικόνα με Python OCR – Πλήρης Οδηγός + +Έχετε χρειαστεί ποτέ να **εξάγετε κείμενο από εικόνα** αλλά δεν ήσασταν σίγουροι ποια βιβλιοθήκη μπορεί να διαχειριστεί αυτόματα πολλές γλώσσες; Δεν είστε μόνοι—οι προγραμματιστές ρωτούν συνεχώς *πώς να εξάγουν κείμενο OCR* όταν εργάζονται με διεθνή έγγραφα, αποδείξεις ή σαρωμένα φυλλάδια. Σε αυτό το tutorial θα περάσουμε από ένα πρακτικό παράδειγμα Python που όχι μόνο εξάγει κείμενο από μια εικόνα αλλά επίσης **ανιχνεύει τη γλώσσα** αυτόματα, καθιστώντας το πολυγλωσσικό OCR εικόνας παιχνιδάκι. + +Θα καλύψουμε τα πάντα, από την εγκατάσταση του πακέτου OCR μέχρι την ενεργοποίηση του **auto detect language OCR**, την εκτέλεση της μηχανής σε ένα δείγμα εικόνας, και τέλος την εκτύπωση τόσο της ανιχνευμένης γλώσσας όσο και του εξαγόμενου κειμένου. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο snippet που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο, είτε χτίζετε μια αλυσίδα μετάφρασης είτε μια υπηρεσία εισαγωγής δεδομένων. + +## Εξαγωγή Κειμένου από Εικόνα – Ρύθμιση Περιβάλλοντος + +Πριν βουτήξουμε στον κώδικα, βεβαιωθείτε ότι το περιβάλλον εργασίας σας πληροί τις ελάχιστες απαιτήσεις: + +- Python 3.8 ή νεότερο (η βιβλιοθήκη χρησιμοποιεί type hints που οι παλαιότερες εκδόσεις αγνοούν) +- `pip` για διαχείριση πακέτων +- Ένα αρχείο εικόνας που περιέχει κείμενο τουλάχιστον σε δύο διαφορετικές γλώσσες (π.χ. Αγγλικά + Ισπανικά) + +Θα χρειαστείτε επίσης τη βιβλιοθήκη OCR που τροφοδοτεί αυτή τη demo. Για το σκοπό αυτού του οδηγού θα χρησιμοποιήσουμε το φανταστικό πακέτο `ocr`, το οποίο αντικατοπτρίζει δημοφιλή πραγματικά εργαλεία όπως το Tesseract ή το EasyOCR αλλά προσφέρει ένα καθαρό Python API. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** Αν αντιμετωπίσετε σφάλματα δικαιωμάτων, προσθέστε `python -m` στην αρχή της εντολής ή χρησιμοποιήστε ένα virtual environment—διατηρεί τα global site‑packages σας καθαρά. + +## Δημιουργία Αντικειμένου OCR Engine + +Τώρα που η βιβλιοθήκη είναι έτοιμη, το πρώτο λογικό βήμα είναι να **δημιουργήσετε ένα αντικείμενο OCR engine**. Σκεφτείτε τη μηχανή ως έναν έξυπνο σαρωτή που μπορείτε να διαμορφώσετε πριν της δώσετε εικόνες. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Γιατί δημιουργούμε το αντικείμενο ξεχωριστά αντί να καλέσουμε μια static μέθοδο; Το αντικείμενο engine κρατάει την κατάσταση διαμόρφωσης (όπως προτιμήσεις γλώσσας) που μπορεί να θέλετε να επαναχρησιμοποιήσετε σε πολλές εικόνες, εξοικονομώντας το κόστος επανεκκίνησής του κάθε φορά. + +## Ενεργοποίηση Auto Detect Language OCR + +Οι περισσότερες εργαλεία OCR απαιτούν να καθορίσετε έναν κωδικό γλώσσας—`eng` για Αγγλικά, `spa` για Ισπανικά, κ.λπ. Η χειροκίνητη εικασία της γλώσσας αντιτίθεται στον σκοπό μιας **πολυγλωσσικής OCR εικόνας**. Ευτυχώς, το πακέτο `ocr` προσφέρει λειτουργία *auto detect language OCR* που εξετάζει την εικόνα και επιλέγει το καλύτερο μοντέλο γλώσσας στο παρασκήνιο. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Η ενεργοποίηση του **detect language OCR** με αυτόν τον τρόπο σημαίνει ότι δεν θα χρειαστεί να διατηρείτε μια μακριά λίστα κωδικών γλώσσας. Η μηχανή θα προσπαθήσει να ταιριάξει το script που βλέπει—Latin, Cyrillic, Han κ.λπ.—και θα φορτώσει το κατάλληλο μοντέλο αυτόματα. + +## Εκτέλεση Πολυγλωσσικού OCR Εικόνας + +Με τη μηχανή έτοιμη, ήρθε η ώρα να **εξάγετε κείμενο από εικόνα**. Η μέθοδος `recognize_image` δέχεται μια διαδρομή αρχείου και επιστρέφει ένα αντικείμενο αποτελέσματος που περιέχει τόσο το ακατέργαστο κείμενο όσο και τη γλώσσα που ανιχνεύθηκε. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Αν αναρωτιέστε *πώς να εξάγετε OCR κείμενο* από PDF αντί για PNG, η ίδια μηχανή προσφέρει `recognize_pdf`—απλώς αλλάξτε το όνομα της μεθόδου. Η λογική ανίχνευσης παραμένει η ίδια, οπότε επωφελείστε από την ίδια λειτουργία **auto detect language OCR**. + +## Εμφάνιση Ανιχνευμένης Γλώσσας και Εξαγόμενου Κειμένου + +Τέλος, εμφανίζουμε ό,τι ανακάλυψε η μηχανή. Το αντικείμενο αποτελέσματος εκθέτει `detected_language` (μια ετικέτα BCP‑47 όπως `en` ή `es`) και `text`, που περιέχει το ακατέργαστο OCR output. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Η εκτέλεση του script στην δείγμα εικόνα μας θα πρέπει να παράγει κάτι παρόμοιο με: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Παρατηρήστε πώς η μηχανή αναγνώρισε σωστά τα Αγγλικά ως κύρια γλώσσα, αλλά κατέγραψε και τη γραμμή στα Ισπανικά—ακριβώς αυτό που περιμένετε από μια αξιόπιστη **πολυγλωσσική OCR εικόνας** λύση. + +### Τι γίνεται αν η ανίχνευση αποτύχει; + +Μερικές φορές η μηχανή OCR μπορεί να επιστρέψει μια προεπιλεγμένη γλώσσα (συνήθως Αγγλικά) αν η εικόνα είναι θολή ή το script είναι πολύ εξωτικό. Σε αυτές τις περιπτώσεις μπορείτε να επιβάλετε μια λίστα γλωσσών: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Αλλά θυμηθείτε, η επιβολή γλωσσών μειώνει την ευκολία του **auto detect language OCR**, οπότε χρησιμοποιήστε το μόνο όταν γνωρίζετε ένα υποσύνολο γλωσσών. + +## Συνηθισμένα Πιθανά Προβλήματα και Πώς να Εξάγετε OCR Κείμενο Αξιόπιστα + +Ακόμη και με auto‑detection, μερικά μικρά προβλήματα μπορεί να σας εμποδίσουν: + +1. **Εικόνες χαμηλής ανάλυσης** – Η ακρίβεια του OCR πέφτει δραστικά κάτω από 150 dpi. Ανεβάστε την ανάλυση ή ζητήστε σάρωση υψηλότερης ανάλυσης. +2. **Θόρυβος και τεχνουργήματα συμπίεσης** – Εφαρμόστε ένα απλό φίλτρο κατωφλίου (`opencv` ή `Pillow`) πριν δώσετε την εικόνα στη μηχανή. +3. **Μικτά scripts σε μία σελίδα** – Κάποιες μηχανές δυσκολεύονται με ταυτόχρονα Latin και CJK χαρακτήρες. Χωρίστε τη σελίδα σε περιοχές και τρέξτε ξεχωριστές αναγνωρίσεις αν χρειαστεί. + +Η αντιμετώπιση αυτών των ζητημάτων βελτιώνει δραματικά την ποιότητα της διαδικασίας **extract text from image**, ειδικά όταν δουλεύετε με πραγματικά, πολυγλωσσικά έγγραφα. + +## Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω βρίσκεται το πλήρες, έτοιμο‑για‑εκτέλεση script που συνδυάζει όλα τα βήματα που συζητήσαμε. Αποθηκεύστε το ως `multilingual_ocr.py` και τρέξτε το από τη γραμμή εντολών. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Αναμενόμενο αποτέλεσμα** (υπόθεση ότι η δείγμα εικόνα περιέχει κείμενο στα Αγγλικά και Ισπανικά): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Αντικαταστήστε το `multilang_page.png` με οποιαδήποτε εικόνα περιέχει κείμενο σε άλλες γλώσσες—χάρη στο **auto detect language OCR**, το script θα δώσει ακόμα μια λογική ετικέτα γλώσσας και το αντίστοιχο κείμενο. + +![Εξαγωγή κειμένου από εικόνα παράδειγμα](https://example.com/ocr-sample.png "Εξαγωγή κειμένου από εικόνα") + +## Συμπέρασμα + +Τώρα ξέρετε ακριβώς **πώς να εξάγετε OCR κείμενο** από μια εικόνα, πώς να ενεργοποιήσετε το **auto detect language OCR**, και πώς να διαχειριστείτε σενάρια **πολυγλωσσικού OCR εικόνας** με ελάχιστο κώδικα. Δημιουργώντας ένα OCR engine instance, ενεργοποιώντας την αυτόματη ανίχνευση γλώσσας, και καλώντας το `recognize_image`, μπορείτε αξιόπιστα να εξάγετε τόσο τον αναγνωριστικό γλώσσας όσο και το ακατέργαστο κείμενο. + +Τι ακολουθεί; Δοκιμάστε να τροφοδοτήσετε τα εξαγόμενα strings σε ένα API μετάφρασης, αποθηκεύστε τα σε μια αναζητήσιμη βάση δεδομένων, ή συνδυάστε πολλές σελίδες σε ένα ενιαίο PDF report. Μπορείτε επίσης να πειραματιστείτε με διαφορετικά OCR back‑ends (Tesseract, EasyOCR, Google Vision) διατηρώντας το ίδιο υψηλού επιπέδου workflow—ευχαριστώντας τη συνεπή **detect language OCR** διεπαφή. + +Αν αντιμετωπίσετε οποιεσδήποτε ιδιαιτερότητες, επιστρέψτε στην ενότητα “Συνηθισμένα Πιθανά Προβλήματα” ή προσαρμόστε τα βήματα προεπεξεργασίας εικόνας. Καλή κωδικοποίηση, και εύχομαι το επόμενο έργο σας να είναι γεμάτο σωστά ανιχνευμένο, τέλεια εξαγόμενο κείμενο! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει ολοκληρωμένα παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στην δική σας υλοποίηση. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/greek/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..2ea1880f2 --- /dev/null +++ b/ocr/greek/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Εξάγετε κείμενο από εικόνες PDF χρησιμοποιώντας Python OCR. Μάθετε πώς + να μετατρέπετε σαρωμένα έγγραφα σε κείμενο γρήγορα με ασύγχρονη ομαδική αναγνώριση. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: el +og_description: Εξάγετε κείμενο από εικόνες PDF με Python. Αυτός ο οδηγός βήμα‑βήμα + δείχνει πώς να μετατρέψετε σαρωμένα έγγραφα σε κείμενο χρησιμοποιώντας ασύγχρονη + OCR. +og_title: Εξαγωγή κειμένου από εικόνες PDF – Python OCR Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Εξαγωγή κειμένου από εικόνες PDF – Οδηγός Python για τη μετατροπή σαρωμένων + εγγράφων σε κείμενο +url: /el/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εξαγωγή Κειμένου από PDF Εικόνων – Οδηγός Python για τη Μετατροπή Σαρωμένων Εγγράφων σε Κείμενο + +Έχετε ποτέ χρειαστεί να **εξάγετε κείμενο από pdf εικόνων** χωρίς να ξοδεύετε ώρες ξαναπληκτρολόγηση; Σε αυτόν τον οδηγό θα σας δείξουμε πώς να **μετατρέψετε σαρωμένα έγγραφα σε κείμενο** χρησιμοποιώντας μια απλή ασύγχρονη ροή εργασίας OCR σε Python. + +Αν έχετε ποτέ κολλήσει μπροστά σε ένα σωρό σαρωμένων PDF και σκεφτείτε, “Πρέπει να υπάρχει πιο γρήγορος τρόπος,” βρίσκεστε στο σωστό μέρος. Θα περάσουμε από κάθε γραμμή κώδικα, θα εξηγήσουμε γιατί κάθε κομμάτι είναι σημαντικό και θα καλύψουμε μερικές περιπτώσεις που μπορεί να συναντήσετε. + +## Τι Θα Μάθετε + +- Πώς να δημιουργήσετε μια μηχανή OCR και να ορίσετε τη γλώσσα αναγνώρισης. +- Τους μηχανισμούς τροφοδοσίας μιας μικτής λίστας PNG και PDF σε έναν batch recognizer. +- Την εκτέλεση της εργασίας OCR ασύγχρονα ώστε η εφαρμογή σας να παραμένει ανταποκρινόμενη. +- Την ανάκτηση των αποτελεσμάτων, τη συσχέτισή τους με τα αρχικά αρχεία και την εκτύπωση καθαρού αποτελέσματος. + +**Προαπαιτούμενα**: Python 3.8+, βασική κατανόηση του `asyncio` ή του `concurrent.futures`, και μια βιβλιοθήκη OCR που εκθέτει μια κλάση `OcrEngine` παρόμοια με το παράδειγμα (π.χ., Aspose.OCR, περιτύλιγμα Tesseract, ή προσαρμοσμένο wrapper). Δεν απαιτείται βαριά εγκατάσταση—απλώς εγκαταστήστε τη βιβλιοθήκη και είστε έτοιμοι. + +![εξαγωγή κειμένου από pdf εικόνων](https://example.com/placeholder.png "Στιγμιότυπο εξόδου OCR – εξαγωγή κειμένου από pdf εικόνων") + +## Εξαγωγή Κειμένου από PDF Εικόνων – Ρύθμιση της Μηχανής OCR + +Το πρώτο που χρειάζεστε είναι μια παρουσία της μηχανής OCR ρυθμισμένη για τη γλώσσα των εγγράφων σας. Στην περίπτωση μας θα χρησιμοποιήσουμε τα Γαλλικά, αλλά μπορείτε να την αλλάξετε σε οποιαδήποτε υποστηριζόμενη γλώσσα. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Γιατί αυτό είναι σημαντικό**: Η προ-ρύθμιση της γλώσσας βελτιώνει δραστικά την ακρίβεια. Η μηχανή χρησιμοποιεί λεξικά και μοντέλα χαρακτήρων ειδικά για τη γλώσσα· η τροφοδοσία με λανθασμένη γλώσσα είναι κοινή πηγή ακατανόητης εξόδου. + +## Προετοιμασία Λίστας Αρχείων – Εικόνες και PDF Μαζί + +Ο batch recognizer μας μπορεί να διαχειριστεί τόσο raster εικόνες (`.png`, `.jpg`) όσο και PDF containers. Απλώς δώστε μια απλή λίστα Python με διαδρομές αρχείων. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Συμβουλή**: Κρατήστε τη λίστα επίπεδη· η μηχανή θα αποσυμπιέσει εσωτερικά κάθε σελίδα PDF σε εικόνες πριν την αναγνώριση. Αν έχετε χιλιάδες αρχεία, σκεφτείτε να χωρίσετε τη λίστα σε μικρότερα batch για να αποφύγετε αυξήσεις μνήμης. + +## Εκκίνηση Ασύγχρονης Batch Αναγνώρισης + +Αντί να μπλοκάρετε το κύριο νήμα, εκκινούμε την εργασία OCR στο παρασκήνιο. Η μέθοδος επιστρέφει ένα `Future` που τελικά θα περιέχει μια λίστα αντικειμένων `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Πώς λειτουργεί**: Στο παρασκήνιο η μηχανή δημιουργεί μια ομάδα νημάτων (ή μια ασύγχρονη εργασία, ανάλογα με την υλοποίηση). Αυτό σας επιτρέπει να συνεχίσετε άλλες εργασίες—όπως ενημέρωση UI, λήψη περισσότερων αρχείων ή καταγραφή προόδου—ενώ η βαριά επεξεργασία γίνεται αλλού. + +## Κάντε Κάτι Χρήσιμο Καθώς Εκτελείται το OCR + +Ένα κοινό λάθος είναι να μένετε αδρανείς και να ελέγχετε το future σε σφιχτό βρόχο. Αντί αυτού, μπορείτε να εκτελείτε οποιαδήποτε ανεξάρτητη εργασία. Για επίδειξη, θα εκτυπώσουμε μια γραμμή κατάστασης. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Συλλογή Αποτελεσμάτων Μόλις Το Future Ολοκληρωθεί + +Όταν είστε έτοιμοι να συγκεντρώσετε την έξοδο OCR, χρησιμοποιήστε `as_completed` από το `concurrent.futures`. Αυτό το μοτίβο λειτουργεί είτε έχετε ένα είτε πολλά futures. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Τι θα δείτε**: Κάθε διαδρομή αρχείου ακολουθείται από την εξαγόμενη αναπαράσταση plain‑text. Για PDF, το `result.text` περιέχει το ενωμένο κείμενο όλων των σελίδων. + +### Αναμενόμενη Έξοδος (παράδειγμα) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Αν παρατηρήσετε ελλιπή χαρακτήρες, ελέγξτε ξανά ότι η γλώσσα που ορίσατε ταιριάζει με τη γλώσσα του εγγράφου, και σκεφτείτε προ‑επεξεργασία των εικόνων (ευθυγράμμιση, αύξηση αντίθεσης) πριν τις τροφοδοτήσετε στη μηχανή. + +## Διαχείριση Περιπτώσεων Άκρων και Συνηθισμένων Παγίδων + +| Κατάσταση | Τι να κάνετε | +|-----------|--------------| +| **Μικτές γλώσσες** | Εκτελέστε πρώτα μια φάση ανίχνευσης γλώσσας, έπειτα δημιουργήστε ξεχωριστές μηχανές ανά γλώσσα. | +| **Μεγάλα PDF (> 100 MB)** | Χωρίστε το PDF σε μεμονωμένες σελίδες στο δίσκο (π.χ., με `PyPDF2`) και τροφοδοτήστε τις ως ξεχωριστές καταχωρήσεις. | +| **Μη‑λατινικά scripts** | Βεβαιωθείτε ότι η βιβλιοθήκη OCR περιλαμβάνει το απαιτούμενο language pack· ορισμένες βιβλιοθήκες απαιτούν λήψη επιπλέον αρχείων δεδομένων. | +| **Προβλήματα απόδοσης** | Αυξήστε το μέγεθος του thread pool (`engine.set_thread_pool_size(8)`) ή μεταβείτε σε backend επιταχυμένο από GPU αν είναι διαθέσιμο. | +| **Απουσία κειμένου σε εικόνες χαμηλής ανάλυσης** | Προ‑επεξεργαστείτε με OpenCV: `cv2.resize`, `cv2.threshold`, και `cv2.medianBlur` για βελτίωση της αναγνωσιμότητας. | + +## Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή‑Επικόλληση) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Αποθηκεύστε το ως `extract_text_async.py`, αντικαταστήστε το `YOUR_DIRECTORY` με τη διαδρομή προς τα αρχεία σας, εγκαταστήστε το πακέτο OCR (`pip install your-ocr-lib`), και τρέξτε `python extract_text_async.py`. Θα πρέπει να δείτε την έξοδο κονσόλας όπως περιγράφηκε νωρίτερα. + +## Επόμενα Βήματα – Πέρα από τη Βασική Εξαγωγή + +- **Post‑processing**: Αφαιρέστε περιττά κενά, κανονικοποιήστε Unicode (`unicodedata.normalize`), ή τρέξτε έναν ορθογραφικό ελεγκτή για να καθαρίσετε τον θόρυβο OCR. +- **Structured output**: Εξάγετε τα αποτελέσματα σε CSV, JSON, ή απευθείας σε βάση δεδομένων για επόμενη αναζήτηση. +- **Parallel batches**: Αν έχετε εκατοντάδες αρχεία, δημιουργήστε πολλαπλά futures και χρησιμοποιήστε μια ουρά για να κρατήσετε την CPU απασχολημένη χωρίς να υπερφορτώσετε τη μνήμη. +- **Integrate with web frameworks**: Συνδέστε αυτό το script με ένα endpoint Flask ή FastAPI για να παρέχετε OCR on‑demand ως υπηρεσία. + +--- + +### TL;DR + +Τώρα ξέρετε πώς να **εξάγετε κείμενο από pdf εικόνων** με ένα ελάχιστο script Python που εκτελεί OCR ασύγχρονα, επιτρέποντάς σας να **μετατρέψετε σαρωμένα έγγραφα σε κείμενο** ενώ το πρόγραμμα σας παραμένει ανταποκρινόμενο. Παίξτε με τις ρυθμίσεις γλώσσας, τα μεγέθη batch, και τις τεχνικές προ‑επεξεργασίας για να εξάγετε την μέγιστη ακρίβεια χαρακτήρων. + +Έχετε κάποιο ιδιαίτερο σενάριο που θέλετε να μοιραστείτε—ίσως OCR σε χειρόγραφες σημειώσεις ή υπηρεσία cloud; Αφήστε ένα σχόλιο, και καλή προγραμματιστική διασκέδαση! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετικές θεματικές που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή Κειμένου από Εικόνα με Aspose OCR – Οδηγός Βήμα‑βήμα](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Εξαγωγή Κειμένου από Εικόνες Χρησιμοποιώντας Λειτουργία OCR σε Φακέλους](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Εξαγωγή Κειμένου από Εικόνες Χρησιμοποιώντας Aspose.OCR – Επιτρεπόμενοι Χαρακτήρες](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/greek/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..327f598c1 --- /dev/null +++ b/ocr/greek/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: Πώς να κάνετε OCR PDF με Python, να εξάγετε κείμενο από PDF, να μετατρέψετε + το κείμενο σκαναρισμένου PDF και να αλλάξετε τη γλώσσα OCR με λίγες μόνο γραμμές + κώδικα. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: el +og_description: 'Πώς να κάνετε OCR σε PDF με Python: ένας πρακτικός οδηγός που σας + δείχνει πώς να εξάγετε κείμενο από PDF, να μετατρέψετε το κείμενο σαρωμένου PDF + και να αλλάξετε τη γλώσσα OCR χωρίς κόπο.' +og_title: Πώς να κάνετε OCR PDF σε Python – Πλήρες Μάθημα Προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Πώς να κάνετε OCR σε PDF με Python – Πλήρης Οδηγός Βήμα‑προς‑Βήμα +url: /el/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να κάνετε OCR PDF σε Python – Πλήρης Οδηγός Βήμα‑βήμα + +Έχετε αναρωτηθεί ποτέ **πώς να κάνετε OCR PDF** χωρίς να πληρώνετε για ακριβά εργαλεία SaaS; Δεν είστε μόνοι. Είτε ψηφιοποιείτε παλιά βιβλία, εξάγετε δεδομένα από τιμολόγια, είτε χρειάζεστε απλώς αναζητήσιμο κείμενο από μια σαρωμένη αναφορά, η εξοικείωση με το PDF OCR σε Python μπορεί να σας εξοικονομήσει ώρες χειροκίνητης αντιγραφής. + +Σε αυτό το tutorial θα περάσουμε από ένα σύντομο, λειτουργικό παράδειγμα που **εξάγει κείμενο από PDF**, σας δείχνει πώς να **μετατρέψετε το κείμενο σαρωμένου PDF** σε επεξεργάσιμες συμβολοσειρές, και ακόμη παρουσιάζει πώς να **αλλάξετε τη γλώσσα OCR** εάν το έγγραφό σας δεν είναι στα Αγγλικά. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο snippet που μπορείτε να ενσωματώσετε σε οποιοδήποτε project. + +## Προαπαιτούμενα & Ρύθμιση + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +- Python 3.8+ εγκατεστημένο (ο κώδικας λειτουργεί σε 3.9, 3.10 και νεότερες εκδόσεις) +- Το πακέτο `ocr` που παρέχει την κλάση `OcrEngine` (μπορείτε να το εγκαταστήσετε μέσω `pip install ocr-lib` – αντικαταστήστε με το πραγματικό όνομα του πακέτου που χρησιμοποιείτε) +- Ένα αρχείο PDF που θέλετε να επεξεργαστείτε· για το demo θα χρησιμοποιήσουμε το `high_res_book.pdf` τοποθετημένο σε φάκελο που ονομάζεται `YOUR_DIRECTORY` + +Αν χρησιμοποιείτε εικονικό περιβάλλον (συνιστάται έντονα), ενεργοποιήστε το πρώτα: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** Κρατήστε τα αρχεία PDF σας σε έναν αφιερωμένο φάκελο `data/` για να αποφύγετε προβλήματα σχετικού με διαδρομές αργότερα. + +## Βήμα 1: Δημιουργία Παραδείγματος OCR Engine (How to OCR PDF – Initialization) + +Το πρώτο πράγμα που πρέπει να κάνετε όταν θέλετε να **εκτελέσετε OCR σε PDF** είναι να δημιουργήσετε το engine. Σκεφτείτε το engine ως τον εγκέφαλο που θα διαβάσει κάθε σελίδα, θα ερμηνεύσει τα γλύφη και θα σας επιστρέψει απλό κείμενο. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Γιατί είναι σημαντικό: χωρίς engine δεν έχετε πλαίσιο για ρυθμίσεις γλώσσας, επιλογές απόδοσης ή διαχείριση PDF. Το αντικείμενο `OcrEngine` κρατά όλα αυτά τα προεπιλεγμένα και σας επιτρέπει να τα τροποποιήσετε αργότερα. + +## Βήμα 2: Ορισμός Γλώσσας Αναγνώρισης (Change OCR Language) + +Οι περισσότερες βιβλιοθήκες OCR προεπιλογή είναι τα Αγγλικά, αλλά τι γίνεται αν το έγγραφό σας είναι στα Γαλλικά, Γερμανικά ή ακόμη και Ιαπωνικά; Η αλλαγή της γλώσσας είναι τόσο απλή όσο η κλήση του `set_recognition_language`. Αυτό ικανοποιεί την απαίτηση **change OCR language** και εξασφαλίζει μεγαλύτερη ακρίβεια. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Γιατί μπορεί να το χρειαστείτε:** Ένα πολύγλωσσο αρχείο συχνά περιέχει σελίδες με μεικτές γλώσσες. Η εναλλαγή γλωσσών εν κινήσει αποτρέπει την λανθασμένη αναγνώριση χαρακτήρων όπως “ß” ή “ñ”. + +## Βήμα 3: Ρύθμιση Επιλογών Απόδοσης PDF (Convert Scanned PDF Text Effectively) + +Κατά την επεξεργασία σαρωμένων PDF, η ανάλυση και η λειτουργία χρώματος επηρεάζουν δραστικά την ποιότητα του OCR. Η απόδοση σε 300 DPI σε κλίμακα του γκρι είναι το ιδανικό σημείο για τα περισσότερα έγγραφα—αρκετά υψηλή για να συλλάβει λεπτομέρειες, αλλά αρκετά χαμηλή για να διατηρήσει τη χρήση μνήμης σε λογικά επίπεδα. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Οι αλυσιδωτές κλήσεις μπορεί να φαίνονται εντυπωσιακές, αλλά είναι απλώς ένα fluent API που επιστρέφει το ίδιο αντικείμενο επιλογών κάθε φορά. Αν χρειάζεστε χρώμα (π.χ. για έγχρωμα διαγράμματα), αντικαταστήστε το `"grayscale"` με `"color"`. + +## Βήμα 4: Αναγνώριση του PDF και Λήψη Κειμένου Πρώτης Σελίδας (Extract Text from PDF) + +Τώρα έρχεται η ουσία του **πώς να κάνετε OCR PDF**: περάστε στο engine τη διαδρομή του αρχείου και εξάγετε το αναγνωρισμένο κείμενο. Η μέθοδος επιστρέφει μια λίστα αποτελεσμάτων ανά σελίδα· κάθε αποτέλεσμα περιέχει ένα χαρακτηριστικό `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Αν χρειάζεστε ολόκληρο το έγγραφο, επαναλάβετε πάνω στο `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Τι γίνεται αν το PDF είναι κρυπτογραφημένο; + +Ορισμένα PDF είναι προστατευμένα με κωδικό. Σε αυτήν την περίπτωση μπορείτε να περάσετε τον κωδικό στο `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Το engine θα το αποκρυπτογραφήσει εν κινήσει πριν εκτελέσει το OCR—χωρίς επιπλέον βήματα. + +## Βήμα 5: Μετα-επεξεργασία του Εξαγόμενου Κειμένου (Fine‑Tuning Extract Text from PDF) + +Η ακατέργαστη έξοδος OCR συχνά περιέχει αλλαγές γραμμής, επιπλέον κενά ή περιστασιακούς λανθασμένους χαρακτήρες. Μια γρήγορη διαδικασία καθαρισμού κάνει τη συμβολοσειρά έτοιμη για επόμενη επεξεργασία (ευρετήριο αναζήτησης, αποθήκευση σε βάση δεδομένων κ.λπ.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Τώρα μπορείτε με ασφάλεια να **εξάγετε κείμενο από PDF** και να το περάσετε σε οποιοδήποτε pipeline NLP, μηχανή αναζήτησης ή απλή λειτουργία `open(...).write()`. + +## Bonus: Επεξεργασία Πολλαπλών PDF σε Batch (Scaling Perform OCR on PDF) + +Αν έχετε έναν φάκελο γεμάτο σαρωμένα PDF, τυλίξτε τη λογική σε βρόχο: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Αυτό το snippet δείχνει πώς να **εκτελέσετε OCR σε PDF** αρχεία μαζικά, μια κοινή ανάγκη για έργα ψηφιοποίησης. + +## Αναμενόμενο Αποτέλεσμα + +Η εκτέλεση του παραδείγματος μίας σελίδας (Βήμα 4) θα πρέπει να εκτυπώσει κάτι σαν: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Αν επεξεργαστείτε ένα βιβλίο πολλαπλών σελίδων, η κονσόλα θα εμφανίσει το καθαρισμένο κείμενο κάθε σελίδας, και το batch script θα δημιουργήσει ένα αρχείο `.txt` δίπλα σε κάθε PDF. + +## Συχνά Προβλήματα & Πώς να τα Αποφύγετε + +| Πρόβλημα | Συμπτώματα | Διόρθωση | +|----------|------------|----------| +| PDF πηγής χαμηλής ανάλυσης | Παραμορφωμένοι χαρακτήρες, λείπουν λέξεις | Αυξήστε το DPI (`set_dpi(400)` ή περισσότερο) | +| Λάθος γλώσσα ορισμένη | Πολλά άγνωστα σύμβολα, ειδικά τονισμένα γράμματα | Χρησιμοποιήστε `engine.set_recognition_language(ocr.Language.FRENCH)` ή το αντίστοιχο enum | +| Μεγάλο PDF που προκαλεί σφάλμα μνήμης | `MemoryError` ή κατάρρευση μετά από λίγες σελίδες | Επεξεργαστείτε τις σελίδες σε τμήματα (`engine.recognize_pdf(..., max_pages=10)`) | +| Λείπουν γραμματοσειρές στο PDF | Κενό αποτέλεσμα για ορισμένες σελίδες | Βεβαιωθείτε ότι το PDF περιέχει πραγματικές ραστερ εικόνες· κάποια PDF είναι μόνο διανυσματικά και απαιτούν διαφορετική προσέγγιση | + +## Εικονογραφική Παράσταση + +Παρακάτω υπάρχει μια γρήγορη οπτική αναπαράσταση της ροής εργασίας. Το alt text είναι σκόπιμα φιλικό προς SEO. + +![διαγράφημα ροής ocr pdf που δείχνει την αρχικοποίηση του engine, τη ρύθμιση γλώσσας, τις επιλογές απόδοσης, την αναγνώριση και την εξαγωγή κειμένου](/images/ocr-workflow.png) + +*Το διάγραμμα δεν είναι απαραίτητο για την εκτέλεση του κώδικα, αλλά βοηθά τους οπτικούς μαθητές να καταλάβουν πού εντάσσεται κάθε βήμα.* + +## Συμπέρασμα + +Καλύψαμε **πώς να κάνετε OCR PDF** σε Python από την αρχή μέχρι το τέλος: δημιουργία OCR engine, **αλλαγή γλώσσας OCR**, ρύθμιση απόδοσης για **μετατροπή κειμένου σαρωμένου PDF**, και τέλος **εξαγωγή κειμένου από PDF** για περαιτέρω χρήση. Το πλήρες, εκτελέσιμο παράδειγμα είναι έτοιμο να ενσωματωθεί σε οποιοδήποτε project, και το προαιρετικό batch script δείχνει πώς να κλιμακώσετε τη λύση. + +Επόμενα βήματα που ίσως θέλετε να εξερευνήσετε: + +- Προσθήκη **perform OCR on PDF** για πολύγλωσσα αρχεία επαναλαμβάνοντας πάνω σε λίστα γλωσσών. +- Ενσωμάτωση του εξαγόμενου κειμένου με Elasticsearch για πλήρη αναζήτηση κειμένου. +- Χρήση OCR για δημιουργία αναζητήσιμων PDF ενσωματώνοντας το επίπεδο κειμένου πίσω στο αρχικό αρχείο (πολλές βιβλιοθήκες παρέχουν μέθοδο `save_as_searchable_pdf`). + +Νιώστε ελεύθεροι να πειραματιστείτε, να τροποποιήσετε τις ρυθμίσεις DPI ή να αλλάξετε σε διαφορετικό backend OCR. Τα θεμέλια παραμένουν ίδια, και τώρα έχετε μια ισχυρή βάση για να χτίσετε πάνω της. + +Καλός κώδικας και καλή επιτυχία με την αναζήτηση κειμένου στα σαρωμένα έγγραφά σας! + +## Τι Πρέπει να Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας projects. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/greek/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..40ce65569 --- /dev/null +++ b/ocr/greek/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-06 +description: Πώς να κάνετε OCR σε PDF και να δημιουργήσετε αναζητήσιμα αρχεία PDF + από εικόνες χρησιμοποιώντας Python. Μάθετε να προσθέτετε αναζητήσιμο κείμενο και + να μετατρέπετε εικόνα σε PDF/A σε λίγα λεπτά. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: el +og_description: Πώς να κάνετε OCR σε PDF βήμα‑βήμα. Μάθετε πώς να προσθέτετε αναζητήσιμο + κείμενο και να μετατρέπετε εικόνα σε PDF/A χρησιμοποιώντας ένα απλό script Python. +og_title: Πώς να κάνετε OCR PDF – Σύντομος οδηγός για τη δημιουργία PDF με δυνατότητα + αναζήτησης +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Πώς να κάνετε OCR PDF σε Python – Δημιουργήστε Αναζητήσιμο PDF από Εικόνες +url: /el/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να OCR PDF – Μετατρέψτε Σαρωμένες Εικόνες σε Αναζητήσιμα PDF + +Έχετε αναρωτηθεί ποτέ **πώς να OCR PDF** όταν το μόνο που έχετε είναι μια σαρωμένη εικόνα από τιμολόγιο ή απόδειξη; Δεν είστε οι μόνοι. Σε πολλά γραφεία τα εισερχόμενα έγγραφα φτάνουν ως επίπεδα PNG ή JPEG, και το επόμενο βήμα — η μετατροπή του περιεχομένου σε αναζητήσιμο — φαίνεται σαν μαύρο κουτί. + +Τα καλά νέα; Με λίγες γραμμές Python μπορείτε να **δημιουργήσετε αναζητήσιμα PDF**, **προσθέσετε αναζητήσιμο κείμενο**, και ακόμη **μετατρέψετε εικόνα σε PDF/A** για μακροπρόθεσμη αρχειοθέτηση. Σε αυτό το tutorial θα περάσουμε από κάθε βήμα, θα εξηγήσουμε γιατί είναι σημαντικό, και θα σας δώσουμε ένα έτοιμο script που μπορείτε να ενσωματώσετε σε οποιοδήποτε project. + +> **Pro tip:** Η ίδια προσέγγιση λειτουργεί για σαρώσεις πολλαπλών σελίδων· απλώς κάντε βρόχο πάνω στα αρχεία και η μηχανή θα κάνει το σκληρό κομμάτι. + +--- + +## Τι Θα Χρειαστείτε + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε τα παρακάτω στον υπολογιστή σας: + +| Απαίτηση | Γιατί είναι σημαντικό | +|----------|------------------------| +| Python 3.9 or newer | Σύγχρονη σύνταξη και καλύτερη υποστήριξη βιβλιοθηκών | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Διαχειρίζεται τόσο την αναγνώριση εικόνας όσο και τη δημιουργία PDF/A | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | Η πηγή του κειμένου | +| Write permission to the output folder | Για να μπορεί το script να αποθηκεύσει το νέο PDF | + +Αν δεν έχετε εγκαταστήσει ακόμη το OCR SDK, τρέξτε: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Αυτό είναι όλο — χωρίς πολύπλοκες εξαρτήσεις συστήματος, μόνο μια εγκατάσταση pip. + +--- + +## Πώς να OCR PDF – Επισκόπηση + +Σε υψηλό επίπεδο η διαδικασία αποτελείται από τρεις απλές ενέργειες: + +1. **Αναγνώριση** του κειμένου μέσα στην εικόνα διατηρώντας τα αρχικά γραφικά. +2. **Εξαγωγή** του αποτελέσματος OCR μαζί με την αρχική εικόνα ως **αναζητήσιμο PDF/A** (η έκδοση PDF φιλική προς την αρχειοθέτηση). +3. **Επικύρωση** ότι το παραγόμενο αρχείο περιέχει επιλέξιμο, αναζητήσιμο κείμενο επάνω από την αρχική εικόνα. + +Παρακάτω θα δείτε κάθε βήμα σε κώδικα, με εξηγήσεις του *γιατί* πίσω από τις εντολές. + +--- + +## Βήμα 1: Αναγνώριση Κειμένου από την Εικόνα + +Πρώτα ζητάμε από τη μηχανή OCR να διαβάσει τα pixel και να επιστρέψει ένα αντικείμενο αποτελέσματος που περιέχει τόσο την ακατέργαστη εικόνα όσο και το εξαγόμενο κείμενο. Σκεφτείτε το σαν η μηχανή “διαβάζει” το τιμολόγιο για εσάς. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Γιατί είναι σημαντικό + +- **Διατήρηση γραφικών** σημαίνει ότι η οπτική διάταξη (πίνακες, λογότυπα, σφραγίδες) παραμένει ακριβώς όπως την κατέγραψε ο σαρωτής. +- Το αντικείμενο `result` συνήθως περιέχει ένα κρυφό στρώμα κειμένου που θα ενσωματώσουμε αργότερα στο PDF. +- Η χρήση του `recognize_image` αντί του `recognize_pdf` αποφεύγει ένα επιπλέον βήμα μετατροπής, κάτι που επιταχύνει την επεξεργασία για εικόνες μονής σελίδας. + +#### Συνηθισμένες παραλλαγές + +- Αν έχετε ένα **πολυσελιδικό TIFF**, περάστε τη διαδρομή του αρχείου απευθείας· οι περισσότερες μηχανές θα αντιμετωπίσουν κάθε σελίδα ως ξεχωριστή εικόνα. +- Για PDF που ήδη περιέχουν εικόνες, μπορείτε να καλέσετε `engine.recognize_pdf("file.pdf")` και να παραλείψετε εντελώς αυτό το βήμα. + +--- + +## Βήμα 2: Εξαγωγή Αποτελέσματος OCR ως Αναζητήσιμο PDF/A + +Τώρα παίρνουμε το `result` από το βήμα 1 και λέμε στη μηχανή να γράψει ένα νέο αρχείο. Η βασική σημαία εδώ είναι *PDF/A* — η έκδοση του PDF σύμφωνα με το πρότυπο ISO για μακροπρόθεσμη διατήρηση. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Γιατί είναι σημαντικό + +- **Αναζητήσιμο PDF**: Το αρχείο εξόδου περιέχει ένα κρυφό, επιλέξιμο στρώμα κειμένου. Μπορείτε τώρα να κάνετε Ctrl + F στο έγγραφο. +- **Συμμόρφωση PDF/A**: Ορισμένοι οργανισμοί (νομικοί, χρηματοοικονομικοί) απαιτούν PDF/A για αρχειακά ίχνη· αυτό το βήμα ικανοποιεί αυτόν τον κανόνα αυτόματα. +- Η μέθοδος επίσης **προσθέτει αναζητήσιμο κείμενο** χωρίς να επίπεδωση της εικόνας, έτσι η οπτική πιστότητα παραμένει τέλεια. + +#### Ειδική περίπτωση: Χρειάζεστε κανονικό PDF; + +Αν δεν σας ενδιαφέρει το PDF/A, αντικαταστήστε το `save_as_pdfa` με `save_as_pdf`. Το υπόλοιπο της ροής παραμένει το ίδιο. + +--- + +## Βήμα 3: Επαλήθευση του Αναζητήσιμου PDF + +Μια γρήγορη επιβεβαίωση σας σώζει από μυστηριώδη σφάλματα αργότερα. Ανοίξτε το παραγόμενο αρχείο σε οποιονδήποτε προβολέα PDF, δοκιμάστε να επιλέξετε μια λέξη και χρησιμοποιήστε τη λειτουργία αναζήτησης. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Αναμενόμενη έξοδος + +Όταν τρέξετε το script, η κονσόλα εκτυπώνει: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Ανοίγοντας το αρχείο, θα δείτε την αρχική εικόνα του τιμολογίου με ένα αχνό, αόρατο στρώμα κειμένου. Επισημάνετε οποιαδήποτε λέξη και θα παρατηρήσετε ότι είναι επιλέξιμη — **αυτό είναι το αναζητήσιμο κείμενο** που μόλις προσθέσατε. + +--- + +## Προσθήκη Αναζητήσιμου Κειμένου σε Υπάρχοντα PDF (Bonus) + +Μερικές φορές έχετε ήδη ένα PDF αλλά χρειάζεται να **προσθέσετε αναζητήσιμο κείμενο** σε αυτό. Η ίδια μηχανή μπορεί να επικάλυψει τα αποτελέσματα OCR πάνω σε ένα υπάρχον PDF: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Εδώ το `apply_to` συγχωνεύει το κρυφό στρώμα με τις αρχικές σελίδες, επιτρέποντάς σας να **δημιουργήσετε αναζητήσιμο PDF** χωρίς επανασάρωση. + +--- + +## Συνηθισμένα Προβλήματα και Συμβουλές + +| Πρόβλημα | Πώς να το αποφύγετε | +|----------|----------------------| +| **Πηγές εικόνας χαμηλής ανάλυσης** (< 150 dpi) | Μεγαλώστε ή ζητήστε σαρωτικό υψηλότερης ανάλυσης· η ακρίβεια OCR πέφτει δραματικά κάτω από 150 dpi. | +| **Απουσία δεδομένων γλώσσας** | Εγκαταστήστε τα κατάλληλα πακέτα γλώσσας για τη μηχανή OCR (`pip install pdfocr[eng,spa]`). | +| **Ο φάκελος εξόδου δεν είναι εγγράψιμος** | Εκτελέστε το script με επαρκή δικαιώματα ή επιλέξτε διαφορετικό κατάλογο. | +| **Αποτυχία επικύρωσης PDF/A** | Βεβαιωθείτε ότι δεν ενσωματώνετε μη υποστηριζόμενες γραμματοσειρές ή JavaScript· οι περισσότερες SDK το διαχειρίζονται αυτόματα όταν χρησιμοποιείτε `save_as_pdfa`. | + +--- + +## Πλήρες Script – Λύση Μίας-Αρχείου + +Παρακάτω είναι ένα αυτόνομο script που ενώνει όλα τα παραπάνω. Αντιγράψτε‑και‑επικολλήστε, αντικαταστήστε τις διαδρομές placeholder, και είστε έτοιμοι να **μετατρέψετε εικόνα σε PDF/A** σε δευτερόλεπτα. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Τι κάνει αυτό το script:** +1. Φορτώνει τη μηχανή OCR. +2. Διαβάζει την επιλεγμένη εικόνα και εξάγει το κείμενο. +3. Γράφει ένα **αναζητήσιμο PDF/A** που μπορείτε άμεσα να διανείμετε ή να αρχειοθετήσετε. + +Μπορείτε ελεύθερα να τυλίξετε τη λογική `main` σε μια συνάρτηση που επεξεργάζεται ολόκληρο φάκελο — απλώς επαναλάβετε `os.listdir()` και εκτελέστε τα τρία βήματα για κάθε αρχείο. + +--- + +## Επόμενα Βήματα & Σχετικά Θέματα + +Τώρα που έχετε κατακτήσει **πώς να OCR PDF**, σκεφτείτε τις παρακάτω ιδέες για επέκταση: + +- **Επεξεργασία παρτίδας:** Χρησιμοποιήστε `concurrent.futures` για OCR δεκάδων τιμολογίων παράλληλα. +- **Ένθεση μεταδεδομένων:** Προσθέστε ημερομηνίες δημιουργίας ή αριθμούς τιμολογίων στα μεταδεδομένα του PDF για ευκολότερη ευρετηρίαση. +- **Υβριδικά PDF:** Συνδυάστε αναζητήσιμο κείμενο με ενσωματωμένες αρχικές εικόνες για ένα “ψηφιακό δίδυμο” του έντυπου εγγράφου. +- **Εναλλακτικές εξόδους:** Εξάγετε σε **DOCX** ή **HTML** αν τα επόμενα συστήματα απαιτούν επεξεργάσιμες μορφές. + +Κάθε μία από αυτές τις προσεγγίσεις βασίζεται στις βασικές έννοιες που μόλις μάθατε — αναγνώριση, εξαγωγή, επαλήθευση. + +--- + +## Συμπέρασμα + +Με λίγες μόνο γραμμές Python, τώρα ξέρετε **πώς να OCR PDF** μετατρέποντας μια απλή εικόνα σε **αναζητήσιμο PDF/A**. Το script αναλαμβάνει το δύσκολο κομμάτι, διατηρεί τα αρχικά γραφικά και σας δίνει ένα σύμφωνο πρότυπο έγγραφο που μπορείτε να αναζητήσετε, να αρχειοθετήσετε ή να μοιραστείτε. + +Δοκιμάστε το με τα δικά σας τιμολόγια, αποδείξεις ή σαρωμένα συμβόλαια. Αν συναντήσετε δυσκολίες, αφήστε ένα σχόλιο παρακάτω ή ελέγξτε την επίσημη τεκμηρίωση του SDK — συνήθως περιέχει επιπλέον παραδείγματα. Καλή κωδικοποίηση, και απολαύστε τη νέα δυνατότητα να κάνετε οποιαδήποτε εικόνα άμεσα αναζητήσιμη! + +![Παράδειγμα OCR PDF που δείχνει την αρχική εικόνα και το επικάλυμμα του αναζητήσιμου PDF](placeholder.png "Παράδειγμα OCR PDF") + +## Τι Πρέπει να Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας projects. + +- [Πώς να OCR PDF σε .NET με Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Αναγνώριση Κειμένου PDF – Λειτουργίες OCR με Aspose.OCR για Java](/ocr/english/java/ocr-operations/) +- [Μετατροπή Εικόνων σε PDF C# – Αποθήκευση Πολυσελιδικού Αποτελέσματος OCR](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/greek/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..21c4e8da1 --- /dev/null +++ b/ocr/greek/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Πώς να κάνετε OCR σε PDF χρησιμοποιώντας το Aspose OCR Cloud. Μάθετε + να εξάγετε κείμενο από PDF, να μετατρέπετε σελίδα PDF σε PNG και να αποθηκεύετε + εικόνες σελίδων PDF με Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: el +og_description: Πώς να κάνετε OCR PDF με το Aspose OCR Cloud. Αυτός ο οδηγός δείχνει + πώς να εξάγετε απλό κείμενο PDF, να μετατρέψετε σελίδα PDF σε PNG και να αποθηκεύσετε + τις εικόνες των σελίδων PDF. +og_title: Πώς να κάνετε OCR PDF με το Aspose OCR Cloud – Βήμα προς βήμα +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Πώς να κάνετε OCR PDF με το Aspose OCR Cloud – Πλήρης Οδηγός +url: /el/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να κάνετε OCR PDF με το Aspose OCR Cloud – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ **πώς να κάνετε OCR PDF** αρχεία χωρίς να παλεύετε με βαριά εργαλεία επιφάνειας εργασίας; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν αυτό το πρόβλημα όταν χρειάζονται έναν γρήγορο, προγραμματιστικό τρόπο να εξάγουν κείμενο από σαρωμένα έγγραφα. Τα καλά νέα; Με το Aspose OCR Cloud μπορείτε **να εξάγετε κείμενο από PDF**, να μετατρέψετε κάθε σελίδα σε PNG, και ακόμη **να αποθηκεύσετε εικόνες σελίδων PDF** για μελλοντική χρήση, όλα από ένα καθαρό script Python. + +Σε αυτό το tutorial θα περάσουμε από όλα όσα χρειάζεται να γνωρίζετε: από την εγκατάσταση του SDK, την αδειοδότηση της μηχανής, και την αναγνώριση πολυ‑σελίδων PDF, μέχρι την εξαγωγή απλού κειμένου, τη μετατροπή σελίδων σε PNG, και την αποθήκευση αυτών των εικόνων στο δίσκο. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο snippet που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο χρειάζεται **how to OCR PDF** δυνατότητες. + +## Τι Θα Χρειαστείτε + +- **Python 3.8+** (ο κώδικας λειτουργεί επίσης σε 3.10 και νεότερες εκδόσεις) +- Ένας λογαριασμός Aspose OCR Cloud – θα λάβετε ένα δωρεάν αρχείο άδειας δοκιμής (`Aspose.OCR.lic`) +- Το πακέτο `asposeocrcloud` (`pip install asposeocrcloud`) +- Ένα σαρωμένο, πολυ‑σελίδες PDF που θέλετε να επεξεργαστείτε + +Αυτό είναι όλο. Χωρίς επιπλέον δυαδικά αρχεία, χωρίς εγγενείς εξαρτήσεις, μόνο καθαρό Python. + +## Πώς να κάνετε OCR PDF – Ρύθμιση και Άδεια + +Πριν μπορέσετε να καλέσετε οποιεσδήποτε μεθόδους OCR, πρέπει να ενημερώσετε το SDK ποιος είστε. Η Aspose χρησιμοποιεί ένα ελαφρύ αρχείο άδειας που τοποθετείτε κάπου προσβάσιμο στο script σας. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Συμβουλή:* Αν παραλείψετε το βήμα της άδειας, το SDK θα λειτουργήσει ακόμα αλλά θα ενσωματώσει ένα μικρό υδατογράφημα στις εικόνες εξόδου. Δεν είναι ιδανικό για παραγωγή. + +## Βήμα 2: Εγκατάσταση του Aspose OCR Cloud Python SDK + +Ανοίξτε ένα τερματικό και εκτελέστε: + +```bash +pip install asposeocrcloud +``` + +Το πακέτο φέρνει όλες τις απαιτούμενες εξαρτήσεις (requests, pillow, κλπ.) ώστε να μην χρειάζεται να ψάχνετε για κάτι άλλο. + +## Βήμα 3: Δημιουργία Μηχανής OCR και Επιλογή Γλώσσας + +Η μηχανή είναι η καρδιά της λειτουργίας. Μπορείτε να καθορίσετε οποιαδήποτε γλώσσα υποστηρίζεται από την Aspose· η Αγγλική λειτουργεί στις περισσότερες περιπτώσεις. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Γιατί να ορίσετε τη γλώσσα; Επειδή η μηχανή OCR χρησιμοποιεί λεξικά ειδικά για τη γλώσσα ώστε να βελτιώσει την ακρίβεια. Αν επεξεργάζεστε PDF στα Γαλλικά, απλώς αντικαταστήστε το `ENGLISH` με `FRENCH`. + +## Βήμα 4: Καθορίστε το Πολυ‑Σελίδες PDF Σας + +Δώστε στη μηχανή τη πλήρη διαδρομή του αρχείου που θέλετε να επεξεργαστείτε. Οι σχετικές διαδρομές είναι εντάξει εφόσον λύνουν από τον τρέχοντα φάκελο του script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Βεβαιωθείτε ότι το αρχείο είναι αναγνώσιμο· διαφορετικά θα δείτε ένα `FileNotFoundError`. + +## Βήμα 5: Εκτέλεση OCR – Λαμβάνετε μια Λίστα Αποτελεσμάτων + +Η κλήση του `recognize_pdf` επιστρέφει μια λίστα όπου κάθε στοιχείο αντιστοιχεί σε μία σελίδα του αρχικού PDF. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Κάθε `OcrResult` περιέχει δύο χρήσιμες ιδιότητες: + +* `text` – η αναπαράσταση plain‑text της σελίδας (ιδανικό για **extract plain text pdf**) +* `image` – ένα αντικείμενο Pillow `Image` της αποδομένης σελίδας (τέλειο για **convert pdf page png**) + +## Βήμα 6: Εξαγωγή Κειμένου από PDF και Μετατροπή Σελίδων σε PNG + +Τώρα επαναλαμβάνουμε τα αποτελέσματα, εκτυπώνουμε το εξαγόμενο κείμενο και αποθηκεύουμε μια έκδοση PNG κάθε σελίδας. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Αναμενόμενη Εξαγωγή στην Κονσόλα + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Θα βρείτε επίσης τα `page_1.png`, `page_2.png`, … στον φάκελο `YOUR_DIRECTORY`. Αυτές είναι οι rasterized εικόνες σελίδων που μπορείτε να τροφοδοτήσετε σε επόμενες pipelines επεξεργασίας εικόνας. + +## Βήμα 7: Αποθήκευση Εικόνων Σελίδων PDF (Προαιρετική Μετα-Επεξεργασία) + +Αν χρειάζεστε μόνο τις εικόνες και όχι το κείμενο, μπορείτε να παραλείψετε τη γραμμή `print(res.text)`. Αντίστροφα, αν θέλετε να αποθηκεύσετε το κείμενο σε ξεχωριστά αρχεία `.txt`, απλώς προσθέστε μια μικρή εγγραφή: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Αυτή η μικρή προσθήκη δείχνει πόσο εύκολο είναι να **save PDF page images** ενώ ταυτόχρονα αποθηκεύετε το εξαγόμενο περιεχόμενο. + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας όλα, εδώ είναι το πλήρες script που μπορείτε να αντιγράψετε‑επικολλήσετε στο `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Τρέξτε το με: + +```bash +python ocr_pdf.py +``` + +Θα πρέπει να δείτε την εκτύπωση στην κονσόλα του κειμένου κάθε σελίδας και μια σειρά από αρχεία PNG + +## Τι Θα Πρέπει Να Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να κάνετε OCR PDF σε .NET με το Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Αναγνώριση Κειμένου PDF – Λειτουργίες OCR με το Aspose.OCR για Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Μετατροπή Εικόνων σε PDF C# – Αποθήκευση Πολυσελίδας OCR Αποτελέσματος](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/greek/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..1e0190a67 --- /dev/null +++ b/ocr/greek/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-06-06 +description: Πώς να προεπεξεργαστείτε εικόνες για OCR χρησιμοποιώντας Python. Μάθετε + να δυαδικοποιήσετε την εικόνα με τη μέθοδο Otsu, πώς να διορθώσετε την κλίση των + σαρωμένων εγγράφων και να βελτιώσετε την ακρίβεια του OCR για γερμανικό κείμενο. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: el +og_description: Πώς να προεπεξεργαστείτε εικόνες για OCR σε Python. Αυτό το σεμινάριο + δείχνει πώς να δυαδικοποιήσετε την εικόνα χρησιμοποιώντας τη μέθοδο Otsu, πώς να + διορθώσετε την κλίση των σαρωμένων εγγράφων και πώς να βελτιώσετε την ακρίβεια του + OCR για γερμανικές εικόνες. +og_title: Πώς να Προεπεξεργαστείτε Εικόνες για OCR – Πλήρης Οδηγός Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Πώς να προεπεξεργαστείτε εικόνες για OCR – Πλήρης οδηγός Python +url: /el/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Προεπεξεργαστείτε Εικόνες για OCR – Πλήρης Οδηγός Python + +Έχετε αναρωτηθεί ποτέ **πώς να προεπεξεργαστείτε εικόνες για OCR** ώστε το κείμενο να βγαίνει κρυστάλλινα καθαρό; Δεν είστε οι μόνοι. Τα σαρωμένα έγγραφα—ιδιαίτερα οι θορυβώδεις γερμανικές σελίδες—μπορούν να γίνουν εφιάλτης για οποιαδήποτε μηχανή OCR. Το καλό νέο; Μερικά έξυπνα βήματα προεπεξεργασίας μπορούν να μετατρέψουν μια θολή, σπασμένη σάρωση σε μια καθαρή, μηχανικά αναγνώσιμη εικόνα. + +Σε αυτό το tutorial θα περάσουμε από ένα πρακτικό παράδειγμα που δείχνει **πώς να προεπεξεργαστείτε εικόνες για OCR** χρησιμοποιώντας Python. Θα μάθετε να **δυαδικοποιείτε εικόνα με Otsu**, **πώς να διορθώνετε την κλίση σαρωμένων εγγράφων**, και γενικά **πώς να βελτιώσετε την ακρίβεια του OCR** όταν χρειάζεται να **εξάγετε κείμενο από γερμανική εικόνα**. Χωρίς περιττές πληροφορίες, μόνο ένα λειτουργικό script που μπορείτε να αντιγράψετε‑επικολλήσετε σήμερα. + +## Τι Θα Χρειαστεί + +- **Python 3.9+** (οποιαδήποτε πρόσφατη έκδοση) +- Μια βιβλιοθήκη OCR που εκθέτει μια κλάση `OcrEngine` – για το demo θα υποθέσουμε ένα γενικό πακέτο `ocr`. Εγκαταστήστε το με `pip install ocr-lib`. +- Μια θορυβώδη γερμανική σάρωση (`noisy_german_scan.tif`) που θέλετε να δοκιμάσετε. +- Μια βασική κατανόηση των συναρτήσεων Python (αν έχετε γράψει ποτέ ένα `def`, είστε εντάξει). + +> **Pro tip:** Αν χρησιμοποιείτε διαφορετικό OCR SDK (π.χ., Tesseract μέσω `pytesseract`), οι έννοιες παραμένουν ίδιες—απλώς προσαρμόστε τα ονόματα μεθόδων. + +## Επισκόπηση της Λύσης + +1. **Δημιουργήστε ένα στιγμιότυπο μηχανής OCR.** +2. **Ορίστε τη γλώσσα αναγνώρισης σε Γερμανικά.** +3. **Κατασκευάστε μια προσαρμοσμένη αλυσίδα προεπεξεργασίας** που περιλαμβάνει διόρθωση κλίσης, αποθορυβοποίηση, δυαδικοποίηση (Otsu) και τέντωμα αντίθεσης. +4. **Συνδέστε την αλυσίδα στη μηχανή** ώστε κάθε εικόνα να περνάει αυτόματα από αυτήν. +5. **Εκτελέστε το OCR** σε μια θορυβώδη γερμανική σάρωση. +6. **Εκτυπώστε το εξαγόμενο κείμενο** για να επαληθεύσετε το αποτέλεσμα. + +Παρακάτω διασπάμε κάθε βήμα, εξηγούμε **γιατί** είναι σημαντικό, και δείχνουμε τον ακριβή κώδικα που χρειάζεστε. + +![πώς να προεπεξεργαστείτε εικόνες για OCR παράδειγμα](image.png "πώς να προεπεξεργαστείτε εικόνες για OCR παράδειγμα") + +## Βήμα 1: Δημιουργία Στιγμιότυπου Μηχανής OCR + +Πρώτα απ' όλα—χωρίς μηχανή, δεν συμβαίνει τίποτα. Το αντικείμενο `OcrEngine` είναι το σημείο εισόδου που συντονίζει όλη τη μεταγενέστερη επεξεργασία. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Γιατί είναι σημαντικό:* Η αρχικοποίηση της μηχανής ρυθμίζει εσωτερικούς πόρους (όπως μοντέλα γλώσσας) και σας δίνει ένα καθαρό καμβά για να συνδέσετε μια προσαρμοσμένη αλυσίδα αργότερα. + +## Βήμα 2: Ορισμός Γλώσσας Αναγνώρισης σε Γερμανικά + +Η ακρίβεια του OCR εξαρτάται σε μεγάλο βαθμό από τη γλώσσα. Αναγγέλλοντας στη μηχανή ότι πρέπει να περιμένει Γερμανικά, ενεργοποιείτε το σωστό σύνολο χαρακτήρων και το μοντέλο γλώσσας. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Αν παραλείψετε αυτό το βήμα, η μηχανή μπορεί να προεπιλέξει τα Αγγλικά, παραγνωρίζοντας τα umlauts (ä, ö, ü) και το χαρακτήρα ß—συνηθισμένα προβλήματα σε γερμανικές σάρωσες. + +## Βήμα 3: Κατασκευή Προσαρμοσμένης Αλυσίδας Προεπεξεργασίας + +Αυτή είναι η καρδιά του **πώς να προεπεξεργαστείτε εικόνες για OCR**. Θα αλυσίδουμε τέσσερις μετασχηματισμούς: + +| Μετασχηματισμός | Τι κάνει | Γιατί βοηθά | +|------------------|----------|--------------| +| **Deskew** | Περιστρέφει την εικόνα πίσω σε οριζόντια (μέγιστο 5°) | Οι σάρωσες σπάνια είναι τέλεια ευθυγραμμισμένες· η διόρθωση κλίσης αφαιρεί την κλίση που μπερδεύει τη διαχωριστική λειτουργία χαρακτήρων. | +| **Denoise** | Μειώνει τυχαίες κηλίδες (ισχύς 0.7) | Ο θόρυβος δημιουργεί ψευδείς άκρες που η μηχανή OCR μπορεί να ερμηνεύσει ως χαρακτήρες. | +| **Binarize (Otsu)** | Μετατρέπει σε ασπρόμαυρο χρησιμοποιώντας τη μέθοδο Otsu | Μια καθαρή δυαδική εικόνα δίνει στην μηχανή έντονη αντίθεση μεταξύ προσκηνίου (κειμένου) και φόντου. | +| **Contrast Stretch** | Επεκτείνει το δυναμικό εύρος | Βελτιώνει την αναγνωσιμότητα αδύναμων γραμμών, ειδικά σε παλιά έγγραφα. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Πώς να Διορθώσετε την Κλίση Σαρωμένων Εγγράφων + +Η κλήση `deskew` παραπάνω είναι η συγκεκριμένη απάντηση στο **πώς να διορθώσετε την κλίση σαρωμένων εγγράφων**. Εσωτερικά εκτιμά τη κυρίαρχη γωνία γραμμής κειμένου μέσω μετασχηματισμού Hough και περιστρέφει την εικόνα πίσω. Αν τα έγγραφά σας είναι περιστραμμένα περισσότερο από 5°, αυξήστε το `max_angle`, αλλά προσέξτε τα τεχνητά σφάλματα υπερ‑περιστροφής. + +### Δυαδικοποίηση Εικόνας με Otsu + +Η γραμμή `binarize(method="otsu")` απαντά άμεσα στο ερώτημα **δυαδικοποιήστε εικόνα με otsu**. Ο αλγόριθμος του Otsu υπολογίζει ένα κατώφλι που ελαχιστοποιεί τη διακύμανση εντός κλάσεων, ιδανικό για έγγραφα με δισκοειδείς ιστογράμματα (σκοτεινό κείμενο vs. ανοιχτό φόντο). + +## Βήμα 4: Σύνδεση της Αλυσίδας στη Μηχανή + +Τώρα λέμε στη μηχανή OCR να εκτελεί κάθε εισερχόμενη εικόνα μέσω της αλυσίδας που μόλις δημιουργήσαμε. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Γιατί είναι σημαντικό:* Χωρίς την εγγραφή, η μηχανή θα επεξεργαστεί την ακατέργαστη σάρωση, αγνοώντας όλη την καθαριότητα που μόλις διαμορφώσαμε. Αυτό το βήμα εξασφαλίζει **πώς να βελτιώσετε την ακρίβεια του OCR** εφαρμόζοντας την ίδια προεπεξεργασία σταθερά. + +## Βήμα 5: Αναγνώριση Κειμένου από Θορυβώδη Γερμανική Σάρωση + +Ώρα να ενώσουμε τα πάντα. Τροφοδοτούμε τη μηχανή με μια θορυβώδη γερμανική εικόνα και αφήνουμε αυτήν να κάνει το σκληρό έργο. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Αν σας ενδιαφέρει η απόδοση, μπορείτε να μετρήσετε το χρόνο εκτέλεσης: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Βήμα 6: Εκτύπωση του Αναγνωρισμένου Κειμένου + +Τέλος, εκτυπώνουμε το εξαγόμενο string. Αυτή είναι η άμεση απάντηση στο **εξάγετε κείμενο από γερμανική εικόνα**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Αναμενόμενο Αποτέλεσμα + +Υποθέτοντας ότι η δείγμα σάρωση περιέχει την πρόταση «Die schnelle braune Füchsin springt über den faulen Hund.» θα πρέπει να δείτε κάτι παρόμοιο με: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Αν το αποτέλεσμα εξακολουθεί να περιέχει ακατανόητους χαρακτήρες, σκεφτείτε να ρυθμίσετε τη δύναμη `denoise` ή να αυξήσετε το `max_angle` για τη διόρθωση κλίσης. + +## Συχνές Παγίδες & Πώς να τις Αντιμετωπίσετε + +- **Λείπει το μοντέλο γλώσσας:** Η παράλειψη του `set_recognition_language(Language.GERMAN)` συχνά οδηγεί σε έλλειψη umlauts. Ελέγξτε ξανά την κλήση. +- **Υπερ‑αποθορυβοποίηση:** Μια ισχύς πάνω από 0.9 μπορεί να σβήσει λεπτές γραμμές, ειδικά σε παλαιά γραμματοσειρά. Κρατήστε το στο 0.5‑0.7 για τις περισσότερες περιπτώσεις. +- **Λανθασμένη μορφή αρχείου:** Κάποιες μηχανές OCR δυσκολεύονται με πολυσελίδες TIFF. Αν έχετε πολυσελιδικό έγγραφο, χωρίστε το σε μονοσέλιδα αρχεία πρώτα. +- **Σειρά αλυσίδας:** Η σειρά που φαίνεται (deskew → denoise → binarize → contrast) είναι σκόπιμη. Η δυαδικοποίηση πριν την αποθορυβοποίηση μπορεί να «κλειδώσει» τον θόρυβο· πάντα αποθορυβώστε πρώτα. + +## Επέκταση της Αλυσίδας (Τι Ακολουθεί;) + +Τώρα που έχετε μια σταθερή βάση, ίσως θέλετε να: + +- **Προσθέσετε ένα μορφολογικό άνοιγμα** για καθαρισμό μικρών σφαιριδίων (`.morph_open(kernel=3)`). +- **Ενσωματώσετε μοντέλο γλώσσας** για διόρθωση μετά την επεξεργασία (`ocr_engine.apply_spellcheck()`). +- **Παραλληλοποιήσετε την επεξεργασία παρτίδας** για μεγάλα σύνολα δεδομένων χρησιμοποιώντας `concurrent.futures`. + +Όλα αυτά είναι φυσικές επεκτάσεις που διατηρούν την κεντρική ιδέα του **πώς να προεπεξεργαστείτε εικόνες για OCR** ενώ ενισχύουν περαιτέρω το **πώς να βελτιώσετε την ακρίβεια του OCR**. + +## Συμπέρασμα + +Καλύψαμε το **πώς να προεπεξεργαστείτε εικόνες για OCR** από την αρχή μέχρι το τέλος: δημιουργία μηχανής, ορισμός γερμανικής γλώσσας, κατασκευή αλυσίδας που **δυαδικοποιεί εικόνα με Otsu**, **πώς να διορθώσετε την κλίση σαρωμένων εγγράφων**, και τελικά **εξάγετε κείμενο από γερμανική εικόνα** με μεγαλύτερη εμπιστοσύνη. Ακολουθώντας τα έξι βήματα παραπάνω θα δείτε μια αισθητή βελτίωση στην ποιότητα αναγνώρισης—χωρίς ατέλειωτες χειροκίνητες διορθώσεις. + +Δοκιμάστε το script με τις δικές σας σάρωσες, πειραματιστείτε με τις παραμέτρους, και αφήστε τα αποτελέσματα να μιλήσουν από μόνα τους. Έχετε ερωτήσεις για κάποια συγκεκριμένη ρύθμιση προεπεξεργασίας; Αφήστε ένα σχόλιο και θα εμβαθύνουμε μαζί. + +Καλό προγραμματισμό, και να είναι το OCR σας πάντα ακριβές! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή κειμένου από εικόνα C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Πώς να Ορίσετε Τιμή Κατωφλίου στην Αναγνώριση Εικόνας OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Πώς να Κάνετε OCR σε Εικόνα – Εκτέλεση OCR σε Εικόνα στην Αναγνώριση Εικόνας OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/greek/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..8e6919783 --- /dev/null +++ b/ocr/greek/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,322 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG εικόνας με Python – μάθετε πώς να εξάγετε κείμενο από εικόνα, + να τρέξετε ένα παράδειγμα OCR σε Python και ακόμη να διαβάζετε εύκολα αρχαίο ελληνικό + κείμενο. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: el +og_description: OCR PNG εικόνα σε Python εξηγείται. Αυτός ο οδηγός δείχνει πώς να + εξάγετε κείμενο από εικόνα, να τρέξετε ένα παράδειγμα OCR σε Python και να διαβάσετε + αρχαία ελληνικά με ευκολία. +og_title: OCR PNG Εικόνα σε Python – Πλήρης Οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR εικόνας PNG σε Python – Πλήρης οδηγός βήμα‑βήμα +url: /el/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image σε Python – Πλήρης Οδηγός Βήμα‑βήμα + +Έχετε ποτέ αναρωτηθεί πώς να **OCR PNG image** αρχεία απευθείας από ένα script Python; Ίσως έχετε έναν φάκελο γεμάτο σαρωμένα αρχαία χειρόγραφα και χρειάζεται να **extract text from image** αρχεία χωρίς να πληκτρολογείτε τα πάντα χειροκίνητα. Τα καλά νέα είναι ότι δεν χρειάζεστε διδακτορικό στην υπολογιστική όραση—απλώς μερικές γραμμές κώδικα και τη σωστή βιβλιοθήκη, και θα διαβάζετε αρχαία ελληνικά σε δευτερόλεπτα. + +Σε αυτό το tutorial θα περάσουμε από ένα **python OCR example** που αναγνωρίζει κείμενο από ένα PNG, ορίζει τη γλώσσα σε Ελληνικά πολυτονικά και εκτυπώνει το αποτέλεσμα. Στο τέλος θα ξέρετε ακριβώς πώς να **recognize image text**, να αντιμετωπίσετε κοινά προβλήματα και να προσαρμόσετε το script για άλλες γλώσσες ή μορφές εικόνας. + +## Τι Θα Μάθετε + +- Εγκατάσταση και ρύθμιση μιας βιβλιοθήκης Python OCR (pytesseract + Tesseract OCR) +- Δημιουργία ενός OCR engine instance και φόρτωση αρχείου PNG +- Ορισμός της γλώσσας αναγνώρισης σε Ελληνικά πολυτονικά ώστε να μπορείτε να **read ancient greek** +- Έξοδος του αναγνωρισμένου κειμένου και αντιμετώπιση τυπικών προβλημάτων +- Επέκταση του script για batch‑process πολλαπλά PNG ή αλλαγή σε άλλη γλώσσα + +### Προαπαιτούμενα + +| Απαίτηση | Γιατί είναι σημαντικό | +|----------|-----------------------| +| Python 3.8+ | Σύγχρονη σύνταξη και type hints | +| `pytesseract` package | Ελαφρύ wrapper γύρω από τη μηχανή Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Η πραγματική μηχανή που κάνει τη βαριά δουλειά | +| Greek language data (`grc.traineddata`) | Απαιτείται για **read ancient greek** σωστά | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Ο στόχος μας για την επίδειξη **ocr png image** | + +Μπορείτε να εγκαταστήσετε το τμήμα Python με: + +```bash +pip install pytesseract Pillow +``` + +Και σε Ubuntu/macOS θα προσθέσετε τη μηχανή: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Μην ξεχάσετε να κατεβάσετε τα Greek polytonic trained data: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Η διαδρομή μπορεί να διαφέρει· προσαρμόστε το `TESSDATA_PREFIX` αν χρειάζεται.)* + +--- + +## OCR PNG Image: Δημιουργία του Engine Instance + +Το πρώτο πράγμα που χρειαζόμαστε είναι ένα αντικείμενο που επικοινωνεί με το Tesseract. Στο `pytesseract` η μηχανή προσπελαύνεται μέσω συναρτήσεων επιπέδου module, αλλά για σαφήνεια θα το τυλίξουμε σε μια μικρή κλάση. Αυτό αντικατοπτρίζει την έννοια του “engine” που είδατε στο αρχικό snippet. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Γιατί να το τυλίξουμε;** +- Διατηρεί το δημόσιο API ίδιο με το snippet που ξεκινήσατε, κάνοντας τη μετανάστευση απρόσκοπτη. +- Επιτρέπει την προσθήκη logging ή error handling αργότερα χωρίς να επηρεάσουμε τη βασική ροή. +- Δείχνει καλή πρακτική OOP—κάτι που εκτιμούν οι senior developers. + +## Εξαγωγή Κειμένου από Εικόνα: Ορισμός Γλώσσας σε Ελληνικά Πολυτονικά + +Τώρα που έχουμε μια μηχανή, πρέπει να της πούμε ποια γλώσσα να περιμένει. Τα Ελληνικά πολυτονικά χρησιμοποιούν διακριτικά που δεν καλύπτονται από τα τυπικά δεδομένα “greek”, έτσι δείχνουμε στο Tesseract το αρχείο `grc` trainedfile. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Αν ποτέ θέλετε να **extract text from image** αρχεία σε άλλη γλώσσα, απλώς αντικαταστήστε το `"grc"` με `"eng"` για Αγγλικά, `"fra"` για Γαλλικά κ.λπ. Η ίδια γραμμή λειτουργεί για οποιαδήποτε γλώσσα έχετε εγκατεστημένη. + +## Αναγνώριση Κειμένου Εικόνας: Εκτέλεση OCR σε PNG + +Με τη γλώσσα ορισμένη, τροφοδοτούμε το PNG στη μηχανή. Το αρχικό παράδειγμα χρησιμοποίησε σκληρά κωδικοποιημένη διαδρομή· θα το κάνουμε λίγο πιο ευέλικτο χρησιμοποιώντας αντικείμενα `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Συμβουλές & Ακραίες Περιπτώσεις** + +- **File not found** – τυλίξτε την κλήση σε `try/except FileNotFoundError` για να δώσετε ένα φιλικό μήνυμα. +- **Low‑resolution PNG** – σκεφτείτε προεπεξεργασία (π.χ., αλλαγή μεγέθους, δυαδικοποίηση) με Pillow πριν το OCR. +- **Non‑Greek text** – το Tesseract θα προσπαθήσει ακόμη να το αποκωδικοποιήσει, αλλά η ακρίβεια μειώνεται δραστικά. Πάντα ταιριάξτε τη γλώσσα. + +## Έξοδος του Αναγνωρισμένου Κειμένου + +Τέλος, εκτυπώνουμε το αποτέλεσμα. Σε ένα πραγματικό πρότζεκτ μπορεί να γράψετε σε βάση δεδομένων, CSV, ή ακόμη να το περάσετε σε pipeline μετάφρασης. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Όταν εκτελέσετε το script σε σαφή σάρωση μιας αρχαίας ελληνικής επιγραφής, θα πρέπει να δείτε κάτι όπως: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Αν η έξοδος φαίνεται ακαταλαβίστικη, ελέγξτε ξανά ότι το αρχείο **greek.traineddata** βρίσκεται στο σωστό φάκελο και ότι το PNG δεν είναι πολύ θορυβώδες. + +## Πλήρες Παράδειγμα Εργασίας (Όλα τα Βήματα σε Ένα Script) + +Παρακάτω είναι το πλήρες, έτοιμο‑για‑εκτέλεση πρόγραμμα. Αποθηκεύστε το ως `ocr_greek.py` και εκτελέστε `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Αναμενόμενη έξοδος** (περιορισμένη για συντομία): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Αν δείτε τους σωστούς ελληνικούς χαρακτήρες, συγχαρητήρια—έχετε ολοκληρώσει με επιτυχία μια λειτουργία **ocr png image** σε Python! + +## Συχνές Ερωτήσεις & Pro Συμβουλές + +### Πώς βελτιώνω την ακρίβεια σε θορυβώδες PNG; + +- Μετατρέψτε την εικόνα σε κλίμακα του γκρι: `img = img.convert('L')` +- Εφαρμόστε δυαδικό κατώφλι: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Αυξήστε την ανάλυση με `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Αυτά τα βήματα συχνά μετατρέπουν έναν εφιάλτη **recognize image text** σε καθαρό αποτέλεσμα. + +### Μπορώ να επεξεργαστώ ολόκληρο φάκελο PNG; + +Απολύτως. Τυλίξτε την κλήση `recognize_image` σε ένα `for` loop πάνω από `Path.glob("*.png")`. Αποθηκεύστε κάθε αποτέλεσμα σε ένα dictionary ή γράψτε σε CSV για μεταγενέστερη ανάλυση. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Τι γίνεται αν χρειάζομαι να εξάγω μόνο αριθμούς; + +Περάστε μια προσαρμοσμένη συμβολοσειρά **config** στο `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Με αυτόν τον τρόπο μπορείτε να **extract text from image** αρχεία που περιέχουν πίνακες, σειριακούς αριθμούς ή χρονικές σφραγίδες. + +### Υπάρχει τρόπος να λάβετε βαθμούς εμπιστοσύνης; + +Ναι—χρησιμοποιήστε `pytesseract.image_to_data` που επιστρέφει ένα TSV με confidence ανά λέξη. Μπορείτε να φιλτράρετε τα tokens χαμηλής εμπιστοσύνης πριν συναρτήσετε το τελικό string. + +## Επέκταση του Tutorial + +Τώρα που έχετε κατακτήσει τα βασικά, σκεφτείτε να εξερευνήσετε τα παρακάτω συναφή θέματα: + +- **Batch OCR with multiprocessing** – επιταχύνετε μεγάλα corpora PNG. +- **Hybrid OCR + NLP pipelines** – αυτόματη μετάφραση του εξαγόμενου αρχαίου ελληνικού σε σύγχρονα Αγγλικά. +- **Alternative engines** – δοκιμάστε `easyocr` ή μεθόδους βασισμένες σε `opencv` για συγκεκριμένες περιπτώσεις. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, ή AWS Textract για serverless scaling. + +Κάθε ένα από αυτά βασίζεται στο κεντρικό **python ocr example** που καλύψαμε, έτσι θα νιώσετε άνετα να εμβαθύνετε περαιτέρω. + +## Συμπέρασμα + +Μετατρέψαμε ένα απλό snippet σε μια ισχυρή ροή εργασίας **ocr png image** σε Python. Δημιουργώντας ένα `OcrEngine`, ορίζοντας τη γλώσσα σε Ελληνικά πολυτονικά, τροφοδοτώντας ένα PNG και εκτυπώνοντας το αποτέλεσμα, τώρα ξέρετε πώς να **extract text from image** αρχεία, **recognize image text**, και ακόμη **read ancient greek**. + +## Τι Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/greek/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..7d467d382 --- /dev/null +++ b/ocr/greek/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-06 +description: Εκπαιδευτικό σε Python OCR που δείχνει πώς να αναγνωρίζετε κείμενο εικόνας, + να εκτελείτε OCR υψηλής ανάλυσης και να εξάγετε ισπανικό κείμενο χρησιμοποιώντας + OCR επιταχυμένο με GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: el +og_description: Μάθημα Python OCR που σας καθοδηγεί στη αναγνώριση κειμένου σε εικόνες, + OCR υψηλής ανάλυσης και εξαγωγή ισπανικού κειμένου με επιτάχυνση GPU. +og_title: Μάθημα OCR με Python – Αναγνώριση κειμένου με επιτάχυνση GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR Tutorial – Αναγνώριση κειμένου εικόνας με επιτάχυνση GPU +url: /el/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Αναγνώριση Κειμένου σε Εικόνα με Επιτάχυνση GPU + +Έχετε αναρωτηθεί ποτέ πώς να **αναγνωρίσετε κείμενο σε εικόνα** σε ένα script Python χωρίς να ξοδεύετε ώρες ρυθμίζοντας παραμέτρους; Δεν είστε ο μόνος. Σε αυτό το **python ocr tutorial** θα σας δείξουμε έναν καθαρό, ολοκληρωμένο τρόπο να εξάγετε ισπανικό κείμενο από μια εικόνα υψηλής ανάλυσης, και θα προσθέσουμε επιτάχυνση GPU ώστε η διαδικασία να τρέχει αστραπιαία. + +Σκεφτείτε το ως μια γρήγορη επίδειξη κατά τη διάρκεια του καφέ, που μπορείτε να επεκτείνετε σε μια παραγωγική γραμμή εργασίας αργότερα. Στο τέλος αυτού του οδηγού θα έχετε ένα εκτελέσιμο πρόγραμμα που εκτελεί **OCR υψηλής ανάλυσης**, αξιοποιεί μια GPU με υποστήριξη CUDA, και παράγει τους ακριβείς ισπανικούς χαρακτήρες που χρειάζεστε. + +## Τι Θα Μάθετε + +- Πώς να εγκαταστήσετε και να εισάγετε μια σύγχρονη βιβλιοθήκη OCR που υποστηρίζει επιτάχυνση GPU. +- Πώς να δημιουργήσετε μια παρουσία (instance) του μηχανήματος OCR και να το ρυθμίσετε να **αναγνωρίζει κείμενο σε εικόνα** στα Ισπανικά. +- Πώς να ενεργοποιήσετε **GPU επιταχυνόμενο OCR** για τεράστια κέρδη ταχύτητας σε αρχεία υψηλής ανάλυσης. +- Πώς να αντιμετωπίσετε ειδικές περιπτώσεις όπως η έλλειψη οδηγών CUDA ή η επιστροφή στην CPU. +- Συμβουλές για τη βελτίωση της ακρίβειας όταν χρειάζεται να **εξάγετε ισπανικό κείμενο** από θορυβώδεις σάρωση. + +### Προαπαιτούμενα + +- Python 3.9+ (ο κώδικας λειτουργεί επίσης σε 3.10 και νεότερες εκδόσεις). +- Μια GPU συμβατή με CUDA (προαιρετική αλλά ιδιαίτερα συνιστώμενη). +- Βασική εξοικείωση με pip και εικονικά περιβάλλοντα. + +Αν λείπει κάποιο από αυτά, το tutorial λειτουργεί ακόμη—απλώς παραλείψτε το βήμα GPU και η βιβλιοθήκη θα επιστρέψει αυτόματα στην CPU. + +--- + +## Python OCR Tutorial: Εγκατάσταση των Απαιτούμενων Πακέτων + +Πρώτα απ' όλα, χρειαζόμαστε μια αξιόπιστη μηχανή OCR. Για αυτό το tutorial θα χρησιμοποιήσουμε το ανοιχτού κώδικα πακέτο **`easyocr`**, το οποίο περιλαμβάνει ενσωματωμένη υποστήριξη GPU όταν εντοπιστεί συμβατή συσκευή. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Αν έχετε ήδη εγκατεστημένο το PyTorch, βεβαιωθείτε ότι ταιριάζει με την έκδοση CUDA σας (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Οι ασυμφωνίες εκδόσεων είναι κοινή πηγή σφαλμάτων “GPU not found”. + +--- + +## Βήμα 1: Δημιουργία μιας Παρουσίας (Instance) του Μηχανήματος OCR + +Τώρα ξεκινάμε τη μηχανή. Το EasyOCR ονομάζει την κύρια κλάση του `Reader`. Ο κατασκευαστής δέχεται μια λίστα κωδικών γλώσσας· θα περάσουμε `"es"` για Ισπανικά. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Γιατί είναι σημαντικό:* Με την προκήρυξη της γλώσσας εκ των προτέρων, η μηχανή φορτώνει μόνο τα απαραίτητα βάρη νευρωνικού δικτύου, εξοικονομώντας μνήμη και επιταχύνοντας την εκτίμηση—ιδιαίτερα χρήσιμο όταν ασχολείστε με **OCR υψηλής ανάλυσης** αργότερα. + +--- + +## Βήμα 2: Προετοιμασία μιας Εικόνας Υψηλής Ανάλυσης + +Οι εικόνες υψηλής ανάλυσης παρέχουν στο μοντέλο περισσότερα pixel για επεξεργασία, κάτι που συνήθως μεταφράζεται σε καλύτερη αναγνώριση χαρακτήρων. Ας υποθέσουμε ότι έχετε ένα αρχείο με όνομα `high_res_spanish.png` σε φάκελο που ονομάζεται `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Αν δεν έχετε διαθέσιμο δείγμα υψηλής ανάλυσης, μπορείτε να κατεβάσετε ένα δωρεάν από το Unsplash ή να δημιουργήσετε μια συνθετική εικόνα με το Pillow. Το κλειδί είναι να διατηρήσετε το DPI πάνω από 300 για τα καλύτερα αποτελέσματα. + +--- + +## Βήμα 3: Ενεργοποίηση Επιτάχυνσης GPU (Προαιρετικό αλλά Συνιστώμενο) + +Το EasyOCR προσπαθεί ήδη να χρησιμοποιήσει την GPU όταν ορίσετε `gpu=True`. Ωστόσο, είναι καλή πρακτική να επαληθεύσετε ότι η συσκευή χρησιμοποιείται πραγματικά, ειδικά σε συστήματα με πολλαπλές GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Γιατί να το ελέγξετε;* Αν το script επιστρέψει σιωπηλά στην CPU, μπορεί να αναρωτηθείτε γιατί μια λειτουργία 5 δευτερολέπτων ξαφνικά διαρκεί 30 δευτερόλεπτα. Αυτός ο μικρός έλεγχος κάνει τη συμπεριφορά διαφανή και διατηρεί την **GPU επιταχυνόμενη OCR** γραμμή εργασίας προβλέψιμη. + +--- + +## Βήμα 4: Εκτέλεση OCR Υψηλής Ανάλυσης και Αναγνώριση Κειμένου σε Εικόνα + +Τώρα το διασκεδαστικό μέρος—να διαβάσουμε πραγματικά το κείμενο. Η μέθοδος `readtext` του EasyOCR επιστρέφει μια λίστα από πλειάδες που περιέχουν το πλαίσιο, τη αναγνωρισμένη συμβολοσειρά και ένα σκορ εμπιστοσύνης. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Αν χρειάζεστε τη ακατέργαστη συμβολοσειρά χωρίς συντεταγμένες, ορίστε `detail=0`. Για τις περισσότερες περιπτώσεις χρήσης **αναγνώρισης κειμένου σε εικόνα**, η προεπιλογή (`detail=1`) σας παρέχει αρκετό πλαίσιο για επεξεργασία αργότερα. + +--- + +## Βήμα 5: Εξαγωγή Ισπανικού Κειμένου και Καθαρισμός του Αποτελέσματος + +Επειδή ζητήσαμε από το EasyOCR Ισπανικά, οι επιστρεφόμενες συμβολοσειρές είναι ήδη σε αυτή τη γλώσσα. Παρόλα αυτά, ίσως θέλετε να τις συνενώσετε, να αφαιρέσετε κενά ή να φιλτράρετε ανιχνεύσεις χαμηλής εμπιστοσύνης. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Τι γίνεται αν η εμπιστοσύνη είναι χαμηλή;** Μπορείτε είτε να μειώσετε το όριο (κινδυνεύοντας θόρυβο) είτε να προεπεξεργαστείτε την εικόνα (αυξήστε την αντίθεση, δυαδικοποιήστε ή διορθώστε την κλίση). Αυτά τα κόλπα είναι κοινά όταν αντιμετωπίζετε **OCR υψηλής ανάλυσης** σε σαρωμένα έγγραφα. + +--- + +## Βήμα 6: Διαχείριση Ειδικών Περιπτώσεων και Ρυθμίσεις Απόδοσης + +Ακόμη και τα καλύτερα εκπαιδευμένα μοντέλα αντιμετωπίζουν προβλήματα σε ορισμένα σενάρια. Παρακάτω υπάρχουν μερικές γρήγορες διορθώσεις που μπορείτε να επικολλήσετε στο script. + +### 6.1 Εναλλακτική Λύση όταν δεν υπάρχει GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Μείωση Δειγματοληψίας Πολύ Μεγάλων Εικόνων + +Αν η εικόνα σας είναι μεγαλύτερη από 4000 × 4000 px, μπορεί να εξαντλήσετε τη μνήμη GPU. Μειώστε τη δειγματοληψία αναλογικά διατηρώντας το DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Αυτά τα αποσπάσματα διατηρούν το script ανθεκτικό, είτε τρέχετε σε workstation είτε σε ένα μέτριο laptop. + +--- + +## Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα, εδώ είναι το πλήρες script που μπορείτε να αντιγράψετε‑επικολλήσετε και να τρέξετε αμέσως: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Αναμενόμενο αποτέλεσμα (παράδειγμα):** + + + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε σε πρόσθετα χαρακτηριστικά API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή Κειμένου από Εικόνα με Aspose OCR – Οδηγός Βήμα‑Βήμα](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Πώς να Κάνετε OCR Κειμένου σε Εικόνα με Γλώσσα Χρησιμοποιώντας Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Πώς να Αναγνωρίσετε Ορθογώνια Σελίδας για Αναγνώριση Κειμένου OCR στο Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/greek/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..b7e6a22e9 --- /dev/null +++ b/ocr/greek/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-06 +description: Αναγνώριση κειμένου από εικόνα χρησιμοποιώντας τη μηχανή OCR της Python. + Μάθετε πώς να ρυθμίσετε τη μηχανή OCR στην Python και να εξάγετε κείμενο από εικόνα + με επεξεργασία στο σύννεφο σε λίγα λεπτά. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: el +og_description: Αναγνώριση κειμένου από εικόνα με τη μηχανή OCR της Python. Αυτός + ο οδηγός δείχνει πώς να ρυθμίσετε τη μηχανή OCR στην Python και να εξάγετε κείμενο + από εικόνα αποδοτικά. +og_title: Αναγνώριση κειμένου από εικόνα σε Python – Πλήρης οδηγός εγκατάστασης +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Αναγνώριση κειμένου από εικόνα σε Python – Πλήρης οδηγός εγκατάστασης μηχανής + OCR +url: /el/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# αναγνώριση κειμένου από εικόνα σε Python – Πλήρης Οδηγός Ρύθμισης + +Έχετε αναρωτηθεί ποτέ πώς να **recognize text from image** χρησιμοποιώντας μόνο μερικές γραμμές Python; Δεν είστε μόνοι. Είτε δημιουργείτε έναν σαρωτή αποδείξεων, έναν ψηφιοποιητή εγγράφων, είτε ένα απλό χόμπι έργο, η δυνατότητα εξαγωγής κειμένου από εικόνα είναι μια δεξιότητα που αποδίδει γρήγορα. + +Σε αυτό το tutorial θα περάσουμε από όλη τη διαδικασία — ξεκινώντας από τη ρύθμιση **configure OCR engine python**, προχωρώντας στην πιστοποίηση στο cloud, και τελικά δείχνοντας πώς να **extract text from image** με αξιόπιστο αποτέλεσμα. Καμία μαγεία, μόνο σαφή βήματα που μπορείτε να αντιγράψετε‑επικολλήσετε και να τρέξετε σήμερα. + +## Τι Θα Μάθετε + +- Πώς να εγκαταστήσετε και να εισάγετε τη απαιτούμενη βιβλιοθήκη OCR. +- Οι ακριβείς εντολές για **configure OCR engine python** για επεξεργασία στο cloud. +- Ένα πλήρες, εκτελέσιμο script που **recognize text from image** και εκτυπώνει το αποτέλεσμα. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων όπως λείπουν κλειδιά API ή μη υποστηριζόμενες μορφές εικόνας. +- Ιδέες επόμενου επιπέδου όπως η επεξεργασία παρτίδων και η τοπική εναλλακτική. + +### Προαπαιτούμενα + +- Python 3.8+ εγκατεστημένο στον υπολογιστή σας. +- Σύνδεση στο internet (το παράδειγμα χρησιμοποιεί υπηρεσία OCR βασισμένη στο cloud). +- Ένα έγκυρο κλειδί API από τον πάροχο OCR (θα δείτε πού να το ενσωματώσετε). + +Αν τα έχετε, ας βουτήξουμε — χωρίς περιττές πληροφορίες, μόνο ένας πρακτικός οδηγός που λειτουργεί. + +--- + +## Βήμα 1: Εγκατάσταση της Βιβλιοθήκης OCR και Εισαγωγή της + +Πριν μπορέσετε να **configure OCR engine python**, χρειάζεστε τη βιβλιοθήκη που επικοινωνεί με την υπηρεσία cloud. Στο παράδειγμά μας θα χρησιμοποιήσουμε ένα φανταστικό αλλά αντιπροσωπευτικό πακέτο που ονομάζεται `ocrcloud`. Αντικαταστήστε το με το πραγματικό πακέτο που χρησιμοποιείτε (π.χ., `easyocr`, `google-cloud-vision`, κλπ.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Γιατί είναι σημαντικό:** Η εισαγωγή της κλάσης σας δίνει πρόσβαση σε μεθόδους όπως `use_cloud()` και `set_api_key()`. Χωρίς την εισαγωγή, το υπόλοιπο του script θα προκαλέσει `NameError`. + +*Pro tip:* Καθορίστε την έκδοση στο `requirements.txt` (`ocrcloud==2.1.0`) για να αποφύγετε απρόσμενες αλλαγές που σπάζουν τη λειτουργία αργότερα. + +--- + +## Βήμα 2: Δημιουργία και **configure OCR engine python** για Λειτουργία Cloud + +Τώρα πραγματικά **configure OCR engine python**. Η μηχανή ξεκινά σε τοπική λειτουργία από προεπιλογή· η εναλλαγή σε λειτουργία cloud σας επιτρέπει να μεταφέρετε την βαριά ανάλυση εικόνας σε ισχυρούς διακομιστές. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Εξήγηση:** +- `OcrEngine()` δημιουργεί ένα νέο αντικείμενο μηχανής — σκεφτείτε το ως το κενό καμβά σας. +- `use_cloud(True)` ενεργοποιεί έναν διακόπτη, λέγοντας στη μηχανή να στέλνει εικόνες μέσω HTTPS αντί να τις επεξεργάζεται τοπικά. Αυτό είναι κρίσιμο για υψηλής ακρίβειας αποτελέσματα σε σύνθετες γραμματοσειρές ή φωτογραφίες χαμηλής ανάλυσης. + +--- + +## Βήμα 3: Πιστοποίηση με το Κλειδί API του Cloud σας + +Οι περισσότερες υπηρεσίες OCR στο cloud απαιτούν κλειδί API. Αυτό το βήμα δείχνει πώς να ενσωματώσετε με ασφάλεια το διαπιστευτήριο. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Σημείωση ασφαλείας:** Ποτέ μην κωδικοποιείτε το κλειδί σε δημόσιο αποθετήριο. Σε παραγωγή θα το αντλήσετε από μια μεταβλητή περιβάλλοντος: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Βήμα 4: **recognize text from image** – Αποστολή Απομακρυσμένης Εικόνας για Επεξεργασία + +Με τη μηχανή ρυθμισμένη, μπορούμε τελικά να **recognize text from image**. Η μέθοδος `recognize_image()` δέχεται μια διαδρομή ή URL και επιστρέφει ένα αντικείμενο που περιέχει το εξαγόμενο κείμενο. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Τι συμβαίνει στο παρασκήνιο;** +Τα bytes της εικόνας ανεβαίνουν στο endpoint του παρόχου, επεξεργάζονται από ένα μοντέλο deep‑learning, και το αποτέλεσμα σε απλό κείμενο επιστρέφεται. Αν η εικόνα είναι μεγάλη, η υπηρεσία μπορεί αυτόματα να μειώσει την ανάλυση για να επιταχύνει τη δουλειά. + +--- + +## Βήμα 5: Εξαγωγή του Αποτελέσματος **extract text from image** + +Τώρα που η υπηρεσία OCR έχει ολοκληρώσει τη δουλειά της, απλώς εκτυπώνουμε το κείμενο. Σε πραγματικές εφαρμογές μπορεί να το αποθηκεύσετε σε βάση δεδομένων ή να το περάσετε σε άλλη λειτουργία. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Αναμενόμενο αποτέλεσμα:** (παράδειγμα) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Αν το αποτέλεσμα φαίνεται χαοτικό, ελέγξτε ξανά ότι η εικόνα είναι καθαρή και ότι έχετε επιλέξει το σωστό μοντέλο γλώσσας (πολλές υπηρεσίες επιτρέπουν να ορίσετε `engine.set_language("en")`). + +--- + +## Διαχείριση Ακραίων Περιπτώσεων & Κοινών Προβλημάτων + +### 1. Λείπει ή Μη Έγκυρο Κλειδί API +Αν δείτε σφάλμα πιστοποίησης, βεβαιωθείτε ότι: +- Το κλειδί είναι ενεργό και δεν έχει λήξει. +- Αναγνώνεται σωστά από το περιβάλλον. +- Το δίκτυό σας επιτρέπει εξερχόμενη κίνηση HTTPS. + +### 2. Μη Υποστηριζόμενες Μορφές Εικόνας +Οι περισσότερες API OCR δέχονται JPEG, PNG και PDF. Η προσπάθεια χρήσης BMP ή TIFF μπορεί να προκαλέσει απάντηση “format not supported”. Μετατρέψτε με Pillow αν χρειάζεται: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Όρια Ρυθμού +Οι υπηρεσίες cloud συχνά περιορίζουν τα αιτήματα ανά λεπτό. Αν φτάσετε το όριο, εφαρμόστε εκθετική καθυστέρηση (back‑off): + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Εναλλακτική σε Τοπικό OCR +Αν το cloud είναι εκτός λειτουργίας, μπορείτε να επιστρέψετε: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Η ύπαρξη εναλλακτικής κρατά την εφαρμογή σας ανθεκτική. + +--- + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας όλα, εδώ είναι ένα script που μπορείτε να τρέξετε αμέσως (απλώς αντικαταστήστε τις τιμές placeholder). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Τρέξτε το:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Θα πρέπει να δείτε το εξαγόμενο κείμενο να εκτυπώνεται στην κονσόλα, επιβεβαιώνοντας ότι έχετε επιτυχώς **recognize text from image** και **extract text from image** χρησιμοποιώντας μια σωστά **configure OCR engine python** ροή εργασίας. + +--- + +## Συμπέρασμα + +Μόλις περάσαμε από μια πλήρη, end‑to‑end διαδικασία που σας επιτρέπει να **recognize text from image** σε Python, από την εγκατάσταση της βιβλιοθήκης μέχρι την πιστοποίηση μιας υπηρεσίας cloud και τελικά **extract text from image** με μία κλήση συνάρτησης. Με το **configure OCR engine python** σωστά, κερδίζετε τόσο ευελιξία (cloud vs. local) όσο και αξιοπιστία (σωστή διαχείριση σφαλμάτων). + +Τι ακολουθεί; Δοκιμάστε επεξεργασία παρτίδων φακέλου αποδείξεων, προσθέστε ανίχνευση γλώσσας, ή πειραματιστείτε με PDFs ως είσοδο. Ο ουρανός είναι το όριο μόλις κυριαρχήσετε τα βασικά. + +Καλό κώδικα, και μη διστάσετε να αφήσετε ερωτήσεις στα σχόλια — τίποτα δεν ξεπερνά τη μάθηση μαζί! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετικές θεματικές που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή Κειμένου από Εικόνα με Aspose OCR – Οδηγός Βήμα‑Βήμα](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Εξαγωγή Κειμένου από Εικόνα – Αναγνώριση Γραμμής με Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Πώς να Εξάγετε Κείμενο από Εικόνα Προετοιμάζοντας Ορθογώνια στο OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/greek/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..fcd60eff1 --- /dev/null +++ b/ocr/greek/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Εκτελέστε OCR σε εικόνα χρησιμοποιώντας Python και δείτε τις βαθμολογίες + εμπιστοσύνης. Μάθετε πώς να φιλτράρετε λέξεις χαμηλής εμπιστοσύνης, να ορίζετε όρια + και να αντιμετωπίζετε ειδικές περιπτώσεις. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: el +og_description: Εκτελέστε OCR σε εικόνα με Python, ελέγξτε τα επίπεδα εμπιστοσύνης + και φιλτράρετε τις λέξεις χαμηλής εμπιστοσύνης. Αυτό το σεμινάριο σας καθοδηγεί + βήμα-βήμα μέσα από ένα πλήρες, εκτελέσιμο παράδειγμα. +og_title: Εκτελέστε OCR σε εικόνα με Python – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Εκτελέστε OCR σε εικόνα με Python – Πλήρης οδηγός βήμα‑βήμα +url: /el/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εκτέλεση OCR σε Εικόνα με Python – Πλήρης Οδηγός Βήμα‑βήμα + +Κάποτε χρειάστηκε να **εκτελέσετε OCR σε εικόνα** αλλά δεν ήξερες πώς να εξάγεις αξιόπιστο κείμενο; Δεν είσαι μόνος σου—πολλοί προγραμματιστές αντιμετωπίζουν το ίδιο πρόβλημα όταν οι εξαγόμενες λέξεις φαίνονται ασαφείς και η βαθμολογία εμπιστοσύνης είναι ακατανόητη. + +Σε αυτόν τον οδηγό θα βουτήξουμε κατευθείαν σε μια λειτουργική λύση: θα δεις πώς να εκτελέσεις OCR σε εικόνα, να διαβάσεις τη συνολική εμπιστοσύνη και να εντοπίσεις τυχόν λέξεις χαμηλής εμπιστοσύνης που ίσως χρειάζονται χειροκίνητη επανεξέταση. Στο τέλος θα έχεις ένα επαναχρησιμοποιήσιμο script, θα καταλάβεις γιατί κάθε γραμμή είναι σημαντική και θα ξέρεις πώς να ρυθμίσεις το όριο εμπιστοσύνης για τα δικά σου έργα. + +## Τι Καλύπτει Αυτό το Tutorial + +Θα περάσουμε από όλη τη ροή εργασίας—από τη φόρτωση μιας εικόνας μέχρι την εκτύπωση μιας τακτοποιημένης αναφοράς λέξεων που έπεσαν κάτω από το όριο 80 % εμπιστοσύνης. Καθ' όλη τη διάρκεια θα συζητήσουμε: + +* Επιλογή αξιόπιστης μηχανής OCR (θα χρησιμοποιήσουμε **EasyOCR**, μια δημοφιλής βιβλιοθήκη OCR για Python) +* Ερμηνεία του χαρακτηριστικού `confidence` που επιστρέφει κάθε αποτέλεσμα OCR +* Φιλτράρισμα λέξεων με προσαρμοσμένο **όριο εμπιστοσύνης OCR** +* Επέκταση του script για επεξεργασία παρτίδας ή εναλλακτικές μηχανές όπως **pytesseract** + +Δεν απαιτείται προηγούμενη εμπειρία OCR, μόνο βασική εξοικείωση με την Python και ένα λειτουργικό περιβάλλον (συνιστάται Python 3.9+). + +Έτοιμος/η να μετατρέψεις θολές λήψεις οθόνης σε καθαρό, αναζητήσιμο κείμενο; Ας ξεκινήσουμε. + +--- + +## ## Πώς να Εκτελέσετε OCR σε Εικόνα με Python + +Η καρδιά του tutorial είναι ένα τρι‑βήμα snippet που αντικατοπτρίζει τον κώδικα που είδες ήδη. Παρακάτω θα αναλύσουμε κάθε γραμμή, θα εξηγήσουμε το «γιατί» και θα σου δώσουμε ένα πλήρες, έτοιμο για αντιγραφή‑επικόλληση script. + +### Βήμα 1: Εγκατάσταση και Εισαγωγή της Μηχανής OCR + +Πρώτα, βεβαιώσου ότι η βιβλιοθήκη OCR είναι διαθέσιμη. **EasyOCR** λειτουργεί αμέσως για πολλές γλώσσες και παρέχει βαθμολογία εμπιστοσύνης ανά λέξη. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Γιατί EasyOCR;* Συμπεριλαμβάνει ένα μοντέλο deep‑learning που έχει εκπαιδευτεί σε ποικίλα σύνολα δεδομένων, οπότε συνήθως λαμβάνεις υψηλότερες τιμές εμπιστοσύνης από την παλαιότερη μηχανή Tesseract, ειδικά σε εικόνες μεικτής ποιότητας. + +> **Pro tip:** Αν εργάζεσαι σε περιορισμένο περιβάλλον (π.χ. μικρό Docker container), το `pytesseract` μπορεί να είναι ελαφρύτερο, αλλά θα χάσεις μέρος της σύγχρονης ακρίβειας που προσφέρει το EasyOCR. + +### Βήμα 2: Εκτέλεση OCR στην Εικόνα + +Τώρα εκτελούμε πραγματικά **OCR σε εικόνα**. Η μέθοδος `recognize_image` από το αρχικό παράδειγμα αντικαθίσταται με την κλήση `readtext` του EasyOCR, η οποία επιστρέφει μια λίστα από πλειάδες `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Κάθε καταχώρηση στο `ocr_results` έχει την εξής μορφή: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Το τρίτο στοιχείο (`0.92` στο παράδειγμα) είναι η βαθμολογία εμπιστοσύνης, η οποία κυμαίνεται από 0 ως 1. + +### Βήμα 3: Σύνοψη Συνολικής Εμπιστοσύνης + +Σε αντίθεση με το προηγούμενο snippet που εκτύπωνε ένα μόνο χαρακτηριστικό `confidence`, το EasyOCR δίνει εμπιστοσύνη ανά λέξη. Για να πάρουμε μια γενική εικόνα, θα υπολογίσουμε τον μέσο όρο τους: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Γιατί ο μέσος όρος;* Σου δίνει έναν γρήγορο έλεγχο υγείας—αν η συνολική εμπιστοσύνη είναι κάτω από, π.χ., 70 %, πιθανότατα χρειάζεται να βελτιώσεις την εικόνα (καλύτερο φωτισμό, προεπεξεργασία κλπ.). + +### Βήμα 4: Λίστα Λέξεων Χαμηλής Εμπιστοσύνης + +Τώρα έρχεται το τμήμα που απαντά άμεσα στην απαίτηση «λίστα λέξεων των οποίων η εμπιστοσύνη είναι κάτω από το επιθυμητό όριο». Θα ορίσουμε ένα **όριο εμπιστοσύνης OCR** στο 0.80 (80 %) από προεπιλογή, αλλά μπορείς να το προσαρμόσεις. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Ο βρόχος εκτυπώνει κάθε λέξη που δεν πέρασε το όριο, μαζί με το ποσοστό εμπιστοσύνης της. Αυτό είναι το ακριβές ισοδύναμο του αρχικού βρόχου `for recognized_word in recognition_result.words`, αλλά τώρα λειτουργεί με τη μορφή εξόδου του EasyOCR. + +--- + +## ## Κατανόηση Βαθμών Εμπιστοσύνης OCR + +Η εμπιστοσύνη δεν είναι ένας μαγικός αριθμός· είναι η εκτίμηση του μοντέλου για το πόσο σίγουρο είναι σχετικά με μια συγκεκριμένη μεταγραφή. Λάβε υπόψη τα εξής: + +| Κατάσταση | Τυπική Εμπιστοσύνη | Τι να Κάνεις | +|-----------|-------------------|--------------| +| Καθαρή, υψηλής ανάλυσης σάρωση | 0.95 – 1.00 | Δεν απαιτείται επιπλέον εργασία | +| Ελαφριά θολότητα ή άνισος φωτισμός | 0.80 – 0.94 | Σκέψου ελαφριά προεπεξεργασία (αύξηση αντίθεσης) | +| Πολύ θόρυβος, κείμενο με κλίση | < 0.70 | Εφάρμοσε προεπεξεργασία εικόνας (απλοποίηση, αποθόρυβο) ή άλλαξε μηχανή OCR | + +> **Προσοχή:** Ορισμένες γλώσσες (π.χ. καλλιγραφική γραφή) παράγουν φυσικά χαμηλότερες βαθμολογίες. Ρύθμισε το όριο ανάλογα. + +### Ακραίες Περιπτώσεις & Παραλλαγές + +1. **Επεξεργασία Παρτίδας** – Αν χρειάζεται να **εκτελέσετε OCR σε εικόνα** σε μεγάλες ποσότητες, τυλίξτε τη λογική σε βρόχο που διατρέχει έναν φάκελο. +2. **Πολλαπλές Γλώσσες** – Περνάτε μια λίστα όπως `['en', 'fr']` στο `easyocr.Reader` και η μηχανή θα εντοπίσει και τις δύο. +3. **Εναλλακτικές Μηχανές** – Θέλετε να δοκιμάσετε **pytesseract**; Αντικαταστήστε το τμήμα reader με: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Θα χρειαστεί να συγκεντρώσετε τις εμπιστοσύνες ανά χαρακτήρα σε επίπεδο λέξης—λίγο πιο πολύπλοκο, αλλά εφικτό. + +4. **Τεχνάσματα Προ‑επεξεργασίας** – Η εφαρμογή φίλτρων OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) μπορεί να αυξήσει την εμπιστοσύνη για θορυβώδεις σάρωσες. + +--- + +## ## Πλήρες, Έτοιμο‑για‑Εκτέλεση Script + +Παρακάτω είναι το ολοκληρωμένο αρχείο Python που μπορείς να προσθέσεις στο πρότζεκτ σου. Αποθήκευσε το ως `ocr_report.py` και τρέξε `python ocr_report.py`. Βεβαιώσου ότι η διαδρομή της εικόνας δείχνει σε πραγματικό αρχείο. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Αναμενόμενη έξοδος** (τα νούμερα θα διαφέρουν): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Αν κάθε λέξη ξεπεράσει το όριο 80 % θα δεις το φιλικό μήνυμα «All words meet the confidence threshold.» αντί για τη λίστα χαμηλής εμπιστοσύνης. + +--- + +## ## Συχνές Ερωτήσεις (FAQ) + +**Ε: Λειτουργεί αυτό με PDF;** +Α: Όχι άμεσα. Μετέτρεψε κάθε σελίδα PDF σε εικόνα πρώτα (π.χ. με `pdf2image`) και μετά δώσε το PNG/JPEG στο script. + +**Ε: Οι αριθμοί εμπιστοσύνης μου είναι όλοι χαμηλοί—τι μπορώ να κάνω;** +Α: Δοκίμασε προεπεξεργασία εικόνας: αύξησε την αντίθεση, αφαίρεσε τον θόρυβο ή περιστρέψτε την εικόνα ώστε να είναι οριζόντια. Το EasyOCR δέχεται επίσης παράμετρο `contrast_ths` που μπορείς να ρυθμίσεις. + +**Ε: Μπορώ να εξάγω τα αποτελέσματα σε CSV;** +Α: Φυσικά. Μετά τον βρόχο χαμηλής εμπιστοσύνης, γράψε το `ocr_results` σε έναν `csv.DictWriter` όπου κάθε γραμμή περιέχει `text`, `confidence` και συντεταγμένες του bounding‑box. + +**Ε: Υπάρχει έκδοση με επιτάχυνση GPU;** +Α: Το EasyOCR χρησιμοποιεί αυτόματα CUDA αν υπάρχει συμβατό GPU και εγκατεστημένο PyTorch. Επαλήθευσε με `torch.cuda.is_available()` πριν τρέξεις το script. + +--- + +## Συμπέρασμα + +Μόλις **εκτελέσαμε OCR σε εικόνα** χρησιμοποιώντας Python, εξετάσαμε τη συνολική εμπιστοσύνη και απομονώσαμε τυχόν λέξεις χαμηλής εμπιστοσύνης που χρειάζονται χειροκίνητη επανεξέταση. + +## Τι Θα Πρέπει Να Μάθεις Στη Σύντομη Μελλοντική Σου + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσεις επιπλέον δυνατότητες API και να εξερευνήσεις εναλλακτικές προσεγγίσεις στα δικά σου έργα. + +- [Πώς να Ορίσετε Τιμή Κατωφλίου στην Αναγνώριση OCR Εικόνας](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Πώς να Χρησιμοποιήσετε το Aspose OCR για Αποτέλεσμα JSON στην Αναγνώριση Εικόνας](/ocr/english/net/text-recognition/get-result-as-json/) +- [Εξαγωγή Κειμένου από Εικόνα – Βελτιστοποίηση OCR με Aspose.OCR για .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/hindi/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..f48ca6a79 --- /dev/null +++ b/ocr/hindi/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR के साथ मिनटों में छवि से टेक्स्ट निकालें। बहुभाषी इमेज OCR, + स्वचालित भाषा पहचान OCR, और सटीक OCR टेक्स्ट निकालने के तरीके खोजें। +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: hi +og_description: Python OCR के साथ जल्दी से छवि से टेक्स्ट निकालें। बहुभाषी इमेज OCR, + ऑटो‑डिटेक्ट लैंग्वेज OCR, और चरण‑दर‑चरण OCR टेक्स्ट निकालने का तरीका सीखें। +og_title: Python OCR का उपयोग करके छवि से टेक्स्ट निकालें – पूर्ण गाइड +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Python OCR का उपयोग करके छवि से टेक्स्ट निकालें – पूर्ण गाइड +url: /hi/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेज से टेक्स्ट निकालें Python OCR का उपयोग करके – पूर्ण गाइड + +क्या आपको कभी **इमेज से टेक्स्ट निकालना** पड़ा है लेकिन यह नहीं पता था कि कौन‑सी लाइब्रेरी कई भाषाओं को स्वचालित रूप से संभाल सकती है? आप अकेले नहीं हैं—डेवलपर्स लगातार *how to extract OCR text* पूछते रहते हैं जब वे अंतरराष्ट्रीय दस्तावेज़, रसीदें या स्कैन किए हुए फ़्लायरों के साथ काम करते हैं। इस ट्यूटोरियल में हम एक व्यावहारिक Python उदाहरण के माध्यम से दिखाएंगे कि कैसे इमेज से टेक्स्ट निकाला जाए और साथ‑साथ **भाषा का पता** भी लगाया जाए, जिससे बहु‑भाषी इमेज OCR बहुत आसान हो जाता है। + +हम सब कुछ कवर करेंगे: OCR पैकेज को इंस्टॉल करना, **auto detect language OCR** को सक्षम करना, सैंपल चित्र पर इंजन चलाना, और अंत में पता लगी भाषा और निकाले गए स्ट्रिंग को प्रिंट करना। अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं, चाहे आप ट्रांसलेशन पाइपलाइन बना रहे हों या डेटा‑इंगेस्ट्शन सर्विस। + +## इमेज से टेक्स्ट निकालें – पर्यावरण सेट‑अप + +कोड में डुबकी लगाने से पहले सुनिश्चित करें कि आपका वर्कस्टेशन इन न्यूनतम आवश्यकताओं को पूरा करता है: + +- Python 3.8 या नया (लाइब्रेरी टाइप हिंट्स का उपयोग करती है जो पुराने संस्करणों में अनदेखा हो जाते हैं) +- `pip` पैकेज मैनेजमेंट के लिए +- एक इमेज फ़ाइल जिसमें कम से कम दो अलग‑अलग भाषाओं में टेक्स्ट हो (जैसे, English + Spanish) + +आपको उस OCR लाइब्रेरी की भी आवश्यकता होगी जो इस डेमो को चलाती है। इस गाइड के लिए हम काल्पनिक `ocr` पैकेज का उपयोग करेंगे, जो वास्तविक‑दुनिया के टूल्स जैसे Tesseract या EasyOCR के समान है लेकिन एक साफ़ Python API प्रदान करता है। + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** यदि आपको परमिशन एरर मिलते हैं, तो कमांड के आगे `python -m` जोड़ें या वर्चुअल एनवायरनमेंट का उपयोग करें—इससे आपके ग्लोबल साइट‑पैकेज साफ़ रहेंगे। + +## OCR इंजन इंस्टेंस बनाएं + +अब लाइब्रेरी तैयार है, पहला तार्किक कदम **OCR इंजन इंस्टेंस बनाना** है। इंजन को एक स्मार्ट स्कैनर की तरह समझें जिसे आप इमेज फीड करने से पहले कॉन्फ़िगर कर सकते हैं। + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +हम इंजन को अलग से इंस्टैंशिएट क्यों करते हैं, न कि सीधे स्टैटिक मेथड कॉल करते हैं? इंजन ऑब्जेक्ट कॉन्फ़िगरेशन स्टेट (जैसे भाषा प्राथमिकताएँ) रखता है जिसे आप कई इमेज पर पुनः उपयोग कर सकते हैं, जिससे हर बार री‑इनीशियलाइज़ करने का ओवरहेड बचता है। + +## Auto Detect Language OCR सक्षम करें + +अधिकांश OCR टूल्स को भाषा कोड निर्दिष्ट करना पड़ता है—`eng` इंग्लिश के लिए, `spa` स्पेनिश के लिए, आदि। भाषा को मैन्युअली अनुमान लगाना **multilingual image OCR** वर्कफ़्लो के उद्देश्य को नष्ट कर देता है। सौभाग्य से, `ocr` पैकेज एक *auto detect language OCR* मोड प्रदान करता है जो इमेज को स्कैन करके बैकग्राउंड में सबसे उपयुक्त भाषा मॉडल चुन लेता है। + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +इस तरह **detect language OCR** को सक्षम करने से आपको लंबी भाषा कोड सूची बनाए रखने की ज़रूरत नहीं पड़ेगी। इंजन देखी गई स्क्रिप्ट (Latin, Cyrillic, Han आदि) से मेल खाने की कोशिश करेगा और स्वचालित रूप से उचित मॉडल लोड करेगा। + +## बहु‑भाषी इमेज OCR निष्पादित करें + +इंजन तैयार है, अब **इमेज से टेक्स्ट निकालने** का समय है। `recognize_image` मेथड एक फ़ाइल पाथ लेता है और एक रिज़ल्ट ऑब्जेक्ट रिटर्न करता है जिसमें कच्चा टेक्स्ट और पता लगी भाषा दोनों होते हैं। + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +यदि आप सोच रहे हैं कि *how to extract OCR text* PDF से कैसे निकाला जाए PNG की बजाय, वही इंजन `recognize_pdf` प्रदान करता है—सिर्फ मेथड नाम बदलें। अंतर्निहित डिटेक्शन लॉजिक समान रहता है, इसलिए आप वही **auto detect language OCR** फ़ीचर का लाभ उठा सकते हैं। + +## पता लगी भाषा और निकाला गया टेक्स्ट दिखाएँ + +अंत में हम वह आउटपुट दिखाते हैं जो इंजन ने खोजा। रिज़ल्ट ऑब्जेक्ट `detected_language` (जैसे `en` या `es` वाला BCP‑47 टैग) और `text` (कच्चा OCR आउटपुट) को एक्सपोज़ करता है। + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +सैंपल इमेज पर स्क्रिप्ट चलाने से आपको कुछ इस तरह का आउटपुट मिलना चाहिए: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +ध्यान दें कि इंजन ने सही तरीके से इंग्लिश को प्राथमिक भाषा के रूप में पहचाना, फिर भी स्पेनिश लाइन को कैप्चर किया—बिल्कुल वही जो आप एक मजबूत **multilingual image OCR** समाधान से उम्मीद करेंगे। + +### अगर डिटेक्शन फेल हो जाए तो क्या करें? + +कभी‑कभी OCR इंजन डिफ़ॉल्ट भाषा (आमतौर पर इंग्लिश) पर फॉल्बैक कर सकता है अगर इमेज धुंधली हो या स्क्रिप्ट बहुत एक्सॉटिक हो। ऐसे मामलों में आप भाषा की सूची फ़ोर्स कर सकते हैं: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +लेकिन याद रखें, भाषाओं को फ़ोर्स करना **auto detect language OCR** की सुविधा को नष्ट कर देता है, इसलिए इसे केवल तब ही उपयोग करें जब आपके पास ज्ञात भाषा का उपसमुच्चय हो। + +## सामान्य समस्याएँ और OCR टेक्स्ट को विश्वसनीय रूप से निकालने के टिप्स + +ऑटो‑डिटेक्शन के साथ भी कुछ छोटी‑छोटी बाधाएँ हो सकती हैं: + +1. **लो‑रेज़ोल्यूशन इमेज** – OCR की सटीकता 150 dpi से नीचे तेज़ी से गिरती है। इमेज को अपस्केल करें या उच्च‑रेज़ोल्यूशन स्कैन माँगें। +2. **नॉइज़ और कम्प्रेशन आर्टिफैक्ट्स** – इमेज को इंजन में फीड करने से पहले एक साधा थ्रेशहोल्ड फ़िल्टर (`opencv` या `Pillow`) लागू करें। +3. **एक पेज पर मिश्रित स्क्रिप्ट्स** – कुछ इंजन एक साथ Latin और CJK कैरेक्टर्स को संभालने में संघर्ष करते हैं। पेज को क्षेत्रों में बाँटें और आवश्यकतानुसार अलग‑अलग रिकग्निशन चलाएँ। + +इन समस्याओं को हल करने से **extract text from image** प्रक्रिया की गुणवत्ता में काफी सुधार होता है, विशेषकर वास्तविक‑दुनिया के बहु‑भाषी दस्तावेज़ों के साथ काम करते समय। + +## पूर्ण कार्यशील उदाहरण + +नीचे पूरा, तैयार‑चलाने‑योग्य स्क्रिप्ट दिया गया है जो हमने चर्चा किए सभी चरणों को जोड़ता है। इसे `multilingual_ocr.py` के रूप में सेव करें और कमांड लाइन से चलाएँ। + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**अपेक्षित आउटपुट** (मान लेते हैं सैंपल इमेज में इंग्लिश और स्पेनिश टेक्स्ट है): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +`multilang_page.png` को किसी भी ऐसी इमेज से बदलें जिसमें अन्य भाषाओं में टेक्स्ट हो—**auto detect language OCR** की बदौलत स्क्रिप्ट अभी भी एक समझदार भाषा टैग और संबंधित टेक्स्ट देगी। + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## निष्कर्ष + +अब आप बिल्कुल जानते हैं कि **इमेज से OCR टेक्स्ट कैसे निकाला जाए**, कैसे **auto detect language OCR** को सक्षम किया जाए, और कैसे न्यूनतम कोड के साथ **multilingual image OCR** परिदृश्यों को संभाला जाए। OCR इंजन इंस्टेंस बनाकर, ऑटोमैटिक भाषा डिटेक्शन चालू करके, और `recognize_image` कॉल करके आप भाषा पहचानकर्ता और कच्चा टेक्स्ट दोनों विश्वसनीय रूप से निकाल सकते हैं। + +अब आगे क्या? निकाले गए स्ट्रिंग्स को एक ट्रांसलेशन API में फीड करें, उन्हें सर्चेबल डेटाबेस में स्टोर करें, या कई पेजों को एक ही PDF रिपोर्ट में जोड़ें। आप विभिन्न OCR बैक‑एंड्स (Tesseract, EasyOCR, Google Vision) के साथ प्रयोग भी कर सकते हैं जबकि वही हाई‑लेवल वर्कफ़्लो बरकरार रहेगा—धन्यवाद **detect language OCR** इंटरफ़ेस की स्थिरता के लिए। + +यदि आपको कोई अजीब व्यवहार दिखे, तो “सामान्य समस्याएँ” सेक्शन को फिर से देखें या इमेज प्री‑प्रोसेसिंग स्टेप्स को ट्यून करें। कोडिंग का आनंद लें, और आपका अगला प्रोजेक्ट सही‑डिटेक्टेड, परफ़ेक्ट‑एक्सट्रैक्टेड टेक्स्ट से भरपूर हो! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण कर सकें। + +- [इमेज को टेक्स्ट में बदलें – URL से इमेज पर OCR करें](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [इमेज से टेक्स्ट निकालें – .NET के लिए Aspose.OCR के साथ OCR ऑप्टिमाइज़ेशन](/ocr/english/net/ocr-optimization/) +- [Aspose OCR के साथ कई भाषाओं में टेक्स्ट इमेज को पहचानें](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/hindi/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..918907e86 --- /dev/null +++ b/ocr/hindi/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR का उपयोग करके इमेज़ PDF से टेक्स्ट निकालें। असिंक्रोनस बैच + पहचान के साथ स्कैन किए गए दस्तावेज़ों को तेज़ी से टेक्स्ट में बदलना सीखें। +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: hi +og_description: Python के साथ छवियों वाले PDF से टेक्स्ट निकालें। यह चरण‑दर‑चरण गाइड + दिखाता है कि असिंक्रोनस OCR का उपयोग करके स्कैन किए गए दस्तावेज़ों को टेक्स्ट में + कैसे बदलें। +og_title: इमेज़ PDF से टेक्स्ट निकालें – पायथन OCR ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: इमेज़ PDF से टेक्स्ट निकालें – स्कैन किए गए दस्तावेज़ों को टेक्स्ट में बदलने + के लिए पाइथन गाइड +url: /hi/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेजेज़ PDF से टेक्स्ट निकालें – स्कैन किए गए दस्तावेज़ों को टेक्स्ट में बदलने के लिए पाइथन गाइड + +क्या आपको कभी **extract text from images pdf** बिना घंटों टाइपिंग किए चाहिए था? इस गाइड में हम आपको दिखाएंगे कि कैसे **convert scanned documents to text** पाइथन में एक सरल असिंक्रोनस OCR वर्कफ़्लो का उपयोग करके किया जाए। + +यदि आपने कभी स्कैन किए गए PDFs के ढेर को देखा है और सोचा है, “कोई तेज़ तरीका होना चाहिए,” तो आप सही जगह पर हैं। हम कोड की हर लाइन को समझेंगे, बताएँगे कि प्रत्येक भाग क्यों महत्वपूर्ण है, और कुछ संभावित किनारी मामलों को भी कवर करेंगे। + +## आप क्या सीखेंगे + +- कैसे एक OCR इंजन को शुरू करें और पहचान भाषा सेट करें। +- बैच रिकग्नाइज़र में PNGs और PDFs की मिश्रित सूची को फीड करने की प्रक्रिया। +- OCR जॉब को असिंक्रोनस रूप से चलाना ताकि आपका ऐप उत्तरदायी बना रहे। +- परिणामों को प्राप्त करना, उन्हें स्रोत फ़ाइलों के साथ जोड़ना, और साफ़ आउटपुट प्रिंट करना। + +**Prerequisites**: Python 3.8+, `asyncio` या `concurrent.futures` की बुनियादी समझ, और एक OCR लाइब्रेरी जो उदाहरण में दिखाए गए `OcrEngine` क्लास को एक्सपोज़ करती हो (जैसे, Aspose.OCR, Tesseract wrapper, या एक कस्टम wrapper)। कोई भारी सेटअप आवश्यक नहीं—सिर्फ लाइब्रेरी इंस्टॉल करें और आप तैयार हैं। + +![extract text from images pdf](https://example.com/placeholder.png "Screenshot of OCR output – extract text from images pdf") + +## इमेजेज़ PDF से टेक्स्ट निकालें – OCR इंजन सेटअप करना + +सबसे पहले आपको एक OCR इंजन इंस्टेंस चाहिए जो आपके दस्तावेज़ों की भाषा के लिए कॉन्फ़िगर किया गया हो। हमारे मामले में हम फ़्रेंच का उपयोग करेंगे, लेकिन आप इसे किसी भी समर्थित भाषा में बदल सकते हैं। + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Why this matters**: भाषा को पहले से सेट करने से सटीकता में काफी सुधार होता है। इंजन भाषा‑विशिष्ट शब्दकोश और कैरेक्टर मॉडल का उपयोग करता है; गलत भाषा फीड करने से अक्सर गड़बड़ आउटपुट मिलता है। + +## फ़ाइल सूची तैयार करें – इमेजेज़ और PDFs साथ में + +हमारा बैच रिकग्नाइज़र रास्टर इमेजेज़ (`.png`, `.jpg`) और PDF कंटेनर दोनों को संभाल सकता है। बस फ़ाइल पाथ्स की एक साधारण पाइथन सूची फीड करें। + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: सूची को फ्लैट रखें; इंजन प्रत्येक PDF पेज को पहचान से पहले इमेजेज़ में अनपैक कर देगा। यदि आपके पास हजारों फ़ाइलें हैं, तो मेमोरी स्पाइक से बचने के लिए सूची को छोटे बैचों में विभाजित करने पर विचार करें। + +## असिंक्रोनस बैच रिकग्निशन शुरू करें + +मुख्य थ्रेड को ब्लॉक करने के बजाय, हम OCR जॉब को बैकग्राउंड में लॉन्च करते हैं। यह मेथड एक `Future` लौटाता है जो अंततः `OcrResult` ऑब्जेक्ट्स की सूची रखेगा। + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**How it works**: इंजन के अंदर यह एक थ्रेड पूल (या असिंक्रोनस टास्क, इम्प्लीमेंटेशन पर निर्भर) बनाता है। इससे आप अन्य काम जारी रख सकते हैं—जैसे UI अपडेट करना, अधिक फ़ाइलें लाना, या प्रोग्रेस लॉग करना—जबकि भारी काम बैकग्राउंड में चलता रहता है। + +## OCR चलते समय कुछ उपयोगी काम करें + +एक सामान्य गलती यह है कि आप निष्क्रिय बैठें और फ्यूचर को टाइट लूप में पोल करें। इसके बजाय, आप कोई भी असंबंधित काम कर सकते हैं। प्रदर्शन के लिए, हम सिर्फ एक स्टेटस लाइन प्रिंट करेंगे। + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## फ्यूचर पूरा होने पर परिणाम इकट्ठा करें + +जब आप OCR आउटपुट इकट्ठा करने के लिए तैयार हों, तो `concurrent.futures` से `as_completed` का उपयोग करें। यह पैटर्न चाहे आपके पास एक फ्यूचर हो या कई, काम करता है। + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**What you’ll see**: प्रत्येक फ़ाइल पाथ के बाद निकाला गया प्लेन‑टेक्स्ट प्रतिनिधित्व। PDFs के लिए, `result.text` में हर पेज का संयोजित टेक्स्ट होता है। + +### अपेक्षित आउटपुट (उदाहरण) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +यदि आप लापता अक्षर देखते हैं, तो दोबारा जांचें कि आपने जो भाषा सेट की है वह दस्तावेज़ की भाषा से मेल खाती है, और इंजन को फीड करने से पहले इमेजेज़ को प्री‑प्रोसेस करने पर विचार करें (डेस्क्यू, कंट्रास्ट बढ़ाना)। + +## किनारी मामलों और सामान्य समस्याओं को संभालना + +| Situation | What to Do | +|-----------|------------| +| **Mixed languages** | पहले भाषा‑डिटेक्शन पास चलाएँ, फिर प्रत्येक भाषा के लिए अलग‑अलग इंजन इंस्टैंशिएट करें। | +| **Huge PDFs (> 100 MB)** | PDF को डिस्क पर व्यक्तिगत पेजों में विभाजित करें (जैसे, `PyPDF2` का उपयोग करके) और उन्हें अलग‑अलग एंट्री के रूप में फीड करें। | +| **Non‑Latin scripts** | सुनिश्चित करें कि OCR लाइब्रेरी में आवश्यक भाषा पैक शामिल है; कुछ लाइब्रेरी को अतिरिक्त डेटा फ़ाइलें डाउनलोड करनी पड़ती हैं। | +| **Performance bottleneck** | थ्रेड पूल साइज बढ़ाएँ (`engine.set_thread_pool_size(8)`) या यदि उपलब्ध हो तो GPU‑सक्षम बैकएंड पर स्विच करें। | +| **Missing text in low‑resolution images** | OpenCV के साथ प्री‑प्रोसेस करें: `cv2.resize`, `cv2.threshold`, और `cv2.medianBlur` का उपयोग करके पठनीयता बढ़ाएँ। | + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट तैयार) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +`extract_text_async.py` के रूप में सहेजें, `YOUR_DIRECTORY` को अपनी फ़ाइलों के पाथ से बदलें, OCR पैकेज इंस्टॉल करें (`pip install your-ocr-lib`), और `python extract_text_async.py` चलाएँ। आपको पहले दिखाए गए कंसोल आउटपुट दिखाई देगा। + +## अगले कदम – बेसिक एक्सट्रैक्शन से आगे बढ़ना + +- **Post‑processing**: अतिरिक्त व्हाइटस्पेस हटाएँ, Unicode को नॉर्मलाइज़ करें (`unicodedata.normalize`), या OCR शोर को साफ़ करने के लिए स्पेल‑चेकर चलाएँ। +- **Structured output**: परिणामों को CSV, JSON में एक्सपोर्ट करें, या डाउनस्ट्रीम सर्च के लिए सीधे डेटाबेस में डालें। +- **Parallel batches**: यदि आपके पास सैकड़ों फ़ाइलें हैं, तो कई फ्यूचर बनाएं और एक क्यू का उपयोग करके CPU को व्यस्त रखें बिना मेमोरी ओवरलोड किए। +- **Integrate with web frameworks**: इस स्क्रिप्ट को Flask या FastAPI एंडपॉइंट में जोड़ें ताकि ऑन‑डिमांड OCR सेवा प्रदान की जा सके। + +--- + +### TL;DR + +अब आप जानते हैं कि कैसे **extract text from images pdf** को एक न्यूनतम पाइथन स्क्रिप्ट से किया जाए जो OCR को असिंक्रोनस रूप से चलाता है, जिससे आप **convert scanned documents to text** कर सकते हैं जबकि आपका प्रोग्राम उत्तरदायी बना रहता है। भाषा सेटिंग्स, बैच साइज, और प्री‑प्रोसेसिंग ट्रिक्स के साथ प्रयोग करें ताकि हर अक्षर की सटीकता प्राप्त हो सके। + +क्या आपके पास कोई नया विचार है—शायद हस्तलिखित नोट्स पर OCR या क्लाउड‑आधारित सेवा? एक टिप्पणी छोड़ें, और कोडिंग का आनंद लें! + +## अब आपको क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोच को एक्सप्लोर करने में मदद करेंगे। + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Images Using Aspose.OCR – Allowed Characters](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..851fb388f --- /dev/null +++ b/ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Python का उपयोग करके PDF को OCR कैसे करें, PDF से टेक्स्ट निकालें, स्कैन + किए गए PDF टेक्स्ट को बदलें, और कुछ ही लाइनों के कोड में OCR भाषा बदलें। +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: hi +og_description: 'Python के साथ PDF को OCR कैसे करें: एक व्यावहारिक गाइड जो आपको दिखाता + है कि PDF से टेक्स्ट कैसे निकालें, स्कैन किए गए PDF टेक्स्ट को कैसे बदलें, और OCR + भाषा को आसानी से कैसे बदलें।' +og_title: Python में PDF को OCR कैसे करें – पूर्ण प्रोग्रामिंग ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Python में PDF को OCR कैसे करें – पूर्ण चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में PDF को OCR कैसे करें – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपने कभी **how to OCR PDF** फ़ाइलों को महंगे SaaS टूल्स के बिना करने के बारे में सोचा है? आप अकेले नहीं हैं। चाहे आप पुरानी किताबों को डिजिटल बना रहे हों, इनवॉइस से डेटा निकाल रहे हों, या सिर्फ स्कैन किए गए रिपोर्ट से खोज योग्य टेक्स्ट चाहिए, Python में PDF OCR में महारत हासिल करने से आप मैन्युअल कॉपी‑पेस्ट में घंटों बचा सकते हैं। + +इस ट्यूटोरियल में हम एक संक्षिप्त, कार्यशील उदाहरण के माध्यम से चलेंगे जो **extracts text from PDF** करता है, आपको दिखाता है कि **convert scanned PDF text** को संपादन योग्य स्ट्रिंग्स में कैसे बदलें, और यहां तक कि यह भी दर्शाता है कि **change OCR language** कैसे करें यदि आपका दस्तावेज़ अंग्रेज़ी में नहीं है। अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं। + +## आवश्यकताएँ और सेटअप + +Before we dive in, make sure you have: + +- Python 3.8+ स्थापित हो (कोड 3.9, 3.10 और नए संस्करणों पर काम करता है) +- `ocr` पैकेज जो `OcrEngine` क्लास प्रदान करता है (आप इसे `pip install ocr-lib` के माध्यम से इंस्टॉल कर सकते हैं – इसे अपने वास्तविक पैकेज नाम से बदलें) +- एक PDF फ़ाइल जिसे आप प्रोसेस करना चाहते हैं; डेमो के लिए हम `high_res_book.pdf` का उपयोग करेंगे जो `YOUR_DIRECTORY` नामक फ़ोल्डर में रखी होगी + +If you’re using a virtual environment (highly recommended), activate it first: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** अपने PDF फ़ाइलों को एक समर्पित `data/` डायरेक्टरी में रखें ताकि बाद में पाथ‑संबंधी समस्याओं से बचा जा सके। + +## चरण 1: OCR इंजन इंस्टेंस बनाएं (How to OCR PDF – Initialization) + +जब आप **perform OCR on PDF** फ़ाइलों पर OCR करना चाहते हैं, तो आपको सबसे पहला काम इंजन को इंस्टैंशिएट करना है। इंजन को आप मस्तिष्क की तरह सोचें जो प्रत्येक पेज को पढ़ेगा, ग्लिफ़्स की व्याख्या करेगा, और आपको साधारण टेक्स्ट वापस देगा। + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +यह क्यों महत्वपूर्ण है: बिना इंजन के आपके पास भाषा सेटिंग्स, रेंडरिंग विकल्प, या PDF हैंडलिंग के लिए कोई संदर्भ नहीं होगा। `OcrEngine` ऑब्जेक्ट इन सभी डिफ़ॉल्ट्स को रखता है और आपको बाद में उन्हें समायोजित करने देता है। + +## चरण 2: पहचान भाषा सेट करें (Change OCR Language) + +अधिकांश OCR लाइब्रेरीज़ डिफ़ॉल्ट रूप से अंग्रेज़ी का उपयोग करती हैं, लेकिन अगर आपका दस्तावेज़ फ्रेंच, जर्मन, या यहाँ तक कि जापानी में है तो क्या? भाषा बदलना इतना सरल है जितना `set_recognition_language` को कॉल करना। यह **change OCR language** आवश्यकता को पूरा करता है और उच्च सटीकता सुनिश्चित करता है। + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Why you might need this:** एक बहुभाषी अभिलेखागार अक्सर मिश्रित‑भाषा वाले पेज़ रखता है। भाषा को तुरंत बदलने से “ß” या “ñ” जैसे अक्षरों की गलत पहचान से बचा जा सकता है। + +## चरण 3: PDF रेंडरिंग विकल्प कॉन्फ़िगर करें (Convert Scanned PDF Text Effectively) + +स्कैन किए गए PDFs से निपटते समय, रिज़ॉल्यूशन और कलर मोड OCR गुणवत्ता को बहुत प्रभावित करते हैं। अधिकांश दस्तावेज़ों के लिए 300 DPI पर ग्रेस्केल में रेंडर करना एक आदर्श बिंदु है—विवरण पकड़ने के लिए पर्याप्त उच्च, लेकिन मेमोरी उपयोग को उचित रखने के लिए पर्याप्त कम। + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +चेन किए गए कॉल्स दिखने में फैंसी लग सकते हैं, लेकिन वे केवल एक फ्लुएंट API हैं जो हर बार वही ऑप्शन ऑब्जेक्ट रिटर्न करता है। यदि आपको रंग चाहिए (जैसे रंगीन डायग्राम के लिए), तो `"grayscale"` को `"color"` से बदल दें। + +## चरण 4: PDF को पहचानें और पहले पेज का टेक्स्ट प्राप्त करें (Extract Text from PDF) + +अब **how to OCR PDF** का मूल भाग आता है: इंजन को फ़ाइल पाथ देना और पहचाने गए टेक्स्ट को निकालना। यह मेथड पेज परिणामों की एक सूची लौटाता है; प्रत्येक परिणाम में एक `text` एट्रिब्यूट होता है। + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +यदि आपको पूरा दस्तावेज़ चाहिए, तो `results` पर इटररेट करें: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### यदि PDF एन्क्रिप्टेड है तो क्या करें? + +कुछ PDFs पासवर्ड‑सुरक्षित होते हैं। ऐसे में आप पासवर्ड को `recognize_pdf` में पास कर सकते हैं: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +इंजन OCR करने से पहले तुरंत डिक्रिप्ट कर देगा—कोई अतिरिक्त कदम आवश्यक नहीं। + +## चरण 5: निकाले गए टेक्स्ट की पोस्ट‑प्रोसेसिंग (Fine‑Tuning Extract Text from PDF) + +कच्चा OCR आउटपुट अक्सर लाइन ब्रेक, अतिरिक्त स्पेस, या कभी‑कभी गलत पहचाने गए अक्षर रखता है। एक त्वरित क्लीन‑अप रूटीन निकाले गए स्ट्रिंग को डाउनस्ट्रीम प्रोसेसिंग (सर्च इंडेक्सिंग, डेटाबेस स्टोरेज, आदि) के लिए तैयार करता है। + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +अब आप सुरक्षित रूप से **extract text from PDF** कर सकते हैं और इसे किसी भी NLP पाइपलाइन, सर्च इंजन, या साधारण `open(...).write()` ऑपरेशन में फीड कर सकते हैं। + +## बोनस: कई PDFs की बैच प्रोसेसिंग (Scaling Perform OCR on PDF) + +यदि आपके पास स्कैन किए गए PDFs से भरा फ़ोल्डर है, तो लॉजिक को एक लूप में रैप करें: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +यह स्निपेट दिखाता है कि कैसे **perform OCR on PDF** फ़ाइलों को बड़े पैमाने पर किया जाए, जो डिजिटलाइजेशन प्रोजेक्ट्स की आम आवश्यकता है। + +## अपेक्षित आउटपुट + +सिंगल‑पेज उदाहरण (चरण 4) चलाने पर कुछ इस तरह का आउटपुट प्रिंट होना चाहिए: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +यदि आपने मल्टी‑पेज बुक प्रोसेस की, तो कंसोल प्रत्येक पेज के साफ़ किए गए टेक्स्ट को दिखाएगा, और बैच स्क्रिप्ट हर PDF के बगल में एक `.txt` फ़ाइल छोड़ देगी। + +## सामान्य समस्याएँ और उन्हें कैसे टालें + +| समस्या | लक्षण | समाधान | +|-------|----------|-----| +| कम‑रिज़ॉल्यूशन स्रोत PDF | गड़बड़ अक्षर, गायब शब्द | DPI बढ़ाएँ (`set_dpi(400)` या अधिक) | +| गलत भाषा सेट | बहुत सारे अज्ञात प्रतीक, विशेषकर उच्चारण वाले अक्षर | उपयोग करें `engine.set_recognition_language(ocr.Language.FRENCH)` या उपयुक्त enum | +| बड़ी PDF से मेमोरी त्रुटि | `MemoryError` या कुछ पेज़ के बाद क्रैश | पेज़ को चंक्स में प्रोसेस करें (`engine.recognize_pdf(..., max_pages=10)`) | +| PDF में फ़ॉन्ट्स गायब | कुछ पेज़ के लिए खाली आउटपुट | सुनिश्चित करें कि PDF वास्तव में रास्टर इमेजेज़ रखता है; कुछ PDFs केवल वेक्टर होते हैं और अलग हैंडलिंग की आवश्यकता होती है | + +## छवि चित्रण + +नीचे वर्कफ़्लो का एक त्वरित दृश्य दिया गया है। alt टेक्स्ट जानबूझकर SEO‑फ़्रेंडली है। + +![how to ocr pdf कार्यप्रवाह आरेख जिसमें इंजन इनिशियलाइज़ेशन, भाषा सेटिंग, रेंडरिंग विकल्प, पहचान, और टेक्स्ट एक्सट्रैक्शन](/images/ocr-workflow.png) + +*यह आरेख कोड चलाने के लिए आवश्यक नहीं है, लेकिन यह विज़ुअल लर्नर्स को दिखाता है कि प्रत्येक चरण कहाँ फिट होता है।* + +## निष्कर्ष + +हमने Python में **how to OCR PDF** फ़ाइलों को शुरू से अंत तक कवर किया: OCR इंजन बनाना, **changing OCR language**, रेंडरिंग को **convert scanned PDF text** के लिए कॉन्फ़िगर करना, और अंत में **extracting text from PDF** को आगे उपयोग के लिए निकालना। पूर्ण, चलाने योग्य उदाहरण किसी भी प्रोजेक्ट में डालने के लिए तैयार है, और वैकल्पिक बैच स्क्रिप्ट दिखाती है कि समाधान को कैसे स्केल किया जाए। + +Next, you might want to explore: + +- बहुभाषी अभिलेखागार के लिए भाषा सूची पर लूप करके **perform OCR on PDF** जोड़ना। +- निकाले गए टेक्स्ट को Elasticsearch के साथ इंटीग्रेट करके पूर्ण‑टेक्स्ट सर्च करना। +- OCR का उपयोग करके मूल फ़ाइल में टेक्स्ट लेयर एम्बेड करके खोज योग्य PDFs बनाना (कई लाइब्रेरीज़ `save_as_searchable_pdf` मेथड प्रदान करती हैं)। + +बिना झिझक प्रयोग करें, DPI सेटिंग्स को समायोजित करें, या किसी अलग OCR बैकएंड पर स्विच करें। मूल बातें वही रहती हैं, और अब आपके पास निर्माण के लिए एक ठोस नींव है। + +कोडिंग का आनंद लें, और आपके स्कैन किए गए दस्तावेज़ अंततः खोज योग्य बन जाएँ! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर करने में मदद करती हैं। + +- [PDF टेक्स्ट को पहचानें – OCR ऑपरेशन्स with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Aspose.OCR का उपयोग करके भाषा के साथ इमेज टेक्स्ट को OCR कैसे करें](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [.NET में Aspose.OCR के साथ PDF को OCR कैसे करें](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..fdb644524 --- /dev/null +++ b/ocr/hindi/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-06 +description: Python का उपयोग करके PDF को OCR कैसे करें और छवियों से खोज योग्य PDF + फ़ाइलें बनाएं। मिनटों में खोज योग्य टेक्स्ट जोड़ना और छवि को PDF/A में बदलना सीखें। +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: hi +og_description: स्टेप‑बाय‑स्टेप PDF को OCR करने का तरीका। सरल Python स्क्रिप्ट का + उपयोग करके खोज योग्य टेक्स्ट जोड़ना और इमेज को PDF/A में बदलना सीखें। +og_title: PDF को OCR कैसे करें – खोज योग्य PDFs बनाने के लिए त्वरित गाइड +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Python में PDF को OCR कैसे करें – छवियों से खोज योग्य PDF बनाएं +url: /hi/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF को OCR कैसे करें – स्कैन किए गए चित्रों को खोज योग्य PDF में बदलें + +क्या आपने कभी सोचा है **PDF को OCR कैसे किया जाए** जब आपके पास केवल इनवॉइस या रसीद की स्कैन की हुई छवि है? आप अकेले नहीं हैं। कई कार्यालयों में आने वाले कागजात PNG या JPEG के रूप में आते हैं, और अगला कदम—उस सामग्री को खोज योग्य बनाना—एक ब्लैक‑बॉक्स जैसा लगता है। + +अच्छी खबर? सिर्फ कुछ पंक्तियों के Python कोड से आप **searchable PDF** फ़ाइलें बना सकते हैं, **searchable text** जोड़ सकते हैं, और यहाँ तक कि **image को PDF/A** में बदल सकते हैं दीर्घकालिक अभिलेखीयकरण के लिए। इस ट्यूटोरियल में हम प्रत्येक चरण को समझेंगे, क्यों यह महत्वपूर्ण है, और आपको एक तैयार‑स्क्रिप्ट देंगे जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं। + +> **Pro tip:** यह ही तरीका मल्टी‑पेज स्कैन पर भी काम करता है; बस फ़ाइलों पर लूप लगाएँ और इंजन बाकी काम खुद कर देगा। + +--- + +## What You’ll Need + +डुबकी लगाने से पहले, सुनिश्चित करें कि आपके मशीन पर निम्नलिखित मौजूद हैं: + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9 or newer | आधुनिक सिंटैक्स और बेहतर लाइब्रेरी समर्थन | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | इमेज पहचान और PDF/A जेनरेशन दोनों को संभालता है | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | वह स्रोत जहाँ से टेक्स्ट निकाला जाएगा | +| Write permission to the output folder | ताकि स्क्रिप्ट नया PDF सहेज सके | + +यदि आपने अभी तक OCR SDK इंस्टॉल नहीं किया है, तो चलाएँ: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +बस इतना ही—कोई जटिल सिस्टम डिपेंडेंसी नहीं, सिर्फ एक pip install। + +--- + +## How to OCR PDF – Overview + +ऊपर से देखा जाए तो प्रक्रिया तीन सरल कार्यों में विभाजित है: + +1. **Recognize** छवि के भीतर का टेक्स्ट पढ़ें जबकि मूल ग्राफ़िक्स को बरकरार रखें। +2. **Export** OCR परिणाम को मूल छवि के साथ **searchable PDF/A** (अभिलेखीय‑अनुकूल PDF फ़्लेवर) के रूप में निर्यात करें। +3. **Validate** यह सुनिश्चित करें कि परिणामी फ़ाइल में मूल चित्र के ऊपर चयन योग्य, खोज योग्य टेक्स्ट लेयर मौजूद है। + +नीचे आप प्रत्येक चरण को कोड में देखेंगे, साथ ही कमांड्स के *क्यों* की व्याख्या भी। + +--- + +## Step 1: Recognize Text from the Image + +पहले हम OCR इंजन को पिक्सेल पढ़ने और एक result ऑब्जेक्ट लौटाने को कहते हैं, जिसमें कच्ची छवि और निकाला गया टेक्स्ट दोनों होते हैं। इसे ऐसे समझें जैसे इंजन आपके लिए इनवॉइस “पढ़” रहा हो। + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Why this matters + +- **Preserving graphics** का मतलब है कि विज़ुअल लेआउट (टेबल, लोगो, स्टैम्प) स्कैनर द्वारा कैप्चर किए गए रूप में ही रहता है। +- `result` ऑब्जेक्ट आमतौर पर एक छिपी हुई टेक्स्ट लेयर रखता है जिसे हम बाद में PDF में एम्बेड करेंगे। +- `recognize_image` का उपयोग `recognize_pdf` की बजाय करने से अतिरिक्त रूपांतरण चरण हट जाता है, जिससे सिंगल‑पेज इमेज की प्रोसेसिंग तेज़ होती है। + +#### Common variations + +- यदि आपके पास **multi‑page TIFF** है, तो फ़ाइल पाथ सीधे पास करें; अधिकांश इंजन प्रत्येक पेज को अलग इमेज मानेंगे। +- उन PDFs के लिए जिनमें पहले से इमेज हैं, आप `engine.recognize_pdf("file.pdf")` कॉल कर सकते हैं और इस चरण को पूरी तरह छोड़ सकते हैं। + +--- + +## Step 2: Export OCR Result as Searchable PDF/A + +अब हम चरण 1 के `result` को लेते हैं और इंजन को नई फ़ाइल लिखने के लिए कहते हैं। यहाँ मुख्य फ़्लैग *PDF/A* है—PDF का ISO‑स्टैंडर्ड संस्करण जो दीर्घकालिक संरक्षण के लिए बनाया गया है। + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Why this matters + +- **Searchable PDF**: आउटपुट फ़ाइल में एक छिपी, चयन योग्य टेक्स्ट लेयर होती है। अब आप दस्तावेज़ में Ctrl + F कर सकते हैं। +- **PDF/A compliance**: कुछ संस्थाएँ (क़ानूनी, वित्तीय) ऑडिट ट्रेल के लिए PDF/A की मांग करती हैं; यह चरण वह नियम स्वचालित रूप से पूरा करता है। +- यह मेथड **searchable text** जोड़ता है बिना इमेज को फ्लैटन किए, इसलिए विज़ुअल फ़िडेलिटी पूरी रहती है। + +#### Edge case: Need a regular PDF instead? + +यदि आपको PDF/A की ज़रूरत नहीं है, तो `save_as_pdfa` को `save_as_pdf` से बदल दें। बाकी वर्कफ़्लो वही रहता है। + +--- + +## Step 3: Verify the Searchable PDF + +एक त्वरित sanity check आपको बाद में अजीब बग्स से बचाता है। उत्पन्न फ़ाइल को किसी भी PDF व्यूअर में खोलें, कोई शब्द चुनें, और सर्च फ़ंक्शन इस्तेमाल करें। + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Expected output + +जब आप स्क्रिप्ट चलाते हैं, तो कंसोल पर यह प्रिंट होता है: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +फ़ाइल खोलने पर आपको मूल इनवॉइस इमेज के साथ एक हल्की, अदृश्य टेक्स्ट लेयर दिखेगी। किसी भी शब्द को हाईलाइट करें और आप देखेंगे कि वह चयन योग्य है—**यही वह searchable text है** जो आपने अभी जोड़ी है। + +--- + +## Adding Searchable Text to Existing PDFs (Bonus) + +कभी‑कभी आपके पास पहले से एक PDF होता है लेकिन आपको उस पर **searchable text** जोड़ना होता है। वही इंजन OCR परिणाम को मौजूदा PDF पर ओवरले कर सकता है: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +यहाँ `apply_to` छिपी लेयर को मूल पेजों के साथ मर्ज करता है, जिससे आप **searchable PDF** बना सकते हैं बिना फिर से स्कैन किए। + +--- + +## Common Pitfalls and Tips + +| Pitfall | How to avoid it | +|---------|-----------------| +| **Low‑resolution source images** (< 150 dpi) | अपस्केल करें या उच्च‑रिज़ॉल्यूशन स्कैन का अनुरोध करें; 150 dpi से नीचे OCR की सटीकता काफी घट जाती है। | +| **Missing language data** | अपने OCR इंजन के लिए उपयुक्त भाषा पैक्स इंस्टॉल करें (`pip install pdfocr[eng,spa]`)। | +| **Output folder not writable** | स्क्रिप्ट को पर्याप्त अनुमतियों के साथ चलाएँ या कोई अलग डायरेक्टरी चुनें। | +| **PDF/A validation fails** | सुनिश्चित करें कि आप असमर्थित फ़ॉन्ट्स या JavaScript एम्बेड नहीं कर रहे हैं; अधिकांश SDK `save_as_pdfa` उपयोग करने पर इसे स्वचालित रूप से संभाल लेते हैं। | + +--- + +## Full Script – One‑File Solution + +नीचे एक स्व-समाहित स्क्रिप्ट है जो सब कुछ जोड़ती है। कॉपी‑पेस्ट करें, प्लेसहोल्डर पाथ बदलें, और आप **image को PDF/A में बदलने** के लिए तैयार हैं। + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**What this script does:** +1. OCR इंजन लोड करता है। +2. चुनी गई इमेज पढ़ता है और टेक्स्ट निकालता है। +3. एक **searchable PDF/A** लिखता है जिसे आप तुरंत वितरित या अभिलेखित कर सकते हैं। + +इसे फ़ंक्शन में रैप करके पूरे फ़ोल्डर को प्रोसेस करने के लिए `os.listdir()` पर इटररेट करें और प्रत्येक फ़ाइल के लिए तीन चरण दोहराएँ। + +--- + +## Next Steps & Related Topics + +अब जब आप **how to OCR PDF** में महारत हासिल कर चुके हैं, तो इन आगे के विचारों को देखें: + +- **Batch processing:** `concurrent.futures` का उपयोग करके दर्जनों इनवॉइस को समानांतर में OCR करें। +- **Metadata injection:** आसान इंडेक्सिंग के लिए PDF मेटाडेटा में निर्माण तिथि या इनवॉइस नंबर जोड़ें। +- **Hybrid PDFs:** मूल इमेज के साथ searchable text को मिलाकर “डिजिटल ट्विन” बनाएं। +- **Alternative outputs:** यदि डाउनस्ट्रीम सिस्टम को एडिटेबल फ़ॉर्मेट चाहिए तो **DOCX** या **HTML** में एक्सपोर्ट करें। + +इनमें से प्रत्येक आपके द्वारा अभी सीखे गए मूल सिद्धांतों—recognize, export, verify—पर आधारित है। + +--- + +## Wrap‑Up + +संक्षेप में, अब आप **how to OCR PDF** फ़ाइलों को सिर्फ तीन पंक्तियों के Python से **searchable PDF/A** में बदलना जानते हैं। स्क्रिप्ट भारी काम संभालती है, मूल ग्राफ़िक्स को बरकरार रखती है, और आपको एक मानक‑अनुपालन दस्तावेज़ देती है जिसे आप खोज, अभिलेख या साझा कर सकते हैं। + +अपने इनवॉइस, रसीद या स्कैन किए हुए कॉन्ट्रैक्ट के साथ इसे आज़माएँ। यदि कोई समस्या आती है, तो नीचे टिप्पणी छोड़ें या SDK की आधिकारिक डॉक्यूमेंटेशन देखें—वहाँ अक्सर अतिरिक्त उदाहरण होते हैं। Happy coding, और अब किसी भी इमेज को तुरंत खोज योग्य बनाने की नई क्षमता का आनंद लें! + +![PDF को OCR करने का उदाहरण, मूल इमेज और searchable PDF ओवरले दिखाते हुए](placeholder.png "PDF को OCR करने का उदाहरण") + +## What Should You Learn Next? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में निपुण हो सकें और अपने प्रोजेक्ट में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण कर सकें। + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/hindi/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..2bdb75af0 --- /dev/null +++ b/ocr/hindi/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-06-06 +description: Aspose OCR Cloud का उपयोग करके PDF को OCR कैसे करें। PDF से टेक्स्ट निकालना, + PDF पेज को PNG में बदलना, और Python में PDF पेज इमेज को सहेजना सीखें। +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: hi +og_description: कैसे Aspose OCR Cloud के साथ PDF को OCR करें। यह गाइड दिखाता है कि + कैसे साधारण टेक्स्ट PDF निकालें, PDF पेज को PNG में बदलें, और PDF पेज की छवियों + को सहेजें। +og_title: Aspose OCR क्लाउड के साथ PDF को OCR कैसे करें – चरण-दर-चरण +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Aspose OCR Cloud के साथ PDF को OCR कैसे करें – पूर्ण गाइड +url: /hi/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Cloud के साथ PDF को OCR कैसे करें – संपूर्ण गाइड + +क्या आपने कभी भारी डेस्कटॉप टूल्स के साथ झगड़े बिना **PDF को OCR कैसे करें** फ़ाइलों के बारे में सोचा है? आप अकेले नहीं हैं—कई डेवलपर्स इस समस्या का सामना करते हैं जब उन्हें स्कैन किए गए दस्तावेज़ों से टेक्स्ट निकालने का तेज़, प्रोग्रामेटिक तरीका चाहिए। अच्छी खबर? Aspose OCR Cloud के साथ आप **PDF से टेक्स्ट निकाल सकते हैं**, प्रत्येक पेज को PNG में बदल सकते हैं, और यहाँ तक कि **PDF पेज इमेजेज़ को सहेज सकते हैं** बाद में उपयोग के लिए, सब कुछ एक साफ़ Python स्क्रिप्ट से। + +इस ट्यूटोरियल में हम आपको वह सब कुछ बताएंगे जो आपको जानना आवश्यक है: SDK को इंस्टॉल करने, इंजन को लाइसेंस करने, और मल्टी‑पेज PDF को पहचानने से लेकर प्लेन टेक्स्ट निकालने, पेज को PNG में बदलने, और उन इमेजेज़ को डिस्क पर सहेजने तक। अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं जिसे **PDF को OCR कैसे करें** क्षमताओं की आवश्यकता है। + +## आप क्या चाहिए + +- **Python 3.8+** (कोड 3.10 और उससे नए संस्करणों पर भी काम करता है) +- एक Aspose OCR Cloud खाता – आपको एक मुफ्त ट्रायल लाइसेंस फ़ाइल (`Aspose.OCR.lic`) मिलेगी +- `asposeocrcloud` पैकेज (`pip install asposeocrcloud`) +- एक स्कैन किया हुआ, मल्टी‑पेज PDF जिसे आप प्रोसेस करना चाहते हैं + +बस इतना ही। कोई अतिरिक्त बाइनरी नहीं, कोई नेटिव डिपेंडेंसी नहीं, सिर्फ शुद्ध Python। + +## PDF को OCR कैसे करें – सेटअप और लाइसेंस + +किसी भी OCR मेथड को कॉल करने से पहले, आपको SDK को बताना होगा कि आप कौन हैं। Aspose एक हल्की लाइसेंस फ़ाइल का उपयोग करता है जिसे आप अपनी स्क्रिप्ट के लिए सुलभ स्थान पर रखते हैं। + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* यदि आप लाइसेंस चरण को छोड़ देते हैं, तो SDK फिर भी काम करेगा लेकिन आउटपुट इमेजेज़ में एक छोटा वॉटरमार्क एम्बेड करेगा। प्रोडक्शन के लिए यह आदर्श नहीं है। + +## स्टेप 2: Aspose OCR Cloud Python SDK इंस्टॉल करें + +एक टर्मिनल खोलें और चलाएँ: + +```bash +pip install asposeocrcloud +``` + +यह पैकेज सभी आवश्यक डिपेंडेंसीज़ (requests, pillow, आदि) को खींच लेता है, इसलिए आपको कुछ और खोजने की जरूरत नहीं। + +## स्टेप 3: OCR इंजन बनाएं और भाषा चुनें + +इंजन ऑपरेशन का दिल है। आप Aspose द्वारा समर्थित कोई भी भाषा निर्दिष्ट कर सकते हैं; अधिकांश मामलों में English काम करता है। + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +भाषा क्यों सेट करें? क्योंकि OCR इंजन सटीकता बढ़ाने के लिए भाषा‑विशिष्ट शब्दकोशों का उपयोग करता है। यदि आप फ्रेंच PDF प्रोसेस कर रहे हैं, तो बस `ENGLISH` को `FRENCH` से बदल दें। + +## स्टेप 4: अपने मल्टी‑पेज PDF की ओर इशारा करें + +इंजन को उस फ़ाइल का पूरा पाथ दें जिसे आप प्रोसेस करना चाहते हैं। रिलेटिव पाथ ठीक हैं जब तक वे स्क्रिप्ट की वर्किंग डायरेक्टरी से हल हो जाते हैं। + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +सुनिश्चित करें कि फ़ाइल पढ़ी जा सकती है; अन्यथा आपको `FileNotFoundError` मिलेगा। + +## स्टेप 5: OCR चलाएँ – आपको परिणामों की एक सूची मिलेगी + +`recognize_pdf` को कॉल करने से एक सूची मिलती है जहाँ प्रत्येक एलिमेंट स्रोत PDF के एक पेज से मेल खाता है। + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +प्रत्येक `OcrResult` दो उपयोगी प्रॉपर्टीज़ रखता है: + +* `text` – पेज का प्लेन‑टेक्स्ट प्रतिनिधित्व ( **extract plain text pdf** के लिए शानदार) +* `image` – रेंडर किए गए पेज का Pillow `Image` ऑब्जेक्ट ( **convert pdf page png** के लिए परफेक्ट) + +## स्टेप 6: PDF से टेक्स्ट निकालें और पेज को PNG में बदलें + +अब हम परिणामों के माध्यम से लूप करते हैं, निकाले गए टेक्स्ट को प्रिंट करते हैं, और प्रत्येक पेज का PNG संस्करण सहेजते हैं। + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### अपेक्षित कंसोल आउटपुट + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +आपको `page_1.png`, `page_2.png`, … `YOUR_DIRECTORY` में मिलेंगे। ये रास्टराइज़्ड पेज इमेजेज़ हैं जिन्हें आप डाउनस्ट्रीम इमेज‑प्रोसेसिंग पाइपलाइन में फीड कर सकते हैं। + +## स्टेप 7: PDF पेज इमेजेज़ सहेजें (वैकल्पिक पोस्ट‑प्रोसेसिंग) + +यदि आपको केवल इमेजेज़ चाहिए और टेक्स्ट नहीं, तो आप `print(res.text)` लाइन को स्किप कर सकते हैं। इसके विपरीत, यदि आप टेक्स्ट को अलग `.txt` फ़ाइलों में स्टोर करना चाहते हैं, तो बस एक छोटा राइट‑आउट जोड़ें: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +यह छोटा जोड़ यह दर्शाता है कि **PDF पेज इमेजेज़ सहेजना** कितना आसान है, साथ ही निकाले गए कंटेंट को भी स्थायी बनाना। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ रखकर, यहाँ पूरा स्क्रिप्ट है जिसे आप `ocr_pdf.py` में कॉपी‑पेस्ट कर सकते हैं: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +इसे चलाएँ: + +```bash +python ocr_pdf.py +``` + +आपको प्रत्येक पेज के टेक्स्ट का कंसोल डम्प और PNG फ़ाइलों की एक श्रृंखला दिखनी चाहिए + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/hindi/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..f7de656df --- /dev/null +++ b/ocr/hindi/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-06-06 +description: Python का उपयोग करके OCR के लिए छवियों की पूर्व-प्रसंस्करण कैसे करें। + Otsu विधि से छवि को बाइनराइज़ करना, स्कैन किए गए दस्तावेज़ों को डेस्क्यू करना, और + जर्मन टेक्स्ट के लिए OCR की सटीकता सुधारना सीखें। +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: hi +og_description: Python में OCR के लिए छवियों की पूर्व-प्रसंस्करण कैसे करें। यह ट्यूटोरियल + Otsu का उपयोग करके छवि को बाइनराइज़ करना, स्कैन किए गए दस्तावेज़ों को डेस्क्यू करना, + और जर्मन छवियों के लिए OCR की सटीकता को सुधारने का तरीका दिखाता है। +og_title: OCR के लिए छवियों की पूर्व-प्रसंस्करण कैसे करें – पूर्ण पायथन गाइड +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: OCR के लिए छवियों को कैसे प्रीप्रोसेस करें – पूर्ण पायथन गाइड +url: /hi/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR के लिए इमेज प्रीप्रोसेस कैसे करें – पूर्ण Python गाइड + +क्या आपने कभी सोचा है **इमेज को OCR के लिए कैसे प्रीप्रोसेस करें** ताकि टेक्स्ट बिल्कुल स्पष्ट निकले? आप अकेले नहीं हैं। स्कैन किए हुए दस्तावेज़—विशेषकर शोरयुक्त जर्मन पृष्ठ—किसी भी OCR इंजन के लिए दुःस्वप्न बन सकते हैं। अच्छी खबर? कुछ स्मार्ट प्रीप्रोसेसिंग स्टेप्स एक धुंधली, धब्बेदार स्कैन को साफ़, मशीन‑रेडेबल इमेज में बदल सकते हैं। + +इस ट्यूटोरियल में हम एक व्यावहारिक उदाहरण के माध्यम से दिखाएंगे **इमेज को OCR के लिए कैसे प्रीप्रोसेस करें** Python का उपयोग करके। आप सीखेंगे **Otsu से इमेज को बाइनराइज़ करना**, **स्कैन किए हुए दस्तावेज़ों को कैसे डेस्क्यू करें**, और कुल मिलाकर **OCR की सटीकता कैसे बढ़ाएँ** जब आपको **जर्मन इमेज फ़ाइलों से टेक्स्ट निकालना** हो। कोई फालतू बातें नहीं, सिर्फ एक कार्यशील स्क्रिप्ट जिसे आप आज ही कॉपी‑पेस्ट कर सकते हैं। + +## What You’ll Need + +- **Python 3.9+** (कोई भी हालिया संस्करण चलेगा) +- एक OCR लाइब्रेरी जो `OcrEngine` क्लास प्रदान करती है – डेमो के लिए हम मानेंगे कि एक सामान्य `ocr` पैकेज है। इसे `pip install ocr-lib` से इंस्टॉल करें। +- एक शोरयुक्त जर्मन स्कैन (`noisy_german_scan.tif`) जिसे आप टेस्ट करना चाहते हैं। +- Python फ़ंक्शन की बुनियादी समझ (यदि आपने पहले `def` लिखा है, तो आप तैयार हैं)। + +> **Pro tip:** यदि आप कोई अलग OCR SDK (जैसे `pytesseract` के माध्यम से Tesseract) उपयोग कर रहे हैं, तो अवधारणाएँ वही रहती हैं—सिर्फ मेथड नामों को अनुकूलित करें। + +## Overview of the Solution + +1. **एक OCR इंजन इंस्टेंस बनाएं।** +2. **पहचान भाषा को जर्मन सेट करें।** +3. **एक कस्टम प्रीप्रोसेसिंग पाइपलाइन बनाएं** जिसमें डेस्क्यूइंग, डिनॉइज़िंग, बाइनराइज़ेशन (Otsu) और कंट्रास्ट स्ट्रेचिंग शामिल हों। +4. **पाइपलाइन को इंजन से जोड़ें** ताकि हर इमेज स्वचालित रूप से उस पर गुज़रें। +5. **शोरयुक्त जर्मन स्कैन पर OCR चलाएँ।** +6. **निकाले गए टेक्स्ट को प्रिंट करें** ताकि परिणाम की पुष्टि हो सके। + +नीचे हम प्रत्येक चरण को तोड़कर समझाते हैं, **क्यों** यह महत्वपूर्ण है, और आपको बिल्कुल वही कोड दिखाते हैं जिसकी आपको जरूरत है। + +![OCR के लिए इमेज प्रीप्रोसेस कैसे करें उदाहरण](image.png "OCR के लिए इमेज प्रीप्रोसेस कैसे करें उदाहरण") + +## Step 1: Create an OCR Engine Instance + +सबसे पहले—बिना इंजन के कुछ नहीं होता। `OcrEngine` ऑब्जेक्ट वह एंट्री पॉइंट है जो बाद की सभी प्रोसेसिंग को समन्वयित करता है। + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Why this matters:* इंजन को इनिशियलाइज़ करने से आंतरिक रिसोर्सेज (जैसे भाषा मॉडल) सेट होते हैं और आपको बाद में कस्टम पाइपलाइन जोड़ने के लिए एक साफ़ स्लेट मिलती है। + +## Step 2: Set the Recognition Language to German + +OCR की सटीकता भाषा‑निर्भर होती है। इंजन को जर्मन की अपेक्षा बताकर आप सही कैरेक्टर सेट और भाषा मॉडल को सक्रिय करते हैं। + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +यदि आप यह कदम छोड़ देते हैं, तो इंजन डिफ़ॉल्ट रूप से अंग्रेज़ी ले सकता है, जिससे umlauts (ä, ö, ü) और ß कैरेक्टर को गलत पहचान सकता है—जर्मन स्कैन के साथ अक्सर होने वाली समस्या। + +## Step 3: Build a Custom Preprocessing Pipeline + +यह **इमेज को OCR के लिए कैसे प्रीप्रोसेस करें** का मुख्य भाग है। हम चार ट्रांसफ़ॉर्मेशन को चेन करेंगे: + +| ट्रांसफ़ॉर्मेशन | क्या करता है | क्यों मदद करता है | +|----------------|--------------|-------------------| +| **Deskew** | इमेज को क्षैतिज (अधिकतम 5°) पर फिर से घुमाता है | स्कैन अक्सर पूरी तरह संरेखित नहीं होते; डेस्क्यूइंग उस झुकाव को हटाता है जो कैरेक्टर सेगमेंटेशन को भ्रमित करता है। | +| **Denoise** | रैंडम स्पॉट्स को कम करता है (strength 0.7) | शोर झूठी किनारों को बनाता है जिन्हें OCR इंजन कैरेक्टर समझ सकता है। | +| **Binarize (Otsu)** | Otsu मेथड से ब्लैक‑एंड‑व्हाइट में बदलता है | एक साफ़ बाइनरी इमेज फ़ोरग्राउंड (टेक्स्ट) और बैकग्राउंड के बीच तीव्र कंट्रास्ट देती है। | +| **Contrast Stretch** | डायनामिक रेंज को विस्तारित करता है | फीके स्ट्रोक्स की पठनीयता बढ़ाता है, विशेषकर पुराने दस्तावेज़ों पर। | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### How to Deskew Scanned Documents + +उपर्युक्त `deskew` कॉल सीधे **स्कैन किए हुए दस्तावेज़ों को कैसे डेस्क्यू करें** का उत्तर देती है। यह आंतरिक रूप से Hough ट्रांसफ़ॉर्म द्वारा प्रमुख टेक्स्ट लाइन एंगल का अनुमान लगाती है और इमेज को फिर से घुमाती है। यदि आपके दस्तावेज़ 5° से अधिक घुंमें हुए हैं, तो `max_angle` को बढ़ाएँ, लेकिन ओवर‑रोटेशन आर्टिफैक्ट से सावधान रहें। + +### Binarize Image Using Otsu + +`binarize(method="otsu")` लाइन सीधे **Otsu से इमेज को बाइनराइज़ कैसे करें** प्रश्न का उत्तर देती है। Otsu का एल्गोरिद्म एक थ्रेशोल्ड निकालता है जो intra‑class variance को न्यूनतम करता है, जो डार्क टेक्स्ट बनाम लाइट बैकग्राउंड वाले दस्तावेज़ों के लिए आदर्श है। + +## Step 4: Attach the Pipeline to the Engine + +अब हम OCR इंजन को बताते हैं कि हर आने वाली इमेज को हमने अभी बनाई हुई पाइपलाइन के माध्यम से प्रोसेस किया जाए। + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Why this matters:* पाइपलाइन को रजिस्टर किए बिना, इंजन कच्ची स्कैन को प्रोसेस करेगा और हमने जो भी सफ़ाई की है, उसे अनदेखा कर देगा। यह कदम **OCR की सटीकता कैसे बढ़ाएँ** को सुनिश्चित करता है, क्योंकि वही प्रीप्रोसेसिंग लगातार लागू होती है। + +## Step 5: Recognize Text from a Noisy German Scan + +अब सब कुछ एक साथ जोड़ते हैं। हम इंजन को शोरयुक्त जर्मन इमेज देते हैं और उसे काम करने देते हैं। + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +यदि आप प्रदर्शन के बारे में जिज्ञासु हैं, तो कॉल को टाइम कर सकते हैं: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Step 6: Output the Recognized Text + +अंत में, हम निकाले गए स्ट्रिंग को प्रिंट करते हैं। यह सीधे **जर्मन इमेज से टेक्स्ट निकालें** प्रश्न का उत्तर है। + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Expected Output + +मान लीजिए सैंपल स्कैन में वाक्य “Die schnelle braune Füchsin springt über den faulen Hund.” है, तो आपको कुछ इस तरह दिखना चाहिए: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +यदि आउटपुट में अभी भी गड़बड़ अक्षर दिखें, तो `denoise` स्ट्रेंथ को समायोजित करें या डेस्क्यूइंग के लिए `max_angle` बढ़ाएँ। + +## Common Pitfalls & How to Tackle Them + +- **भाषा मॉडल की कमी:** `set_recognition_language(Language.GERMAN)` को भूलने से अक्सर umlauts गायब रह जाते हैं। इस कॉल को दोबारा जाँचें। +- **ओवर‑डिनॉइज़िंग:** 0.9 से ऊपर की स्ट्रेंथ पतली स्ट्रोक्स को मिटा सकती है, विशेषकर पुराने फ़ॉन्ट्स में। अधिकांश मामलों में 0.5‑0.7 रखें। +- **गलत फ़ाइल फ़ॉर्मेट:** कुछ OCR इंजन मल्टी‑पेज TIFF को संभाल नहीं पाते। यदि आपके पास मल्टी‑पेज दस्तावेज़ है, तो पहले उसे सिंगल‑पेज फ़ाइलों में बाँटें। +- **पाइपलाइन क्रम:** दिखाया गया क्रम (डेस्क्यू → डिनॉइज़ → बाइनराइज़ → कंट्रास्ट) जानबूझकर है। बाइनराइज़ करने से पहले डिनॉइज़ करना जरूरी है; नहीं तो शोर स्थिर हो जाता है। + +## Extending the Pipeline (What’s Next?) + +अब आपके पास एक ठोस बेसलाइन है, आप आगे चाहेंगे: + +- **मॉर्फ़ोलॉजिकल ओपनिंग** जोड़ें ताकि छोटे ब्लॉब साफ़ हों (`.morph_open(kernel=3)`)। +- **भाषा मॉडल** को इंटीग्रेट करें पोस्ट‑प्रोसेसिंग करेक्शन के लिए (`ocr_engine.apply_spellcheck()`)। +- **बड़े डेटासेट** के लिए बैच प्रोसेसिंग को `concurrent.futures` से पैराललाइज़ करें। + +इन सभी को जोड़ने से **इमेज को OCR के लिए कैसे प्रीप्रोसेस करें** की मूल अवधारणा बनी रहती है, जबकि **OCR की सटीकता कैसे बढ़ाएँ** और भी बेहतर हो जाती है। + +## Conclusion + +हमने अभी-अभी **इमेज को OCR के लिए कैसे प्रीप्रोसेस करें** को शुरू से अंत तक कवर किया: एक इंजन बनाएं, जर्मन भाषा सेट करें, एक पाइपलाइन बनाएं जो **Otsu से इमेज को बाइनराइज़ करे**, **स्कैन किए हुए दस्तावेज़ों को कैसे डेस्क्यू करें**, और अंत में **जर्मन इमेज से टेक्स्ट निकालें** उच्च विश्वसनीयता के साथ। ऊपर बताए गए छह चरणों का पालन करके आप पहचान की गुणवत्ता में स्पष्ट सुधार देखेंगे—अब और अनंत मैन्युअल सुधार नहीं। + +स्क्रिप्ट को अपने स्कैन के साथ चलाएँ, पैरामीटरों के साथ प्रयोग करें, और परिणाम खुद बोलें। किसी विशेष प्रीप्रोसेसिंग ट्यूनिंग के बारे में सवाल हैं? टिप्पणी करें, हम साथ‑साथ गहराई में जाएंगे। + +Happy coding, and may your OCR be ever accurate! + + +## What Should You Learn Next? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण कर सकें। + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ C# में इमेज टेक्स्ट निकालें](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [OCR इमेज रिकग्निशन में थ्रेशोल्ड वैल्यू कैसे सेट करें](/ocr/english/net/ocr-settings/set-threshold-value/) +- [इमेज OCR – OCR इमेज रिकग्निशन में इमेज पर OCR कैसे करें](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..0dabcdc80 --- /dev/null +++ b/ocr/hindi/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-06 +description: Python के साथ OCR PNG इमेज – सीखें कैसे इमेज से टेक्स्ट निकालें, एक Python + OCR उदाहरण चलाएँ और यहाँ तक कि प्राचीन ग्रीक टेक्स्ट भी आसानी से पढ़ें। +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: hi +og_description: Python में OCR PNG इमेज की व्याख्या। यह गाइड दिखाता है कि कैसे इमेज + से टेक्स्ट निकाला जाए, Python OCR उदाहरण चलाया जाए और आसानी से प्राचीन ग्रीक पढ़ा + जाए। +og_title: Python में OCR PNG इमेज – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python में PNG इमेज का OCR – पूर्ण चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में OCR PNG इमेज – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपने कभी सोचा है कि **OCR PNG image** फ़ाइलों को सीधे Python स्क्रिप्ट से कैसे किया जाए? शायद आपके पास स्कैन किए हुए प्राचीन पांडुलिपियों की एक फ़ोल्डर है और आपको **extract text from image** फ़ाइलों को मैन्युअल रूप से टाइप किए बिना निकालना है। अच्छी खबर यह है कि आपको कंप्यूटर विज़न में पीएचडी की जरूरत नहीं है—बस कुछ लाइनों का कोड और सही लाइब्रेरी, और आप सेकंडों में प्राचीन ग्रीक पढ़ पाएँगे। + +इस ट्यूटोरियल में हम एक **python OCR example** के माध्यम से चलेंगे जो PNG से टेक्स्ट पहचानता है, भाषा को Greek polytonic पर सेट करता है, और परिणाम प्रिंट करता है। अंत तक आप बिल्कुल जानेंगे कि कैसे **recognize image text** किया जाता है, सामान्य समस्याओं का समाधान करें, और स्क्रिप्ट को अन्य भाषाओं या इमेज फ़ॉर्मेट्स के लिए अनुकूलित किया जा सकता है। + +## आप क्या सीखेंगे + +- Python OCR लाइब्रेरी (pytesseract + Tesseract OCR) स्थापित और कॉन्फ़िगर करें +- एक OCR इंजन इंस्टेंस बनाएं और PNG फ़ाइल लोड करें +- पहचान भाषा को Greek polytonic पर सेट करें ताकि आप **read ancient greek** कर सकें +- पहचाने गए टेक्स्ट को आउटपुट करें और सामान्य समस्याओं का समाधान करें +- स्क्रिप्ट को कई PNGs को बैच‑प्रोसेस करने या किसी अन्य भाषा में स्विच करने के लिए विस्तारित करें + +### आवश्यकताएँ + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | आधुनिक सिंटैक्स और टाइप हिंट्स | +| `pytesseract` package | Tesseract इंजन के चारों ओर का हल्का रैपर | +| Tesseract OCR binaries (≥ 5.0) | वास्तविक इंजन जो भारी काम करता है | +| Greek language data (`grc.traineddata`) | **read ancient greek** के लिए सही रूप से आवश्यक | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | हमारा लक्ष्य **ocr png image** डेमो के लिए | + +आप Python पक्ष को इस प्रकार स्थापित कर सकते हैं: + +```bash +pip install pytesseract Pillow +``` + +और Ubuntu/macOS पर आप स्वयं इंजन जोड़ेंगे: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Greek polytonic प्रशिक्षित डेटा डाउनलोड करना न भूलें: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +* (पाथ अलग हो सकता है; यदि आवश्यक हो तो `TESSDATA_PREFIX` समायोजित करें।)* + +## OCR PNG इमेज: इंजन इंस्टेंस बनाएं + +पहली चीज़ जो हमें चाहिए वह एक ऑब्जेक्ट है जो Tesseract से बात करता है। `pytesseract` में इंजन को मॉड्यूल‑लेवल फ़ंक्शन्स के माध्यम से एक्सेस किया जाता है, लेकिन स्पष्टता के लिए हम इसे एक छोटी क्लास में रैप करेंगे। यह मूल स्निपेट में देखे गए “engine” कॉन्सेप्ट को दर्शाता है। + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**क्यों रैप करें?** +- सार्वजनिक API को उसी स्निपेट जैसा रखता है जिससे आप शुरू हुए थे, जिससे माइग्रेशन आसान हो जाता है। +- मुख्य प्रवाह को छुए बिना बाद में लॉगिंग या एरर हैंडलिंग जोड़ने की अनुमति देता है। +- अच्छा OOP अभ्यास दर्शाता है—जो वरिष्ठ डेवलपर्स सराहते हैं। + +## इमेज से टेक्स्ट निकालें: भाषा को Greek Polytonic पर सेट करें + +अब जब हमारे पास इंजन है, हमें उसे बताना है कि कौन सी भाषा की अपेक्षा करनी है। Greek polytonic में ऐसे डायाक्रिटिक्स होते हैं जो मानक “greek” डेटा में नहीं होते, इसलिए हम Tesseract को `grc` प्रशिक्षित फ़ाइल की ओर इंगित करते हैं। + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +यदि आप कभी किसी अन्य भाषा में **extract text from image** फ़ाइलें निकालना चाहते हैं, तो बस `"grc"` को `"eng"` (अंग्रेज़ी), `"fra"` (फ़्रेंच) आदि से बदलें। वही लाइन किसी भी स्थापित भाषा के लिए काम करती है। + +## इमेज टेक्स्ट पहचानें: PNG पर OCR चलाएँ + +भाषा सेट करने के बाद, हम PNG को इंजन में फीड करते हैं। मूल उदाहरण में हार्ड‑कोडेड पाथ उपयोग किया गया था; हम इसे `Path` ऑब्जेक्ट्स का उपयोग करके थोड़ा अधिक लचीला बनाएँगे। + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**टिप्स और किनारे के केस** + +- **File not found** – कॉल को `try/except FileNotFoundError` में रैप करें ताकि एक मित्रवत संदेश दिया जा सके। +- **Low‑resolution PNG** – OCR से पहले Pillow के साथ प्री‑प्रोसेसिंग (जैसे, रिसाइज़िंग, बाइनराइज़ेशन) पर विचार करें। +- **Non‑Greek text** – Tesseract अभी भी डिकोड करने की कोशिश करेगा, लेकिन सटीकता तेज़ी से घटती है। हमेशा भाषा से मेल रखें। + +## पहचाने गए टेक्स्ट को आउटपुट करें + +अंत में, हम परिणाम को प्रिंट करते हैं। वास्तविक प्रोजेक्ट में आप इसे डेटाबेस, CSV, या यहाँ तक कि ट्रांसलेशन पाइपलाइन में भी फीड कर सकते हैं। + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +जब आप स्क्रिप्ट को प्राचीन ग्रीक शिलालेख की स्पष्ट स्कैन पर चलाते हैं, तो आपको कुछ इस तरह दिखना चाहिए: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +यदि आउटपुट गड़बड़ दिखता है, तो दोबारा जांचें कि **greek.traineddata** फ़ाइल सही फ़ोल्डर में है और PNG बहुत शोरयुक्त नहीं है। + +## पूर्ण कार्यशील उदाहरण (सभी चरण एक स्क्रिप्ट में) + +नीचे पूर्ण, तैयार‑चलाने योग्य प्रोग्राम है। इसे `ocr_greek.py` के रूप में सहेजें और `python ocr_greek.py` चलाएँ। + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**अपेक्षित आउटपुट** (संक्षिप्त रूप में): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +यदि आप सही ग्रीक अक्षर देखते हैं, तो बधाई—आपने Python में सफलतापूर्वक **ocr png image** ऑपरेशन किया है! + +## सामान्य प्रश्न और प्रो टिप्स + +### शोरयुक्त PNG पर सटीकता कैसे बढ़ाएँ? + +- इमेज को ग्रेस्केल में बदलें: `img = img.convert('L')` +- बाइनरी थ्रेशोल्ड लागू करें: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` के साथ अपस्केल करें + +ये कदम अक्सर एक **recognize image text** दुःस्वप्न को साफ़ परिणाम में बदल देते हैं। + +### क्या मैं PNGs के पूरे फ़ोल्डर को प्रोसेस कर सकता हूँ? + +बिल्कुल। `recognize_image` कॉल को `Path.glob("*.png")` पर `for` लूप में रैप करें। प्रत्येक परिणाम को डिक्शनरी में रखें या बाद में विश्लेषण के लिए CSV में लिखें। + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### यदि मुझे केवल संख्याएँ निकालनी हों तो क्या करें? + +`image_to_string` को एक कस्टम **config** स्ट्रिंग पास करें: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +इस तरह आप **extract text from image** फ़ाइलें निकाल सकते हैं जिनमें टेबल, सीरियल नंबर, या टाइमस्टैम्प होते हैं। + +### क्या कॉन्फिडेंस स्कोर प्राप्त करने का तरीका है? + +हाँ—`pytesseract.image_to_data` का उपयोग करें जो प्रत्येक शब्द के कॉन्फिडेंस के साथ TSV लौटाता है। आप अंतिम स्ट्रिंग बनाने से पहले कम‑कॉन्फिडेंस टोकन को फ़िल्टर कर सकते हैं। + +## ट्यूटोरियल का विस्तार + +अब जब आप बुनियादी बातों में निपुण हो गए हैं, तो इन संबंधित विषयों को देखें: + +- **Batch OCR with multiprocessing** – PNGs के बड़े कॉर्पोरा को तेज़ करने के लिए। +- **Hybrid OCR + NLP pipelines** – निकाले गए प्राचीन ग्रीक को स्वचालित रूप से आधुनिक अंग्रेज़ी में अनुवाद करने के लिए। +- **Alternative engines** – विशिष्ट उपयोग‑केस के लिए `easyocr` या `opencv`‑आधारित विधियों को आज़माएँ। +- **Cloud OCR services** – सर्वरलेस स्केलिंग के लिए Google Vision, Azure Computer Vision, या AWS Textract। + +इनमें से प्रत्येक हमारे द्वारा कवर किए गए मूल **python ocr example** पर आधारित है, इसलिए आप गहराई में जाने में सहज महसूस करेंगे। + +## निष्कर्ष + +हमने एक सरल स्निपेट को Python में एक मजबूत **ocr png image** वर्कफ़्लो में बदल दिया है। `OcrEngine` बनाकर, भाषा को Greek polytonic पर सेट करके, PNG फीड करके, और परिणाम प्रिंट करके, अब आप जानते हैं कि **extract text from image** फ़ाइलें, **recognize image text** कैसे करें, और यहाँ तक कि **read ancient greek** भी। + +## अब आपको क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में निपुण बनने और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों की खोज करने में मदद करेंगे। + +- [Aspose OCR के साथ इमेज से टेक्स्ट निकालें – चरण‑दर‑चरण गाइड](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [OCR इमेज पहचान में थ्रेशोल्ड वैल्यू कैसे सेट करें](/ocr/english/net/ocr-settings/set-threshold-value/) +- [एकाधिक भाषाओं के लिए Aspose OCR के साथ टेक्स्ट इमेज पहचानें](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/hindi/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..bc1fba0e0 --- /dev/null +++ b/ocr/hindi/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR ट्यूटोरियल जो दिखाता है कि कैसे इमेज टेक्स्ट को पहचानें, हाई‑रिज़ॉल्यूशन + OCR करें और GPU‑त्वरित OCR का उपयोग करके स्पेनिश टेक्स्ट निकालें। +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: hi +og_description: Python OCR ट्यूटोरियल जो आपको इमेज टेक्स्ट की पहचान, हाई‑रिज़ॉल्यूशन + OCR, और GPU एक्सेलेरेशन के साथ स्पेनिश टेक्स्ट निकालने के माध्यम से ले जाता है। +og_title: Python OCR ट्यूटोरियल – GPU‑त्वरित टेक्स्ट पहचान +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR ट्यूटोरियल – GPU एक्सेलेरेशन के साथ छवि टेक्स्ट को पहचानें +url: /hi/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Recognize Image Text with GPU Acceleration + +क्या आपने कभी सोचा है कि **छवि टेक्स्ट को पहचानने** के लिए Python स्क्रिप्ट में सेटिंग्स को कई घंटे तक ट्यून किए बिना कैसे किया जाए? आप अकेले नहीं हैं। इस **python ocr tutorial** में हम आपको एक साफ़, एंड‑टू‑एंड तरीका दिखाएंगे जिससे आप हाई‑रेज़ोल्यूशन तस्वीर से स्पेनिश टेक्स्ट निकाल सकें, और साथ ही GPU एक्सेलेरेशन जोड़ेंगे ताकि प्रक्रिया तेज़ी से चले। + +इसे एक तेज़ कॉफ़ी‑ब्रेक डेमो की तरह सोचें जिसे बाद में आप प्रोडक्शन‑ग्रेड पाइपलाइन में बदल सकते हैं। इस गाइड के अंत तक आपके पास एक चलने योग्य प्रोग्राम होगा जो **हाई रेज़ोल्यूशन OCR** करता है, CUDA‑सक्षम GPU का उपयोग करता है, और आपको बिल्कुल वही स्पेनिश अक्षर देता है जिसकी आपको ज़रूरत है। + +## What You’ll Learn + +- GPU एक्सेलेरेशन को सपोर्ट करने वाली आधुनिक OCR लाइब्रेरी को कैसे इंस्टॉल और इम्पोर्ट करें। +- OCR इंजन इंस्टेंस बनाना और इसे स्पेनिश में **छवि टेक्स्ट को पहचानने** के लिए सेट करना। +- हाई‑रेज़ोल्यूशन फ़ाइलों पर बड़े स्पीड बूस्ट के लिए **gpu accelerated OCR** को सक्षम करना। +- CUDA ड्राइवर की कमी या CPU फ़ॉलबैक जैसी एज केस को कैसे हैंडल करें। +- शोरयुक्त स्कैन से **स्पेनिश टेक्स्ट निकालने** के समय एक्यूरेसी बढ़ाने के टिप्स। + +### Prerequisites + +- Python 3.9+ (कोड 3.10 और उससे ऊपर भी काम करता है)। +- CUDA‑संगत GPU (वैकल्पिक लेकिन अत्यधिक अनुशंसित)। +- pip और वर्चुअल एनवायरनमेंट्स की बेसिक समझ। + +यदि इनमें से कोई भी चीज़ आपके पास नहीं है, तो ट्यूटोरियल फिर भी चलेगा—सिर्फ GPU स्टेप को स्किप कर दें और लाइब्रेरी स्वचालित रूप से CPU पर फ़ॉलबैक कर लेगी। + +--- + +## Python OCR Tutorial: Install the Required Packages + +सबसे पहले, हमें एक ठोस OCR इंजन चाहिए। इस ट्यूटोरियल के लिए हम ओपन‑सोर्स **`easyocr`** पैकेज का उपयोग करेंगे, जो संगत डिवाइस मिलने पर बिल्ट‑इन GPU सपोर्ट के साथ आता है। + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** यदि आपके पास पहले से PyTorch इंस्टॉल है, तो सुनिश्चित करें कि वह आपके CUDA संस्करण से मेल खाता है (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`)। संस्करणों का बेमेल “GPU not found” त्रुटियों का आम कारण है। + +--- + +## Step 1: Create an OCR Engine Instance + +अब हम इंजन को स्पिन अप करते हैं। EasyOCR अपनी मुख्य क्लास को `Reader` कहता है। कंस्ट्रक्टर भाषा कोड की लिस्ट लेता है; हम स्पेनिश के लिए `"es"` पास करेंगे। + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* भाषा को पहले से घोषित करके, इंजन केवल आवश्यक न्यूरल नेटवर्क वेट्स लोड करता है, जिससे मेमोरी बचती है और इन्फरेंस तेज़ होता है—विशेषकर जब आप बाद में **हाई रेज़ोल्यूशन OCR** कर रहे हों। + +--- + +## Step 2: Prepare a High‑Resolution Image + +हाई‑रेज़ोल्यूशन इमेज मॉडल को अधिक पिक्सेल देती है, जिससे आमतौर पर कैरेक्टर रिकग्निशन बेहतर होता है। मान लीजिए आपके पास `high_res_spanish.png` नाम की फ़ाइल `samples` फ़ोल्डर में मौजूद है। + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +यदि आपके पास हाई‑रेज़ोल्यूशन सैंपल नहीं है, तो आप Unsplash से मुफ्त में डाउनलोड कर सकते हैं या Pillow से सिंथेटिक इमेज बना सकते हैं। सबसे अच्छा परिणाम पाने के लिए DPI को 300 से ऊपर रखें। + +--- + +## Step 3: Enable GPU Acceleration (Optional but Recommended) + +EasyOCR `gpu=True` सेट करने पर GPU का उपयोग करने की कोशिश करता है। हालांकि, मल्टी‑GPU सेटअप में यह सुनिश्चित करना अच्छा अभ्यास है कि डिवाइस वास्तव में उपयोग हो रहा है या नहीं। + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* यदि स्क्रिप्ट चुपचाप CPU पर फ़ॉलबैक हो जाती है, तो आप आश्चर्य करेंगे कि 5‑सेकंड का ऑपरेशन अचानक 30 सेकंड क्यों ले रहा है। यह छोटा चेक व्यवहार को स्पष्ट बनाता है और आपके **gpu accelerated OCR** पाइपलाइन को प्रेडिक्टेबल रखता है। + +--- + +## Step 4: Perform High‑Resolution OCR and Recognize Image Text + +अब मज़ेदार हिस्सा—वास्तव में टेक्स्ट पढ़ना। EasyOCR की `readtext` मेथड ट्यूपल की लिस्ट रिटर्न करती है जिसमें बाउंडिंग बॉक्स, पहचाना गया स्ट्रिंग, और कॉन्फिडेंस स्कोर होता है। + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +यदि आपको कोऑर्डिनेट्स के बिना केवल रॉ स्ट्रिंग चाहिए, तो `detail=0` सेट करें। अधिकांश **recognize image text** उपयोग मामलों के लिए डिफ़ॉल्ट (`detail=1`) पर्याप्त कॉन्टेक्स्ट देता है जिससे बाद में पोस्ट‑प्रोसेसिंग आसान हो जाती है। + +--- + +## Step 5: Extract Spanish Text and Clean the Output + +क्योंकि हमने EasyOCR को स्पेनिश के लिए कहा है, रिटर्न किए गए स्ट्रिंग्स पहले से ही उस भाषा में हैं। फिर भी आप उन्हें जोड़ना, व्हाइटस्पेस हटाना, या लो‑कॉन्फिडेंस डिटेक्शन को फ़िल्टर करना चाह सकते हैं। + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** आप थ्रेशोल्ड को कम कर सकते हैं (शोर का जोखिम बढ़ता है) या इमेज को प्री‑प्रोसेस कर सकते हैं (कॉन्ट्रास्ट बढ़ाएँ, बाइनराइज़ करें, या डेस्क्यू करें)। ये ट्रिक्स स्कैन किए गए दस्तावेज़ों पर **हाई रेज़ोल्यूशन OCR** करते समय आम हैं। + +--- + +## Step 6: Handling Edge Cases and Performance Tweaks + +सबसे बेहतरीन मॉडल भी कुछ परिस्थितियों में फँस जाते हैं। नीचे कुछ त्वरित फ़िक्स हैं जिन्हें आप स्क्रिप्ट में पेस्ट कर सकते हैं। + +### 6.1 Fallback When No GPU Is Present + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling Very Large Images + +यदि आपकी इमेज 4000 × 4000 px से बड़ी है, तो GPU मेमोरी खत्म हो सकती है। DPI को बनाए रखते हुए प्रोपोर्शनली डाउन‑सैंपल करें: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +ये स्निपेट्स स्क्रिप्ट को मजबूत बनाते हैं, चाहे आप वर्कस्टेशन पर चलाएँ या एक साधारण लैपटॉप पर। + +--- + +## Full Working Example + +सब कुछ एक साथ मिलाकर, यहाँ पूरा स्क्रिप्ट है जिसे आप कॉपी‑पेस्ट करके तुरंत चला सकते हैं: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Expected output (example):** + + + +## What Should You Learn Next? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण कर सकें। + +- [छवि से टेक्स्ट निकालें Aspose OCR के साथ – चरण‑दर‑चरण गाइड](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose.OCR का उपयोग करके भाषा के साथ इमेज टेक्स्ट OCR कैसे करें](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR में OCR टेक्स्ट रिकग्निशन के लिए पेज रेक्टेंगल्स कैसे तैयार करें](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/hindi/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..c7a05a9fb --- /dev/null +++ b/ocr/hindi/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR इंजन का उपयोग करके छवि से टेक्स्ट को पहचानें। मिनटों में क्लाउड + प्रोसेसिंग के साथ OCR इंजन को कॉन्फ़िगर करना और छवि से टेक्स्ट निकालना सीखें। +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: hi +og_description: Python OCR इंजन के साथ छवि से टेक्स्ट पहचानें। यह गाइड दिखाता है कि + OCR इंजन को Python में कैसे कॉन्फ़िगर करें और छवि से टेक्स्ट को प्रभावी ढंग से निकालें। +og_title: Python में छवि से टेक्स्ट पहचानें – पूर्ण सेटअप ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python में छवि से टेक्स्ट पहचानें – पूर्ण OCR इंजन सेटअप गाइड +url: /hi/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेज से टेक्स्ट को पहचानें Python में – पूर्ण सेटअप ट्यूटोरियल + +क्या आपने कभी सोचा है कि सिर्फ कुछ पंक्तियों के Python कोड से **recognize text from image** कैसे किया जाए? आप अकेले नहीं हैं। चाहे आप रसीद‑स्कैनर, दस्तावेज़ डिजिटाइज़र, या एक साधा शौकिया प्रोजेक्ट बना रहे हों, इमेज से टेक्स्ट निकालने की क्षमता एक ऐसी कौशल है जो जल्दी ही लाभ देता है। + +इस ट्यूटोरियल में हम पूरी प्रक्रिया को चरण‑दर‑चरण देखेंगे—**configure OCR engine python** शैली की सेटअप से शुरू करके, क्लाउड ऑथेंटिकेशन तक, और अंत में आपको दिखाएंगे कि कैसे **extract text from image** को विश्वसनीय परिणाम के साथ किया जाए। कोई जादू नहीं, सिर्फ स्पष्ट कदम जिन्हें आप आज ही कॉपी‑पेस्ट करके चला सकते हैं। + +## आप क्या सीखेंगे + +- आवश्यक OCR लाइब्रेरी को कैसे इंस्टॉल और इम्पोर्ट करें। +- क्लाउड प्रोसेसिंग के लिए **configure OCR engine python** के सटीक कमांड। +- एक पूर्ण, चलाने योग्य स्क्रिप्ट जो **recognize text from image** करती है और आउटपुट प्रिंट करती है। +- सामान्य समस्याओं जैसे गायब API कीज़ या असमर्थित इमेज फ़ॉर्मेट को संभालने के टिप्स। +- बैच प्रोसेसिंग और लोकल फ़ॉलबैक जैसी उन्नत विचार। + +### पूर्वापेक्षाएँ + +- आपके मशीन पर Python 3.8+ स्थापित हो। +- इंटरनेट कनेक्शन (उदाहरण में क्लाउड‑आधारित OCR सेवा का उपयोग किया गया है)। +- OCR प्रदाता से वैध API की (आप देखेंगे कि इसे कहाँ डालना है)। + +यदि आपके पास ये हैं, तो चलिए शुरू करते हैं—कोई फालतू नहीं, सिर्फ एक व्यावहारिक गाइड जो काम करता है। + +--- + +## चरण 1: OCR लाइब्रेरी इंस्टॉल करें और इम्पोर्ट करें + +**configure OCR engine python** करने से पहले, आपको उस लाइब्रेरी की जरूरत है जो क्लाउड सेवा से बात करती है। हमारे उदाहरण में हम एक काल्पनिक लेकिन प्रतिनिधि पैकेज `ocrcloud` का उपयोग करेंगे। इसे उस वास्तविक पैकेज से बदलें जो आप उपयोग कर रहे हैं (जैसे, `easyocr`, `google-cloud-vision`, आदि)। + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Why this matters:** क्लास को इम्पोर्ट करने से आपको `use_cloud()` और `set_api_key()` जैसे मेथड्स तक पहुंच मिलती है। इम्पोर्ट नहीं किया तो स्क्रिप्ट का बाकी हिस्सा `NameError` देगा। + +*Pro tip:* भविष्य में अनपेक्षित ब्रेकिंग बदलावों से बचने के लिए अपने `requirements.txt` में संस्करण पिन करें (`ocrcloud==2.1.0`)। + +## चरण 2: क्लाउड मोड के लिए **configure OCR engine python** बनाएं और सेट करें + +अब हम वास्तव में **configure OCR engine python** करेंगे। इंजन डिफ़ॉल्ट रूप से लोकल मोड में शुरू होता है; क्लाउड मोड में स्विच करने से आप भारी इमेज विश्लेषण को शक्तिशाली सर्वरों पर ऑफलोड कर सकते हैं। + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explanation:** +- `OcrEngine()` एक नया इंजन ऑब्जेक्ट बनाता है—इसे अपने खाली कैनवास की तरह समझें। +- `use_cloud(True)` एक स्विच को बदलता है, इंजन को इमेज को HTTPS के माध्यम से भेजने को कहता है बजाय स्थानीय रूप से प्रोसेस करने के। यह जटिल फ़ॉन्ट्स या कम रिज़ॉल्यूशन फ़ोटो पर उच्च‑सटीकता परिणामों के लिए महत्वपूर्ण है। + +## चरण 3: अपने क्लाउड API की के साथ ऑथेंटिकेट करें + +अधिकांश क्लाउड OCR सेवाओं को API की की आवश्यकता होती है। यह चरण दिखाता है कि क्रेडेंशियल को सुरक्षित रूप से कैसे इंजेक्ट किया जाए। + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Security note:** सार्वजनिक रेपो में की को कभी हार्ड‑कोड न करें। प्रोडक्शन में आप इसे एक environment variable से प्राप्त करेंगे: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## चरण 4: **recognize text from image** – प्रोसेसिंग के लिए रिमोट इमेज भेजें + +इंजन कॉन्फ़िगर होने के बाद, हम अंततः **recognize text from image** कर सकते हैं। मेथड `recognize_image()` एक पाथ या URL लेता है और निकाले गए टेक्स्ट वाले ऑब्जेक्ट को रिटर्न करता है। + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**What happens under the hood?** +इमेज बाइट्स प्रोवाइडर के एंडपॉइंट पर अपलोड होते हैं, एक डीप‑लर्निंग मॉडल द्वारा प्रोसेस किए जाते हैं, और प्लेन‑टेक्स्ट परिणाम वापस स्ट्रीम किया जाता है। यदि इमेज बड़ी है, तो सेवा स्वचालित रूप से डाउन्स्केल कर सकती है ताकि जॉब तेज़ हो सके। + +## चरण 5: **extract text from image** परिणाम आउटपुट करें + +अब OCR सेवा ने अपना काम कर लिया है, हम बस टेक्स्ट को प्रिंट करेंगे। वास्तविक एप्लिकेशन में आप इसे डेटाबेस में स्टोर कर सकते हैं या किसी अन्य फ़ंक्शन को पास कर सकते हैं। + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Expected output:** (उदाहरण) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +यदि आउटपुट गड़बड़ दिखता है, तो दोबारा जांचें कि इमेज स्पष्ट है और आपने सही भाषा मॉडल चुना है (कई सेवाएँ आपको `engine.set_language("en")` निर्दिष्ट करने देती हैं)। + +## एज केस और सामान्य समस्याओं को संभालना + +### 1. गायब या अमान्य API की + +यदि आप ऑथेंटिकेशन एरर देखते हैं, तो सुनिश्चित करें: +- की सक्रिय है और समाप्त नहीं हुई है। +- यह environment से सही ढंग से पढ़ी जा रही है। +- आपका नेटवर्क आउटबाउंड HTTPS ट्रैफ़िक की अनुमति देता है। + +### 2. असमर्थित इमेज फ़ॉर्मेट + +अधिकांश OCR API JPEG, PNG, और PDF को स्वीकार करते हैं। BMP या TIFF आज़माने पर “format not supported” प्रतिक्रिया मिल सकती है। आवश्यकता होने पर Pillow से कन्वर्ट करें: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. रेट लिमिट्स + +क्लाउड सेवाएँ अक्सर प्रति मिनट अनुरोधों की सीमा लगाती हैं। यदि आप सीमा तक पहुँचते हैं, तो एक्सपोनेंशियल बैक‑ऑफ़ लागू करें: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. लोकल OCR पर फ़ॉलबैक + +यदि क्लाउड डाउन है, तो आप वापस स्विच कर सकते हैं: + +```python +engine.use_cloud(False) # revert to local mode +``` + +फ़ॉलबैक होने से आपका ऐप लचीला रहता है। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ मिलाकर, यहाँ एक स्क्रिप्ट है जिसे आप अभी चला सकते हैं (सिर्फ प्लेसहोल्डर वैल्यूज़ को बदलें)। + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**इसे चलाएँ:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +आपको कंसोल में निकाला गया टेक्स्ट प्रिंट होता दिखेगा, जो पुष्टि करता है कि आपने सफलतापूर्वक **recognize text from image** और **extract text from image** को एक सही **configure OCR engine python** वर्कफ़्लो का उपयोग करके किया है। + +## निष्कर्ष + +हमने अभी एक पूर्ण, एंड‑टू‑एंड प्रक्रिया को देखा है जो आपको Python में **recognize text from image** करने देती है, लाइब्रेरी इंस्टॉल करने से लेकर क्लाउड सेवा को ऑथेंटिकेट करने और अंत में एक ही फ़ंक्शन कॉल से **extract text from image** करने तक। सही तरीके से **configure OCR engine python** करके आप लचीलापन (क्लाउड बनाम लोकल) और विश्वसनीयता (उचित एरर हैंडलिंग) दोनों प्राप्त करते हैं। + +अगला क्या? रसीदों के फ़ोल्डर को बैच में प्रोसेस करने की कोशिश करें, भाषा डिटेक्शन जोड़ें, या इनपुट के रूप में PDFs के साथ प्रयोग करें। बुनियादी चीज़ें सीखने के बाद संभावनाएँ असीमित हैं। + +कोडिंग का आनंद लें, और टिप्पणी में कोई भी सवाल पूछने में संकोच न करें—साथ मिलकर सीखने से बेहतर कुछ नहीं! + +## अब आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर करने में मदद करती हैं। + +- [Aspose OCR के साथ इमेज से टेक्स्ट निकालें – चरण‑दर‑चरण गाइड](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [इमेज से टेक्स्ट निकालें – Aspose.OCR के साथ लाइन पहचानें](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [OCR में रेक्टेंगल तैयार करके इमेज से टेक्स्ट निकालना](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..037c0ffaf --- /dev/null +++ b/ocr/hindi/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Python का उपयोग करके छवि पर OCR चलाएँ और विश्वास स्कोर देखें। सीखें कि + कम‑विश्वास वाले शब्दों को कैसे फ़िल्टर करें, थ्रेशोल्ड सेट करें, और किनारी मामलों + को कैसे संभालें। +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: hi +og_description: Python में छवि पर OCR चलाएँ, विश्वास स्तरों की जाँच करें, और कम‑विश्वास + वाले शब्दों को फ़िल्टर करें। यह ट्यूटोरियल आपको एक पूर्ण, चलाने योग्य उदाहरण के + माध्यम से ले जाता है। +og_title: Python के साथ छवि पर OCR चलाएँ – पूर्ण गाइड +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Python के साथ छवि पर OCR चलाएँ – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python के साथ इमेज पर OCR चलाएँ – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको कभी **run OCR on image** फ़ाइलों को चलाने की ज़रूरत पड़ी है लेकिन यह नहीं पता था कि उनसे विश्वसनीय टेक्स्ट कैसे प्राप्त करें? आप अकेले नहीं हैं—कई डेवलपर्स इसी समस्या का सामना करते हैं जब निकाले गए शब्द अस्थिर लगते हैं और confidence स्कोर रहस्य बन जाता है। + +इस गाइड में हम सीधे एक कार्यशील समाधान में डुबकी लगाएंगे: आप देखेंगे कि **run OCR on image** कैसे किया जाता है, समग्र confidence कैसे पढ़ा जाता है, और किसी भी low‑confidence शब्द को कैसे निकाला जाए जिसे मैन्युअल समीक्षा की आवश्यकता हो सकती है। अंत तक आपके पास एक पुन: उपयोग योग्य स्क्रिप्ट होगी, आप समझेंगे कि प्रत्येक पंक्ति क्यों महत्वपूर्ण है, और अपने प्रोजेक्ट्स के लिए confidence थ्रेशोल्ड को कैसे समायोजित किया जाए। + +## इस ट्यूटोरियल में क्या कवर किया गया है + +हम पूरे वर्कफ़्लो को चरण‑दर‑चरण देखेंगे—इमेज लोड करने से लेकर उन शब्दों की साफ़ रिपोर्ट प्रिंट करने तक जो 80 % confidence सीमा से नीचे गिरते हैं। इस दौरान हम चर्चा करेंगे: + +* एक ठोस OCR इंजन चुनना (हम **EasyOCR**, एक लोकप्रिय Python OCR लाइब्रेरी का उपयोग करेंगे) +* `confidence` एट्रिब्यूट की व्याख्या करना जो हर OCR परिणाम लौटाता है +* कस्टम **OCR confidence threshold** के साथ शब्दों को फ़िल्टर करना +* बैच प्रोसेसिंग या **pytesseract** जैसे वैकल्पिक इंजनों के लिए स्क्रिप्ट को विस्तारित करना + +कोई पूर्व OCR अनुभव आवश्यक नहीं है, बस Python की बुनियादी समझ और एक कार्यशील वातावरण (Python 3.9+ की सिफारिश) चाहिए। + +धुंधली स्क्रीनशॉट्स को साफ़, खोजने योग्य टेक्स्ट में बदलने के लिए तैयार हैं? चलिए शुरू करते हैं। + +--- + +## ## Python के साथ इमेज पर OCR कैसे चलाएँ + +ट्यूटोरियल का मुख्य भाग एक तीन‑स्टेप स्निपेट है जो आपने पहले देखा कोड को प्रतिबिंबित करता है। नीचे हम प्रत्येक पंक्ति को तोड़ेंगे, कारण समझाएंगे, और फिर आपको एक पूर्ण, कॉपी‑एंड‑पेस्ट‑तैयार स्क्रिप्ट देंगे। + +### चरण 1: OCR इंजन स्थापित और इम्पोर्ट करें + +सबसे पहले, सुनिश्चित करें कि OCR लाइब्रेरी उपलब्ध है। **EasyOCR** कई भाषाओं के लिए तुरंत काम करता है और आपको प्रत्येक शब्द के लिए confidence स्कोर देता है। + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Why EasyOCR?* यह एक डीप‑लर्निंग मॉडल को बंडल करता है जो विविध डेटासेट पर प्रशिक्षित है, इसलिए आप आमतौर पर पुराने Tesseract इंजन की तुलना में उच्च confidence मान प्राप्त करते हैं, विशेषकर मिश्रित‑गुणवत्ता वाली इमेज पर। + +> **Pro tip:** यदि आप सीमित वातावरण (जैसे, एक छोटा Docker कंटेनर) में हैं, तो `pytesseract` हल्का हो सकता है, लेकिन आप EasyOCR द्वारा प्रदान की गई कुछ आधुनिक सटीकता खो देंगे। + +### चरण 2: इमेज पर OCR चलाएँ + +अब हम वास्तव में **run OCR on image** करते हैं। मूल उदाहरण की `recognize_image` मेथड को EasyOCR की `readtext` कॉल से बदल दिया गया है, जो `(bbox, text, confidence)` ट्यूपल की सूची लौटाती है। + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +`ocr_results` में प्रत्येक एंट्री इस प्रकार दिखती है: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +तीसरा तत्व (`0.92` उदाहरण में) confidence स्कोर है जो 0 से 1 तक रहता है। + +### चरण 3: समग्र confidence का सारांश + +पहले के स्निपेट के विपरीत जो एकल `confidence` एट्रिब्यूट प्रिंट करता था, EasyOCR प्रत्येक शब्द के लिए confidence देता है। समग्र समझ पाने के लिए, हम उनका औसत निकालेंगे: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Why average?* यह आपको एक त्वरित स्वास्थ्य जांच देता है—यदि समग्र confidence, उदाहरण के लिए, 70 % से नीचे है, तो आपको संभवतः इमेज को सुधारना होगा (बेहतर प्रकाश, प्री‑प्रोसेसिंग, आदि)। + +### चरण 4: कम‑confidence वाले शब्दों की सूची बनाएँ + +अब वह भाग आता है जो सीधे “उन शब्दों की सूची बनाता है जिनका confidence वांछित थ्रेशोल्ड से नीचे है” की आवश्यकता को पूरा करता है। हम डिफ़ॉल्ट रूप से **OCR confidence threshold** को 0.80 (80 %) पर सेट करेंगे, लेकिन आप इसे समायोजित कर सकते हैं। + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +यह लूप प्रत्येक शब्द को प्रिंट करता है जो कट नहीं हुआ, उसके प्रतिशत confidence के साथ। यह मूल `for recognized_word in recognition_result.words` लूप का सटीक समकक्ष है, लेकिन अब EasyOCR के आउटपुट फ़ॉर्मेट के साथ काम करता है। + +--- + +## ## OCR confidence स्कोर को समझना + +Confidence कोई जादुई संख्या नहीं है; यह मॉडल का अनुमान है कि वह किसी विशेष ट्रांसक्रिप्शन के बारे में कितना आश्वस्त है। यहाँ कुछ बातें हैं जिन्हें ध्यान में रखना चाहिए: + +| स्थिति | सामान्य confidence | क्या करें | +|-----------|-------------------|------------| +| स्पष्ट, उच्च‑रिज़ॉल्यूशन स्कैन | 0.95 – 1.00 | कोई अतिरिक्त काम आवश्यक नहीं | +| हल्का धुंधलापन या असमान प्रकाश | 0.80 – 0.94 | हल्का प्री‑प्रोसेसिंग (कॉन्ट्रास्ट बढ़ाना) पर विचार करें | +| भारी शोर, घुमा हुआ टेक्स्ट | < 0.70 | इमेज प्री‑प्रोसेसिंग (डेस्क्यू, डीनॉइज़) लागू करें या किसी अन्य OCR इंजन पर स्विच करें | + +> **Watch out:** कुछ भाषाएँ (जैसे, कर्सिव हस्तलेख) स्वाभाविक रूप से कम स्कोर देती हैं। थ्रेशोल्ड को उसी अनुसार समायोजित करें। + +### एज केस और विविधताएँ + +1. **Batch Processing** – यदि आपको बड़े पैमाने पर **run OCR on image** फ़ाइलें चलानी हैं, तो ऊपर की लॉजिक को एक लूप में लपेटें जो किसी डायरेक्टरी पर इटररेट करता है। +2. **Multiple Languages** – `easyocr.Reader` को `['en', 'fr']` जैसी सूची पास करें और इंजन दोनों को पहचान लेगा। +3. **Alternative Engines** – क्या आप **pytesseract** आज़माना चाहते हैं? रीडर ब्लॉक को इस से बदलें: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + फिर आपको प्रति‑अक्षर confidence को प्रति‑शब्द मानों में एकत्रित करना होगा—थोड़ा अधिक काम है लेकिन संभव है। + +4. **Pre‑processing Tricks** – OpenCV फ़िल्टर (`cv2.threshold`, `cv2.GaussianBlur`) लागू करने से शोरयुक्त स्कैन की confidence बढ़ सकती है। + +--- + +## ## पूर्ण, तैयार‑चलाने‑योग्य स्क्रिप्ट + +नीचे पूरा Python फ़ाइल है जिसे आप अपने प्रोजेक्ट में डाल सकते हैं। इसे `ocr_report.py` के रूप में सहेजें और `python ocr_report.py` चलाएँ। सुनिश्चित करें कि इमेज पाथ वास्तविक फ़ाइल की ओर इशारा करता है। + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Expected output** (आपके नंबर अलग हो सकते हैं): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +यदि हर शब्द 80 % की सीमा को पार करता है तो आपको मैत्रीपूर्ण “All words meet the confidence threshold.” संदेश दिखेगा। + +--- + +## ## अक्सर पूछे जाने वाले प्रश्न (FAQ) + +**Q: क्या यह PDFs के साथ काम करता है?** +A: सीधे नहीं। प्रत्येक PDF पेज को पहले इमेज में बदलें (जैसे, `pdf2image` से) और फिर PNG/JPEG को स्क्रिप्ट में फीड करें। + +**Q: मेरे confidence नंबर सभी कम हैं—मैं क्या करूँ?** +A: इमेज प्री‑प्रोसेसिंग आज़माएँ: कॉन्ट्रास्ट बढ़ाएँ, बैकग्राउंड शोर हटाएँ, या इमेज को क्षैतिज बेसलाइन पर घुमाएँ। EasyOCR एक `contrast_ths` पैरामीटर भी स्वीकार करता है जिसे आप समायोजित कर सकते हैं। + +**Q: क्या मैं परिणामों को CSV में एक्सपोर्ट कर सकता हूँ?** +A: बिल्कुल। लो‑confidence लूप के बाद, `ocr_results` को `csv.DictWriter` में लिखें जहाँ प्रत्येक पंक्ति में `text`, `confidence`, और बाउंडिंग‑बॉक्स कॉर्डिनेट्स हों। + +**Q: क्या कोई GPU‑त्वरित संस्करण है?** +A: EasyOCR स्वचालित रूप से CUDA का उपयोग करता है यदि संगत GPU और PyTorch स्थापित हैं। स्क्रिप्ट चलाने से पहले `torch.cuda.is_available()` से जांचें। + +--- + +## निष्कर्ष + +हमने अभी **run OCR on image** Python का उपयोग करके किया, समग्र confidence की जांच की, और किसी भी low‑confidence शब्द को अलग किया जिसे + +## अगला आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण करने में मदद करेंगे। + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/hongkong/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..d5de901db --- /dev/null +++ b/ocr/hongkong/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python OCR 在幾分鐘內從圖片中提取文字。探索多語言圖片 OCR、自動偵測語言的 OCR,以及如何準確提取 OCR 文字。 +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: zh-hant +og_description: 使用 Python OCR 快速從圖像中提取文字。學習多語言圖像 OCR、自動偵測語言 OCR,以及一步步提取 OCR 文字的方法。 +og_title: 使用 Python OCR 從圖片提取文字 – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: 使用 Python OCR 從圖像提取文字 – 完整指南 +url: /zh-hant/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從圖像中提取文字的 Python OCR 完整指南 + +是否曾需要 **從圖像中提取文字**,卻不確定哪個函式庫能自動處理多語言?你並不孤單——開發者在面對國際文件、收據或掃描傳單時,常會問 *如何提取 OCR 文字*。在本教學中,我們將示範一個實用的 Python 範例,不僅能從圖像中提取文字,還能 **即時偵測語言**,讓多語言圖像 OCR 變得輕而易舉。 + +我們會從安裝 OCR 套件、啟用 **自動偵測語言 OCR**、在範例圖片上執行引擎,最後印出偵測到的語言與提取的字串。完成後,你將擁有一段可重複使用的程式碼,無論是建構翻譯管線或資料擷取服務,都能直接套用。 + +## 從圖像中提取文字 – 環境設定 + +在開始撰寫程式碼之前,請先確保你的工作站符合以下最低需求: + +- Python 3.8 或更新版本(此函式庫使用型別提示,舊版會被忽略) +- `pip` 進行套件管理 +- 至少包含兩種不同語言文字的圖像檔(例如 English + Spanish) + +你還需要支援此示範的 OCR 函式庫。為了本教學的目的,我們使用虛構的 `ocr` 套件,它的介面類似 Tesseract、EasyOCR 等常見工具,但提供更乾淨的 Python API。 + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **小技巧:** 若遇到權限錯誤,可在指令前加上 `python -m`,或使用虛擬環境——這樣可以保持全域 site‑packages 的整潔。 + +## 建立 OCR 引擎實例 + +函式庫安裝完成後,第一步是 **建立 OCR 引擎實例**。可以把引擎想像成一部可在輸入圖像前先行設定的智慧掃描器。 + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +為什麼要先實例化引擎,而不是直接呼叫靜態方法?引擎物件會保存設定狀態(例如語言偏好),讓你在處理多張圖像時可以重複使用,免除每次重新初始化的開銷。 + +## 啟用自動偵測語言 OCR + +大多數 OCR 工具都需要手動指定語言代碼——`eng` 代表英文、`spa` 代表西班牙文,依此類推。手動猜測語言會失去 **多語言圖像 OCR** 工作流程的意義。幸好,`ocr` 套件提供 *自動偵測語言 OCR* 模式,會在背景自動檢查圖像並選擇最適合的語言模型。 + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +以這種方式啟用 **偵測語言 OCR**,就不必維護長長的語言代碼清單。引擎會嘗試匹配圖像中出現的文字系統——拉丁、斯拉夫、漢字等——並自動載入相應模型。 + +## 執行多語言圖像 OCR + +引擎已就緒,現在可以真正 **從圖像中提取文字**。`recognize_image` 方法接受檔案路徑,回傳一個結果物件,內含原始文字與偵測到的語言。 + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +如果你想知道 *如何從 PDF 提取 OCR 文字*,只要改用 `recognize_pdf` 方法即可。底層的偵測邏輯相同,仍能受惠於 **自動偵測語言 OCR** 功能。 + +## 顯示偵測語言與提取文字 + +最後,我們把引擎發現的資訊輸出。結果物件提供 `detected_language`(如 `en`、`es` 的 BCP‑47 標籤)以及 `text`(原始 OCR 輸出)。 + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +在範例圖像上執行腳本,應會得到類似以下的結果: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +可以看到,引擎正確辨識出英文為主要語言,同時也捕捉到西班牙文行——這正是 **多語言圖像 OCR** 解決方案所應具備的表現。 + +### 假如偵測失敗? + +當圖像模糊或文字系統過於罕見時,OCR 引擎可能會退回預設語言(通常是英文)。此時你可以強制指定語言清單: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +但請記得,強制指定語言會失去 **自動偵測語言 OCR** 的便利性,僅在已知語言子集時使用。 + +## 常見陷阱與可靠提取 OCR 文字的方法 + +即使有自動偵測,仍有幾個常見問題可能卡住你: + +1. **低解析度圖像** – 當解析度低於 150 dpi 時,OCR 準確度會急劇下降。請升級圖像或要求更高解析度的掃描。 +2. **噪點與壓縮雜訊** – 在送入引擎前,先使用簡單的二值化濾鏡(`opencv` 或 `Pillow`)清理圖像。 +3. **單頁混合文字系統** – 部分引擎在同時處理拉丁與中日韓字符時表現不佳。必要時可將頁面切割成多個區塊,分別辨識。 + +解決上述問題後,**從圖像中提取文字** 的品質會大幅提升,特別是面對真實世界的多語言文件時。 + +## 完整可執行範例 + +以下是結合前述所有步驟的完整腳本。將其存為 `multilingual_ocr.py`,然後在命令列執行。 + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**預期輸出**(假設範例圖像同時包含英文與西班牙文): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +隨意將 `multilang_page.png` 換成任何含有其他語言文字的圖片——得益於 **自動偵測語言 OCR**,腳本仍會回傳合理的語言標籤與對應文字。 + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## 結論 + +現在你已掌握 **如何從圖像中提取 OCR 文字**、如何啟用 **自動偵測語言 OCR**,以及如何以最少程式碼處理 **多語言圖像 OCR** 情境。只要建立 OCR 引擎實例、開啟自動語言偵測,並呼叫 `recognize_image`,就能可靠地取得語言標識與原始文字。 + +接下來可以嘗試將提取的字串送入翻譯 API、存入可搜尋的資料庫,或把多頁合併成單一 PDF 報告。你也可以實驗不同的 OCR 後端(Tesseract、EasyOCR、Google Vision),只要保持相同的高階工作流程——感謝一致的 **偵測語言 OCR** 介面。 + +若遇到任何怪異情況,請回顧「常見陷阱」章節或微調圖像前處理步驟。祝開發順利,願你的下一個專案充滿正確偵測、完美提取的文字! + +## 接下來該學什麼? + +以下教學與本指南的技術緊密相關,能幫助你進一步掌握 API 功能,並在自己的專案中探索其他實作方式: + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/hongkong/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..fe1b557a1 --- /dev/null +++ b/ocr/hongkong/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python OCR 從圖片 PDF 中提取文字。了解如何透過非同步批次辨識快速將掃描文件轉換為文字。 +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: zh-hant +og_description: 使用 Python 從圖片 PDF 中提取文字。本分步指南展示如何使用非同步 OCR 將掃描文件轉換為文字。 +og_title: 從圖片 PDF 中提取文字 – Python OCR 教學 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: 從影像 PDF 中提取文字 – Python 教學:將掃描文件轉換為文字 +url: /zh-hant/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從圖像 PDF 提取文字 – Python 教學:將掃描文件轉換為文字 + +是否曾經想要 **從圖像 PDF 提取文字**,卻不想花上數小時重新打字?在本教學中,我們將示範如何使用簡單的非同步 OCR 工作流程,於 Python 中 **將掃描文件轉換為文字**。 + +如果你曾經盯著一堆掃描的 PDF,心想「一定有更快的方法」,那麼你來對地方了。我們會逐行說明程式碼,解釋每個部份的意義,甚至涵蓋你可能會遇到的幾個邊緣情況。 + +## 你將學會 + +- 如何啟動 OCR 引擎並設定辨識語言。 +- 如何將 PNG 與 PDF 的混合清單餵入批次辨識器。 +- 以非同步方式執行 OCR 工作,讓你的應用保持回應。 +- 取得結果、將其與來源檔案配對,並輸出整潔的文字。 + +**先備條件**:Python 3.8+、對 `asyncio` 或 `concurrent.futures` 有基本了解,以及一個提供類似 `OcrEngine` 類別的 OCR 函式庫(例如 Aspose.OCR、Tesseract 包裝器,或自訂包裝器)。不需要繁雜的設定——只要安裝函式庫即可開始。 + +![從圖像 PDF 提取文字](https://example.com/placeholder.png "OCR 輸出截圖 – 從圖像 PDF 提取文字") + +## 從圖像 PDF 提取文字 – 設定 OCR 引擎 + +首先,你需要一個已設定好文件語言的 OCR 引擎實例。此範例使用法文,你可以自行換成任何支援的語言。 + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**為什麼這很重要**:事先設定語言能大幅提升辨識準確度。引擎會使用語言專屬的字典與字元模型;若使用錯誤的語言,常會出現亂碼。 + +## 準備檔案清單 – 圖片與 PDF 同時處理 + +我們的批次辨識器能同時處理點陣圖 (`.png`, `.jpg`) 與 PDF 容器。只要提供一個普通的 Python 檔案路徑清單即可。 + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**小技巧**:保持清單為單層結構;引擎會在內部將每個 PDF 頁面解壓為圖像再進行辨識。如果檔案數量達到數千,建議將清單切成較小的批次,以避免記憶體激增。 + +## 發起非同步批次辨識 + +我們不會阻塞主執行緒,而是將 OCR 工作放到背景執行。此方法會回傳一個 `Future`,最終會持有 `OcrResult` 物件的清單。 + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**運作原理**:在底層,引擎會建立執行緒池(或非同步任務,視實作而定)。這讓你可以同時執行其他工作——例如更新 UI、取得更多檔案,或記錄進度——而繁重的辨識工作則在其他地方完成。 + +## OCR 執行時做點有用的事 + +常見錯誤是空等並在緊密迴圈中輪詢 `Future`。相反地,你可以在此期間執行任何不相關的工作。以下示範僅列印一行狀態訊息。 + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## 未來完成後收集結果 + +當你準備好取得 OCR 輸出時,使用 `concurrent.futures` 的 `as_completed`。無論是單一 `Future` 或多個,都適用此模式。 + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**你會看到的結果**:每個檔案路徑後面接著抽取出的純文字。對於 PDF,`result.text` 包含所有頁面的合併文字。 + +### 預期輸出(範例) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +如果發現缺字,請再次確認設定的語言與文件語言相符,並考慮在送入引擎前先對圖像做前處理(去斜、提升對比度)。 + +## 處理邊緣情況與常見陷阱 + +| 情況 | 處理方式 | +|-----------|------------| +| **混合語言** | 先執行語言偵測,再為每種語言建立獨立的引擎。 | +| **大型 PDF(> 100 MB)** | 使用 `PyPDF2` 等工具將 PDF 拆成單頁檔案,並分別作為條目餵入。 | +| **非拉丁文字** | 確認 OCR 函式庫已包含所需語言套件;部分函式庫需自行下載額外資料檔。 | +| **效能瓶頸** | 增加執行緒池大小(`engine.set_thread_pool_size(8)`)或改用支援 GPU 的後端(若有)。 | +| **低解析度圖像缺字** | 使用 OpenCV 前處理:`cv2.resize`、`cv2.threshold`、`cv2.medianBlur` 以提升可讀性。 | + +## 完整可執行範例(直接複製貼上) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +將此檔案存為 `extract_text_async.py`,將 `YOUR_DIRECTORY` 替換成你的檔案路徑,安裝 OCR 套件(`pip install your-ocr-lib`),然後執行 `python extract_text_async.py`。你應該會看到前面示範的主控台輸出。 + +## 往後的步驟 – 超越基礎抽取 + +- **後處理**:去除多餘空白、正規化 Unicode(`unicodedata.normalize`),或使用拼字檢查器清理 OCR 噪聲。 +- **結構化輸出**:將結果匯出為 CSV、JSON,或直接寫入資料庫,以供後續搜尋使用。 +- **平行批次**:若有上百個檔案,可同時啟動多個 `Future`,並使用佇列讓 CPU 持續忙碌而不致記憶體過載。 +- **整合 Web 框架**:將此腳本掛接至 Flask 或 FastAPI 端點,提供即時 OCR 服務。 + +--- + +### TL;DR + +現在你已掌握如何使用最小的 Python 腳本,透過非同步 OCR **從圖像 PDF 提取文字**,在程式保持回應的同時 **將掃描文件轉換為文字**。可自行調整語言設定、批次大小與前處理技巧,以爭取最高的辨識正確率。 + +有任何想法想分享——例如手寫筆記的 OCR,或雲端服務的應用?歡迎留言,祝開發愉快! + +## 接下來該學什麼? + +以下教學與本指南的技術緊密相關,能在此基礎上延伸更多 API 功能與實作方式,並提供完整可執行的程式碼範例與逐步說明,協助你在自己的專案中深入應用。 + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Images Using Aspose.OCR – Allowed Characters](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0b325bd03 --- /dev/null +++ b/ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Python 進行 PDF OCR,從 PDF 中提取文字,轉換掃描 PDF 的文字,並僅用幾行程式碼更改 OCR 語言。 +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: zh-hant +og_description: 如何使用 Python 進行 PDF OCR:實用指南,教您如何從 PDF 提取文字、轉換掃描 PDF 文字,並輕鬆變更 OCR 語言。 +og_title: 如何在 Python 中對 PDF 進行 OCR – 完整程式設計教學 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: 如何在 Python 中對 PDF 進行 OCR – 完整逐步指南 +url: /zh-hant/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Python 中 OCR PDF – 完整步驟指南 + +有沒有想過在不付高價 SaaS 工具的情況下 **如何 OCR PDF** 檔案?你並不是唯一有此需求的人。無論是將舊書數位化、從發票中提取資料,或只是需要從掃描報告中取得可搜尋的文字,掌握 Python 的 PDF OCR 能為你節省大量手動複製的時間。 + +在本教學中,我們將示範一個簡潔且可運作的範例,該範例 **從 PDF 中提取文字**,示範如何 **將掃描的 PDF 文字** 轉換為可編輯的字串,甚至演示如何 **變更 OCR 語言**(若文件不是英文)。完成後,你將擁有一段可重複使用的程式碼片段,隨時可嵌入任何專案。 + +## 前置條件與設定 + +- 已安裝 Python 3.8+(程式碼在 3.9、3.10 及更新版本皆可執行) +- 提供 `OcrEngine` 類別的 `ocr` 套件(可透過 `pip install ocr-lib` 安裝——請替換為實際使用的套件名稱) +- 想要處理的 PDF 檔案;示範中使用放在 `YOUR_DIRECTORY` 資料夾下的 `high_res_book.pdf` + +如果你使用虛擬環境(強烈建議),請先啟動它: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **小技巧:** 請將 PDF 檔案放在專屬的 `data/` 目錄下,以免日後遭遇路徑相關的麻煩。 + +## 步驟 1:建立 OCR 引擎實例(How to OCR PDF – 初始化) + +當你想要 **對 PDF 執行 OCR** 時,第一件事就是實例化引擎。可以把引擎想像成大腦,負責閱讀每一頁、解讀字形,並回傳純文字。 + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +為什麼這很重要:若沒有引擎,就無法設定語言、渲染選項或 PDF 處理的相關資訊。`OcrEngine` 物件保存了所有預設值,並允許你之後進行調整。 + +## 步驟 2:設定辨識語言(變更 OCR 語言) + +大多數 OCR 函式庫預設為英文,但若文件是法文、德文,甚至日文該怎麼辦?只要呼叫 `set_recognition_language` 即可變更語言。這就滿足了 **變更 OCR 語言** 的需求,並提升辨識準確度。 + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **為什麼可能需要這樣做:** 多語言檔案庫常包含混合語言的頁面。即時切換語言可避免將 “ß” 或 “ñ” 等字元誤辨。 + +## 步驟 3:設定 PDF 渲染選項(有效轉換掃描 PDF 文字) + +處理掃描 PDF 時,解析度與色彩模式會大幅影響 OCR 品質。以 300 DPI 的灰階方式渲染,對大多數文件而言是最佳平衡——足以捕捉細節,同時不會佔用過多記憶體。 + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +鏈式呼叫看起來很炫,但其實只是回傳同一個選項物件的流暢 API。若需要彩色(例如彩色圖表),只要將 `"grayscale"` 改成 `"color"` 即可。 + +## 步驟 4:辨識 PDF 並取得第一頁文字(從 PDF 提取文字) + +現在進入 **如何 OCR PDF** 的核心:將檔案路徑傳給引擎,取得辨識後的文字。此方法會回傳每頁結果的列表;每個結果都有 `text` 屬性。 + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +若需要整本文件,可遍歷 `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### 若 PDF 被加密怎麼辦? + +有些 PDF 受密碼保護。此時可將密碼傳給 `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +引擎會在執行 OCR 前即時解密——不需要額外步驟。 + +## 步驟 5:後處理提取的文字(微調從 PDF 提取的文字) + +原始 OCR 輸出常帶有換行、額外空格或偶發的錯誤字元。快速清理例程可讓提取的字串可直接用於後續處理(搜尋索引、資料庫儲存等)。 + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +現在你可以安全地 **從 PDF 提取文字**,並將其輸入任何 NLP 流程、搜尋引擎,或簡單的 `open(...).write()` 操作。 + +## 加分項:批次處理多個 PDF(擴展 PDF OCR) + +如果你有一個資料夾裡放滿掃描 PDF,只需將邏輯包在迴圈中: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +此程式碼片段示範如何批量 **對 PDF 執行 OCR**,這是數位化專案的常見需求。 + +## 預期輸出 + +執行單頁範例(步驟 4)時,應會印出類似以下內容: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +若處理的是多頁書籍,控制台會顯示每頁清理過的文字,且批次腳本會在每個 PDF 旁產生相應的 `.txt` 檔案。 + +## 常見陷阱與避免方法 + +| 問題 | 徵兆 | 解決方式 | +|-------|----------|-----| +| 來源 PDF 解析度過低 | 字元亂碼、遺失文字 | 提升 DPI(`set_dpi(400)` 或更高) | +| 語言設定錯誤 | 大量未知符號,尤其是帶重音的字元 | 使用 `engine.set_recognition_language(ocr.Language.FRENCH)` 或相應的列舉值 | +| 大型 PDF 造成記憶體錯誤 | `MemoryError` 或在數頁後當機 | 分批處理頁面(`engine.recognize_pdf(..., max_pages=10)`) | +| PDF 缺少字型 | 某些頁面輸出為空白 | 確認 PDF 確實包含點陣圖像;有些 PDF 為純向量,需要其他處理方式 | + +## 圖像說明 + +以下是一張工作流程的快速示意圖。alt 文字特意設計為 SEO 友好。 + +![如何 OCR PDF 工作流程圖,顯示引擎初始化、語言設定、渲染選項、辨識與文字提取](/images/ocr-workflow.png) + +*此圖示對程式執行並非必要,但有助於視覺學習者了解每個步驟的定位。* + +## 結論 + +我們已完整說明如何在 Python 中 **OCR PDF**:建立 OCR 引擎、**變更 OCR 語言**、設定渲染以 **轉換掃描 PDF 文字**,最後 **從 PDF 提取文字** 供後續使用。完整且可執行的範例已可直接嵌入任何專案,且可選的批次腳本示範了如何擴展此解決方案。 + +接下來,你可能想探索: + +- 為多語言檔案庫加入 **對 PDF 執行 OCR**,透過迴圈遍歷語言清單。 +- 將提取的文字整合至 Elasticsearch 以進行全文搜尋。 +- 使用 OCR 產生可搜尋的 PDF,將文字層嵌入原始檔案(許多函式庫提供 `save_as_searchable_pdf` 方法)。 + +歡迎自行實驗、調整 DPI 設定,或切換至其他 OCR 後端。基本原理不變,現在你已具備堅實的基礎可供延伸。 + +祝程式開發順利,願你的掃描文件終於變得可搜尋! + +## 接下來該學什麼? + +以下教學涵蓋與本指南密切相關的主題,建立在此處示範的技巧之上。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [辨識 PDF 文字 – 使用 Aspose.OCR for Java 的 OCR 操作](/ocr/english/java/ocr-operations/) +- [如何使用 Aspose.OCR 以語言辨識圖像文字](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [如何在 .NET 使用 Aspose.OCR OCR PDF](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..21f4b4b2e --- /dev/null +++ b/ocr/hongkong/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Python 進行 PDF OCR,並從圖像建立可搜尋的 PDF 檔案。學習在數分鐘內加入可搜尋文字並將圖像轉換為 PDF/A。 +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: zh-hant +og_description: 一步一步教你 OCR PDF。學習使用簡易 Python 腳本為 PDF 添加可搜尋文字,並將影像轉換為 PDF/A。 +og_title: 如何對 PDF 進行 OCR – 快速指南:建立可搜尋的 PDF +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: 如何在 Python 中對 PDF 進行 OCR – 從圖片建立可搜尋的 PDF +url: /zh-hant/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何 OCR PDF – 將掃描圖像轉換為可搜尋的 PDF + +有沒有想過 **如何 OCR PDF** 檔案,當你手上只有發票或收據的掃描圖像?你並不是唯一有此困惑的人。在許多辦公室,收到的文件往往是平面的 PNG 或 JPEG,而接下來的步驟——讓內容可搜尋——常常像個黑盒子。 + +好消息是?只要幾行 Python 程式碼,你就能 **建立可搜尋的 PDF** 檔案、**加入可搜尋的文字**,甚至 **將影像轉換為 PDF/A** 以作長期保存。在本教學中,我們會逐步說明每個步驟、解釋其重要性,並提供一段可直接執行的腳本,讓你可以隨時放入任何專案中使用。 + +> **專業提示:** 同樣的方法也適用於多頁掃描;只需對檔案進行迴圈,引擎會自行處理繁重的工作。 + +--- + +## 您需要的環境 + +在開始之前,請確保您的機器已具備以下項目: + +| 需求 | 重要原因 | +|------|----------| +| Python 3.9 或更新版本 | 現代語法與更好的函式庫支援 | +| `pdfium` 為基礎的 OCR 引擎(例如 `pdfocr` 或商業 SDK) | 同時處理影像辨識與 PDF/A 產生 | +| 欲轉換為可搜尋 PDF 的影像檔(PNG、JPEG、TIFF) | 文字的來源 | +| 對輸出資料夾的寫入權限 | 讓腳本能儲存新 PDF | + +如果尚未安裝 OCR SDK,請執行以下指令: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +就這樣——不需要複雜的系統相依,只要 pip 安裝即可。 + +--- + +## 如何 OCR PDF – 概觀 + +從高層次來看,整個流程包含三個簡單動作: + +1. **辨識** 影像內的文字,同時保留原始圖形。 +2. **匯出** OCR 結果與原始影像為 **可搜尋的 PDF/A**(適合長期保存的 PDF 版本)。 +3. **驗證** 產生的檔案是否在原圖上疊加了可選取、可搜尋的文字層。 + +以下會以程式碼展示每個步驟,並說明指令背後的 *為什麼*。 + +--- + +## 步驟 1:從影像辨識文字 + +首先,我們請 OCR 引擎讀取像素,回傳一個同時包含原始影像與擷取文字的 result 物件。可以把它想成引擎為你「閱讀」發票。 + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### 為什麼這很重要 + +- **保留圖形** 表示視覺版面(表格、商標、印章)會完全如掃描時的樣子保留下來。 +- `result` 物件通常會包含一個隱藏的文字層,我們稍後會把它嵌入 PDF。 +- 使用 `recognize_image` 而非 `recognize_pdf` 可避免額外的轉換步驟,對單頁影像的處理速度更快。 + +#### 常見變化 + +- 若你有 **多頁 TIFF**,直接傳入檔案路徑;大多數引擎會把每一頁視為獨立影像。 +- 若 PDF 已經內含影像,可呼叫 `engine.recognize_pdf("file.pdf")`,直接跳過此步驟。 + +--- + +## 步驟 2:將 OCR 結果匯出為可搜尋的 PDF/A + +現在把步驟 1 取得的 `result` 交給引擎寫入新檔案。此處的關鍵旗標是 *PDF/A*——ISO 標準的長期保存 PDF 版本。 + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### 為什麼這很重要 + +- **可搜尋的 PDF**:輸出檔案會包含隱藏且可選取的文字層,現在可以使用 Ctrl + F 進行搜尋。 +- **PDF/A 相容**:某些組織(法律、財務)要求使用 PDF/A 作為稽核追蹤,此步驟會自動滿足此規範。 +- 此方法同時 **加入可搜尋文字** 而不會將影像平面化,確保視覺保真度完好。 + +#### 邊緣情況:需要一般 PDF 而非 PDF/A? + +如果不在乎 PDF/A,只要把 `save_as_pdfa` 換成 `save_as_pdf` 即可,其餘工作流程保持不變。 + +--- + +## 步驟 3:驗證可搜尋的 PDF + +快速的 sanity check 可以避免日後出現神祕的錯誤。用任何 PDF 閱讀器開啟產生的檔案,試著選取文字,並使用搜尋功能。 + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### 預期輸出 + +執行腳本時,主控台會印出: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +開啟檔案後,你應該會看到原始發票影像上覆蓋著淡淡、看不見的文字層。選取任意單字會發現它是可選取的——**這就是剛剛加入的可搜尋文字**。 + +--- + +## 為既有 PDF 加入可搜尋文字(加分) + +有時候你已經有 PDF,但需要 **加入可搜尋文字**。同樣的引擎可以把 OCR 結果覆蓋到既有 PDF 上: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +此處的 `apply_to` 會將隱藏層與原始頁面合併,讓你 **建立可搜尋的 PDF** 而不必重新掃描。 + +--- + +## 常見問題與技巧 + +| 常見問題 | 避免方法 | +|----------|----------| +| **低解析度來源影像** (< 150 dpi) | 放大或要求更高解析度的掃描;解析度低於 150 dpi 時 OCR 準確度會急劇下降。 | +| **缺少語言資料** | 安裝對應的語言套件,例如 `pip install pdfocr[eng,spa]`。 | +| **輸出資料夾無寫入權限** | 以足夠權限執行腳本,或改用其他目錄。 | +| **PDF/A 驗證失敗** | 確認未嵌入不支援的字型或 JavaScript;使用 `save_as_pdfa` 時大多數 SDK 會自動處理。 | + +--- + +## 完整腳本 – 單檔解決方案 + +以下是一段自包含的腳本,將所有步驟串接在一起。直接複製貼上、替換佔位路徑,即可在數秒內 **將影像轉換為 PDF/A**。 + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**此腳本的功能:** +1. 載入 OCR 引擎。 +2. 讀取選定的影像並擷取文字。 +3. 寫入 **可搜尋的 PDF/A**,可立即分發或保存。 + +如需批次處理整個資料夾,只要把 `main` 邏輯包在函式裡,使用 `os.listdir()` 迭代即可,對每個檔案重複上述三個步驟。 + +--- + +## 後續步驟與相關主題 + +既然已掌握 **如何 OCR PDF**,不妨探索以下進階想法: + +- **批次處理:** 使用 `concurrent.futures` 同時 OCR 數十張發票。 +- **中繼資料注入:** 為 PDF 加入建立日期或發票編號等中繼資料,方便索引。 +- **混合 PDF:** 結合可搜尋文字與嵌入的原始影像,打造文件的「數位雙生」。 +- **其他輸出格式:** 若下游系統需要可編輯檔案,可匯出為 **DOCX** 或 **HTML**。 + +上述每項都建基於你剛學會的三個核心概念:辨識、匯出、驗證。 + +--- + +## 總結 + +簡而言之,你現在已掌握 **如何 OCR PDF**:只要三行 Python 程式碼,就能把單純的影像變成 **可搜尋的 PDF/A**。腳本負責繁重的工作、保留原始圖形,並產生符合標準的文件,讓你可以搜尋、保存或分享。 + +快把它套用在自己的發票、收據或掃描合約上吧。若遇到任何問題,歡迎在下方留言或查閱 SDK 官方文件——那裡通常還有更多範例。祝開發愉快,盡情享受將任何影像即時變為可搜尋的全新能力! + +![How to OCR PDF example showing original image and searchable PDF overlay](placeholder.png "How to OCR PDF example") + +## 接下來該學什麼? + +以下教學與本指南示範的技術緊密相關,提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何在 .NET 使用 Aspose.OCR 進行 OCR PDF](/ocr/english/net/text-recognition/recognize-pdf/) +- [使用 Aspose.OCR for Java 進行 PDF 文字辨識 – OCR 操作](/ocr/english/java/ocr-operations/) +- [C# 影像轉 PDF – 儲存多頁 OCR 結果](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/hongkong/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..225b41712 --- /dev/null +++ b/ocr/hongkong/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Aspose OCR Cloud 進行 PDF OCR。學習從 PDF 提取文字、將 PDF 頁面轉換為 PNG,並在 Python + 中儲存 PDF 頁面圖像。 +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: zh-hant +og_description: 如何使用 Aspose OCR Cloud 進行 PDF OCR。本指南說明如何提取純文字 PDF、將 PDF 頁面轉換為 PNG,以及保存 + PDF 頁面圖像。 +og_title: 如何使用 Aspose OCR Cloud 進行 PDF OCR – 步驟說明 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: 如何使用 Aspose OCR Cloud 進行 PDF OCR – 完整指南 +url: /zh-hant/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Aspose OCR Cloud 進行 PDF OCR – 完整指南 + +有沒有想過在不與笨重的桌面工具搏鬥的情況下 **如何 OCR PDF** 檔案?你並不孤單——許多開發者在需要快速、程式化地從掃描文件中提取文字時,都會碰到這個問題。好消息是?使用 Aspose OCR Cloud,你可以 **從 PDF 提取文字**,將每一頁轉成 PNG,甚至 **保存 PDF 頁面圖像** 以供日後使用,全部只需一段簡潔的 Python 程式碼。 + +在本教學中,我們將逐步說明你需要了解的所有內容:從安裝 SDK、授權引擎、辨識多頁 PDF,到提取純文字、將頁面轉換為 PNG,以及將這些圖像持久化到磁碟。完成後,你將擁有一段可重複使用的程式碼片段,能夠嵌入任何需要 **如何 OCR PDF** 功能的專案中。 + +## 你需要的條件 + +- **Python 3.8+**(此程式碼亦可在 3.10 及更新版本上執行) +- 一個 Aspose OCR Cloud 帳號 – 你將獲得免費試用授權檔 (`Aspose.OCR.lic`) +- `asposeocrcloud` 套件(`pip install asposeocrcloud`) +- 一個你想要處理的掃描多頁 PDF + +就這樣。無需額外的二進位檔案,無需原生相依性,僅需純 Python。 + +## 如何 OCR PDF – 設定與授權 + +在呼叫任何 OCR 方法之前,你必須先告訴 SDK 你的身份。Aspose 使用一個輕量級的授權檔案,你需要將它放在腳本可存取的位置。 + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*小技巧:* 如果跳過授權步驟,SDK 仍會運作,但會在輸出圖像中嵌入小水印。這對於正式環境並不理想。 + +## 步驟 2:安裝 Aspose OCR Cloud Python SDK + +在終端機中執行以下指令: + +```bash +pip install asposeocrcloud +``` + +此套件會自動下載所有必要的相依套件(如 requests、pillow 等),讓你不必自行搜尋其他套件。 + +## 步驟 3:建立 OCR 引擎並選擇語言 + +引擎是此操作的核心。你可以指定任何 Aspose 支援的語言;英語在大多數情況下皆適用。 + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +為什麼要設定語言?因為 OCR 引擎會使用特定語言的字典來提升辨識準確度。如果你在處理法文 PDF,只需將 `ENGLISH` 換成 `FRENCH` 即可。 + +## 步驟 4:指向你的多頁 PDF + +將檔案的完整路徑提供給引擎,以便處理。只要相對路徑能從腳本的工作目錄解析,即可使用相對路徑。 + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +確保檔案可讀取;否則會拋出 `FileNotFoundError`。 + +## 步驟 5:執行 OCR – 取得結果清單 + +呼叫 `recognize_pdf` 會回傳一個清單,清單中的每個元素對應來源 PDF 的一頁。 + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +每個 `OcrResult` 包含兩個實用屬性: + +* `text` – 該頁面的純文字表示(適用於 **extract plain text pdf**) +* `image` – 渲染頁面的 Pillow `Image` 物件(適用於 **convert pdf page png**) + +## 步驟 6:從 PDF 提取文字並將頁面轉為 PNG + +現在我們遍歷結果,印出提取的文字,並將每一頁儲存為 PNG 版本。 + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### 預期的主控台輸出 + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +你還會在 `YOUR_DIRECTORY` 中看到 `page_1.png`、`page_2.png` … 等檔案。這些是已光柵化的頁面圖像,可供後續的影像處理流程使用。 + +## 步驟 7:保存 PDF 頁面圖像(可選的後處理) + +如果你只需要圖像而不需要文字,可以省略 `print(res.text)` 那一行。相反地,若想將文字存成獨立的 `.txt` 檔,只需加上一小段寫入程式碼: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +這個小小的補充示範了在 **save PDF page images** 的同時,如何輕鬆保存提取的內容。 + +## 完整可執行範例 + +將所有步驟整合起來,以下是可直接複製貼上至 `ocr_pdf.py` 的完整腳本: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +使用以下指令執行: + +```bash +python ocr_pdf.py +``` + +你應該會在主控台看到每頁文字的輸出,並產生一系列 PNG 檔案 + +## 接下來你可以學習什麼? + +以下教學涵蓋與本指南密切相關的主題,並以此為基礎延伸技術。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/hongkong/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..650a3774e --- /dev/null +++ b/ocr/hongkong/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-06 +description: 如何使用 Python 進行 OCR 圖像前處理。學習使用 Otsu 方法二值化圖像、如何校正掃描文件的傾斜,以及提升德文文本的 OCR + 準確度。 +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: zh-hant +og_description: 如何在 Python 中對圖像進行 OCR 前處理。本教程展示如何使用 Otsu 方法二值化圖像、如何校正掃描文件的傾斜,以及如何提升德文圖像的 + OCR 準確度。 +og_title: 如何為 OCR 預處理圖像 – 完整 Python 指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: 如何為 OCR 預處理圖像 – 完整 Python 指南 +url: /zh-hant/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何為 OCR 前處理圖像 – 完整 Python 指南 + +有沒有想過 **如何為 OCR 前處理圖像**,讓文字呈現得晶瑩剔透?你並不是唯一有此困擾的人。掃描文件——尤其是雜訊較多的德文頁面——對任何 OCR 引擎來說都是噩夢。好消息是,只要採取幾個聰明的前處理步驟,就能把模糊、斑點密布的掃描件變成乾淨、機器可讀的圖像。 + +在本教學中,我們將示範一個實用範例,說明 **如何為 OCR 前處理圖像**,使用 Python 完成。你將學會 **使用 Otsu 進行二值化**、**如何校正掃描文件的傾斜**,以及在 **從德文圖像檔案中提取文字** 時 **如何提升 OCR 準確度**。沒有冗長說明,只有可直接複製貼上的完整腳本。 + +## 需要的環境 + +- **Python 3.9+**(任何較新的版本皆可) +- 提供 `OcrEngine` 類別的 OCR 套件——此示範假設有一個通用的 `ocr` 套件,請使用 `pip install ocr-lib` 安裝。 +- 一個雜訊較多的德文掃描檔(`noisy_german_scan.tif`)作為測試對象。 +- 基本的 Python 函式概念(只要寫過 `def` 就足夠)。 + +> **小技巧:** 若你使用的是其他 OCR SDK(例如透過 `pytesseract` 的 Tesseract),概念仍然相同,只需對應調整方法名稱即可。 + +## 解決方案概覽 + +1. **建立 OCR 引擎實例。** +2. **設定辨識語言為德文。** +3. **建構自訂前處理管線**,包含校正傾斜、去雜訊、二值化(Otsu)與對比度拉伸。 +4. **將管線掛載至引擎**,讓每張圖像自動通過前處理。 +5. **對雜訊德文掃描執行 OCR**。 +6. **列印擷取出的文字**,以驗證結果。 + +以下逐步說明每個步驟的意義,並提供完整程式碼。 + +![如何為 OCR 前處理圖像範例](image.png "如何為 OCR 前處理圖像範例") + +## 步驟 1:建立 OCR 引擎實例 + +首先,沒有引擎就什麼都不會發生。`OcrEngine` 物件是後續所有處理的入口。 + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*為什麼重要:* 初始化引擎會配置內部資源(例如語言模型),同時為之後掛載自訂管線提供乾淨的起點。 + +## 步驟 2:設定辨識語言為德文 + +OCR 的準確度高度依賴語言。告訴引擎使用德文,即可啟用正確的字元集與語言模型。 + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +若省略此步驟,引擎可能預設為英文,導致無法正確辨識變音符(ä、ö、ü)與 ß,這是處理德文掃描時常見的陷阱。 + +## 步驟 3:建構自訂前處理管線 + +這是 **如何為 OCR 前處理圖像** 的核心。我們將串接四個轉換: + +| 轉換 | 功能說明 | 為什麼有幫助 | +|------|----------|--------------| +| **校正傾斜** | 將圖像旋轉回水平(最大 5°) | 掃描件很少能完美對齊;校正傾斜可去除會干擾字元分割的斜度。 | +| **去雜訊** | 降低隨機斑點(強度 0.7) | 雜訊會產生偽邊緣,OCR 可能把它當成字元。 | +| **二值化(Otsu)** | 使用 Otsu 方法轉為黑白圖 | 乾淨的二值圖提供文字與背景之間的高對比度。 | +| **對比度拉伸** | 擴展動態範圍 | 提升舊文件中淡弱筆劃的可讀性。 | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### 如何校正掃描文件的傾斜 + +上面的 `deskew` 呼叫即是 **如何校正掃描文件的傾斜** 的具體答案。它會透過 Hough 變換估算主要文字行的角度,然後將圖像旋轉回正。若文件傾斜超過 5°,可將 `max_angle` 提高,但需注意過度旋轉可能產生 artefacts。 + +### 使用 Otsu 進行二值化 + +`binarize(method="otsu")` 這行直接回應 **二值化圖像使用 Otsu** 的需求。Otsu 演算法會計算一個使類內變異最小的阈值,特別適合文字(暗)與背景(亮)呈雙峰分佈的文件。 + +## 步驟 4:將管線掛載至引擎 + +現在告訴 OCR 引擎,所有進入的圖像都要經過剛才建立的管線。 + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*為什麼重要:* 若未註冊管線,引擎會直接處理原始掃描,忽略我們剛配置的清理步驟。此步驟確保 **如何提升 OCR 準確度**,讓前處理始終如一地套用。 + +## 步驟 5:辨識雜訊德文掃描的文字 + +把所有東西組合起來,將雜訊德文圖像交給引擎處理。 + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +如果想了解效能,可以測量呼叫時間: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## 步驟 6:輸出辨識結果 + +最後,列印擷取出的字串。這正是 **從德文圖像中提取文字** 的直接答案。 + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### 預期輸出 + +假設範例掃描包含句子 “Die schnelle braune Füchsin springt über den faulen Hund.”,則應看到類似以下結果: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +若輸出仍出現亂碼,請考慮調整 `denoise` 強度或提升 `max_angle` 以改善校正。 + +## 常見問題與解決方式 + +- **缺少語言模型:** 忘記呼叫 `set_recognition_language(Language.GERMAN)` 常會導致變音符遺失,請務必檢查此行程式。 +- **過度去雜訊:** 強度超過 0.9 可能會抹除細小筆劃,特別是舊字體。大多數情況建議使用 0.5‑0.7。 +- **檔案格式不正確:** 某些 OCR 引擎無法處理多頁 TIFF。若有多頁文件,請先拆分為單頁檔。 +- **管線順序錯誤:** 本範例的順序(校正傾斜 → 去雜訊 → 二值化 → 對比度拉伸)是特意安排的。若先二值化再去雜訊,噪點會被鎖定,效果會變差,務必先去雜訊。 + +## 延伸管線(下一步是什麼?) + +有了穩固的基礎後,你可以考慮: + +- **加入形態學開運算** 以清除微小斑點(`.morph_open(kernel=3)`)。 +- **整合語言模型** 進行後處理校正(`ocr_engine.apply_spellcheck()`)。 +- **平行化批次處理**,使用 `concurrent.futures` 針對大型資料集加速。 + +以上皆是自然的延伸,仍保留 **如何為 OCR 前處理圖像** 的核心概念,同時進一步提升 **如何提升 OCR 準確度**。 + +## 結論 + +我們已完整說明 **如何為 OCR 前處理圖像**:建立引擎、設定德文、建構包含 **使用 Otsu 進行二值化**、**校正掃描文件的傾斜** 的管線,最後 **從德文圖像中提取文字**,並大幅提升辨識品質。依照上述六個步驟操作,你會明顯感受到辨識品質的提升——不再需要無止盡的手動校正。 + +快把腳本套用到自己的掃描件上,調整參數,讓結果說話吧。對特定前處理技巧有疑問嗎?留下評論,我們一起深入探討。 + +祝編程愉快,願你的 OCR 永遠精準! + +## 接下來該學什麼? + +以下教學與本指南緊密相關,能在此基礎上延伸技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能,並在專案中探索其他實作方式。 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..a3cc58d77 --- /dev/null +++ b/ocr/hongkong/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,317 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python 進行 PNG 圖片 OCR – 學習如何從圖片中提取文字,執行 Python OCR 範例,甚至輕鬆閱讀古希臘文。 +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: zh-hant +og_description: 在 Python 中說明 OCR PNG 圖像。本指南展示如何從圖像中提取文字、執行 Python OCR 範例,並輕鬆閱讀古希臘文。 +og_title: OCR PNG 圖片於 Python – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 在 Python 中對 PNG 圖像進行 OCR – 完整逐步指南 +url: /zh-hant/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python 中的 OCR PNG 圖像 – 完整步驟指南 + +有沒有想過如何直接在 Python 腳本中 **OCR PNG image** 檔案?也許你有一個充滿掃描古代手稿的資料夾,需要 **extract text from image** 檔案而不必手動逐字輸入。好消息是,你不需要計算機視覺的博士學位——只要幾行程式碼和合適的函式庫,你就能在幾秒鐘內閱讀古希臘文。 + +在本教學中,我們將逐步說明一個 **python OCR example**,它能辨識 PNG 中的文字、將語言設定為希臘語多音調,並輸出結果。完成後,你將清楚知道如何 **recognize image text**、處理常見問題,並將腳本套用到其他語言或圖像格式。 + +## 你將學到什麼 + +- 安裝與設定 Python OCR 函式庫(pytesseract + Tesseract OCR) +- 建立 OCR 引擎實例並載入 PNG 檔案 +- 設定辨識語言為希臘語多音調,以便 **read ancient greek** +- 輸出辨識出的文字並排除常見問題 +- 擴充腳本以批次處理多個 PNG 或切換至其他語言 + +### 前置條件 + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | 現代語法與型別提示 | +| `pytesseract` package | Tesseract 引擎的輕量包裝器 | +| Tesseract OCR binaries (≥ 5.0) | 執行實際運算的核心引擎 | +| Greek language data (`grc.traineddata`) | 正確 **read ancient greek** 所必需 | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | 我們的 **ocr png image** 示範目標 | + +你可以使用以下指令安裝 Python 端: + +```bash +pip install pytesseract Pillow +``` + +在 Ubuntu/macOS 上,你需要安裝引擎本身: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +別忘了下載希臘語多音調的訓練資料: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(路徑可能不同;如有需要請調整 `TESSDATA_PREFIX`。)* + +--- + +## OCR PNG 圖像:建立引擎實例 + +我們首先需要一個與 Tesseract 溝通的物件。在 `pytesseract` 中,透過模組層級的函式存取引擎,但為了清晰,我們會將它包裝在一個小型類別中。這與原始程式碼中看到的「engine」概念相呼應。 + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**為什麼要包裝?** +- 保持公開 API 與你最初的程式碼片段相同,讓遷移毫無痛感。 +- 允許日後加入日誌或錯誤處理,而不必修改主要流程。 +- 展示良好的 OOP 實踐——讓資深開發者讚賞。 + +## 從圖像提取文字:設定語言為希臘語多音調 + +現在我們已有引擎,需要告訴它預期的語言。希臘語多音調使用標準「greek」資料未涵蓋的變音符號,因此我們將 Tesseract 指向 `grc` 訓練檔案。 + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +如果你想在其他語言的 **extract text from image** 檔案中使用,只需將 `"grc"` 替換為 `"eng"`(英文)、`"fra"`(法文)等。只要安裝了相應語言,這行指令皆可使用。 + +## 辨識圖像文字:對 PNG 執行 OCR + +設定語言後,我們將 PNG 輸入引擎。原始範例使用硬編碼路徑;我們將改用 `Path` 物件,使其更具彈性。 + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**提示與邊緣情況** +- **File not found** – 將呼叫包在 `try/except FileNotFoundError` 中,以提供友善訊息。 +- **Low‑resolution PNG** – 考慮在 OCR 前使用 Pillow 進行前處理(例如調整大小、二值化)。 +- **Non‑Greek text** – Tesseract 仍會嘗試解碼,但準確度會大幅下降。務必使用相符的語言設定。 + +## 輸出辨識文字 + +最後,我們將結果印出。在實際專案中,你可能會寫入資料庫、CSV,或甚至將其送入翻譯流程。 + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +當你對清晰的古希臘銘文掃描圖執行腳本時,應該會看到類似以下的輸出: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +如果輸出呈現亂碼,請再次確認 **greek.traineddata** 檔案位於正確資料夾,且 PNG 圖像沒有過於雜訊。 + +## 完整可執行範例(一步到位腳本) + +以下是完整、可直接執行的程式。將其儲存為 `ocr_greek.py`,然後執行 `python ocr_greek.py`。 + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**預期輸出**(為簡潔起見已截斷): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +如果你看到正確的希臘字元,恭喜你——你已成功在 Python 中執行 **ocr png image** 操作! + +## 常見問題與專業技巧 + +### 如何提升噪點 PNG 的辨識準確度? + +- 將圖像轉為灰階:`img = img.convert('L')` +- 套用二元化閾值:`img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- 使用 `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` 進行放大 + +這些步驟常能將 **recognize image text** 的噩夢轉變為乾淨的結果。 + +### 我可以一次處理整個 PNG 資料夾嗎? + +當然可以。將 `recognize_image` 呼叫包在 `for` 迴圈中,遍歷 `Path.glob("*.png")`。將每個結果存入字典或寫入 CSV,以供之後分析。 + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### 如果我只需要提取數字呢? + +將自訂的 **config** 字串傳遞給 `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +如此一來,你就能從包含表格、序號或時間戳記的 **extract text from image** 檔案中提取文字。 + +### 有辦法取得信心分數嗎? + +可以——使用 `pytesseract.image_to_data`,它會回傳每個詞的信心分數 TSV。你可以在組合最終字串前過濾掉低信心的詞彙。 + +## 延伸本教學 + +既然你已掌握基礎,建議探索以下相關主題: + +- **Batch OCR with multiprocessing** – 加速大量 PNG 語料庫的處理。 +- **Hybrid OCR + NLP pipelines** – 自動將提取的古希臘文翻譯成現代英文。 +- **Alternative engines** – 嘗試 `easyocr` 或基於 `opencv` 的方法以因應特定使用情境。 +- **Cloud OCR services** – 使用 Google Vision、Azure Computer Vision 或 AWS Textract 進行無伺服器擴展。 + +上述每項皆以我們剛剛介紹的核心 **python ocr example** 為基礎,讓你能更自在地深入探索。 + +## 結論 + +我們將簡單的程式碼片段轉變為在 Python 中穩健的 **ocr png image** 工作流程。透過建立 `OcrEngine`、設定語言為希臘語多音調、輸入 PNG 並印出結果,你現在已掌握如何 **extract text from image** 檔案、**recognize image text**,甚至 **read ancient greek**。 + +## 接下來該學什麼? + +以下教學涵蓋與本指南密切相關的主題,並以此為基礎。每個資源都提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/hongkong/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..08ba45fcd --- /dev/null +++ b/ocr/hongkong/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR 教學,示範如何辨識影像文字、執行高解析度 OCR 以及使用 GPU 加速的 OCR 來擷取西班牙文文字。 +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: zh-hant +og_description: Python OCR 教學,帶你一步步認識圖像文字、高解析度 OCR,以及使用 GPU 加速提取西班牙文文字。 +og_title: Python OCR 教學 – GPU 加速文字辨識 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR 教學 – 使用 GPU 加速辨識影像文字 +url: /zh-hant/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR 教學 – 使用 GPU 加速辨識影像文字 + +有沒有想過如何在 Python 程式中 **recognize image text**,而不需要花上數小時調整設定?你並不是唯一有此疑問的人。在本篇 **python ocr tutorial** 中,我們將示範一個乾淨、端對端的方式,從高解析度圖片中擷取西班牙文文字,並加入 GPU 加速,使整個過程快如閃電。 + +把它想像成一個快速的咖啡休息示範,之後你可以將它擴展成生產等級的工作流程。閱讀完本指南後,你將擁有一個可執行的程式,能執行 **high resolution OCR**、利用支援 CUDA 的 GPU,並輸出你所需的西班牙文字。 + +## 你將學到什麼 + +- 如何安裝與匯入支援 GPU 加速的現代 OCR 函式庫。 +- 如何建立 OCR 引擎實例,並設定為西班牙文的 **recognize image text**。 +- 如何啟用 **gpu accelerated OCR**,在高解析度檔案上獲得巨大的速度提升。 +- 如何處理如缺少 CUDA 驅動程式或回退至 CPU 等邊緣情況。 +- 提升準確度的技巧,當你需要從噪點掃描中 **extract spanish text** 時。 + +### 先決條件 + +- Python 3.9+(程式碼在 3.10 及更新版本亦可執行)。 +- 支援 CUDA 的 GPU(非必須,但強烈建議)。 +- 對 pip 與虛擬環境有基本了解。 + +如果缺少上述任一項目,教學仍可執行——只要跳過 GPU 步驟,函式庫會自動回退至 CPU。 + +--- + +## Python OCR 教學:安裝必要套件 + +首先,我們需要一個穩固的 OCR 引擎。於本教學中,我們將使用開源的 **`easyocr`** 套件,當偵測到相容裝置時,它會內建 GPU 支援。 + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** 如果你已經安裝了 PyTorch,請確保它與你的 CUDA 版本相符(`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`)。版本不匹配是導致「GPU not found」錯誤的常見原因。 + +--- + +## 步驟 1:建立 OCR 引擎實例 + +現在我們啟動引擎。EasyOCR 的主要類別為 `Reader`。建構子接受語言代碼的清單,我們將傳入西班牙語的 `"es"`。 + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* 透過事先宣告語言,引擎只會載入必要的神經網路權重,從而節省記憶體並加速推論——在之後處理 **high resolution OCR** 時特別有用。 + +## 步驟 2:準備高解析度影像 + +高解析度影像提供模型更多像素可供處理,通常會轉化為更佳的字元辨識。假設你有一個名為 `high_res_spanish.png`,位於 `samples` 資料夾中的檔案。 + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +如果手頭沒有高解析度樣本,你可以從 Unsplash 下載免費圖片,或使用 Pillow 產生合成影像。關鍵是將 DPI 保持在 300 以上,以獲得最佳效果。 + +## 步驟 3:啟用 GPU 加速(可選但建議) + +當你設定 `gpu=True` 時,EasyOCR 已會嘗試使用 GPU。然而,特別在多 GPU 環境下,驗證實際使用的裝置仍是良好做法。 + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* 若腳本悄悄回退至 CPU,你可能會疑惑為何原本 5 秒的操作突然變成 30 秒。這個小檢查讓行為透明,並使你的 **gpu accelerated OCR** 流程保持可預測。 + +## 步驟 4:執行高解析度 OCR 並辨識影像文字 + +現在是有趣的部分——實際讀取文字。EasyOCR 的 `readtext` 方法會回傳一個包含邊界框、辨識字串與信心分數的 tuple 清單。 + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +若你只需要純文字而不含座標,請設定 `detail=0`。對於大多數 **recognize image text** 的使用情境,預設值(`detail=1`)已提供足夠的上下文以便之後後處理。 + +## 步驟 5:擷取西班牙文字並清理輸出 + +因為我們向 EasyOCR 指定了西班牙語,回傳的字串已是該語言。儘管如此,你可能仍想將它們串接、去除空白,或過濾低信心的偵測結果。 + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** 你可以降低門檻(但可能產生雜訊),或在影像上做前處理(提升對比、二值化或去斜)。在掃描文件上執行 **high resolution OCR** 時,這些技巧相當常見。 + +## 步驟 6:處理邊緣案例與效能調整 + +即使是最佳訓練的模型也會在某些情況下失誤。以下提供幾個快速修正,你可以直接貼入腳本中。 + +### 6.1 無 GPU 時的回退方案 + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 大尺寸影像的降採樣 + +如果你的影像大於 4000 × 4000 px,可能會耗盡 GPU 記憶體。請在保留 DPI 的同時按比例降採樣: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +這些程式碼片段可讓腳本更具韌性,無論你是在工作站或是一般筆記型電腦上執行。 + +## 完整範例程式 + +將上述步驟整合起來,以下是完整的腳本,你可以直接複製貼上並立即執行: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**預期輸出(範例):** + + + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,並在此基礎上進一步說明。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [使用 Aspose OCR 從影像擷取文字 – 步驟指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [使用 Aspose.OCR 以語言辨識影像文字的方法](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [在 Aspose.OCR 中辨識頁面矩形以進行文字辨識](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/hongkong/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..762750179 --- /dev/null +++ b/ocr/hongkong/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python OCR 引擎辨識圖片中的文字。學習如何設定 OCR 引擎(Python),並在數分鐘內透過雲端處理從圖片提取文字。 +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: zh-hant +og_description: 使用 Python OCR 引擎辨識影像文字。本指南說明如何在 Python 中設定 OCR 引擎,並高效地從影像中擷取文字。 +og_title: 在 Python 中辨識圖像文字 – 完整設定教學 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 在 Python 中從圖像辨識文字 – 完整 OCR 引擎設定指南 +url: /zh-hant/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中從圖像辨識文字 – 完整設定教學 + +有沒有想過只用幾行 Python 就能 **從圖像辨識文字**?你並不孤單。無論你在開發收據掃描器、文件數位化工具,或是單純的興趣小專案,能從圖像提取文字都是一項快速見效的技能。 + +在本教學中,我們會一步步走過整個流程——從 **configure OCR engine python** 的設定開始,接著雲端驗證,最後示範如何 **extract text from image** 並取得可靠的結果。沒有魔法,只有可直接 copy‑paste 並立即執行的清晰步驟。 + +## 您將學會 + +- 如何安裝與匯入所需的 OCR 函式庫。 +- 用於 **configure OCR engine python** 以進行雲端處理的完整指令。 +- 一個可直接執行的腳本,能 **recognize text from image** 並印出結果。 +- 處理常見問題(如缺少 API 金鑰或不支援的圖像格式)的技巧。 +- 進階想法,例如批次處理與本地備援。 + +### 前置條件 + +- 已在機器上安裝 Python 3.8+。 +- 有網路連線(範例使用雲端 OCR 服務)。 +- 取得 OCR 服務提供者的有效 API 金鑰(稍後會說明如何放入)。 + +如果以上都備妥,讓我們直接進入實作——不囉嗦,只提供實用指南。 + +--- + +## 步驟 1:安裝 OCR 函式庫並匯入 + +在能 **configure OCR engine python** 之前,你必須先安裝能與雲端服務溝通的函式庫。此範例使用一個虛構但具代表性的套件 `ocrcloud`,請自行替換成實際使用的套件(例如 `easyocr`、`google-cloud-vision` 等)。 + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**為什麼這很重要:** 匯入類別後才能使用 `use_cloud()`、`set_api_key()` 等方法。若未匯入,腳本其餘部分會拋出 `NameError`。 + +*小技巧:* 在 `requirements.txt` 中鎖定版本(`ocrcloud==2.1.0`),可避免日後因更新而產生的相容性問題。 + +--- + +## 步驟 2:建立並 **configure OCR engine python** 為雲端模式 + +現在正式 **configure OCR engine python**。預設情況下引擎會在本地運作;切換至雲端模式即可把繁重的影像分析交給強大的伺服器處理。 + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**說明:** +- `OcrEngine()` 會建立一個全新的引擎物件——相當於你的空白畫布。 +- `use_cloud(True)` 會打開開關,指示引擎改以 HTTPS 傳送影像,而非在本機處理。這對於複雜字型或低解析度照片的高準確度結果至關重要。 + +--- + +## 步驟 3:使用雲端 API 金鑰進行驗證 + +大多數雲端 OCR 服務都需要 API 金鑰。此步驟示範如何安全地注入憑證。 + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**安全提醒:** 千萬不要在公開的 repo 中硬編碼金鑰。正式環境應從環境變數取得: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## 步驟 4:**recognize text from image** – 送出遠端影像進行處理 + +引擎設定完成後,我們終於可以 **recognize text from image**。`recognize_image()` 方法接受本機路徑或 URL,回傳包含擷取文字的物件。 + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**底層發生了什麼?** +影像位元組會上傳至服務提供者的端點,由深度學習模型處理,然後以純文字形式回傳。如果影像檔案過大,服務可能會自動降階以加速處理。 + +--- + +## 步驟 5:輸出 **extract text from image** 結果 + +OCR 服務完成工作後,我們只需要把文字印出。實際應用中,你可能會把結果寫入資料庫或傳給其他函式。 + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**預期輸出:**(範例) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +如果輸出看起來亂碼,請確認影像清晰且已選擇正確的語言模型(許多服務允許使用 `engine.set_language("en")` 指定語言)。 + +--- + +## 處理邊緣案例與常見陷阱 + +### 1. 缺少或無效的 API 金鑰 +若出現驗證錯誤,請檢查: +- 金鑰是否仍在有效期內。 +- 是否正確從環境變數讀取。 +- 網路是否允許外部 HTTPS 流量。 + +### 2. 不支援的圖像格式 +大多數 OCR API 支援 JPEG、PNG 與 PDF。若使用 BMP 或 TIFF 可能會回傳「格式不支援」的錯誤。必要時可使用 Pillow 轉檔: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. 請求速率限制 +雲端服務常會限制每分鐘的請求次數。若觸發上限,請實作指數退避機制: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. 回退至本地 OCR +若雲端服務暫時不可用,你可以切回本地模式: + +```python +engine.use_cloud(False) # revert to local mode +``` + +有備援機制可以提升應用的韌性。 + +--- + +## 完整可執行範例 + +以下將所有步驟整合成一個可直接執行的腳本(只要把佔位值換成自己的即可)。 + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**執行方式:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +執行後應會在終端機印出擷取的文字,證明你已成功 **recognize text from image** 並 **extract text from image**,且流程已正確 **configure OCR engine python**。 + +--- + +## 結論 + +我們完整走過從安裝函式庫、驗證雲端服務,到最終 **extract text from image** 的全流程。透過正確的 **configure OCR engine python**,你同時取得彈性(雲端 vs. 本地)與可靠性(完善的錯誤處理)。 + +接下來可以嘗試批次處理一整資料夾的收據、加入語言偵測,或是以 PDF 為輸入。掌握基礎後,想像空間無限。 + +祝開發順利,若有任何問題歡迎在留言區討論——一起學習最棒! + +## 接下來您可以學習什麼? + +以下教學與本篇內容密切相關,能進一步擴充你的技巧。每篇都提供完整可執行的程式碼範例與逐步說明,協助你在專案中探索更多 API 功能與不同實作方式。 + +- [使用 Aspose OCR 從圖像提取文字 – 步驟指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [從圖像提取文字 – 使用 Aspose.OCR 辨識行](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [透過 OCR 事先劃定矩形來提取文字](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..6f647c665 --- /dev/null +++ b/ocr/hongkong/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,335 @@ +--- +category: general +date: 2026-06-06 +description: 使用 Python 對圖像執行 OCR,查看信心分數。學習如何過濾低信心字詞、設定閾值以及處理邊緣情況。 +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: zh-hant +og_description: 在 Python 中對圖像執行 OCR,檢查信心分數,並過濾低信心的詞彙。本教學將帶你完成一個完整且可執行的範例。 +og_title: 使用 Python 在圖片上執行 OCR – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: 使用 Python 在圖片上執行 OCR – 完整逐步教學 +url: /zh-hant/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Python 進行圖像 OCR – 完整步驟指南 + +曾經需要 **對圖像執行 OCR**,卻不確定如何取得可靠的文字嗎?你並不孤單——許多開發者在抽取出的文字顯得搖晃且信心分數成謎時,都會卡在同一個問題上。 + +在本指南中,我們將直接切入可運作的解決方案:示範如何對圖像執行 OCR、讀取整體信心分數,並挑出任何需要人工審核的低信心字詞。完成後,你將擁有可重複使用的腳本、了解每一行程式碼的意義,並知道如何為自己的專案調整信心閾值。 + +## 本教學涵蓋內容 + +我們會一步步走過完整工作流程——從載入圖像到列印出低於 80 % 信心門檻的字詞報告。過程中會討論: + +* 選擇穩定的 OCR 引擎(我們將使用 **EasyOCR**,一個熱門的 Python OCR 函式庫) +* 解析每筆 OCR 結果都會回傳的 `confidence` 屬性 +* 以自訂 **OCR 信心閾值** 篩選字詞 +* 延伸腳本以支援批次處理或改用 **pytesseract** 等其他引擎 + +不需要事先具備 OCR 經驗,只要對 Python 有基本認識,且有可執行的環境(建議 Python 3.9+)即可。 + +準備好把模糊的螢幕截圖變成乾淨、可搜尋的文字了嗎?讓我們開始吧。 + +--- + +## ## 如何使用 Python 對圖像執行 OCR + +本教學的核心是一段三步驟程式碼,與前面示範的程式相同。以下我們會逐行拆解說明原因,最後提供完整、可直接複製貼上的腳本。 + +### 步驟 1:安裝與匯入 OCR 引擎 + +首先,確保已安裝 OCR 函式庫。**EasyOCR** 開箱即支援多種語言,且會為每個字詞提供信心分數。 + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*為什麼選 EasyOCR?* 它內建已於多樣資料集上訓練的深度學習模型,通常比舊版的 Tesseract 引擎在混合品質圖像上取得更高的信心分數。 + +> **小技巧:** 若你使用的環境受限(例如極小的 Docker container),`pytesseract` 可能較輕量,但會犧牲 EasyOCR 所提供的現代化準確度。 + +### 步驟 2:對圖像執行 OCR + +現在真正 **對圖像執行 OCR**。原範例的 `recognize_image` 方法改為 EasyOCR 的 `readtext` 呼叫,會回傳 `(bbox, text, confidence)` 三元組的列表。 + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +`ocr_results` 中的每筆資料長這樣: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +第三個元素(範例中的 `0.92`)即為 0~1 之間的信心分數。 + +### 步驟 3:彙總整體信心分數 + +與前面的程式只印出單一 `confidence` 屬性不同,EasyOCR 為每個字詞提供信心分數。為了快速掌握整體情況,我們會取平均值: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*為什麼要取平均?* 這能快速檢查健康狀況——若整體信心低於 70 % 左右,可能需要改善圖像(例如提升光線、前處理等)。 + +### 步驟 4:列出低信心字詞 + +接下來就是直接回應「列出信心低於設定門檻的字詞」需求的部分。我們預設 **OCR 信心閾值** 為 0.80(80 %),當然你可以自行調整。 + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +迴圈會印出每個未達門檻的字詞,並顯示其百分比信心。這正是原本 `for recognized_word in recognition_result.words` 迴圈的等價寫法,只是改用 EasyOCR 的輸出格式。 + +--- + +## ## 了解 OCR 信心分數 + +信心分數並非魔法數字;它是模型對特定轉錄結果的確定程度估計。以下幾點值得留意: + +| 情境 | 典型信心分數 | 建議處理方式 | +|-----------|-------------------|------------| +| 清晰、高解析度的掃描 | 0.95 – 1.00 | 不需額外處理 | +| 輕微模糊或光線不均 | 0.80 – 0.94 | 考慮輕度前處理(提升對比) | +| 噪點嚴重、文字旋轉 | < 0.70 | 進行圖像前處理(去斜、去噪)或改用其他 OCR 引擎 | + +> **注意:** 某些語言(例如手寫草寫)天生會得到較低分數,請依需求調整閾值。 + +### 邊緣案例與變化 + +1. **批次處理** – 若需 **對圖像執行 OCR** 的檔案大量處理,只要把上述邏輯包在遍歷目錄的迴圈中即可。 +2. **多語言** – 傳入 `['en', 'fr']` 給 `easyocr.Reader`,引擎會同時偵測兩種語言。 +3. **替代引擎** – 想試試 **pytesseract**?只要把讀取區塊換成: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + 之後需要把每個字元的信心聚合成每個字詞的值——稍微多點工作但可行。 + +4. **前處理技巧** – 使用 OpenCV 濾鏡(`cv2.threshold`、`cv2.GaussianBlur`)可提升噪點掃描的信心分數。 + +--- + +## ## 完整、可直接執行的腳本 + +以下是完整的 Python 檔案,你只要把它放入專案即可。存為 `ocr_report.py`,然後執行 `python ocr_report.py`。別忘了把圖像路徑改成實際檔案。 + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**預期輸出**(實際數字會因圖像而異): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +如果所有字詞都通過 80 % 門檻,會看到友善的「All words meet the confidence threshold.」訊息。 + +--- + +## ## 常見問題 (FAQ) + +**Q: 這能直接處理 PDF 嗎?** +A: 不能直接。先把每頁 PDF 轉成圖像(例如使用 `pdf2image`),再把產生的 PNG/JPEG 丟給腳本。 + +**Q: 我的信心分數全部很低,該怎麼辦?** +A: 嘗試圖像前處理:提升對比、去除背景噪點,或將圖像旋轉至水平基線。EasyOCR 也接受 `contrast_ths` 參數,可自行微調。 + +**Q: 可以把結果匯出成 CSV 嗎?** +A: 當然可以。在低信心迴圈之後,使用 `csv.DictWriter` 把 `ocr_results` 寫入 CSV,每列包含 `text`、`confidence` 與邊界框座標。 + +**Q: 有支援 GPU 加速的版本嗎?** +A: 若安裝了相容的 GPU 與 PyTorch,EasyOCR 會自動使用 CUDA。執行前可用 `torch.cuda.is_available()` 先確認。 + +--- + +## 結論 + +我們剛剛 **對圖像執行 OCR**,檢視了整體信心,並挑出需要人工檢查的低信心字詞。 + +## 接下來該學什麼? + +以下教學與本指南的技巧密切相關,能幫助你進一步掌握 API 功能,或探索其他實作方式: + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/hungarian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..3c0e11079 --- /dev/null +++ b/ocr/hungarian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Néhány perc alatt szöveget nyerj ki képből Python OCR-rel. Fedezd fel + a többnyelvű képoszályozást, az automatikus nyelvfelismerést, és megtudd, hogyan + lehet pontosan kinyerni az OCR-szöveget. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: hu +og_description: Gyorsan vonjon ki szöveget képből Python OCR-rel. Tanulja meg a többnyelvű + képoszlopolvasást, az automatikus nyelvfelismerést, és a lépésről lépésre történő + OCR-szöveg kinyerés módját. +og_title: Kép szövegének kinyerése Python OCR segítségével – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Képből szöveg kinyerése Python OCR-rel – Teljes útmutató +url: /hu/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kép szövegének kinyerése Python OCR-rel – Teljes útmutató + +Valaha is szükséged volt **kép szövegének kinyerésére**, de nem tudtad, melyik könyvtár tudja automatikusan kezelni a több nyelvet? Nem vagy egyedül – a fejlesztők gyakran kérdezik, *hogyan lehet OCR‑szöveget kinyerni*, amikor nemzetközi dokumentumokkal, nyugtákkal vagy beolvasott szórólapokkal dolgoznak. Ebben a bemutatóban egy gyakorlati Python példán keresztül mutatjuk be, hogyan lehet szöveget kinyerni egy képből, és közben **valós időben felismerni a nyelvet**, így a többnyelvű kép‑OCR egyszerűvé válik. + +Mindent lefedünk a OCR‑csomag telepítésétől a **nyelv automatikus felismerésének** engedélyezéséig, a motor futtatásáig egy mintaképen, és végül a felismert nyelv és a kinyert szöveg kiírásáig. A végére egy újrahasználható kódrészletet kapsz, amelyet bármely projektbe beilleszthetsz, legyen szó fordítási csővezetékekről vagy adat‑befogadó szolgáltatásról. + +## Kép szövegének kinyerése – A környezet előkészítése + +Mielőtt a kódba merülnénk, győződj meg róla, hogy a munkakörnyezeted megfelel az alábbi minimális követelményeknek: + +- Python 3.8 vagy újabb (a könyvtár típusjelzéseket használ, amelyeket a régebbi verziók figyelmen kívül hagynak) +- `pip` a csomagkezeléshez +- Egy olyan képfájl, amely legalább két különböző nyelven tartalmaz szöveget (pl. angol + spanyol) + +Szükséged lesz az OCR‑könyvtárra, amely ezt a demót hajtja. A bemutató kedvéért a fiktív `ocr` csomagot használjuk, amely a Tesseract vagy az EasyOCR valós eszközeinek működését tükrözi, de tiszta Python API‑t kínál. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tipp:** Ha jogosultsági hibákkal találkozol, előzd meg a parancsot `python -m`‑vel, vagy használj virtuális környezetet – így a globális site‑packages tisztán marad. + +## OCR motor példány létrehozása + +Miután a könyvtár készen áll, az első logikus lépés **OCR motor példány létrehozása**. Tekintsd a motort egy okos szkennernek, amelyet a képek betáplálása előtt konfigurálhatsz. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Miért hozunk létre külön motor példányt a statikus metódus hívása helyett? A motor objektum tárolja a konfigurációs állapotot (például a nyelvi beállításokat), amelyet sok kép esetén újra felhasználhatsz, így elkerülve a motor minden egyes alkalommal történő újra‑inicializálását. + +## Nyelv automatikus felismerésének engedélyezése + +A legtöbb OCR eszköz megköveteli a nyelvkód megadását – `eng` az angolhoz, `spa` a spanyolhoz stb. A nyelv kézi kitalálása ellentétes a **többnyelvű kép‑OCR** munkafolyamat céljával. Szerencsére a `ocr` csomag kínál egy *auto detect language OCR* módot, amely a képet elemzi, és a háttérben a legmegfelelőbb nyelvi modellt választja ki. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Az **detect language OCR** ilyen módon történő engedélyezése azt jelenti, hogy nem kell hosszú nyelvkód-listát karbantartanod. A motor megpróbálja egyeztetni a látott írásrendszert – latin, cirill, han stb. – és automatikusan betölti a megfelelő modellt. + +## Többnyelvű kép‑OCR végrehajtása + +Miután a motor elő van készítve, itt az ideje, hogy ténylegesen **kép szövegét kinyerjük**. A `recognize_image` metódus egy fájlútvonalat fogad, és egy eredményobjektust ad vissza, amely tartalmazza a nyers szöveget és a felismert nyelvet. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Ha arra vagy kíváncsi, *hogyan lehet OCR‑szöveget kinyerni* egy PDF‑ből PNG helyett, ugyanaz a motor kínál `recognize_pdf`‑t – csak cseréld le a metódus nevét. A háttérben lévő felismerési logika azonos, így ugyanazt a **auto detect language OCR** funkciót használod. + +## Felismert nyelv és kinyert szöveg megjelenítése + +Végül kiírjuk, amit a motor felfedezett. Az eredményobjektum tartalmazza a `detected_language` (egy BCP‑47 címke, mint `en` vagy `es`) és a `text` mezőt, amely a nyers OCR‑kimenetet tárolja. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +A szkript futtatása a mintaképen valami ilyesmit kell, hogy eredményezzen: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Figyeld meg, hogy a motor helyesen azonosította az angolt elsődleges nyelvként, ugyanakkor a spanyol sort is rögzítette – éppen ezt várod egy robusztus **többnyelvű kép‑OCR** megoldástól. + +### Mi történik, ha a felismerés sikertelen? + +Előfordulhat, hogy az OCR motor egy alapértelmezett nyelvre (általában angolra) vált vissza, ha a kép elmosódott vagy az írásrendszer túl egzotikus. Ilyen esetben kényszerítheted a nyelvlistát: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +De ne feledd, a nyelvek kényszerítése ellentétes a **auto detect language OCR** kényelmével, ezért csak akkor használd, ha egy ismert nyelvkészlettel dolgozol. + +## Gyakori buktatók és a OCR‑szöveg megbízható kinyerése + +Még az automatikus felismerés mellett is előfordulhatnak kisebb akadályok: + +1. **Alacsony felbontású képek** – Az OCR pontossága drasztikusan csökken 150 dpi alatti felbontásnál. Nagyíts fel, vagy kérj nagyobb felbontású beolvasást. +2. **Zaj és tömörítési artefaktusok** – Alkalmazz egyszerű küszöb‑szűrőt (`opencv` vagy `Pillow`) a kép motorba való betáplálása előtt. +3. **Vegyes írásrendszerek egy oldalon** – Néhány motor nehezen birkózik meg egyszerre latin és CJK karakterekkel. Oszd fel az oldalt régiókra, és futtass külön‑külön felismerést, ha szükséges. + +Ezeknek a problémáknak a kezelése jelentősen javítja a **kép szövegének kinyerése** folyamat minőségét, különösen valós, többnyelvű dokumentumok esetén. + +## Teljes működő példa + +Az alábbiakban a teljes, azonnal futtatható szkript látható, amely egyesíti az összes korábban bemutatott lépést. Mentsd `multilingual_ocr.py` néven, és futtasd a parancssorból. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Várható kimenet** (feltételezve, hogy a mintakép angol és spanyol szöveget tartalmaz): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Nyugodtan cseréld le a `multilang_page.png`‑t bármely olyan képre, amely más nyelveken is tartalmaz szöveget – a **auto detect language OCR** köszönhetően a szkript továbbra is értelmes nyelvcímkét és a megfelelő szöveget adja vissza. + +![Kép szövegének kinyerése példa](https://example.com/ocr-sample.png "Kép szövegének kinyerése") + +## Összegzés + +Most már pontosan tudod, **hogyan kell OCR‑szöveget kinyerni** egy képből, hogyan kell engedélyezni a **nyelv automatikus felismerését**, és hogyan kell kezelni a **többnyelvű kép‑OCR** helyzeteket minimális kóddal. Egy OCR motor példány létrehozásával, az automatikus nyelvfelismerés bekapcsolásával, és a `recognize_image` meghívásával megbízhatóan kinyerheted a nyelvi azonosítót és a nyers szöveget. + +Mi a következő lépés? Próbáld meg a kinyert szövegeket egy fordítási API‑ba továbbítani, tárold őket kereshető adatbázisban, vagy több oldalt egyetlen PDF‑jelentésbe egyesíteni. Kísérletezhetsz különböző OCR háttér‑rendszerekkel (Tesseract, EasyOCR, Google Vision) is, miközben ugyanazt a magas szintű munkafolyamatot tartod – köszönhetően a konzisztens **detect language OCR** interfésznek. + +Ha bármilyen furcsaságot tapasztalsz, nézd át újra a „Gyakori buktatók” részt, vagy finomítsd a kép előfeldolgozási lépéseket. Jó kódolást, és legyen a következő projekted tele helyesen felismert, tökéletesen kinyert szöveggel! + +## Mit érdemes még megtanulni? + +A következő oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy segítsenek további API‑funkciók elsajátításában és alternatív megvalósítási megközelítések felfedezésében a saját projektjeidben. + +- [Kép konvertálása szöveggé – OCR végrehajtása URL‑ről származó képen](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Kép szövegének kinyerése – OCR optimalizálás Aspose.OCR‑rel .NET‑hez](/ocr/english/net/ocr-optimization/) +- [szöveg felismerése képen több nyelven az Aspose OCR‑rel](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/hungarian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..9c47ccf53 --- /dev/null +++ b/ocr/hungarian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Szöveg kinyerése képekből és PDF-ből Python OCR-rel. Tanulja meg, hogyan + konvertálhatja a beolvasott dokumentumokat szöveggé gyorsan aszinkron kötegelt felismeréssel. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: hu +og_description: Szöveg kinyerése képekből és PDF‑ből Python segítségével. Ez a lépésről‑lépésre + útmutató bemutatja, hogyan lehet a beolvasott dokumentumokat szöveggé konvertálni + aszinkron OCR használatával. +og_title: Szöveg kinyerése képekből PDF-ben – Python OCR oktató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Szöveg kinyerése képek PDF-ből – Python útmutató a beolvasott dokumentumok + szöveggé konvertálásához +url: /hu/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Képek PDF-ből szöveg kinyerése – Python útmutató a beolvasott dokumentumok szöveggé konvertálásához + +Valaha is szükséged volt **szöveg kinyerésére képek PDF-ből** anélkül, hogy órákat töltenél a gépeléssel? Ebben az útmutatóban megmutatjuk, hogyan **konvertálhatod a beolvasott dokumentumokat szöveggé** egy egyszerű aszinkron OCR munkafolyamat segítségével Pythonban. + +Ha már valaha is egy csomó beolvasott PDF-et néztél, és azt gondoltad: „Biztos van gyorsabb módja”, akkor jó helyen vagy. Át fogjuk nézni a kód minden sorát, elmagyarázzuk, miért fontos minden részlet, és még néhány edge case‑et is bemutatunk, amivel előfordulhat, hogy találkozol. + +## Mit fogsz megtanulni + +- Hogyan indítsunk el egy OCR motort és állítsuk be a felismerési nyelvet. +- A vegyes PNG‑ és PDF‑lista betáplálásának mechanikája egy kötegelt felismerőbe. +- Az OCR feladat aszinkron futtatása, hogy az alkalmazásod reagálóképes maradjon. +- Az eredmények visszakeresése, párosítása a forrásfájlokkal, és tiszta kimenet nyomtatása. + +**Előfeltételek**: Python 3.8+, alapvető ismeretek az `asyncio`‑ról vagy a `concurrent.futures`‑ről, valamint egy OCR könyvtár, amely egy példához hasonló `OcrEngine` osztályt biztosít (pl. Aspose.OCR, Tesseract wrapper, vagy egy egyedi wrapper). Nehéz beállításra nincs szükség – csak telepítsd a könyvtárat, és már indulhatsz. + +![szöveg kinyerése képek PDF-ből](https://example.com/placeholder.png "OCR kimenet képernyőképe – szöveg kinyerése képek PDF-ből") + +## Képek PDF-ből szöveg kinyerése – OCR motor beállítása + +Az első dolog, amire szükséged van, egy OCR motor példány, amely a dokumentumaid nyelvére van konfigurálva. A példában franciát használunk, de bármely támogatott nyelvre cserélheted. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Miért fontos ez**: A nyelv előzetes beállítása drámaian javítja a pontosságot. A motor nyelvspecifikus szótárakat és karaktermodelleket használ; a rossz nyelv megadása gyakori oka a torz kimenetnek. + +## Fájllista előkészítése – Képek és PDF-ek együtt + +A kötegelt felismerő képes kezelni mind a raszteres képeket (`.png`, `.jpg`), mind a PDF konténereket. Csak adj át egy egyszerű Python listát a fájlutakból. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tipp**: Tartsd a listát lapos struktúrában; a motor belsőleg minden PDF‑oldalt képekké bont, mielőtt a felismerés megtörténik. Ha több ezer fájlod van, fontold meg a lista kisebb adagokra bontását, hogy elkerüld a memóriahullámokat. + +## Aszinkron kötegelt felismerés indítása + +A fő szál blokkolása helyett a OCR feladatot a háttérben indítjuk el. A metódus egy `Future`‑t ad vissza, amely végül egy `OcrResult` objektumok listáját fogja tartalmazni. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Hogyan működik**: A motor a háttérben egy szálcsoportot (vagy aszinkron feladatot, a megvalósítástól függően) hoz létre. Ez lehetővé teszi, hogy más munkákat is végezz – például UI frissítést, további fájlok betöltését vagy a folyamat állapotának naplózását – miközben a nehéz feldolgozás máshol zajlik. + +## Hasznos feladat végrehajtása OCR futása közben + +Gyakori hiba, hogy üresjáratban várakozol és szoros ciklusban lekérdezed a future‑t. Ehelyett végezhetsz bármilyen más, nem kapcsolódó feladatot. Demonstrációként csak egy státuszsor kiírását mutatjuk. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Eredmények összegyűjtése a Future befejezése után + +Amikor készen állsz az OCR kimenet begyűjtésére, használd a `as_completed`‑t a `concurrent.futures`‑ből. Ez a minta akkor is működik, ha egy vagy több future‑d van. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Mit fogsz látni**: Minden fájlút után a kinyert egyszerű szöveg jelenik meg. PDF-ek esetén a `result.text` tartalmazza az összes oldal összefűzött szövegét. + +### Várható kimenet (példa) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Ha hiányzó karaktereket észlelsz, ellenőrizd, hogy a beállított nyelv megegyezik‑e a dokumentum nyelvével, és fontold meg a képek előfeldolgozását (kiegyenesítés, kontraszt növelés) a motorba való betáplálás előtt. + +## Széljegyek és gyakori buktatók kezelése + +| Helyzet | Mit kell tenni | +|-----------|------------| +| **Vegyes nyelvek** | Először futtass nyelvfelismerő lépést, majd hozz létre külön motorokat nyelvenként. | +| **Óriási PDF-ek (> 100 MB)** | Oszd fel a PDF-et egyes oldalakra a lemezen (pl. a `PyPDF2`‑vel), és tápláld be őket külön bejegyzésként. | +| **Nem latin írásrendszerek** | Győződj meg róla, hogy az OCR könyvtár tartalmazza a szükséges nyelvi csomagot; egyes könyvtárakhoz további adatfájlok letöltése szükséges. | +| **Teljesítménybottleneck** | Növeld a szálcsoport méretét (`engine.set_thread_pool_size(8)`) vagy válts GPU‑gyorsított backendre, ha elérhető. | +| **Hiányzó szöveg alacsony felbontású képeken** | Előfeldolgozás OpenCV‑vel: `cv2.resize`, `cv2.threshold`, és `cv2.medianBlur` a olvashatóság javításához. | + +## Teljes működő példa (másolás-beillesztés kész) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Mentsd el `extract_text_async.py` néven, cseréld le a `YOUR_DIRECTORY`‑t a fájljaid elérési útjára, telepítsd az OCR csomagot (`pip install your-ocr-lib`), és futtasd a `python extract_text_async.py` parancsot. A konzolon a korábban illusztrált kimenetet kell látnod. + +## Következő lépések – Alapvető kinyerésen túl + +- **Utófeldolgozás**: Távolítsd el a felesleges szóközöket, normalizáld a Unicode‑t (`unicodedata.normalize`), vagy futtass helyesírás-ellenőrzőt az OCR zaj csökkentéséhez. +- **Strukturált kimenet**: Exportáld az eredményeket CSV‑be, JSON‑ba, vagy közvetlenül egy adatbázisba a további kereséshez. +- **Párhuzamos kötegek**: Ha több száz fájlod van, indíts több future‑t, és használj egy sort, hogy a CPU folyamatosan dolgozzon anélkül, hogy a memória túlterhelődne. +- **Integráció webes keretrendszerekkel**: Kapcsold ezt a szkriptet egy Flask vagy FastAPI végponthoz, hogy igény szerint OCR‑szolgáltatást nyújts. + +--- + +### TL;DR + +Most már tudod, hogyan **szöveget nyerhetsz ki képek PDF‑ből** egy minimális Python szkripttel, amely aszinkron módon futtatja az OCR‑t, így **beolvasott dokumentumokat szöveggé konvertálhatsz**, miközben a programod reagálóképes marad. Kísérletezz a nyelvi beállításokkal, kötegméretekkel és előfeldolgozási trükkökkel, hogy a lehető legmagasabb karakter‑pontosságot érjed el. + +Van egy saját ötleted – például OCR kézírásos jegyzeteken vagy felhőalapú szolgáltatáson? Írj egy megjegyzést, és jó kódolást! + +## Mit érdemes még tanulni? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek az API további funkcióinak elsajátításában és alternatív megvalósítási megközelítések felfedezésében a saját projektjeidben. + +- [Szöveg kinyerése képből Aspose OCR-rel – Lépésről‑lépésre útmutató](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Szöveg kinyerése képekből OCR művelettel mappákon](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Szöveg kinyerése képekből Aspose.OCR-rel – Engedélyezett karakterek](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..87351c335 --- /dev/null +++ b/ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Hogyan OCR-eljünk PDF-et Pythonban, szöveget nyerjünk ki PDF-ből, konvertáljuk + a beolvasott PDF szövegét, és csak néhány kódsorral változtassuk meg az OCR nyelvét. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: hu +og_description: 'Hogyan OCR-elj PDF-et Python-nal: egy gyakorlati útmutató, amely + megmutatja, hogyan lehet szöveget kinyerni PDF-ből, átalakítani a beolvasott PDF + szöveget, és könnyedén megváltoztatni az OCR nyelvet.' +og_title: Hogyan OCR-elj PDF-et Pythonban – Teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Hogyan OCR-eljünk PDF-et Pythonban – Teljes lépésről‑lépésre útmutató +url: /hu/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan OCR-elj PDF-et Pythonban – Teljes Lépésről‑Lépésre Útmutató + +Gondoltad már valaha, **hogyan OCR-elj PDF** fájlokat anélkül, hogy drága SaaS eszközöket fizetnél? Nem vagy egyedül. Akár régi könyveket digitalizálsz, számlákról nyersz ki adatokat, vagy egyszerűen csak kereshető szöveget szeretnél egy beolvasott jelentésből, a PDF OCR Pythonban való elsajátítása órákat takaríthat meg a kézi másolástól. + +Ebben a tutorialban egy tömör, működő példán keresztül vezetünk végig, amely **kivonja a szöveget a PDF-ből**, megmutatja, hogyan **alakítsd át a beolvasott PDF szöveget** szerkeszthető karakterláncokká, és még azt is bemutatja, hogyan **változtasd meg az OCR nyelvet**, ha a dokumentumod nem angol nyelvű. A végére egy újrahasználható kódrészletet kapsz, amelyet bármely projektbe beilleszthetsz. + +## Előkövetelmények és Beállítás + +- Python 3.8+ telepítve (a kód 3.9, 3.10 és újabb verziókon is működik) +- Az `ocr` csomag, amely biztosítja az `OcrEngine` osztályt (telepítheted a `pip install ocr-lib` paranccsal – cseréld ki a tényleges csomagnévre) +- Egy PDF fájl, amelyet feldolgozni szeretnél; a demóhoz a `high_res_book.pdf` fájlt használjuk, amely a `YOUR_DIRECTORY` nevű mappában van + +Ha virtuális környezetet használsz (erősen ajánlott), először aktiváld azt: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tipp:** Tartsd a PDF fájljaidat egy dedikált `data/` könyvtárban, hogy később elkerüld az útvonallal kapcsolatos fejfájást. + +## 1. lépés: OCR Engine példány létrehozása (Hogyan OCR-elj PDF – Inicializálás) + +Az első dolog, amit meg kell tenned, ha **PDF-en szeretnél OCR-t végezni**, az az engine példányosítása. Gondolj az engine-re úgy, mint az agyra, amely minden oldalt beolvas, értelmezi a glifeket, és egyszerű szöveget ad vissza. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Miért fontos: engine nélkül nincs kontextusod a nyelvi beállításokhoz, renderelési opciókhoz vagy a PDF kezeléséhez. Az `OcrEngine` objektum tartalmazza ezeket az alapértelmezéseket, és később finomhangolhatod őket. + +## 2. lépés: Felismerési nyelv beállítása (OCR nyelv megváltoztatása) + +A legtöbb OCR könyvtár alapértelmezés szerint angolt használ, de mi van, ha a dokumentumod francia, német vagy akár japán nyelvű? A nyelv megváltoztatása olyan egyszerű, mint a `set_recognition_language` meghívása. Ez teljesíti a **change OCR language** követelményt, és magasabb pontosságot biztosít. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Miért lehet erre szükséged:** Egy többnyelvű archívum gyakran vegyes nyelvű oldalakat tartalmaz. A nyelvek valós időben történő váltása megakadályozza a karakterek, például a “ß” vagy “ñ” helytelen felismerését. + +## 3. lépés: PDF renderelési opciók konfigurálása (Beolvasott PDF szöveg hatékony átalakítása) + +Beolvasott PDF-ekkel dolgozva a felbontás és a színmód drámaian befolyásolja az OCR minőségét. A 300 DPI-s, szürkeárnyalatos renderelés a legtöbb dokumentum számára ideális – elég magas a részletek rögzítéséhez, de alacsony ahhoz, hogy a memóriahasználat ésszerű maradjon. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +A láncolt hívások talán elegánsnak tűnnek, de valójában egy folyékony API-ról van szó, amely minden alkalommal ugyanazt az opcióobjektumot adja vissza. Ha színt szeretnél (például színes diagramokhoz), cseréld a `"grayscale"`-t `"color"`-ra. + +## 4. lépés: PDF felismerése és az első oldal szövegének lekérése (Szöveg kinyerése a PDF-ből) + +Most következik a **hogyan OCR-elj PDF** lényeges része: a motor átadása egy fájlútnak, és a felismert szöveg kinyerése. A metódus egy oldal eredmények listáját adja vissza; minden eredmény egy `text` attribútumot tartalmaz. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Ha az egész dokumentumra szükséged van, iterálj a `results`-en: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Mi van, ha a PDF titkosított? + +Néhány PDF jelszóval védett. Ebben az esetben átadhatod a jelszót a `recognize_pdf`-nek: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Az engine a futás közben feloldja a titkosítást, mielőtt az OCR-t elvégezné – nincs szükség további lépésekre. + +## 5. lépés: Kinyert szöveg utófeldolgozása (Finomhangolás a PDF szöveg kinyeréséhez) + +A nyers OCR kimenet gyakran tartalmaz sortöréseket, felesleges szóközöket vagy időnként hibásan felismert karaktereket. Egy gyors tisztító rutin a kinyert karakterláncot készen áll a további feldolgozásra (kereső indexelés, adatbázis tárolás, stb.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Most már biztonságosan **kivonhatod a szöveget a PDF-ből**, és betáplálhatod bármely NLP csővezetékbe, keresőmotorba vagy egyszerű `open(...).write()` műveletbe. + +## Bónusz: Több PDF kötegelt feldolgozása (OCR skálázása PDF-eken) + +Ha egy mappád tele van beolvasott PDF-ekkel, csomagold a logikát egy ciklusba: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Ez a kódrészlet megmutatja, hogyan **perform OCR on PDF** fájlokat kötegelt módon, ami gyakori igény a digitalizációs projektekben. + +## Várható kimenet + +A egyoldalas példa (4. lépés) futtatása valami ilyesmit kell, hogy kiírjon: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Ha többoldalas könyvet dolgoztál fel, a konzol minden oldal tisztított szövegét megjeleníti, és a kötegelt szkript minden PDF mellé egy `.txt` fájlt hagy. + +## Gyakori hibák és elkerülésük módja + +| Probléma | Tünetek | Megoldás | +|----------|----------|----------| +| Alacsony felbontású forrás PDF | Torzuló karakterek, hiányzó szavak | Növeld a DPI-t (`set_dpi(400)` vagy magasabb) | +| Helytelen nyelv beállítva | Sok ismeretlen szimbólum, különösen ékezetes karakterek | Használd a `engine.set_recognition_language(ocr.Language.FRENCH)`-t vagy a megfelelő enumot | +| Nagy PDF memóriahibát okoz | `MemoryError` vagy összeomlás néhány oldal után | Dolgozd fel az oldalakat darabokban (`engine.recognize_pdf(..., max_pages=10)`) | +| Hiányzó betűkészletek a PDF-ben | Üres kimenet bizonyos oldalakon | Győződj meg róla, hogy a PDF valóban raszteres képeket tartalmaz; egyes PDF-ek csak vektorosak, és más kezelést igényelnek | + +## Képi illusztráció + +Alább egy gyors vizuális ábra a munkafolyamatról. Az alt szöveg szándékosan SEO‑barát. + +![hogyan OCR-elj pdf munkafolyamat diagram, amely mutatja az engine inicializálását, nyelv beállítását, renderelési opciókat, felismerést és szöveg kinyerést](/images/ocr-workflow.png) + +*A diagram nem szükséges a kód futtatásához, de segít a vizuális tanulóknak látni, hogy melyik lépés hova illeszkedik.* + +## Következtetés + +Áttekintettük, hogyan **OCR-elj PDF** fájlokat Pythonban a kezdetektől a végéig: OCR engine létrehozása, **OCR nyelv megváltoztatása**, a renderelés konfigurálása a **beolvasott PDF szöveg átalakításához**, és végül a **szöveg kinyerése a PDF-ből** további felhasználásra. A teljes, futtatható példa készen áll bármely projektbe beilleszteni, és a opcionális kötegelt szkript megmutatja, hogyan skálázható a megoldás. + +Következő lépésként érdemes lehet: + +- Többnyelvű archívumokhoz **perform OCR on PDF** hozzáadása nyelvlistán való iterálással. +- A kinyert szöveg integrálása Elasticsearch-be a teljes szöveges kereséshez. +- OCR használata kereshető PDF-ek létrehozásához, a szövegréteg visszaágyazásával az eredeti fájlba (számos könyvtár biztosít `save_as_searchable_pdf` metódust). + +Nyugodtan kísérletezz, finomhangold a DPI beállításokat, vagy válts másik OCR backendre. Az alapok változatlanok, és most már szilárd alapod van a további fejlesztéshez. + +Boldog kódolást, és legyenek a beolvasott dokumentumaid végre kereshetők! + +## Mit érdemes következőként megtanulni? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [PDF szöveg felismerése – OCR műveletek Aspose.OCR-rel Java-hoz](/ocr/english/java/ocr-operations/) +- [Hogyan OCR-elj képszöveget nyelvvel az Aspose.OCR használatával](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Hogyan OCR-elj PDF-et .NET-ben az Aspose.OCR-rel](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..7ca174b1d --- /dev/null +++ b/ocr/hungarian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-06 +description: Hogyan OCR-elj PDF-et, és hozz létre kereshető PDF-fájlokat képekből + Python használatával. Tanulj meg kereshető szöveget hozzáadni és képet PDF/A formátumba + konvertálni percek alatt. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: hu +og_description: Hogyan OCR-elj PDF-et lépésről lépésre. Tanulja meg, hogyan adjon + hozzá kereshető szöveget, és konvertálja a képet PDF/A formátumba egy egyszerű Python + szkript segítségével. +og_title: Hogyan OCR-elj PDF-et – Gyors útmutató kereshető PDF-ek létrehozásához +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Hogyan OCR-elj PDF-et Pythonban – Kereshető PDF létrehozása képekből +url: /hu/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan OCR PDF – Szkennelt képek átalakítása kereshető PDF‑ekké + +Valaha is elgondolkodtál **hogyan OCR PDF-et** készíthetsz, ha csak egy szkennelt számla‑ vagy nyugta‑kép áll rendelkezésedre? Nem vagy egyedül. Sok irodában a beérkező papírok PNG‑ként vagy JPEG‑ként érkeznek, és a következő lépés – a tartalom kereshetővé tétele – gyakran fekete dobozként jelenik meg. + +A jó hír? Néhány Python‑sorral **kereshető PDF** fájlokat hozhatsz létre, **kereshető szöveget adhatsz hozzá**, sőt **kép‑PDF/A‑vá konvertálhatsz** hosszú távú archiváláshoz. Ebben a tutorialban lépésről lépésre végigvezetünk, elmagyarázzuk, miért fontos, és adunk egy azonnal futtatható szkriptet, amit bármely projektbe beilleszthetsz. + +> **Pro tipp:** Ugyanez a megközelítés működik többoldalas szkeneknél is; csak iterálj a fájlokon, és a motor elvégzi a nehéz munkát. + +--- + +## Amire szükséged lesz + +Mielőtt belevágnánk, győződj meg róla, hogy a következők telepítve vannak a gépeden: + +| Követelmény | Miért fontos | +|-------------|--------------| +| Python 3.9 vagy újabb | Modern szintaxis és jobb könyvtár‑támogatás | +| `pdfium`‑alapú OCR motor (pl. `pdfocr` vagy kereskedelmi SDK) | Képfelismerést és PDF/A generálást is kezel | +| Egy kép‑fájl (PNG, JPEG, TIFF), amit kereshető PDF‑é szeretnél alakítani | A szöveg forrása | +| Írási jogosultság a kimeneti mappához | Ahhoz, hogy a szkript el tudja menteni az új PDF‑et | + +Ha még nem telepítetted az OCR SDK‑t, futtasd: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Ennyi – nincs bonyolult rendszer‑függőség, csak egy pip install. + +--- + +## Hogyan OCR PDF – Áttekintés + +Magas szinten a folyamat három egyszerű lépésből áll: + +1. **Felismerni** a képen lévő szöveget, miközben az eredeti grafikát megőrizzük. +2. **Exportálni** az OCR‑eredményt az eredeti képpel együtt **kereshető PDF/A‑ként** (az archiválásra optimalizált PDF‑változat). +3. **Érvényesíteni**, hogy a kapott fájl tartalmazza a kiválasztható, kereshető szöveget a kép rétege felett. + +Az alábbiakban minden lépést kóddal mutatunk be, a parancsok mögötti *miért* magyarázatával. + +--- + +## 1. lépés: Szöveg felismerése a képből + +Először megkérjük az OCR motort, hogy olvassa be a pixeleket, és adjon vissza egy eredményobjektumot, amely a nyers képet és a kinyert szöveget egyaránt tartalmazza. Gondolj rá úgy, mintha a motor „elolvasná” a számlát helyetted. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Miért fontos + +- **A grafika megőrzése** azt jelenti, hogy a vizuális elrendezés (táblázatok, logók, pecsétek) pontosan úgy marad, ahogy a szkenner rögzítette. +- A `result` objektum általában egy rejtett szövegréteget tartalmaz, amelyet később beágyazunk a PDF‑be. +- A `recognize_image` használata a `recognize_pdf` helyett elkerüli a felesleges konverziós lépést, így gyorsabb a feldolgozás egyoldalas képek esetén. + +#### Gyakori variációk + +- Ha **többoldalas TIFF**‑ed van, add meg közvetlenül a fájl útvonalát; a legtöbb motor minden oldalt külön képként kezel. +- PDF‑ek esetén, amelyek már tartalmaznak képeket, meghívhatod a `engine.recognize_pdf("file.pdf")`‑t, és kihagyhatod ezt a lépést teljesen. + +--- + +## 2. lépés: OCR‑eredmény exportálása kereshető PDF/A‑ként + +Most a 1. lépésből származó `result`‑ot átadjuk a motornak, hogy egy új fájlt írjon ki. A kulcsfontosságú jelző itt a *PDF/A* – az ISO‑szabványú PDF‑változat, amelyet hosszú távú megőrzésre terveztek. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Miért fontos + +- **Kereshető PDF**: A kimeneti fájl egy rejtett, kiválasztható szövegréteget tartalmaz. Most már Ctrl + F‑el kereshetsz a dokumentumban. +- **PDF/A megfelelőség**: Néhány szervezet (jogi, pénzügyi) megköveteli a PDF/A‑t audit‑nyomokhoz; ez a lépés automatikusan teljesíti ezt a szabályt. +- A metódus **kereshető szöveget ad hozzá** anélkül, hogy a képet laposítaná, így a vizuális hűség tökéletes marad. + +#### Szél eset: Normál PDF‑re van szükséged? + +Ha nem érdekel a PDF/A, cseréld a `save_as_pdfa`‑t `save_as_pdf`‑re. A munkafolyamat többi része változatlan marad. + +--- + +## 3. lépés: A kereshető PDF ellenőrzése + +Egy gyors ellenőrzés megakadályozza a későbbi rejtélyes hibákat. Nyisd meg a generált fájlt bármely PDF‑olvasóval, próbálj ki egy szót kijelölni, és használd a keresőfunkciót. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Várt kimenet + +A szkript futtatásakor a konzol a következőt írja ki: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +A fájl megnyitásakor az eredeti számla‑képnek kell látszania egy halvány, láthatatlan szövegréteggel. Jelölj ki bármely szót, és láthatod, hogy kiválasztható – **ez a kereshető szöveg**, amit most hozzáadtál. + +--- + +## Kereshető szöveg hozzáadása meglévő PDF‑ekhez (Bónusz) + +Néha már van egy PDF‑ed, de szükséged van **kereshető szöveg** hozzáadására. Ugyanaz a motor képes az OCR‑eredményeket egy meglévő PDF‑re rétegezni: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Itt a `apply_to` egyesíti a rejtett réteget az eredeti oldalakkal, így **kereshető PDF‑et hozhatsz létre** újraszkennelés nélkül. + +--- + +## Gyakori hibák és tippek + +| Hiba | Hogyan kerüld el | +|------|-----------------| +| **Alacsony felbontású forrásképek** (< 150 dpi) | Nagyíts fel, vagy kérj magasabb felbontású szkennt; az OCR pontossága drámaian csökken 150 dpi alatt. | +| **Hiányzó nyelvi adatok** | Telepítsd a megfelelő nyelvi csomagokat az OCR motorodhoz (`pip install pdfocr[eng,spa]`). | +| **A kimeneti mappa nem írható** | Futtasd a szkriptet megfelelő jogosultságokkal, vagy válassz másik könyvtárat. | +| **PDF/A validálás sikertelen** | Ügyelj arra, hogy ne ágyazz be nem támogatott betűtípusokat vagy JavaScript‑et; a legtöbb SDK automatikusan kezeli ezt a `save_as_pdfa` használatakor. | + +--- + +## Teljes szkript – Egy‑fájlos megoldás + +Az alábbi önálló szkript mindent összekapcsol. Másold be, cseréld ki a helyőrző útvonalakat, és máris **kép‑PDF/A‑vá konvertálhatsz** néhány másodperc alatt. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**A szkript működése:** +1. Betölti az OCR motort. +2. Beolvassa a kiválasztott képet, és kinyeri a szöveget. +3. **Kereshető PDF/A**‑t ír, amelyet azonnal terjeszthetsz vagy archiválhatsz. + +Nyugodtan csomagold a `main` logikát egy függvénybe, amely egy egész mappát dolgoz fel – egyszerűen iterálj az `os.listdir()`‑en, és ismételd meg a három lépést minden fájlra. + +--- + +## Következő lépések és kapcsolódó témák + +Miután elsajátítottad, **hogyan OCR PDF-et**, érdemes ezeket a további ötleteket felfedezni: + +- **Kötegelt feldolgozás:** Használd a `concurrent.futures`‑t, hogy egyszerre több tucat számlát OCR‑elj párhuzamosan. +- **Metaadat‑injektálás:** Adj hozzá létrehozási dátumot vagy számlaszámot a PDF metaadataihoz a könnyebb indexelés érdekében. +- **Hibrid PDF‑ek:** Kombináld a kereshető szöveget az eredeti képekkel, így egy „digitális ikertestet” kapsz a papír dokumentumról. +- **Alternatív kimenetek:** Exportálj **DOCX**‑be vagy **HTML**‑be, ha a downstream rendszerek szerkeszthető formátumot igényelnek. + +Mindegyik a most tanult alapfogalmakra épül – felismerés, export, ellenőrzés. + +--- + +## Összegzés + +Röviden, most már tudod, **hogyan OCR PDF-et** készíthetsz úgy, hogy egy egyszerű képet **kereshető PDF/A‑vá** alakítasz néhány Python‑sorral. A szkript elvégzi a nehéz munkát, megőrzi az eredeti grafikát, és egy szabványos, kereshető dokumentumot ad, amelyet archiválhatsz, megoszthatsz vagy tovább feldolgozhatsz. + +Próbáld ki a saját számláiddal, nyugtáiddal vagy szkennelt szerződéseiddel. Ha elakadsz, írj egy megjegyzést alább, vagy nézd meg az SDK hivatalos dokumentációját – általában rengeteg további példát tartalmaz. Boldog kódolást, és élvezd az új képességet, hogy bármely képet azonnal kereshetővé tegyél! + +![How to OCR PDF example showing original image and searchable PDF overlay](placeholder.png "How to OCR PDF example") + +## Mit érdemes még megtanulni? + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy további API‑funkciókat saját projektjeidben is felfedezhess. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/hungarian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..8a9c89be8 --- /dev/null +++ b/ocr/hungarian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Hogyan OCR-elj PDF-et az Aspose OCR Cloud segítségével. Tanulja meg, + hogyan nyerjen ki szöveget PDF-ből, konvertáljon PDF-oldalakat PNG-re, és mentse + el a PDF-oldalak képeit Pythonban. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: hu +og_description: Hogyan OCR-eljünk PDF-et az Aspose OCR Cloud segítségével. Ez az útmutató + bemutatja, hogyan lehet szöveges PDF-et kinyerni, PDF-oldalakat PNG-re konvertálni, + és PDF-oldalak képeit menteni. +og_title: Hogyan OCR-elj PDF-et az Aspose OCR Cloud segítségével – Lépésről lépésre +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Hogyan OCR-eljük a PDF-et az Aspose OCR Cloud segítségével – Teljes útmutató +url: /hu/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan OCR-elj PDF-et az Aspose OCR Cloud segítségével – Teljes útmutató + +Valaha is elgondolkodtál már azon, hogy **hogyan OCR-elj PDF** fájlokat anélkül, hogy nehéz asztali eszközökkel küzdenél? Nem vagy egyedül – sok fejlesztő ütközik ebbe a falba, amikor gyors, programozott módra van szükségük a beolvasott dokumentumok szövegének kinyeréséhez. A jó hír? Az Aspose OCR Cloud segítségével **kivonhatod a szöveget a PDF‑ből**, minden oldalt PNG‑vé alakíthatsz, és akár **elmentheted a PDF oldal képeit** későbbi felhasználásra, mindezt egy rendezett Python szkriptből. + +Ebben az útmutatóban mindent végigvezetünk, amit tudnod kell: a SDK telepítésétől, a motor licencelésén át a többoldalas PDF‑ek felismeréséig, a sima szöveg kinyeréséig, az oldalak PNG‑re konvertálásáig, és a képek lemezre mentéséig. A végére egy újrahasználható kódrészletet kapsz, amelyet bármely projektbe beilleszthetsz, amelynek **hogyan OCR-elj PDF** képességre van szüksége. + +## Amire szükséged lesz + +- **Python 3.8+** (a kód 3.10‑n és újabb verziókon is működik) +- Aspose OCR Cloud fiók – ingyenes próba licencfájlt kapsz (`Aspose.OCR.lic`) +- A `asposeocrcloud` csomag (`pip install asposeocrcloud`) +- Egy beolvasott, többoldalas PDF, amelyet fel szeretnél dolgozni + +Ennyi. Nincs extra bináris, nincs natív függőség, csak tiszta Python. + +## Hogyan OCR-elj PDF – Beállítás és licenc + +Mielőtt bármilyen OCR metódust meghívnál, el kell mondanod a SDK-nak, ki vagy. Az Aspose egy könnyű licencfájlt használ, amelyet a szkripted számára elérhető helyre kell elhelyezned. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tipp:* Ha kihagyod a licenc lépést, a SDK még mindig működik, de egy kis vízjelet ágyaz be a kimeneti képekbe. Nem ideális a termeléshez. + +## 2. lépés: Az Aspose OCR Cloud Python SDK telepítése + +Nyiss egy terminált és futtasd: + +```bash +pip install asposeocrcloud +``` + +A csomag letölti az összes szükséges függőséget (requests, pillow, stb.), így nem kell mást keresned. + +## 3. lépés: OCR motor létrehozása és nyelv kiválasztása + +A motor a művelet szíve. Bármely, az Aspose által támogatott nyelvet megadhatod; az angol a legtöbb esetben működik. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Miért állítsd be a nyelvet? Mert az OCR motor nyelvspecifikus szótárakat használ a pontosság javításához. Ha francia PDF‑eket dolgozol fel, egyszerűen cseréld le az `ENGLISH`‑t `FRENCH`‑re. + +## 4. lépés: Mutass a többoldalas PDF‑re + +Add meg a motor számára a teljes elérési utat a feldolgozni kívánt fájlhoz. Relatív utak is megfelelőek, amíg a szkript munkakönyvtárából feloldódnak. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Győződj meg róla, hogy a fájl olvasható; különben `FileNotFoundError` hibát kapsz. + +## 5. lépés: OCR futtatása – Lista eredményekkel + +A `recognize_pdf` hívása egy listát ad vissza, ahol minden elem a forrás PDF egy oldalának felel meg. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Minden `OcrResult` két hasznos tulajdonságot tartalmaz: + +* `text` – az oldal egyszerű szöveges ábrázolása (nagyszerű a **extract plain text pdf**-hez) +* `image` – egy Pillow `Image` objektum a renderelt oldalról (tökéletes a **convert pdf page png**-hez) + +## 6. lépés: Szöveg kinyerése a PDF‑ből és oldalak PNG‑re konvertálása + +Most végigiterálunk az eredményeken, kiírjuk a kinyert szöveget, és minden oldalról elmentünk egy PNG verziót. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Várható konzolkimenet + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +A `page_1.png`, `page_2.png`, … fájlok is megtalálhatók a `YOUR_DIRECTORY` könyvtárban. Ezek a rasterizált oldalképek, amelyeket továbbadhatsz az utólagos képfeldolgozó csővezetékeknek. + +## 7. lépés: PDF oldal képek mentése (opcionális utófeldolgozás) + +Ha csak a képekre van szükséged, a szövegre nem, kihagyhatod a `print(res.text)` sort. Fordítva, ha a szöveget külön `.txt` fájlokban szeretnéd tárolni, csak adj hozzá egy apró írási lépést: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Ez a kis kiegészítés azt mutatja, milyen egyszerű **PDF oldal képek mentése**, miközben a kinyert tartalmat is elmentjük. + +## Teljes működő példa + +Mindent összevonva, itt a teljes szkript, amelyet átmásolhatsz a `ocr_pdf.py` fájlba: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Futtasd a következővel: + +```bash +python ocr_pdf.py +``` + +A konzolon látnod kell minden oldal szövegének kiírását és egy sor PNG fájlt + +## Mit érdemes következőként megtanulni? + +A következő útmutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes működő kódpéldákat tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan OCR-elj PDF-et .NET-ben az Aspose.OCR-rel](/ocr/english/net/text-recognition/recognize-pdf/) +- [PDF szöveg felismerése – OCR műveletek az Aspose.OCR Java verziójával](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Képek konvertálása PDF‑re C#‑ban – Többoldalas OCR eredmény mentése](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/hungarian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..37fdf4a5b --- /dev/null +++ b/ocr/hungarian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Hogyan előfeldolgozzuk a képeket OCR-hez Python használatával. Tanulja + meg, hogyan binarizálja a képet Otsu módszerrel, hogyan korrigálja a beolvasott + dokumentumok dőlését, és hogyan javítsa az OCR pontosságát német szövegek esetén. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: hu +og_description: Hogyan előfeldolgozzuk a képeket OCR-hez Pythonban. Ez az útmutató + bemutatja, hogyan binarizáljuk a képet Otsu módszerrel, hogyan korrigáljuk a beolvasott + dokumentumok dőlését, és hogyan javítható az OCR pontossága német nyelvű képeken. +og_title: Hogyan előfeldolgozzuk a képeket OCR-hez – Teljes Python útmutató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Hogyan előfeldolgozzuk a képeket OCR-hez – Teljes Python útmutató +url: /hu/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan előfeldolgozzuk a képeket OCR-hez – Teljes Python útmutató + +Valaha is elgondolkodtál **hogyan előfeldolgozzuk a képeket OCR-hez**, hogy a szöveg kristálytiszta legyen? Nem vagy egyedül. A beolvasott dokumentumok – különösen a zajos német oldalak – rémálom lehet bármely OCR motor számára. A jó hír? Néhány okos előfeldolgozási lépés egy homályos, pöttyös szkennelt oldalt tiszta, gép‑olvasható képpé változtathat. + +Ebben a tutorialban egy gyakorlati példán keresztül mutatjuk be, **hogyan előfeldolgozzuk a képeket OCR-hez** Python használatával. Megtanulod, hogyan **binarizáld a képet Otsu‑val**, **hogyan korrigáld a ferde beolvasott dokumentumokat**, és általánosságban **hogyan javítható az OCR pontossága**, amikor **német képfájlokból kell szöveget kinyerni**. Felesleges szócséplés nélkül, csak egy működő szkript, amit ma is másolhatsz‑beilleszthetsz. + +## Amire szükséged lesz + +- **Python 3.9+** (bármely friss verzió megfelelő) +- Egy OCR könyvtár, amely egy `OcrEngine` osztályt biztosít – a bemutatóhoz egy általános `ocr` csomagot feltételezünk. Telepítsd a `pip install ocr-lib` paranccsal. +- Egy zajos német szken (`noisy_german_scan.tif`), amivel tesztelni szeretnél. +- Alapvető Python‑függvényismeret (ha már írtál `def`‑et, akkor jó vagy). + +> **Pro tipp:** Ha másik OCR SDK‑t használsz (pl. Tesseract a `pytesseract`‑on keresztül), a koncepciók ugyanazok – csak a metódusneveket igazítsd a saját könyvtáradhoz. + +## A megoldás áttekintése + +1. **Hozz létre egy OCR motor példányt.** +2. **Állítsd be a felismert nyelvet németre.** +3. **Építs egy egyedi előfeldolgozó pipeline‑t**, amely tartalmazza a ferdekorrekciót, zajszűrést, binarizálást (Otsu) és kontrasztnyújtást. +4. **Csatold a pipeline‑t a motorhoz**, hogy minden kép automatikusan átmenjen rajta. +5. **Futtasd az OCR‑t** egy zajos német szkennelt képen. +6. **Írd ki a kinyert szöveget**, hogy ellenőrizd az eredményt. + +Alább minden lépést részletezünk, elmagyarázzuk, **miért** fontos, és megmutatjuk a pontos kódot, amire szükséged lesz. + +![hogyan előfeldolgozzuk a képeket OCR-hez példa](image.png "hogyan előfeldolgozzuk a képeket OCR-hez példa") + +## 1. lépés: OCR motor példány létrehozása + +Először is – motor nélkül semmi sem történik. Az `OcrEngine` objektum a belépési pont, amely koordinálja a későbbi feldolgozást. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Miért fontos:* A motor inicializálása beállítja a belső erőforrásokat (például nyelvi modelleket), és tiszta alapot ad a későbbi egyedi pipeline csatolásához. + +## 2. lépés: A felismert nyelv beállítása németre + +Az OCR pontossága erősen nyelvtől függ. Ha a motor tudja, hogy német szöveget vár, aktiválja a megfelelő karakterkészletet és nyelvi modellt. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Ha ezt kihagyod, a motor alapértelmezés szerint angolt használhat, és hibásan ismeri fel az umlautokat (ä, ö, ü) valamint a ß karaktert – gyakori buktatók német szkennelt anyagoknál. + +## 3. lépés: Egyedi előfeldolgozó pipeline felépítése + +Ez a **hogyan előfeldolgozzuk a képeket OCR-hez** központi része. Négy átalakítást láncolunk össze: + +| Átalakítás | Mit csinál | Miért segít | +|------------|------------|-------------| +| **Deskew** | Visszaforgatja a képet vízszintesre (max 5°) | A szkenek ritkán tökéletesen igazodnak; a ferdekorrekció eltávolítja a dőlést, ami megzavarja a karakterszegmentálást. | +| **Denoise** | Csökkenti a véletlenszerű pöttyöket (erősség 0.7) | A zaj hamis éleket hoz létre, amelyeket az OCR motor karakterként értelmezhet. | +| **Binarize (Otsu)** | Fekete‑fehérre konvertálja Otsu módszerével | Egy tiszta bináris kép éles kontrasztot biztosít az előtér (szöveg) és a háttér között. | +| **Contrast Stretch** | Kiterjeszti a dinamikus tartományt | Javítja a gyenge vonalak olvashatóságát, különösen régi dokumentumoknál. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Hogyan korrigáljuk a ferde beolvasott dokumentumokat + +A fenti `deskew` hívás a konkrét válasz a **hogyan korrigáljuk a ferde beolvasott dokumentumokat** kérdésre. Belsőleg a domináns szövegsor‑szöget Hough‑transzformációval becsüli, majd elforgatja a képet. Ha a dokumentumaid több mint 5°‑kal vannak elforgatva, növeld a `max_angle` értékét, de vigyázz a túlzott forgatás miatti artefaktusokra. + +### Képbinarizálás Otsu‑val + +A `binarize(method="otsu")` sor közvetlenül válasz a **binarize image using otsu** kérdésre. Az Otsu‑algoritmus egy olyan küszöböt számol ki, amely minimalizálja az osztályon belüli varianciát, ami tökéletes a kétcsúcsú hisztogramú dokumentumokhoz (sötét szöveg vs. világos háttér). + +## 4. lépés: Pipeline csatolása a motorhoz + +Most megmondjuk az OCR motornak, hogy minden bejövő képet futtasson le a most épített pipeline‑on. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Miért fontos:* Regisztráció nélkül a motor a nyers szkennel dolgozna, figyelmen kívül hagyva az általunk beállított tisztítást. Ez a lépés biztosítja, hogy **hogyan javítható az OCR pontossága** a konzisztens előfeldolgozással. + +## 5. lépés: Szövegfelismerés egy zajos német szkennelt képen + +Most rakjuk össze a teljes folyamatot. Betápláljuk a motorba a zajos német képet, és hagyjuk, hogy elvégezze a nehéz munkát. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Ha érdekel a teljesítmény, időzítsd a hívást: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## 6. lépés: A felismert szöveg kiírása + +Végül kiírjuk a kinyert karakterláncot. Ez a közvetlen válasz a **extract text from german image** kérdésre. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Várt kimenet + +Tegyük fel, hogy a minta szken a következő mondatot tartalmazza: „Die schnelle braune Füchsin springt über den faulen Hund.” A kimenet valahogy így nézhet ki: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Ha a kimenet még mindig torz karaktereket tartalmaz, próbáld finomhangolni a `denoise` erősségét vagy növeld a `max_angle` értékét a ferdekorrekcióhoz. + +## Gyakori hibák és megoldások + +- **Hiányzó nyelvi modell:** A `set_recognition_language(Language.GERMAN)` elhagyása gyakran eredményez hiányzó umlautokat. Ellenőrizd a hívást. +- **Túlzott zajszűrés:** 0.9‑nél nagyobb erősség törölheti a vékony vonalakat, különösen a régi betűtípusoknál. 0.5‑0.7 közötti érték a legtöbb esetben megfelelő. +- **Nem megfelelő fájlformátum:** Egyes OCR motorok nem bírnak meg többoldalas TIFF‑ekkel. Ha többoldalas dokumentumod van, bontsd szét egyoldalas fájlokra először. +- **Pipeline sorrend:** A bemutatott sorrend (deskew → denoise → binarize → contrast) szándékos. A binarizálás zajszűrés előtt rögzítheti a zajt; mindig előbb zajszűrj. + +## A pipeline bővítése (Mi következik?) + +Miután van egy stabil alapod, érdemes lehet: + +- **Morfológiai nyitást** hozzáadni a kis foltok tisztításához (`.morph_open(kernel=3)`). +- **Nyelvi modellt** integrálni a poszt‑feldolgozási korrekcióhoz (`ocr_engine.apply_spellcheck()`). +- **Kötegelt feldolgozást párhuzamosítani** nagy adathalmazok esetén a `concurrent.futures` használatával. + +Ezek mind természetes kiterjesztései a **hogyan előfeldolgozzuk a képeket OCR-hez** koncepciónak, miközben tovább növelik a **hogyan javítható az OCR pontossága**. + +## Összegzés + +Most már ismered a **hogyan előfeldolgozzuk a képeket OCR-hez** teljes folyamatát: motor létrehozása, német nyelv beállítása, olyan pipeline építése, amely **binarize image using Otsu**, **how to deskew scanned documents**, és végül **extract text from german image** magasabb megbízhatósággal. A hat lépés követésével jelentős javulást fogsz látni a felismert szöveg minőségében – többé már nincs végtelen kézi javítás. + +Próbáld ki a szkriptet a saját szkenneiddel, kísérletezz a paraméterekkel, és hagyd, hogy az eredmények beszéljenek. Van kérdésed egy konkrét előfeldolgozási trükkel kapcsolatban? Írj kommentet, és mélyebben is belemerülünk. + +Boldog kódolást, és legyen az OCR‑ed mindig pontos! + +## Mit érdemes még megtanulni? + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy további API‑funkciókat saját projektjeidben is könnyedén alkalmazhasd. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..66c7f198a --- /dev/null +++ b/ocr/hungarian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,336 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG kép Python-nal – tanulja meg, hogyan lehet szöveget kinyerni + a képből, futtasson egy Python OCR példát, és még az ókori görög szöveget is könnyedén + olvashassa. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: hu +og_description: OCR PNG kép Pythonban magyarázva. Ez az útmutató megmutatja, hogyan + lehet szöveget kinyerni a képből, futtatni egy Python OCR példát, és könnyedén olvasni + az ókori görög nyelvet. +og_title: OCR PNG kép Pythonban – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR PNG kép Pythonban – Teljes lépésről lépésre útmutató +url: /hu/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Kép Pythonban – Teljes Lépésről‑Lépésre Útmutató + +Gondolkodtál már azon, hogyan **OCR PNG képet** tudsz közvetlenül egy Python szkriptből? Talán egy mappád tele van szkennelt ókori kéziratokkal, és **szöveget szeretnél kinyerni a képből** anélkül, hogy mindent kézzel gépelnél be. A jó hír, hogy nem kell PhD‑nek lenned a számítógépes látás területén – csak néhány sor kód és a megfelelő könyvtár, és már percek alatt olvasni tudsz ókori görögül. + +Ebben a bemutatóban egy **python OCR példát** fogunk végigvinni, amely PNG‑ból ismeri fel a szöveget, a nyelvet görög polytonikusra állítja, és kiírja az eredményt. A végére pontosan tudni fogod, hogyan **ismerj fel képen lévő szöveget**, hogyan kezeld a gyakori buktatókat, és hogyan adaptáld a szkriptet más nyelvekre vagy képtípusokra. + +## Mit Tanulhatsz Meg + +- Python OCR könyvtár telepítése és konfigurálása (pytesseract + Tesseract OCR) +- OCR motor példány létrehozása és PNG fájl betöltése +- A felismerési nyelv beállítása görög polytonikusra, hogy **olvasni tudj ókori görögül** +- A felismert szöveg kiírása és tipikus problémák megoldása +- A szkript kiterjesztése több PNG kötegelt feldolgozására vagy más nyelvre váltásra + +### Előfeltételek + +| Követelmény | Miért fontos | +|-------------|--------------| +| Python 3.8+ | Modern szintaxis és típusjelölések | +| `pytesseract` csomag | Vékony wrapper a Tesseract motor körül | +| Tesseract OCR binárisok (≥ 5.0) | A tényleges motor, ami a nehéz munkát végzi | +| Görög nyelvi adat (`grc.traineddata`) | Szükséges a **ó görög olvasásához** | +| Egy PNG kép, amit elemezni szeretnél (pl. `ancient_greek.png`) | A **ocr png image** demó célja | + +A Python oldalt a következővel telepítheted: + +```bash +pip install pytesseract Pillow +``` + +Ubuntu/macOS rendszeren a motor telepítése: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Ne felejtsd el letölteni a görög polytonikus nyelvi adatot: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Az útvonal eltérhet; szükség esetén állítsd be a `TESSDATA_PREFIX` változót.)* + +--- + +## OCR PNG Kép: Motor Példány Létrehozása + +Az első dolog, amire szükségünk van, egy objektum, ami a Tesseracttal kommunikál. A `pytesseract` esetében a motor a modul‑szintű függvényeken keresztül érhető el, de a tisztaság kedvéért egy kis osztályba csomagoljuk. Ez tükrözi az eredeti kódrészletben látható „engine” koncepciót. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Miért csomagoljuk?** +- Az API nyilvános felülete megegyezik az eredeti snippet‑el, így a migráció zökkenőmentes. +- Később könnyen hozzáadhatunk naplózást vagy hibakezelést anélkül, hogy a fő folyamatot módosítanánk. +- Jó OOP gyakorlatot mutat – amit a senior fejlesztők értékelnek. + +--- + +## Szöveg Kinyerése Képből: Állítsd be a Nyelvet Görög Polytonikusra + +Most, hogy van egy motorunk, meg kell mondanunk, milyen nyelvet várjon. A görög polytonikus diakritikus jeleket használ, amik nincsenek benne a standard „greek” adatokban, ezért a Tesseractot a `grc` tréningfájlra irányítjuk. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Ha valaha **szöveget szeretnél kinyerni a képből** egy másik nyelven, egyszerűen cseréld a `"grc"`‑t `"eng"`‑re angolhoz, `"fra"`‑ra franciához, stb. Ugyanez a sor minden telepített nyelvre működik. + +--- + +## Kép Szöveg Felismerése: OCR futtatása PNG-n + +A nyelv beállítása után betöltjük a PNG‑t a motorba. Az eredeti példa egy keményen kódolt útvonalat használt; most egy kicsit rugalmasabbá tesszük `Path` objektumokkal. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tippek és Szélsőséges Esetek** + +- **Fájl nem található** – csomagold a hívást `try/except FileNotFoundError`‑rel, hogy barátságos üzenetet kapj. +- **Alacsony felbontású PNG** – fontold meg előfeldolgozást (pl. átméretezés, binarizálás) a Pillow‑val az OCR előtt. +- **Nem‑görög szöveg** – a Tesseract megpróbálja dekódolni, de a pontosság drasztikusan csökken. Mindig a megfelelő nyelvet válaszd. + +--- + +## A Felismert Szöveg Kiírása + +Végül kiírjuk az eredményt. Egy valódi projektben adatbázisba, CSV‑be vagy akár egy fordítási pipeline‑ba is mentheted. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Amikor a szkriptet egy tiszta ókori görög felirat szkennelésén futtatod, valami ilyesmit kell látnod: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Ha a kimenet összezavartnak tűnik, ellenőrizd, hogy a **greek.traineddata** fájl a megfelelő mappában van-e, és hogy a PNG nem túl zajos-e. + +--- + +## Teljes Működő Példa (Minden Lépés Egy Szkriptben) + +Az alábbiakban a teljes, azonnal futtatható program látható. Mentsd `ocr_greek.py` néven és futtasd `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Várható kimenet** (rövidítve): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Ha a megfelelő görög karaktereket látod, gratulálok – sikeresen végrehajtottad az **ocr png image** műveletet Pythonban! + +--- + +## Gyakori Kérdések és Profi Tippek + +### Hogyan javítható a pontosság egy zajos PNG‑n? + +- Konvertáld a képet szürkeárnyalatossá: `img = img.convert('L')` +- Alkalmazz bináris küszöböt: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Növeld fel a felbontást: `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Ezek a lépések gyakran egy **recognize image text** rémálmot tiszta eredménnyé változtatnak. + +### Feldolgozhatok egy egész mappát PNG‑kből? + +Természetesen. Csomagold a `recognize_image` hívást egy `for` ciklusba, ami a `Path.glob("*.png")`‑t iterálja. Az eredményeket tárold szótárban vagy írd CSV‑be későbbi elemzéshez. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Mi van, ha csak számokat kell kinyerni? + +Adj egy egyedi **config** stringet az `image_to_string`‑nek: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Így **szöveget tudsz kinyerni a képből**, amely táblázatokat, sorozatszámokat vagy időbélyegeket tartalmaz. + +### Van mód a megbízhatósági pontszámok lekérésére? + +Igen – használd a `pytesseract.image_to_data`‑t, ami TSV‑t ad vissza szó‑szintű megbízhatósági értékekkel. Alacsony bizalomú tokeneket kiszűrhetsz, mielőtt összeállítod a végső szöveget. + +--- + +## A Bemutató Bővítése + +Miután elsajátítottad az alapokat, érdemes ezeket a kapcsolódó témákat is felfedezni: + +- **Batch OCR multiprocessing‑kel** – gyorsítsd fel a nagy PNG korpuszok feldolgozását. +- **Hibrid OCR + NLP pipeline** – automatikusan fordítsd le az ókori görög szöveget modern angolra. +- **Alternatív motorok** – próbáld ki az `easyocr`‑t vagy az `opencv`‑alapú módszereket speciális esetekre. +- **Felhő alapú OCR szolgáltatások** – Google Vision, Azure Computer Vision vagy AWS Textract szerver‑nélküli skálázáshoz. + +Mindegyik a most bemutatott **python OCR példára** épül, így magabiztosan merülhetsz el mélyebben. + +--- + +## Következtetés + +Egy egyszerű snippet‑ből egy robusztus **ocr png image** munkafolyamatot hoztunk létre Pythonban. Létrehoztunk egy `OcrEngine`‑t, beállítottuk a nyelvet görög polytonikusra, betápláltunk egy PNG‑t, és kiírtuk az eredményt. Most már tudod, hogyan **szöveget nyerj ki a képből**, hogyan **ismerj fel képen lévő szöveget**, és még **olvasni tudsz ókori görögül** is. + +## Mit Tanulj Meg Következőként? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutató technikáira épülnek. Minden forrás komplett, működő kódrészleteket és lépésről‑lépésre magyarázatokat tartalmaz, hogy további API‑funkciókat saját projektjeidben is könnyedén alkalmazhass. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/hungarian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..5fae39af1 --- /dev/null +++ b/ocr/hungarian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR oktatóanyag, amely bemutatja, hogyan ismerjünk fel képi szöveget, + végezzünk nagy felbontású OCR-t, és extraháljunk spanyol szöveget GPU-gyorsított + OCR használatával. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: hu +og_description: Python OCR oktatóanyag, amely végigvezet a képszöveg felismerésén, + a nagy felbontású OCR-en és a spanyol szöveg GPU-gyorsítással történő kinyerésén. +og_title: Python OCR oktatóanyag – GPU-gyorsított szövegfelismerés +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR útmutató – Képszöveg felismerése GPU gyorsítással +url: /hu/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Képszöveg felismerése GPU gyorsítással + +Gondolkodtál már azon, hogyan **ismerheted fel a képen lévő szöveget** egy Python szkriptben anélkül, hogy órákat töltenél a beállítások finomhangolásával? Nem vagy egyedül. Ebben a **python ocr tutorial**‑ban bemutatunk egy tiszta, vég‑től‑végig megoldást, amellyel spanyol szöveget nyerhetsz ki egy nagy felbontású képből, és GPU gyorsítást is bevetünk, hogy a folyamat villámgyors legyen. + +Tekintsd ezt egy gyors kávészünetes demónak, amelyet később egy termelés‑kész csővezetékké bővíthetsz. A végére egy futtatható programod lesz, amely **magas felbontású OCR**‑t végez, CUDA‑támogatott GPU‑t használ, és kiadja a pontos spanyol karaktereket, amire szükséged van. + +## Amit megtanulsz + +- Hogyan telepíts és importálj egy modern OCR könyvtárat, amely támogatja a GPU gyorsítást. +- Hogyan hozz létre egy OCR motor példányt, és állítsd be **képszöveg felismerésére** spanyol nyelven. +- Hogyan engedélyezd a **gpu accelerated OCR**‑t a hatalmas sebességnyereség érdekében nagy felbontású fájloknál. +- Hogyan kezeld az olyan szélhelyzeteket, mint a hiányzó CUDA driver vagy a CPU‑ra való visszaesés. +- Tippek a pontosság javításához, ha **spanyol szöveget kell kinyerni** zajos beolvasásokból. + +### Előfeltételek + +- Python 3.9+ (a kód 3.10‑n és újabb verziókon is működik). +- CUDA‑kompatibilis GPU (opcionális, de erősen ajánlott). +- Alapvető ismeretek a pip‑ről és a virtuális környezetekről. + +Ha valamelyik hiányzik, a tutorial még mindig működik — csak hagyd ki a GPU lépést, és a könyvtár automatikusan CPU‑ra vált. + +--- + +## Python OCR Tutorial: A szükséges csomagok telepítése + +Először is szükségünk van egy stabil OCR motorra. Ehhez a tutorialhoz a nyílt forráskódú **`easyocr`** csomagot használjuk, amely beépített GPU támogatással rendelkezik, ha kompatibilis eszköz van jelen. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tipp:** Ha már telepítve van a PyTorch, győződj meg róla, hogy a CUDA verzióddal egyezik (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). A verzióeltérés gyakori oka a „GPU not found” hibáknak. + +--- + +## 1. lépés: OCR motor példány létrehozása + +Most elindítjuk a motort. az EasyOCR fő osztálya a `Reader`. A konstruktor egy nyelvkódok listáját várja; a spanyolhoz a `"es"` kódot adjuk meg. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Miért fontos:* A nyelv előzetes deklarálásával a motor csak a szükséges neurális hálózati súlyokat tölti be, ami memóriát takarít meg és felgyorsítja az inferenciát — különösen hasznos, ha később **magas felbontású OCR**‑t végzel. + +--- + +## 2. lépés: Magas felbontású kép előkészítése + +A magas felbontású képek több pixelt biztosítanak a modellnek, ami általában jobb karakterfelismerést eredményez. Tegyük fel, hogy van egy `high_res_spanish.png` nevű fájlod a `samples` mappában. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Ha nincs kéznél magas felbontású minta, letölthetsz egy ingyeneset az Unsplash‑ről, vagy generálhatsz szintetikus képet a Pillow‑val. A legjobb eredményhez a DPI‑t tartsd 300 felett. + +--- + +## 3. lépés: GPU gyorsítás engedélyezése (opcionális, de ajánlott) + +Az EasyOCR már megpróbálja a GPU‑t használni, ha `gpu=True`‑t állítasz be. Azonban jó gyakorlat ellenőrizni, hogy a készülék ténylegesen használatban van‑e, különösen több GPU‑s rendszereknél. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Miért ellenőrizd?* Ha a szkript csendben visszaesik CPU‑ra, megkérdezheted magadtól, miért tart egy 5 másodperces művelet hirtelen 30 másodpercig. Ez a kis ellenőrzés átláthatóvá teszi a viselkedést, és a **gpu accelerated OCR** csővezetékedet kiszámíthatóvá teszi. + +--- + +## 4. lépés: Magas felbontású OCR végrehajtása és képszöveg felismerése + +Most jön a szórakoztató rész — a tényleges szövegolvasás. Az EasyOCR `readtext` metódusa egy tuple‑ok listáját adja vissza, amelyek a körülhatároló dobozt, a felismert sztringet és egy biztonsági pontszámot tartalmaznak. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Ha a koordináták nélkül csak a nyers sztringre van szükséged, állítsd `detail=0`‑ra. A legtöbb **recognize image text** esetben az alapértelmezett (`detail=1`) elegendő kontextust ad a későbbi utófeldolgozáshoz. + +--- + +## 5. lépés: Spanyol szöveg kinyerése és a kimenet tisztítása + +Mivel az EasyOCR‑t spanyolra kérdeztük, a visszakapott sztringek már ebben a nyelvben vannak. Ennek ellenére érdemes lehet összefűzni őket, eltávolítani a felesleges szóközöket, vagy kiszűrni az alacsony biztonsági értékű detekciókat. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Mi a teendő, ha a biztonság alacsony?** Csökkentheted a küszöböt (ez zajt hozhat), vagy előfeldolgozhatod a képet (kontraszt növelése, binarizálás, vagy kiegyenesítés). Ezek a trükkök gyakoriak, ha **magas felbontású OCR**‑t végzel beolvasott dokumentumokon. + +--- + +## 6. lépés: Szélhelyzetek kezelése és teljesítményfinomítás + +Még a legjobban betanított modellek is akadnak néhány szituációban. Az alábbiakban néhány gyors javítást találsz, amelyeket beilleszthetsz a szkriptbe. + +### 6.1 Visszaesés, ha nincs GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Nagyon nagy képek lecsökkentése + +Ha a képed nagyobb, mint 4000 × 4000 px, a GPU memória kifogyhat. Csökkentsd arányosan, miközben megőrzöd a DPI‑t: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Ezek a kódrészletek robusztussá teszik a szkriptet, akár munkaállomáson, akár szerény laptopon futtatod. + +--- + +## Teljes működő példa + +Összeállítva, itt a teljes szkript, amelyet másolhatsz‑beilleszthetsz és azonnal futtathatsz: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Várható kimenet (példa):** + + + +## Mi legyen a következő tanulnivaló? + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljesen működő kódrészleteket lépés‑ről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API‑funkciókat és alternatív implementációs megközelítéseket a saját projektjeidben. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/hungarian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..0e10d8f07 --- /dev/null +++ b/ocr/hungarian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-06 +description: Ismerje fel a szöveget a képen Python OCR motorral. Tanulja meg, hogyan + konfigurálja az OCR motort Pythonban, és percek alatt vonjon ki szöveget a képből + felhőalapú feldolgozással. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: hu +og_description: Ismerje fel a szöveget a képről a Python OCR motorral. Ez az útmutató + bemutatja, hogyan konfigurálja a Python OCR motort, és hogyan nyerjen ki szöveget + a képből hatékonyan. +og_title: Képről szöveg felismerése Pythonban – Teljes beállítási útmutató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Szöveg felismerése képről Pythonban – Teljes OCR motor beállítási útmutató +url: /hu/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# szöveg felismerése képből Pythonban – Teljes Beállítási Útmutató + +Gondolkodtál már azon, hogyan **szöveget lehet felismerni képből** csak néhány Python sorral? Nem vagy egyedül. Legyen szó nyugtavizsgálatról, dokumentumdigitalizálásról vagy egy egyszerű hobbi projektről, a képből történő szövegkivonás egy olyan készség, amely gyorsan megtérül. + +Ebben az útmutatóban végigvezetünk a teljes folyamaton – a **OCR motor konfigurálása Pythonban** típusú beállítástól kezdve, a felhő hitelesítésén át, egészen addig, hogy **szöveget nyerjünk ki képből** megbízható eredménnyel. Nincs varázslat, csak világos lépések, amelyeket ma másolhatsz‑beilleszthetsz és futtathatsz. + +## Mit Tanulhatsz Meg + +- Hogyan telepítsd és importáld a szükséges OCR könyvtárat. +- A pontos parancsok a **OCR motor konfigurálása Pythonban** felhőfeldolgozáshoz. +- Egy teljes, futtatható szkript, amely **szöveget felismer képből** és kiírja az eredményt. +- Tippek a gyakori buktatók kezeléséhez, mint a hiányzó API kulcsok vagy nem támogatott képformátumok. +- Haladó ötletek, például kötegelt feldolgozás és helyi tartalékmegoldás. + +### Előfeltételek + +- Python 3.8+ telepítve a gépeden. +- Internetkapcsolat (a példa felhőalapú OCR szolgáltatást használ). +- Érvényes API kulcs az OCR szolgáltatótól (megmutatjuk, hová kell beilleszteni). + +Ha ezek megvannak, vágjunk bele – semmi felesleges részlet, csak egy gyakorlati útmutató, ami működik. + +--- + +## 1. lépés: Az OCR Könyvtár Telepítése és Importálása + +Mielőtt **OCR motor konfigurálása Pythonban**-t végrehajtanád, szükséged van a felhőszolgáltatással kommunikáló könyvtárra. Példánkban egy fiktív, de reprezentatív csomagot használunk, amelynek neve `ocrcloud`. Cseréld le a saját csomagodra (pl. `easyocr`, `google-cloud-vision`, stb.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Miért fontos:** Az osztály importálása hozzáférést biztosít olyan metódusokhoz, mint a `use_cloud()` és a `set_api_key()`. Importálás nélkül a szkript a továbbiakban `NameError`‑t dobna. + +*Pro tipp:* Rögzítsd a verziót a `requirements.txt`‑ben (`ocrcloud==2.1.0`), hogy elkerüld a későbbi váratlan változásokat. + +--- + +## 2. lépés: **OCR motor konfigurálása Pythonban** a Felhő Módhoz + +Most ténylegesen **OCR motor konfigurálása Pythonban**. Az motor alapértelmezés szerint helyi módban indul; a felhő módra váltás lehetővé teszi, hogy a nehéz képanalízist erőteljes szerverekre bízd. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Magyarázat:** +- `OcrEngine()` egy új motorobjektumot hoz létre – mintha egy üres vászon lenne. +- `use_cloud(True)` egy kapcsolót kapcsol be, amely azt mondja a motornak, hogy a képeket HTTPS‑en küldje el a helyi feldolgozás helyett. Ez kulcsfontosságú a magas pontosságú eredményekhez összetett betűtípusok vagy alacsony felbontású fotók esetén. + +--- + +## 3. lépés: Hitelesítés a Felhő API Kulcsoddal + +A legtöbb felhő OCR szolgáltatás igényel API kulcsot. Ez a lépés megmutatja, hogyan lehet biztonságosan beilleszteni a hitelesítő adatot. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Biztonsági megjegyzés:** Soha ne kódold be a kulcsot nyilvános repóba. Éles környezetben egy környezeti változóból kellene beolvasni: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## 4. lépés: **szöveg felismerése képből** – Távoli Kép Küldése Feldolgozásra + +A motor konfigurálása után végre **szöveget felismerhetünk képből**. A `recognize_image()` metódus egy útvonalat vagy URL‑t vár, és egy objektumot ad vissza, amely a kinyert szöveget tartalmazza. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Mi történik a háttérben?** +A kép bájtjai feltöltődnek a szolgáltató végpontjára, egy mélytanuló modell dolgozza fel őket, majd a tiszta szöveg visszaáramlik. Ha a kép nagy, a szolgáltatás automatikusan lecsökkentheti a méretét a gyorsabb feldolgozás érdekében. + +--- + +## 5. lépés: A **szöveg kinyerése képből** Eredmény Kiírása + +Miután az OCR szolgáltatás befejezte a munkát, egyszerűen kiírjuk a szöveget. Valós alkalmazásokban adatbázisba mentheted vagy egy másik függvénynek adhatod át. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Várható kimenet:** (példa) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Ha a kimenet értelmetlennek tűnik, ellenőrizd, hogy a kép tiszta‑e és a megfelelő nyelvi modellt választottad‑e (sok szolgáltatás lehetővé teszi, hogy megadd például `engine.set_language("en")`). + +--- + +## Széljegyek Kezelése és Gyakori Buktatók + +### 1. Hiányzó vagy Érvénytelen API Kulcs +Ha hitelesítési hibát látsz, ellenőrizd: +- A kulcs aktív és nem lejárt. +- Helyesen olvasod be a környezeti változóból. +- A hálózatod engedélyezi a kimenő HTTPS forgalmat. + +### 2. Nem Támogatott Képformátumok +A legtöbb OCR API a JPEG, PNG és PDF formátumokat támogatja. BMP vagy TIFF használata „format not supported” választ válthat ki. Szükség esetén konvertálj Pillow‑lal: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Kéréskorlátok +A felhőszolgáltatások gyakran korlátozzák a percenkénti kérések számát. Ha elérsz egy határt, alkalmazz exponenciális visszatartást: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Helyi OCR Tartalék +Ha a felhő nem elérhető, visszakapcsolhatod a helyi módot: + +```python +engine.use_cloud(False) # revert to local mode +``` + +A tartalék megoldás növeli az alkalmazásod rugalmasságát. + +--- + +## Teljes Működő Példa + +Összegezve, itt egy szkript, amelyet most azonnal futtathatsz (csak cseréld ki a helyőrző értékeket). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Futtasd:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +A konzolon meg kell jelennie a kinyert szövegnek, ezzel megerősítve, hogy sikeresen **szöveget felismertél képből** és **kivontad a szöveget a képből** egy megfelelően **OCR motor konfigurálása Pythonban** munkafolyamat segítségével. + +--- + +## Összegzés + +Áttekintettük a teljes, vég‑től‑végig folyamatot, amely lehetővé teszi a **szöveg felismerését képből** Pythonban, a könyvtár telepítésétől a felhőszolgáltatás hitelesítéséig, majd a **szöveg kinyerését képből** egyetlen függvényhívással. A **OCR motor konfigurálása Pythonban** helyes módja rugalmasságot (felhő vs. helyi) és megbízhatóságot (megfelelő hiba‑kezelés) biztosít. + +Mi a következő? Próbáld ki egy mappában lévő nyugták kötegelt feldolgozását, adj hozzá nyelvfelismerést, vagy kísérletezz PDF‑ekkel bemenetként. A lehetőségek határtalanok, amint elsajátítottad az alapokat. + +Boldog kódolást, és nyugodtan tegyél fel kérdéseket a megjegyzésekben – semmi sem felülmúlja a közös tanulást! + + +## Mit Tanulj Meg Következőként? + + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódrészleteket lépés‑ről‑lépésre magyarázatokkal, hogy segítsenek további API funkciók elsajátításában és alternatív megvalósítási megközelítések felfedezésében a saját projektjeidben. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0a601f280 --- /dev/null +++ b/ocr/hungarian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Futtass OCR-t egy képen Python segítségével, és nézd meg a bizalmi pontszámokat. + Tanuld meg, hogyan szűrd ki az alacsony bizalomú szavakat, állíts be küszöbértékeket, + és kezeld a szélső eseteket. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: hu +og_description: Futtass OCR-t képen Pythonban, vizsgáld meg a megbízhatósági szinteket, + és szűrd ki az alacsony megbízhatóságú szavakat. Ez az útmutató végigvezet egy teljes, + futtatható példán. +og_title: OCR futtatása képen Python segítségével – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: OCR futtatása képen Python segítségével – Teljes lépésről lépésre útmutató +url: /hu/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR futtatása képen Python‑nal – Teljes lépés‑ről‑lépésre útmutató + +Valaha is szükséged volt **OCR futtatására képen** fájlokon, de nem tudtad, hogyan nyerj megbízható szöveget belőlük? Nem vagy egyedül – sok fejlesztő szembesül ugyanazzal a problémával, amikor a kinyert szavak bizonytalanok, és a biztonsági pontszám rejtély marad. + +Ebben az útmutatóban egy működő megoldásba mélyedünk el: megmutatjuk, hogyan futtass OCR‑t képen, olvasd ki az általános biztonságot, és szűrd ki az alacsony biztonságú szavakat, amelyeket manuálisan kell ellenőrizni. A végére egy újrahasználható szkriptet kapsz, megérted, miért fontos minden sor, és tudni fogod, hogyan állítsd be a biztonsági küszöböt a saját projektjeidhez. + +## Mit fed le ez a tutorial + +Áttekintjük a teljes munkafolyamatot – a kép betöltésétől egy rendezett jelentés nyomtatásáig, amely a 80 % alatti biztonságú szavakat listázza. Útközben megvitatjuk: + +* Egy megbízható OCR motor kiválasztását (használni fogjuk a **EasyOCR**‑t, egy népszerű Python OCR könyvtárat) +* A `confidence` attribútum értelmezését, amely minden OCR eredményhez tartozik +* Szavak szűrését egy egyedi **OCR confidence threshold**‑el +* A szkript kiterjesztését kötegelt feldolgozáshoz vagy alternatív motorokhoz, mint a **pytesseract** + +Előzetes OCR tapasztalat nem szükséges, csak alapvető Python ismeret és egy működő környezet (Python 3.9+ ajánlott). + +Készen állsz, hogy a homályos képernyőképeket tiszta, kereshető szöveggé alakítsd? Kezdjünk bele. + +--- + +## ## Hogyan futtass OCR‑t képen Python‑nal + +A tutorial központja egy háromlépéses kódrészlet, amely tükrözi a már látott kódot. Alább minden sort külön bontunk, elmagyarázzuk a miértjét, majd egy teljes, másolás‑beillesztésre kész szkriptet adunk. + +### 1. lépés: Telepítsd és importáld az OCR motort + +Először győződj meg róla, hogy az OCR könyvtár elérhető. **EasyOCR** azonnal működik sok nyelven, és minden szóhoz biztonsági pontszámot ad. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Miért EasyOCR?* Egy mélytanuló modellt tartalmaz, amely változatos adathalmazokon lett betanítva, így általában magasabb biztonsági értékeket kapsz, mint a régebbi Tesseract motor, különösen vegyes minőségű képeken. + +> **Pro tip:** Ha korlátozott környezetben vagy (pl. egy kis Docker konténer), a `pytesseract` könnyebb lehet, de elveszítheted az EasyOCR által nyújtott modern pontosságot. + +### 2. lépés: OCR futtatása a képen + +Most ténylegesen **run OCR on image**. Az eredeti példában szereplő `recognize_image` metódus helyett az EasyOCR `readtext` hívását használjuk, amely egy `(bbox, text, confidence)` elemekből álló listát ad vissza. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Az `ocr_results` minden eleme így néz ki: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +A harmadik elem (`0.92` a példában) a biztonsági pontszám, amely 0‑tól 1‑ig terjed. + +### 3. lépés: Az általános biztonság összegzése + +Míg a korábbi kódrészlet egyetlen `confidence` attribútumot írt ki, az EasyOCR minden szóhoz ad biztonságot. Az általános kép érdekében átlagoljuk őket: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Miért átlagolunk?* Gyors egészségügyi ellenőrzést nyújt – ha az általános biztonság 70 % alá esik, valószínűleg javítanod kell a képet (jobb megvilágítás, előfeldolgozás stb.). + +### 4. lépés: Alacsony biztonságú szavak listázása + +Most jön a rész, amely közvetlenül a “list words whose confidence is below the desired threshold” követelményt teljesíti. Alapértelmezés szerint **OCR confidence threshold**‑et 0.80‑ra (80 %) állítjuk, de ezt módosíthatod. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +A ciklus kiírja minden olyan szót, amely nem érte el a küszöböt, a százalékos biztonságával együtt. Ez pontosan az eredeti `for recognized_word in recognition_result.words` ciklus analógja, de most az EasyOCR kimeneti formátumával működik. + +--- + +## ## Az OCR biztonsági pontszámok megértése + +A biztonság nem varázslatos szám; a modell becslése arról, mennyire biztos a konkrét transzkripcióban. Néhány fontos szempont: + +| Helyzet | Tipikus biztonság | Mit tegyünk | +|-----------|-------------------|------------| +| Tiszta, nagy felbontású szken | 0.95 – 1.00 | Nincs további teendő | +| Enyhe elmosódás vagy egyenetlen megvilágítás | 0.80 – 0.94 | Fontold meg a kisebb előfeldolgozást (kontraszt növelése) | +| Erős zaj, elfordított szöveg | < 0.70 | Alkalmazz képelőfeldolgozást (kiegyenesítés, zajszűrés) vagy válts másik OCR motorra | + +> **Figyelem:** Egyes nyelvek (pl. folyó kézírás) természetesen alacsonyabb pontszámokat adnak. Ennek megfelelően állítsd be a küszöböt. + +### Szélsőséges esetek és variációk + +1. **Kötegelt feldolgozás** – Ha **run OCR on image** fájlokat nagy mennyiségben kell feldolgozni, csomagold a fenti logikát egy ciklusba, amely egy könyvtár fájljait iterálja. +2. **Több nyelv** – Adj meg egy listát, például `['en', 'fr']` a `easyocr.Reader`‑nek, és a motor mindkettőt felismeri. +3. **Alternatív motorok** – Szeretnéd kipróbálni a **pytesseract**‑ot? Cseréld le a reader blokkot a következőre: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Ezután össze kell gyűjtened a karakterek biztonságát szónként – egy kicsit több munka, de megoldható. + +4. **Előfeldolgozási trükkök** – OpenCV szűrők (`cv2.threshold`, `cv2.GaussianBlur`) alkalmazása növelheti a biztonságot zajos szkenek esetén. + +--- + +## ## Teljes, futtatható szkript + +Az alábbiakban a teljes Python fájl található, amelyet egyszerűen beilleszthetsz a projektedbe. Mentsd `ocr_report.py`‑ként, és futtasd `python ocr_report.py`‑vel. Győződj meg róla, hogy a kép útvonala valós fájlra mutat. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Várható kimenet** (a számaid eltérhetnek): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Ha minden szó átmegy a 80 % küszöbön, akkor a barátságos “All words meet the confidence threshold.” üzenetet fogod látni. + +--- + +## ## Gyakran Ismételt Kérdések (FAQ) + +**Q: Működik ez PDF‑ekkel?** +A: Nem közvetlenül. Először minden PDF oldalt alakíts át képpé (pl. a `pdf2image`‑vel), majd add a PNG/JPEG fájlt a szkriptnek. + +**Q: A biztonsági számok mind alacsonyak – mit tehetek?** +A: Próbálj meg képelőfeldolgozást: növeld a kontrasztot, távolítsd el a háttérzajt, vagy forgasd a képet vízszintes alapvonalra. Az EasyOCR egy `contrast_ths` paramétert is elfogad, amelyet finomhangolhatsz. + +**Q: Exportálhatom az eredményeket CSV‑be?** +A: Természetesen. Az alacsony‑biztonságú ciklus után írd ki az `ocr_results`‑t egy `csv.DictWriter`‑rel, ahol minden sor tartalmazza a `text`, `confidence` és a keretkoordinátákat. + +**Q: Van GPU‑gyorsított változat?** +A: Az EasyOCR automatikusan használja a CUDA‑t, ha kompatibilis GPU és a PyTorch telepítve van. Ellenőrizd a `torch.cuda.is_available()` függvénnyel a futtatás előtt. + +--- + +## Következtetés + +Most már **run OCR on image** Python‑nal, megvizsgáltuk az általános biztonságot, és elkülönítettük az alacsony biztonságú szavakat, amelyeket manuálisan kell felülvizsgálni. + +## Mit érdemes még megtanulni? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódrészleteket és lépés‑ről‑lépésre magyarázatokat tartalmaz, hogy elsajátíthasd a további API funkciókat és alternatív megvalósítási megközelítéseket saját projektjeidben. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/indonesian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..2f5d1b57b --- /dev/null +++ b/ocr/indonesian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Ekstrak teks dari gambar dengan Python OCR dalam hitungan menit. Temukan + OCR gambar multibahasa, deteksi otomatis bahasa OCR, dan cara mengekstrak teks OCR + secara akurat. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: id +og_description: Ekstrak teks dari gambar dengan Python OCR secara cepat. Pelajari + OCR gambar multibahasa, deteksi otomatis bahasa OCR, dan cara mengekstrak teks OCR + langkah demi langkah. +og_title: Ekstrak Teks dari Gambar Menggunakan OCR Python – Panduan Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Ekstrak Teks dari Gambar Menggunakan Python OCR – Panduan Lengkap +url: /id/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Image Using Python OCR – Complete Guide + +Pernah perlu **extract text from image** tetapi tidak yakin pustaka mana yang dapat menangani banyak bahasa secara otomatis? Anda tidak sendirian—para pengembang terus menanyakan *how to extract OCR text* saat berurusan dengan dokumen internasional, kwitansi, atau selebaran yang dipindai. Dalam tutorial ini kami akan membahas contoh Python praktis yang tidak hanya mengekstrak teks dari gambar tetapi juga **detects the language** secara dinamis, menjadikan multilingual image OCR sangat mudah. + +Kami akan membahas semuanya mulai dari menginstal paket OCR hingga mengaktifkan **auto detect language OCR**, menjalankan engine pada gambar contoh, dan akhirnya mencetak bahasa yang terdeteksi serta string yang diekstrak. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat dipakai ulang dalam proyek apa pun, baik Anda membangun pipeline terjemahan atau layanan data‑ingestion. + +## Extract Text from Image – Setting Up the Environment + +Sebelum kita masuk ke kode, pastikan workstation Anda memenuhi persyaratan minimal berikut: + +- Python 3.8 atau lebih baru (pustaka ini menggunakan type hints yang diabaikan oleh versi lama) +- `pip` untuk manajemen paket +- Sebuah file gambar yang berisi teks dalam setidaknya dua bahasa berbeda (misalnya English + Spanish) + +Anda juga memerlukan pustaka OCR yang mendukung demo ini. Untuk keperluan panduan ini kami akan menggunakan paket fiktif `ocr`, yang meniru alat populer dunia nyata seperti Tesseract atau EasyOCR tetapi menawarkan API Python yang bersih. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** Jika Anda menemui error izin, tambahkan `python -m` di depan perintah atau gunakan virtual environment—akan menjaga site‑packages global Anda tetap rapi. + +## Create OCR Engine Instance + +Setelah pustaka siap, langkah logis pertama adalah **create an OCR engine instance**. Anggap engine sebagai pemindai pintar yang dapat Anda konfigurasi sebelum memberi gambar kepadanya. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Mengapa kita menginstansiasi engine secara terpisah alih‑alih memanggil metode statis? Objek engine menyimpan status konfigurasi (seperti preferensi bahasa) yang mungkin ingin Anda gunakan kembali pada banyak gambar, sehingga mengurangi beban inisialisasi berulang kali. + +## Enable Auto Detect Language OCR + +Sebagian besar alat OCR mengharuskan Anda menentukan kode bahasa—`eng` untuk English, `spa` untuk Spanish, dan seterusnya. Menebak bahasa secara manual menghilangkan tujuan **multilingual image OCR**. Untungnya, paket `ocr` menyediakan mode *auto detect language OCR* yang memeriksa gambar dan memilih model bahasa terbaik di balik layar. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Mengaktifkan **detect language OCR** dengan cara ini berarti Anda tidak perlu memelihara daftar panjang kode bahasa. Engine akan mencoba mencocokkan skrip yang terlihat—Latin, Cyrillic, Han, dll.—dan memuat model yang tepat secara otomatis. + +## Perform Multilingual Image OCR + +Setelah engine siap, saatnya **extract text from image** secara nyata. Metode `recognize_image` menerima path file dan mengembalikan objek hasil yang berisi teks mentah serta bahasa yang terdeteksi. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Jika Anda bertanya-tanya *how to extract OCR text* dari PDF alih‑alih PNG, engine yang sama menyediakan `recognize_pdf`—cukup ganti nama metodenya. Logika deteksi yang mendasarinya tetap sama, sehingga Anda tetap mendapatkan fitur **auto detect language OCR**. + +## Display Detected Language and Extracted Text + +Akhirnya, kami menampilkan apa yang ditemukan engine. Objek hasil mengekspos `detected_language` (tag BCP‑47 seperti `en` atau `es`) dan `text`, yang berisi output OCR mentah. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Menjalankan skrip pada gambar contoh kami seharusnya menghasilkan sesuatu yang mirip dengan: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Perhatikan bagaimana engine berhasil mengidentifikasi English sebagai bahasa utama, namun tetap menangkap baris Spanish—tepat seperti yang Anda harapkan dari solusi **multilingual image OCR** yang kuat. + +### What If Detection Fails? + +Kadang‑kadang engine OCR dapat kembali ke bahasa default (biasanya English) jika gambar blur atau skrip terlalu eksotik. Dalam kasus tersebut Anda dapat memaksa daftar bahasa: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Namun ingat, memaksa bahasa menghilangkan kenyamanan **auto detect language OCR**, jadi gunakan hanya bila Anda memiliki subset bahasa yang diketahui. + +## Common Pitfalls and How to Extract OCR Text Reliably + +Meskipun dengan auto‑detection, beberapa kendala dapat mengganggu: + +1. **Low‑resolution images** – Akurasi OCR turun drastis di bawah 150 dpi. Upscale atau minta scan dengan resolusi lebih tinggi. +2. **Noise and compression artifacts** – Terapkan filter threshold sederhana (`opencv` atau `Pillow`) sebelum memberi gambar ke engine. +3. **Mixed scripts on one page** – Beberapa engine kesulitan dengan karakter Latin dan CJK secara bersamaan. Bagi halaman menjadi wilayah terpisah dan jalankan pengenalan terpisah bila diperlukan. + +Menangani masalah‑masalah ini secara signifikan meningkatkan kualitas proses **extract text from image**, terutama saat berurusan dengan dokumen multibahasa dunia nyata. + +## Full Working Example + +Berikut adalah skrip lengkap yang siap dijalankan, menggabungkan semua langkah yang telah dibahas. Simpan sebagai `multilingual_ocr.py` dan jalankan dari command line. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Expected output** (asumsi gambar contoh berisi teks English dan Spanish): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Silakan ganti `multilang_page.png` dengan gambar apa pun yang berisi teks dalam bahasa lain—berkat **auto detect language OCR**, skrip tetap akan memberikan tag bahasa yang masuk akal serta teks yang bersesuaian. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Conclusion + +Anda kini tahu persis **how to extract OCR text** dari gambar, cara mengaktifkan **auto detect language OCR**, dan cara menangani skenario **multilingual image OCR** dengan kode minimal. Dengan membuat OCR engine instance, mengaktifkan deteksi bahasa otomatis, dan memanggil `recognize_image`, Anda dapat secara andal mengambil identifier bahasa serta teks mentah. + +Apa selanjutnya? Cobalah mengirimkan string yang diekstrak ke API terjemahan, simpan dalam basis data yang dapat dicari, atau gabungkan beberapa halaman menjadi satu laporan PDF. Anda juga dapat bereksperimen dengan back‑end OCR lain (Tesseract, EasyOCR, Google Vision) sambil mempertahankan alur kerja tingkat tinggi yang sama—berkat antarmuka **detect language OCR** yang konsisten. + +Jika menemukan keanehan, tinjau kembali bagian “Common Pitfalls” atau sesuaikan langkah pra‑pemrosesan gambar. Selamat coding, semoga proyek Anda penuh dengan teks yang terdeteksi dengan benar dan diekstrak secara sempurna! + +## What Should You Learn Next? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/indonesian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..d027813e0 --- /dev/null +++ b/ocr/indonesian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Ekstrak teks dari gambar PDF menggunakan OCR Python. Pelajari cara mengonversi + dokumen yang dipindai menjadi teks dengan cepat menggunakan pengenalan batch asynchronous. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: id +og_description: Ekstrak teks dari gambar PDF dengan Python. Panduan langkah demi langkah + ini menunjukkan cara mengonversi dokumen yang dipindai menjadi teks menggunakan + OCR asinkron. +og_title: Ekstrak Teks dari PDF Gambar – Tutorial OCR Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Ekstrak Teks dari PDF Gambar – Panduan Python untuk Mengonversi Dokumen Pindai + menjadi Teks +url: /id/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ekstrak Teks dari PDF Gambar – Panduan Python untuk Mengonversi Dokumen Pindai menjadi Teks + +Pernah membutuhkan untuk **extract text from images pdf** tanpa menghabiskan berjam‑jam mengetik ulang? Dalam panduan ini kami akan menunjukkan cara **convert scanned documents to text** menggunakan alur kerja OCR asynchronous yang sederhana di Python. + +Jika Anda pernah menatap tumpukan PDF yang dipindai dan berpikir, “Harusnya ada cara yang lebih cepat,” Anda berada di tempat yang tepat. Kami akan menelusuri setiap baris kode, menjelaskan mengapa setiap bagian penting, dan bahkan membahas beberapa kasus tepi yang mungkin Anda temui. + +## Apa yang Akan Anda Pelajari + +- Cara memulai mesin OCR dan mengatur bahasa pengenalan. +- Mekanisme memberi daftar campuran PNG dan PDF ke pengenalan batch. +- Menjalankan pekerjaan OCR secara asynchronous sehingga aplikasi Anda tetap responsif. +- Mengambil kembali hasilnya, memadukannya dengan file sumber, dan mencetak output yang bersih. + +**Prerequisites**: Python 3.8+, pemahaman dasar tentang `asyncio` atau `concurrent.futures`, dan perpustakaan OCR yang menyediakan kelas `OcrEngine` serupa dengan contoh (misalnya, Aspose.OCR, wrapper Tesseract, atau wrapper khusus). Tidak memerlukan pengaturan berat—cukup instal perpustakaan dan Anda siap. + +![extract text from images pdf](https://example.com/placeholder.png "Screenshot of OCR output – extract text from images pdf") + +## Ekstrak Teks dari PDF Gambar – Menyiapkan Mesin OCR + +Hal pertama yang Anda butuhkan adalah sebuah instance mesin OCR yang dikonfigurasi untuk bahasa dokumen Anda. Dalam kasus kami, kami akan menggunakan bahasa Prancis, tetapi Anda dapat menggantinya dengan bahasa apa pun yang didukung. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Why this matters**: Menetapkan bahasa di awal secara dramatis meningkatkan akurasi. Mesin menggunakan kamus dan model karakter khusus bahasa; memberi bahasa yang salah merupakan sumber umum output yang kacau. + +## Siapkan Daftar File – Gambar dan PDF Bersama-sama + +Pengrecognizer batch kami dapat menangani baik gambar raster (`.png`, `.jpg`) maupun kontainer PDF. Cukup berikan daftar Python biasa berisi jalur file. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: Jaga daftar tetap datar; mesin akan secara internal mengekstrak setiap halaman PDF menjadi gambar sebelum pengenalan. Jika Anda memiliki ribuan file, pertimbangkan memecah daftar menjadi batch lebih kecil untuk menghindari lonjakan memori. + +## Memulai Pengakuan Batch Asynchronous + +Alih-alih memblokir thread utama, kami meluncurkan pekerjaan OCR di latar belakang. Metode ini mengembalikan sebuah `Future` yang pada akhirnya akan berisi daftar objek `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**How it works**: Di balik layar, mesin membuat thread pool (atau tugas async, tergantung implementasinya). Ini memungkinkan Anda terus melakukan pekerjaan lain—seperti memperbarui UI, mengambil lebih banyak file, atau mencatat kemajuan—sementara proses berat terjadi di tempat lain. + +## Lakukan Sesuatu yang Berguna Saat OCR Berjalan + +Kesalahan umum adalah duduk diam dan mem-poll future dalam loop ketat. Sebagai gantinya, Anda dapat melakukan pekerjaan tidak terkait apa pun. Untuk demonstrasi, kami hanya akan mencetak baris status. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Kumpulkan Hasil Setelah Future Selesai + +Saat Anda siap mengumpulkan output OCR, gunakan `as_completed` dari `concurrent.futures`. Pola ini bekerja baik Anda memiliki satu future atau banyak. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**What you’ll see**: Setiap jalur file diikuti oleh representasi teks polos yang diekstrak. Untuk PDF, `result.text` berisi teks yang digabungkan dari setiap halaman. + +### Output yang Diharapkan (contoh) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Jika Anda melihat karakter yang hilang, periksa kembali bahwa bahasa yang Anda atur cocok dengan bahasa dokumen, dan pertimbangkan pra‑pemrosesan gambar (meluruskan, meningkatkan kontras) sebelum memberikannya ke mesin. + +## Menangani Kasus Tepi dan Jebakan Umum + +| Situasi | Apa yang Harus Dilakukan | +|-----------|------------| +| **Mixed languages** | Jalankan proses deteksi bahasa terlebih dahulu, kemudian buat instance mesin terpisah per bahasa. | +| **Huge PDFs (> 100 MB)** | Bagi PDF menjadi halaman individual di disk (mis., menggunakan `PyPDF2`) dan berikan sebagai entri terpisah. | +| **Non‑Latin scripts** | Pastikan perpustakaan OCR menyertakan paket bahasa yang diperlukan; beberapa perpustakaan mengharuskan Anda mengunduh file data tambahan. | +| **Performance bottleneck** | Tingkatkan ukuran thread pool (`engine.set_thread_pool_size(8)`) atau beralih ke backend yang dipercepat GPU jika tersedia. | +| **Missing text in low‑resolution images** | Pra‑proses dengan OpenCV: `cv2.resize`, `cv2.threshold`, dan `cv2.medianBlur` untuk meningkatkan keterbacaan. | + +## Contoh Lengkap yang Berfungsi (Siap Salin‑Tempel) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Simpan ini sebagai `extract_text_async.py`, ganti `YOUR_DIRECTORY` dengan jalur ke file Anda, instal paket OCR (`pip install your-ocr-lib`), dan jalankan `python extract_text_async.py`. Anda akan melihat output konsol seperti yang ditunjukkan sebelumnya. + +## Langkah Selanjutnya – Melampaui Ekstraksi Dasar + +- **Post‑processing**: Hapus spasi ekstra, normalisasi Unicode (`unicodedata.normalize`), atau jalankan pemeriksa ejaan untuk membersihkan noise OCR. +- **Structured output**: Ekspor hasil ke CSV, JSON, atau langsung ke basis data untuk pencarian downstream. +- **Parallel batches**: Jika Anda memiliki ratusan file, buat beberapa future dan gunakan antrian untuk menjaga CPU sibuk tanpa membebani memori. +- **Integrate with web frameworks**: Sambungkan skrip ini ke endpoint Flask atau FastAPI untuk menyediakan OCR on‑demand sebagai layanan. + +--- + +### TL;DR + +Anda sekarang tahu cara **extract text from images pdf** dengan skrip Python minimal yang menjalankan OCR secara asynchronous, memungkinkan Anda **convert scanned documents to text** sementara program Anda tetap responsif. Bereksperimenlah dengan pengaturan bahasa, ukuran batch, dan trik pra‑pemrosesan untuk memperoleh akurasi karakter hingga yang terakhir. + +Ada variasi yang ingin Anda bagikan—mungkin OCR pada catatan tulisan tangan atau layanan berbasis cloud? Tinggalkan komentar, dan selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Ekstrak Teks dari Gambar dengan Aspose OCR – Panduan Langkah‑per‑Langkah](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Ekstrak Teks dari Gambar Menggunakan Operasi OCR pada Folder](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Ekstrak Teks dari Gambar Menggunakan Aspose.OCR – Karakter yang Diizinkan](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..d27151708 --- /dev/null +++ b/ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: Cara melakukan OCR PDF menggunakan Python, mengekstrak teks dari PDF, + mengonversi teks PDF yang dipindai, dan mengubah bahasa OCR hanya dalam beberapa + baris kode. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: id +og_description: 'Cara OCR PDF dengan Python: panduan praktis yang menunjukkan cara + mengekstrak teks dari PDF, mengonversi teks PDF yang dipindai, dan mengubah bahasa + OCR dengan mudah.' +og_title: Cara OCR PDF dengan Python – Tutorial Pemrograman Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Cara OCR PDF di Python – Panduan Lengkap Langkah demi Langkah +url: /id/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara OCR PDF di Python – Panduan Lengkap Langkah‑per‑Langkah + +Pernah bertanya-tanya **bagaimana cara OCR PDF** tanpa harus membayar alat SaaS yang mahal? Anda bukan satu-satunya. Baik Anda sedang mendigitalkan buku lama, mengambil data dari faktur, atau hanya membutuhkan teks yang dapat dicari dari laporan yang dipindai, menguasai PDF OCR di Python dapat menghemat berjam‑jam penyalinan manual. + +Dalam tutorial ini kami akan membahas contoh singkat dan berfungsi yang **mengekstrak teks dari PDF**, menunjukkan cara **mengonversi teks PDF yang dipindai** menjadi string yang dapat diedit, dan bahkan mendemonstrasikan cara **mengubah bahasa OCR** jika dokumen Anda bukan dalam bahasa Inggris. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat digunakan kembali dan dapat dimasukkan ke dalam proyek apa pun. + +## Prasyarat & Penyiapan + +Sebelum kita mulai, pastikan Anda memiliki: + +- Python 3.8+ terinstal (kode ini bekerja pada 3.9, 3.10, dan yang lebih baru) +- Paket `ocr` yang menyediakan kelas `OcrEngine` (Anda dapat menginstalnya via `pip install ocr-lib` – ganti dengan nama paket sebenarnya yang Anda gunakan) +- File PDF yang ingin Anda proses; untuk demo kami akan menggunakan `high_res_book.pdf` yang ditempatkan di folder bernama `YOUR_DIRECTORY` + +Jika Anda menggunakan lingkungan virtual (sangat disarankan), aktifkan terlebih dahulu: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** Simpan file PDF Anda di dalam direktori `data/` khusus untuk menghindari masalah terkait jalur di kemudian hari. + +## Langkah 1: Buat Instance OCR Engine (Cara OCR PDF – Inisialisasi) + +Hal pertama yang harus Anda lakukan ketika ingin **melakukan OCR pada PDF** adalah menginstansiasi engine. Anggap engine sebagai otak yang akan membaca setiap halaman, menafsirkan glyph, dan memberikan kembali teks polos. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Mengapa ini penting: tanpa engine Anda tidak memiliki konteks untuk pengaturan bahasa, opsi rendering, atau penanganan PDF. Objek `OcrEngine` menyimpan semua default tersebut dan memungkinkan Anda menyesuaikannya nanti. + +## Langkah 2: Atur Bahasa Pengakuan (Ubah Bahasa OCR) + +Sebagian besar perpustakaan OCR default ke bahasa Inggris, tetapi bagaimana jika dokumen Anda dalam bahasa Prancis, Jerman, atau bahkan Jepang? Mengubah bahasa semudah memanggil `set_recognition_language`. Ini memenuhi persyaratan **change OCR language** dan memastikan akurasi yang lebih tinggi. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Mengapa Anda mungkin memerlukannya:** Arsip multibahasa sering berisi halaman dengan bahasa campuran. Mengganti bahasa secara dinamis mencegah kesalahan pengenalan karakter seperti “ß” atau “ñ”. + +## Langkah 3: Konfigurasikan Opsi Rendering PDF (Konversi Teks PDF yang Dipindai Secara Efektif) + +Saat menangani PDF yang dipindai, resolusi dan mode warna sangat memengaruhi kualitas OCR. Rendering pada 300 DPI dalam skala abu‑abu adalah titik optimal untuk kebanyakan dokumen—cukup tinggi untuk menangkap detail namun cukup rendah untuk menjaga penggunaan memori tetap wajar. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Pemanggilan berantai mungkin terlihat mewah, tetapi sebenarnya hanyalah API fluida yang mengembalikan objek opsi yang sama setiap kali. Jika Anda membutuhkan warna (misalnya, untuk diagram berwarna), ganti `"grayscale"` dengan `"color"`. + +## Langkah 4: Kenali PDF dan Ambil Teks Halaman Pertama (Ekstrak Teks dari PDF) + +Sekarang tiba pada inti **bagaimana cara OCR PDF**: memberikan engine jalur file dan mengambil teks yang dikenali. Metode ini mengembalikan daftar hasil per halaman; setiap hasil berisi atribut `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Jika Anda membutuhkan seluruh dokumen, iterasikan `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Bagaimana Jika PDF Terenkripsi? + +Beberapa PDF dilindungi kata sandi. Dalam kasus itu Anda dapat mengirimkan kata sandi ke `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Engine akan mendekripsi secara langsung sebelum melakukan OCR—tidak diperlukan langkah tambahan. + +## Langkah 5: Pemrosesan Pasca Teks yang Diekstrak (Penyetelan Halus Ekstrak Teks dari PDF) + +Output OCR mentah sering berisi pemutusan baris, spasi berlebih, atau karakter yang terkadang salah dikenali. Rutinitas pembersihan cepat membuat string yang diekstrak siap untuk pemrosesan lanjutan (pengindeksan pencarian, penyimpanan basis data, dll.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Anda kini dapat dengan aman **mengekstrak teks dari PDF** dan memasukkannya ke dalam pipeline NLP apa pun, mesin pencari, atau operasi sederhana `open(...).write()`. + +## Bonus: Pemrosesan Batch Banyak PDF (Skala Perform OCR pada PDF) + +Jika Anda memiliki folder penuh PDF yang dipindai, bungkus logika dalam sebuah loop: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Potongan kode ini menunjukkan cara **perform OCR on PDF** secara massal, kebutuhan umum untuk proyek digitalisasi. + +## Output yang Diharapkan + +Menjalankan contoh satu‑halaman (Langkah 4) seharusnya mencetak sesuatu seperti: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Jika Anda memproses buku multi‑halaman, konsol akan menampilkan teks bersih setiap halaman, dan skrip batch akan meninggalkan file `.txt` di samping setiap PDF. + +## Kesalahan Umum & Cara Menghindarinya + +| Masalah | Gejala | Solusi | +|-------|----------|-----| +| PDF sumber beresolusi rendah | Karakter kacau, kata hilang | Tingkatkan DPI (`set_dpi(400)` atau lebih tinggi) | +| Pengaturan bahasa salah | Banyak simbol tidak dikenal, terutama karakter beraksen | Gunakan `engine.set_recognition_language(ocr.Language.FRENCH)` atau enum yang sesuai | +| PDF besar menyebabkan error memori | `MemoryError` atau crash setelah beberapa halaman | Proses halaman secara bertahap (`engine.recognize_pdf(..., max_pages=10)`) | +| Font hilang di PDF | Output kosong untuk halaman tertentu | Pastikan PDF memang berisi gambar raster; beberapa PDF hanya vektor dan memerlukan penanganan berbeda | + +## Ilustrasi Gambar + +Berikut adalah visual cepat dari alur kerja. Teks alt sengaja dibuat SEO‑friendly. + +![diagram alur kerja cara OCR PDF yang menunjukkan inisialisasi engine, pengaturan bahasa, opsi rendering, pengenalan, dan ekstraksi teks](/images/ocr-workflow.png) + +*Diagram ini tidak diperlukan agar kode berjalan, tetapi membantu pembelajar visual melihat di mana setiap langkah berada.* + +## Kesimpulan + +Kami telah membahas **bagaimana cara OCR PDF** di Python dari awal hingga akhir: membuat OCR engine, **mengubah bahasa OCR**, mengonfigurasi rendering untuk **mengonversi teks PDF yang dipindai**, dan akhirnya **mengekstrak teks dari PDF** untuk penggunaan lebih lanjut. Contoh lengkap yang dapat dijalankan siap disisipkan ke dalam proyek apa pun, dan skrip batch opsional menunjukkan cara menskalakan solusi. + +Selanjutnya, Anda mungkin ingin mengeksplorasi: + +- Menambahkan **perform OCR on PDF** untuk arsip multibahasa dengan melakukan loop pada daftar bahasa. +- Mengintegrasikan teks yang diekstrak dengan Elasticsearch untuk pencarian full‑text. +- Menggunakan OCR untuk membuat PDF yang dapat dicari dengan menyematkan lapisan teks kembali ke file asli (banyak perpustakaan menyediakan metode `save_as_searchable_pdf`). + +Silakan bereksperimen, mengubah pengaturan DPI, atau beralih ke backend OCR yang berbeda. Dasar-dasarnya tetap sama, dan Anda kini memiliki fondasi yang kuat untuk dibangun. + +Selamat coding, dan semoga dokumen yang dipindai akhirnya menjadi dapat dicari! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..b7136c208 --- /dev/null +++ b/ocr/indonesian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-06 +description: Cara melakukan OCR pada PDF dan membuat file PDF yang dapat dicari dari + gambar menggunakan Python. Pelajari cara menambahkan teks yang dapat dicari dan + mengonversi gambar ke PDF/A dalam hitungan menit. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: id +og_description: Cara OCR PDF langkah demi langkah. Pelajari cara menambahkan teks + yang dapat dicari dan mengonversi gambar ke PDF/A menggunakan skrip Python sederhana. +og_title: Cara OCR PDF – Panduan Cepat Membuat PDF yang Dapat Dicari +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Cara OCR PDF di Python – Membuat PDF yang Dapat Dicari dari Gambar +url: /id/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara OCR PDF – Mengubah Gambar Pindai menjadi PDF yang Dapat Dicari + +Pernah bertanya-tanya **cara OCR PDF** ketika yang Anda miliki hanya gambar pindai dari faktur atau kwitansi? Anda tidak sendirian. Di banyak kantor, dokumen masuk datang sebagai PNG atau JPEG datar, dan langkah selanjutnya—membuat konten tersebut dapat dicari—terasa seperti kotak hitam. + +Kabar baik? Dengan hanya beberapa baris Python Anda dapat **membuat PDF yang dapat dicari**, **menambahkan teks yang dapat dicari**, dan bahkan **mengonversi gambar ke PDF/A** untuk pengarsipan jangka panjang. Dalam tutorial ini kami akan membahas setiap langkah, menjelaskan mengapa langkah tersebut penting, dan memberi Anda skrip siap‑jalankan yang dapat Anda masukkan ke proyek apa pun. + +> **Pro tip:** Pendekatan yang sama bekerja untuk pemindaian multi‑halaman; cukup lakukan loop pada file‑file dan mesin akan menangani proses beratnya. + +--- + +## Apa yang Anda Butuhkan + +Sebelum kita mulai, pastikan Anda memiliki hal‑hal berikut di mesin Anda: + +| Persyaratan | Mengapa penting | +|-------------|-----------------| +| Python 3.9 atau lebih baru | Sintaks modern dan dukungan pustaka yang lebih baik | +| Mesin OCR berbasis `pdfium` (misalnya `pdfocr` atau SDK komersial) | Menangani baik pengenalan gambar maupun pembuatan PDF/A | +| File gambar (PNG, JPEG, TIFF) yang ingin Anda ubah menjadi PDF yang dapat dicari | Sumber teks | +| Izin menulis ke folder output | Agar skrip dapat menyimpan PDF baru | + +Jika Anda belum menginstal SDK OCR, jalankan: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Itu saja—tidak ada ketergantungan sistem yang rumit, hanya instalasi pip. + +--- + +## Cara OCR PDF – Ikhtisar + +Secara umum prosesnya terdiri dari tiga tindakan sederhana: + +1. **Mengenali** teks di dalam gambar sambil mempertahankan grafik asli. +2. **Mengekspor** hasil OCR bersama gambar asli sebagai **PDF/A yang dapat dicari** (varian PDF yang ramah arsip). +3. **Memvalidasi** bahwa file yang dihasilkan berisi teks yang dapat dipilih dan dicari di atas gambar asli. + +Di bawah ini Anda akan melihat setiap langkah dalam kode, dengan penjelasan *mengapa* di balik perintah‑perintah tersebut. + +--- + +## Langkah 1: Mengenali Teks dari Gambar + +Pertama kami meminta mesin OCR membaca piksel dan mengembalikan objek hasil yang memuat baik gambar mentah maupun teks yang diekstrak. Anggap saja mesin “membaca” faktur untuk Anda. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Mengapa ini penting + +- **Mempertahankan grafis** berarti tata letak visual (tabel, logo, stempel) tetap persis seperti yang dipindai. +- Objek `result` biasanya berisi lapisan teks tersembunyi yang nanti akan kami sematkan ke PDF. +- Menggunakan `recognize_image` alih‑alih `recognize_pdf` menghindari langkah konversi tambahan, yang mempercepat pemrosesan untuk gambar satu halaman. + +#### Variasi umum + +- Jika Anda memiliki **TIFF multi‑halaman**, berikan jalur file secara langsung; kebanyakan mesin akan memperlakukan setiap halaman sebagai gambar terpisah. +- Untuk PDF yang sudah berisi gambar, Anda dapat memanggil `engine.recognize_pdf("file.pdf")` dan melewati langkah ini sepenuhnya. + +--- + +## Langkah 2: Mengekspor Hasil OCR sebagai PDF/A yang Dapat Dicari + +Sekarang kami mengambil `result` dari langkah 1 dan memberi tahu mesin untuk menulis file baru. Flag kunci di sini adalah *PDF/A*—versi standar ISO dari PDF yang dirancang untuk preservasi jangka panjang. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Mengapa ini penting + +- **PDF yang dapat dicari**: File output berisi lapisan teks tersembunyi yang dapat dipilih. Anda kini dapat menggunakan Ctrl + F pada dokumen. +- **Kepatuhan PDF/A**: Beberapa organisasi (hukum, keuangan) memerlukan PDF/A untuk jejak audit; langkah ini memenuhi aturan tersebut secara otomatis. +- Metode ini juga **menambahkan teks yang dapat dicari** tanpa meratakan gambar, sehingga kesetiaan visual tetap sempurna. + +#### Kasus khusus: Membutuhkan PDF biasa saja? + +Jika Anda tidak memerlukan PDF/A, ganti `save_as_pdfa` dengan `save_as_pdf`. Sisa alur kerja tetap sama. + +--- + +## Langkah 3: Memverifikasi PDF yang Dapat Dicari + +Pemeriksaan cepat menyelamatkan Anda dari bug misterius di kemudian hari. Buka file yang dihasilkan di penampil PDF apa pun, coba pilih sebuah kata, dan gunakan fungsi pencarian. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Output yang Diharapkan + +Saat Anda menjalankan skrip, konsol akan mencetak: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Membuka file, Anda akan melihat gambar faktur asli dengan lapisan teks yang samar dan tak terlihat. Sorot kata apa pun dan Anda akan melihat bahwa teks tersebut dapat dipilih—**itulah teks yang dapat dicari** yang baru saja Anda tambahkan. + +--- + +## Menambahkan Teks yang Dapat Dicari ke PDF yang Ada (Bonus) + +Kadang‑kadang Anda sudah memiliki PDF tetapi perlu **menambahkan teks yang dapat dicari** ke dalamnya. Mesin yang sama dapat menimpa hasil OCR pada PDF yang sudah ada: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Di sini `apply_to` menggabungkan lapisan tersembunyi dengan halaman‑halaman asli, memungkinkan Anda **membuat PDF yang dapat dicari** tanpa harus memindai ulang. + +--- + +## Kesalahan Umum dan Tips + +| Masalah | Cara menghindarinya | +|---------|---------------------| +| **Gambar sumber beresolusi rendah** (< 150 dpi) | Perbesar atau minta pemindaian beresolusi lebih tinggi; akurasi OCR turun drastis di bawah 150 dpi. | +| **Data bahasa hilang** | Instal paket bahasa yang sesuai untuk mesin OCR Anda (`pip install pdfocr[eng,spa]`). | +| **Folder output tidak dapat ditulis** | Jalankan skrip dengan izin yang cukup atau pilih direktori lain. | +| **Validasi PDF/A gagal** | Pastikan Anda tidak menyematkan font yang tidak didukung atau JavaScript; kebanyakan SDK menangani ini secara otomatis ketika Anda menggunakan `save_as_pdfa`. | + +--- + +## Skrip Lengkap – Solusi Satu‑File + +Berikut adalah skrip mandiri yang mengikat semua langkah bersama. Salin‑tempel, ganti jalur placeholder, dan Anda siap **mengonversi gambar ke PDF/A** dalam hitungan detik. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Apa yang dilakukan skrip ini:** +1. Memuat mesin OCR. +2. Membaca gambar yang dipilih dan mengekstrak teks. +3. Menulis **PDF/A yang dapat dicari** yang dapat langsung Anda distribusikan atau arsipkan. + +Silakan bungkus logika `main` dalam fungsi yang memproses seluruh folder—cukup iterasi melalui `os.listdir()` dan ulangi tiga langkah untuk setiap file. + +--- + +## Langkah Selanjutnya & Topik Terkait + +Sekarang Anda telah menguasai **cara OCR PDF**, pertimbangkan menjelajahi ide‑ide lanjutan berikut: + +- **Pemrosesan batch:** Gunakan `concurrent.futures` untuk OCR puluhan faktur secara paralel. +- **Penyuntikan metadata:** Tambahkan tanggal pembuatan atau nomor faktur ke metadata PDF untuk indeksasi yang lebih mudah. +- **PDF hibrida:** Gabungkan teks yang dapat dicari dengan gambar asli yang disematkan untuk “kembar digital” dokumen kertas. +- **Output alternatif:** Ekspor ke **DOCX** atau **HTML** jika sistem hilir memerlukan format yang dapat diedit. + +Masing‑masing hal ini dibangun di atas konsep inti yang baru saja Anda pelajari—mengenali, mengekspor, memverifikasi. + +--- + +## Wrap‑Up + +Singkatnya, Anda kini tahu **cara OCR PDF** dengan mengubah gambar sederhana menjadi **PDF/A yang dapat dicari** hanya dengan tiga baris Python. Skrip menangani pekerjaan berat, mempertahankan grafis asli, dan memberi Anda dokumen yang sesuai standar yang dapat Anda cari, arsipkan, atau bagikan. + +Cobalah dengan faktur, kwitansi, atau kontrak pindai Anda sendiri. Jika Anda menemui kendala, tinggalkan komentar di bawah atau periksa dokumentasi resmi SDK—biasanya penuh dengan contoh tambahan. Selamat coding, dan nikmati kemampuan baru untuk membuat gambar apa pun langsung dapat dicari! + +![Contoh Cara OCR PDF yang menampilkan gambar asli dan lapisan PDF yang dapat dicari](placeholder.png "Contoh Cara OCR PDF") + +## Apa yang Harus Anda Pelajari Selanjutnya? + + +Tutorial berikut mencakup topik‑topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara OCR PDF di .NET dengan Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Mengenali Teks PDF – Operasi OCR dengan Aspose.OCR untuk Java](/ocr/english/java/ocr-operations/) +- [Mengonversi Gambar ke PDF C# – Simpan Hasil OCR Multi‑halaman](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/indonesian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..e2cbc8da4 --- /dev/null +++ b/ocr/indonesian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Cara melakukan OCR PDF menggunakan Aspose OCR Cloud. Pelajari cara mengekstrak + teks dari PDF, mengonversi halaman PDF ke PNG, dan menyimpan gambar halaman PDF + dengan Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: id +og_description: Cara OCR PDF dengan Aspose OCR Cloud. Panduan ini menunjukkan cara + mengekstrak teks biasa dari PDF, mengonversi halaman PDF ke PNG, dan menyimpan gambar + halaman PDF. +og_title: Cara OCR PDF dengan Aspose OCR Cloud – Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Cara OCR PDF dengan Aspose OCR Cloud – Panduan Lengkap +url: /id/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara OCR PDF dengan Aspose OCR Cloud – Panduan Lengkap + +Pernah bertanya-tanya **bagaimana cara OCR PDF** tanpa harus berurusan dengan alat desktop yang berat? Anda tidak sendirian—banyak pengembang mengalami hal yang sama ketika mereka membutuhkan cara cepat dan programatis untuk mengambil teks dari dokumen yang dipindai. Kabar baiknya? Dengan Aspose OCR Cloud Anda dapat **mengekstrak teks dari PDF**, mengubah setiap halaman menjadi PNG, dan bahkan **menyimpan gambar halaman PDF** untuk penggunaan nanti, semuanya dari skrip Python yang rapi. + +Dalam tutorial ini kami akan membahas semua yang perlu Anda ketahui: mulai dari menginstal SDK, melisensikan engine, dan mengenali PDF multi‑halaman, hingga mengekstrak teks biasa, mengonversi halaman ke PNG, dan menyimpan gambar-gambar tersebut ke disk. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat digunakan kembali dan dapat dimasukkan ke proyek mana pun yang membutuhkan kemampuan **how to OCR PDF**. + +## Apa yang Anda Butuhkan + +- **Python 3.8+** (kode ini juga berfungsi pada 3.10 dan yang lebih baru) +- Akun Aspose OCR Cloud – Anda akan mendapatkan file lisensi percobaan gratis (`Aspose.OCR.lic`) +- Paket `asposeocrcloud` (`pip install asposeocrcloud`) +- PDF yang dipindai dan multi‑halaman yang ingin Anda proses + +Itu saja. Tidak ada binary tambahan, tidak ada dependensi native, hanya Python murni. + +## Cara OCR PDF – Penyiapan dan Lisensi + +Sebelum Anda dapat memanggil metode OCR apa pun, Anda harus memberi tahu SDK siapa Anda. Aspose menggunakan file lisensi ringan yang Anda tempatkan di lokasi yang dapat diakses oleh skrip Anda. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* Jika Anda melewatkan langkah lisensi, SDK tetap akan berfungsi tetapi akan menambahkan watermark kecil pada gambar output. Tidak ideal untuk produksi. + +## Langkah 2: Instal Aspose OCR Cloud Python SDK + +Buka terminal dan jalankan: + +```bash +pip install asposeocrcloud +``` + +Paket ini mengunduh semua dependensi yang diperlukan (requests, pillow, dll.) sehingga Anda tidak perlu mencari apa pun lagi. + +## Langkah 3: Buat Engine OCR dan Pilih Bahasa + +Engine adalah inti dari operasi. Anda dapat menentukan bahasa apa pun yang didukung oleh Aspose; Bahasa Inggris bekerja untuk kebanyakan kasus. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Mengapa mengatur bahasa? Karena engine OCR menggunakan kamus khusus bahasa untuk meningkatkan akurasi. Jika Anda memproses PDF berbahasa Prancis, cukup ganti `ENGLISH` dengan `FRENCH`. + +## Langkah 4: Arahkan ke PDF Multi‑Halaman Anda + +Berikan engine path lengkap ke file yang ingin Anda proses. Path relatif dapat digunakan selama dapat diresolusikan dari direktori kerja skrip. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Pastikan file dapat dibaca; jika tidak, Anda akan melihat `FileNotFoundError`. + +## Langkah 5: Jalankan OCR – Anda Mendapatkan Daftar Hasil + +Memanggil `recognize_pdf` mengembalikan sebuah daftar di mana setiap elemen sesuai dengan satu halaman dari PDF sumber. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Setiap `OcrResult` berisi dua properti berguna: + +* `text` – representasi teks biasa dari halaman (bagus untuk **extract plain text pdf**) +* `image` – objek `Image` Pillow dari halaman yang dirender (sempurna untuk **convert pdf page png**) + +## Langkah 6: Ekstrak Teks dari PDF dan Konversi Halaman ke PNG + +Sekarang kita mengulangi hasil, mencetak teks yang diekstrak, dan menyimpan versi PNG dari setiap halaman. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Output Konsol yang Diharapkan + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Anda juga akan menemukan `page_1.png`, `page_2.png`, … berada di `YOUR_DIRECTORY`. Itu adalah gambar halaman yang dirasterisasi yang dapat Anda masukkan ke pipeline pemrosesan gambar selanjutnya. + +## Langkah 7: Simpan Gambar Halaman PDF (Pemrosesan Pasca Opsional) + +Jika Anda hanya membutuhkan gambar dan bukan teks, Anda dapat melewatkan baris `print(res.text)`. Sebaliknya, jika Anda ingin menyimpan teks dalam file `.txt` terpisah, cukup tambahkan penulisan kecil berikut: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Penambahan kecil ini menunjukkan betapa mudahnya **save PDF page images** sambil juga menyimpan konten yang diekstrak. + +## Contoh Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut skrip lengkap yang dapat Anda salin‑tempel ke `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Jalankan dengan: + +```bash +python ocr_pdf.py +``` + +Anda akan melihat dump konsol dari teks setiap halaman dan serangkaian file PNG + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara OCR PDF di .NET dengan Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Mengenali Teks PDF – Operasi OCR dengan Aspose.OCR untuk Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Mengonversi Gambar ke PDF C# – Simpan Hasil OCR Multi‑halaman](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/indonesian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..22fad74dc --- /dev/null +++ b/ocr/indonesian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Cara memproses gambar untuk OCR menggunakan Python. Pelajari cara membinarisasi + gambar dengan Otsu, cara memperbaiki kemiringan dokumen yang dipindai, dan meningkatkan + akurasi OCR untuk teks berbahasa Jerman. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: id +og_description: Cara memproses gambar untuk OCR di Python. Tutorial ini menunjukkan + cara mengbinerkan gambar menggunakan Otsu, cara memperbaiki kemiringan dokumen yang + dipindai, dan cara meningkatkan akurasi OCR untuk gambar berbahasa Jerman. +og_title: Cara Memproses Gambar untuk OCR – Panduan Python Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Cara Praproses Gambar untuk OCR – Panduan Python Lengkap +url: /id/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Memproses Gambar untuk OCR – Panduan Python Lengkap + +Pernah bertanya‑tanya **bagaimana cara memproses gambar untuk OCR** agar teksnya menjadi sangat jelas? Anda bukan satu‑satunya. Dokumen yang dipindai—terutama halaman Jerman yang berisik—bisa menjadi mimpi buruk bagi mesin OCR mana pun. Kabar baik? Beberapa langkah pra‑pemrosesan cerdas dapat mengubah pemindaian yang buram dan berbutir menjadi gambar bersih yang dapat dibaca mesin. + +Dalam tutorial ini kami akan menelusuri contoh praktis yang menunjukkan **bagaimana cara memproses gambar untuk OCR** menggunakan Python. Anda akan belajar **binarize image using Otsu**, **how to deskew scanned documents**, dan secara keseluruhan **how to improve OCR accuracy** ketika Anda perlu **extract text from German image** file. Tanpa basa‑basi, hanya skrip yang dapat langsung Anda salin‑tempel hari ini. + +## Apa yang Anda Butuhkan + +- **Python 3.9+** (versi terbaru apa pun dapat digunakan) +- Sebuah pustaka OCR yang menyediakan kelas `OcrEngine` – untuk demo kami akan mengasumsikan paket `ocr` generik. Instal dengan `pip install ocr-lib`. +- Sebuah pemindaian Jerman yang berisik (`noisy_german_scan.tif`) yang ingin Anda uji. +- Pemahaman dasar tentang fungsi Python (jika Anda pernah menulis `def`, Anda sudah siap). + +> **Pro tip:** Jika Anda menggunakan SDK OCR yang berbeda (misalnya, Tesseract via `pytesseract`), konsepnya tetap sama—cukup sesuaikan nama metodenya. + +## Ikhtisar Solusi + +1. **Buat sebuah instance mesin OCR.** +2. **Atur bahasa pengenalan ke Jerman.** +3. **Bangun pipeline pra‑pemrosesan khusus** yang mencakup deskewing, denoising, binarization (Otsu), dan contrast stretching. +4. **Lampirkan pipeline ke mesin** sehingga setiap gambar melewatinya secara otomatis. +5. **Jalankan OCR** pada pemindaian Jerman yang berisik. +6. **Cetak teks yang diekstrak** untuk memverifikasi hasilnya. + +Di bawah ini kami memecah setiap langkah, menjelaskan **mengapa** itu penting, dan menampilkan kode tepat yang Anda perlukan. + +![contoh cara memproses gambar untuk OCR](image.png "contoh cara memproses gambar untuk OCR") + +## Langkah 1: Buat Instance Mesin OCR + +Hal pertama yang harus dilakukan—tanpa mesin, tidak ada yang terjadi. Objek `OcrEngine` adalah titik masuk yang mengkoordinasikan semua pemrosesan selanjutnya. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Mengapa ini penting:* Menginisialisasi mesin menyiapkan sumber daya internal (seperti model bahasa) dan memberi Anda kanvas bersih untuk melampirkan pipeline khusus nanti. + +## Langkah 2: Atur Bahasa Pengakuan ke Jerman + +Akurasi OCR sangat bergantung pada bahasa. Dengan memberi tahu mesin untuk mengharapkan bahasa Jerman, Anda mengaktifkan set karakter dan model bahasa yang tepat. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Jika Anda melewatkan langkah ini, mesin mungkin default ke bahasa Inggris, sehingga salah mengenali umlaut (ä, ö, ü) dan karakter ß—kesalahan umum saat menangani pemindaian Jerman. + +## Langkah 3: Bangun Pipeline Pra‑Pemrosesan Khusus + +Inilah inti **bagaimana cara memproses gambar untuk OCR**. Kami akan merangkai empat transformasi: + +| Transformasi | Apa yang dilakukan | Mengapa membantu | +|--------------|--------------------|------------------| +| **Deskew** | Memutar gambar kembali ke posisi horizontal (maks 5°) | Pemindaian jarang sekali sejajar sempurna; deskew menghilangkan kemiringan yang membingungkan segmentasi karakter. | +| **Denoise** | Mengurangi bintik‑bintik acak (kekuatan 0.7) | Noise menghasilkan tepi palsu yang dapat diinterpretasikan mesin OCR sebagai karakter. | +| **Binarize (Otsu)** | Mengubah menjadi hitam‑putih menggunakan metode Otsu | Gambar biner yang bersih memberikan kontras tajam antara latar depan (teks) dan latar belakang. | +| **Contrast Stretch** | Memperluas rentang dinamis | Meningkatkan keterbacaan goresan tipis, terutama pada dokumen lama. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Cara Deskew Dokumen yang Dipindai + +Pemanggilan `deskew` di atas adalah jawaban konkret untuk **how to deskew scanned documents**. Secara internal ia memperkirakan sudut baris teks dominan lewat transformasi Hough dan memutar gambar kembali. Jika dokumen Anda berputar lebih dari 5°, naikkan `max_angle`, namun hati‑hati dengan artefak rotasi berlebih. + +### Binarize Image Using Otsu + +Baris `binarize(method="otsu")` langsung menjawab kueri **binarize image using otsu**. Algoritma Otsu menghitung ambang yang meminimalkan variansi intra‑kelas, sangat cocok untuk dokumen dengan histogram bimodal (teks gelap vs. latar belakang terang). + +## Langkah 4: Lampirkan Pipeline ke Mesin + +Sekarang kami memberi tahu mesin OCR untuk menjalankan setiap gambar masuk melalui pipeline yang baru saja kami bangun. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Mengapa ini penting:* Tanpa pendaftaran, mesin akan memproses pemindaian mentah, mengabaikan semua pembersihan yang baru saja kami konfigurasi. Langkah ini memastikan **how to improve OCR accuracy** dengan menerapkan pra‑pemrosesan yang sama secara konsisten. + +## Langkah 5: Kenali Teks dari Pemindaian Jerman yang Berisik + +Saatnya menggabungkan semuanya. Kami memberi mesin gambar Jerman yang berisik dan membiarkannya melakukan pekerjaan berat. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Jika Anda penasaran dengan performa, Anda dapat mengukur waktu pemanggilan: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Langkah 6: Keluarkan Teks yang Dikenali + +Akhirnya, kami mencetak string yang diekstrak. Ini adalah jawaban langsung untuk **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Output yang Diharapkan + +Dengan asumsi pemindaian contoh berisi kalimat “Die schnelle braune Füchsin springt über den faulen Hund.” Anda akan melihat sesuatu seperti: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Jika output masih berisi karakter kacau, pertimbangkan untuk menyesuaikan kekuatan `denoise` atau meningkatkan `max_angle` untuk deskewing. + +## Kesalahan Umum & Cara Menanganinya + +- **Model bahasa hilang:** Lupa memanggil `set_recognition_language(Language.GERMAN)` sering mengakibatkan hilangnya umlaut. Periksa kembali pemanggilan tersebut. +- **Over‑denoising:** Kekuatan di atas 0.9 dapat menghapus goresan tipis, terutama pada font lama. Gunakan 0.5‑0.7 untuk kebanyakan kasus. +- **Format file tidak tepat:** Beberapa mesin OCR tidak dapat menangani TIFF multi‑halaman. Jika Anda memiliki dokumen multi‑halaman, bagi menjadi file satu‑halaman terlebih dahulu. +- **Urutan pipeline:** Urutan yang ditunjukkan (deskew → denoise → binarize → contrast) sengaja dipilih. Binarisasi sebelum denoising dapat mengunci noise; selalu lakukan denoise terlebih dahulu. + +## Memperluas Pipeline (Apa Selanjutnya?) + +Setelah Anda memiliki baseline yang solid, Anda mungkin ingin: + +- **Menambahkan morphological opening** untuk membersihkan blob kecil (`.morph_open(kernel=3)`). +- **Mengintegrasikan model bahasa** untuk koreksi pasca‑pemrosesan (`ocr_engine.apply_spellcheck()`). +- **Paralelisasi pemrosesan batch** untuk dataset besar menggunakan `concurrent.futures`. + +Semua ini merupakan ekstensi alami yang tetap menjaga inti **bagaimana cara memproses gambar untuk OCR** sambil meningkatkan **how to improve OCR accuracy** lebih jauh. + +## Kesimpulan + +Kami baru saja membahas **bagaimana cara memproses gambar untuk OCR** dari awal hingga akhir: buat mesin, atur bahasa Jerman, bangun pipeline yang **binarize image using Otsu**, **how to deskew scanned documents**, dan akhirnya **extract text from german image** dengan kepercayaan lebih tinggi. Dengan mengikuti enam langkah di atas Anda akan melihat lonjakan signifikan dalam kualitas pengenalan—tidak ada lagi koreksi manual yang tak berujung. + +Cobalah skrip ini dengan pemindaian Anda sendiri, bereksperimen dengan parameter, dan biarkan hasilnya berbicara. Ada pertanyaan tentang tweak pra‑pemrosesan tertentu? Tinggalkan komentar, dan kami akan menyelami lebih dalam bersama. + +Selamat coding, semoga OCR Anda selalu akurat! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Cara Mengatur Nilai Ambang pada Pengenalan Gambar OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Cara OCR Gambar – Lakukan OCR pada Gambar dalam Pengenalan Gambar OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..7e5d030ee --- /dev/null +++ b/ocr/indonesian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-06-06 +description: OCR gambar PNG dengan Python – pelajari cara mengekstrak teks dari gambar, + jalankan contoh OCR Python, dan bahkan baca teks bahasa Yunani kuno dengan mudah. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: id +og_description: OCR gambar PNG di Python dijelaskan. Panduan ini menunjukkan cara + mengekstrak teks dari gambar, menjalankan contoh OCR Python, dan membaca bahasa + Yunani kuno dengan mudah. +og_title: OCR Gambar PNG di Python – Tutorial Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Gambar PNG di Python – Panduan Lengkap Langkah demi Langkah +url: /id/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image di Python – Panduan Langkah‑demi‑Langkah Lengkap + +Pernah bertanya-tanya bagaimana cara **OCR PNG image** langsung dari skrip Python? Mungkin Anda memiliki folder penuh naskah kuno yang dipindai dan Anda perlu **extract text from image** tanpa harus mengetik semuanya secara manual. Kabar baiknya, Anda tidak memerlukan gelar PhD dalam computer vision—hanya beberapa baris kode dan pustaka yang tepat, dan Anda akan membaca bahasa Yunani kuno dalam hitungan detik. + +Dalam tutorial ini kami akan membahas **python OCR example** yang mengenali teks dari PNG, mengatur bahasa ke Greek polytonic, dan mencetak hasilnya. Pada akhir tutorial Anda akan tahu persis cara **recognize image text**, menangani jebakan umum, dan menyesuaikan skrip untuk bahasa atau format gambar lain. + +## Apa yang Akan Anda Pelajari + +- Instal dan konfigurasikan pustaka OCR Python (pytesseract + Tesseract OCR) +- Buat instance mesin OCR dan muat file PNG +- Atur bahasa pengenalan ke Greek polytonic sehingga Anda dapat **read ancient greek** +- Keluarkan teks yang dikenali dan selesaikan masalah umum +- Perluas skrip untuk memproses batch‑multiple PNG atau beralih ke bahasa lain + +### Prasyarat + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | Sintaks modern dan petunjuk tipe | +| `pytesseract` package | Pembungkus tipis di sekitar mesin Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Mesin sebenarnya yang melakukan pekerjaan berat | +| Greek language data (`grc.traineddata`) | Diperlukan untuk **read ancient greek** dengan benar | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Target kami untuk demo **ocr png image** | + +Anda dapat menginstal sisi Python dengan: + +```bash +pip install pytesseract Pillow +``` + +Dan di Ubuntu/macOS Anda akan menambahkan mesin itu sendiri: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Jangan lupa mengunduh data terlatih Greek polytonic: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Path mungkin berbeda; sesuaikan `TESSDATA_PREFIX` jika diperlukan.)* + +--- + +## OCR PNG Image: Buat Instance Mesin + +Hal pertama yang kita butuhkan adalah objek yang berkomunikasi dengan Tesseract. Pada `pytesseract` mesin diakses melalui fungsi tingkat modul, tetapi demi kejelasan kami akan membungkusnya dalam kelas kecil. Ini mencerminkan konsep “engine” yang Anda lihat pada cuplikan asli. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Mengapa membungkusnya?** +- Menjaga API publik tetap identik dengan cuplikan yang Anda mulai, sehingga migrasi menjadi mudah. +- Memungkinkan kami menambahkan logging atau penanganan error nanti tanpa mengubah alur utama. +- Menunjukkan praktik OOP yang baik—sesuatu yang dihargai oleh pengembang senior. + +--- + +## Ekstrak Teks dari Gambar: Atur Bahasa ke Greek Polytonic + +Sekarang kita memiliki mesin, kita perlu memberi tahu bahasa apa yang diharapkan. Greek polytonic menggunakan diakritik yang tidak tercakup dalam data “greek” standar, jadi kami mengarahkan Tesseract ke file terlatih `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Jika Anda ingin **extract text from image** dalam bahasa lain, cukup ganti `"grc"` dengan `"eng"` untuk Bahasa Inggris, `"fra"` untuk Bahasa Prancis, dll. Baris yang sama berfungsi untuk bahasa apa pun yang telah Anda instal. + +## Kenali Teks Gambar: Jalankan OCR pada PNG + +Dengan bahasa yang sudah diatur, kami memasukkan PNG ke dalam mesin. Contoh asli menggunakan path yang di‑hard‑code; kami akan membuatnya sedikit lebih fleksibel dengan menggunakan objek `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tips & Kasus Tepi** + +- **File not found** – bungkus pemanggilan dalam `try/except FileNotFoundError` untuk memberikan pesan yang ramah. +- **Low‑resolution PNG** – pertimbangkan pra‑pemrosesan (mis., mengubah ukuran, binarisasi) dengan Pillow sebelum OCR. +- **Non‑Greek text** – Tesseract tetap akan mencoba mendekode, tetapi akurasi turun drastis. Selalu cocokkan bahasanya. + +## Keluarkan Teks yang Dikenali + +Akhirnya, kami mencetak hasilnya. Dalam proyek nyata Anda mungkin menulis ke basis data, CSV, atau bahkan mengirimnya ke pipeline terjemahan. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Saat Anda menjalankan skrip terhadap pemindaian bersih dari sebuah prasasti Yunani kuno, Anda akan melihat sesuatu seperti: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Jika output terlihat berantakan, periksa kembali bahwa file **greek.traineddata** berada di folder yang tepat dan PNG tidak terlalu berisik. + +--- + +## Contoh Kerja Penuh (Semua Langkah dalam Satu Skrip) + +Berikut adalah program lengkap yang siap dijalankan. Simpan sebagai `ocr_greek.py` dan jalankan `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Output yang Diharapkan** (dipotong untuk singkat): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Jika Anda melihat karakter Yunani yang tepat, selamat—Anda telah berhasil melakukan operasi **ocr png image** di Python! + +--- + +## Pertanyaan Umum & Tips Pro + +### Bagaimana cara meningkatkan akurasi pada PNG yang berisik? + +- Ubah gambar menjadi skala abu‑abu: `img = img.convert('L')` +- Terapkan ambang biner: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Perbesar dengan `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Langkah‑langkah ini sering mengubah mimpi buruk **recognize image text** menjadi hasil yang bersih. + +### Bisakah saya memproses seluruh folder PNG? + +Tentu saja. Bungkus pemanggilan `recognize_image` dalam loop `for` pada `Path.glob("*.png")`. Simpan setiap hasil dalam kamus atau tulis ke CSV untuk analisis selanjutnya. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Bagaimana jika saya hanya perlu mengekstrak angka? + +Berikan string **config** khusus ke `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Dengan cara itu Anda dapat **extract text from image** file yang berisi tabel, nomor seri, atau timestamp. + +### Apakah ada cara untuk mendapatkan skor kepercayaan? + +Ya—gunakan `pytesseract.image_to_data` yang mengembalikan TSV dengan kepercayaan per kata. Anda dapat menyaring token dengan kepercayaan rendah sebelum menyusun string akhir. + +--- + +## Memperluas Tutorial + +Sekarang Anda telah menguasai dasar‑dasarnya, pertimbangkan untuk menjelajahi topik terkait berikut: + +- **Batch OCR with multiprocessing** – mempercepat korpora besar PNG. +- **Hybrid OCR + NLP pipelines** – secara otomatis menerjemahkan Greek kuno yang diekstrak ke dalam Bahasa Inggris modern. +- **Alternative engines** – coba `easyocr` atau metode berbasis `opencv` untuk kasus penggunaan khusus. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, atau AWS Textract untuk skala tanpa server. + +Masing‑masing ini dibangun di atas **python ocr example** inti yang baru saja kami bahas, sehingga Anda akan merasa nyaman menyelam lebih dalam. + +--- + +## Kesimpulan + +Kami telah mengambil cuplikan sederhana dan mengubahnya menjadi alur kerja **ocr png image** yang kuat di Python. Dengan membuat `OcrEngine`, mengatur bahasa ke Greek polytonic, memasukkan PNG, dan mencetak hasilnya, Anda kini tahu cara **extract text from image** file, **recognize image text**, dan bahkan **read ancient greek**. + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang dibangun di atas teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda. + +- [Ekstrak Teks dari Gambar dengan Aspose OCR – Panduan Langkah‑demi‑Langkah](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Cara Mengatur Nilai Ambang pada Pengenalan Gambar OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [mengenali teks gambar dengan Aspose OCR untuk banyak bahasa](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/indonesian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..8e09953fd --- /dev/null +++ b/ocr/indonesian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-06 +description: Tutorial OCR Python yang menunjukkan cara mengenali teks gambar, melakukan + OCR resolusi tinggi, dan mengekstrak teks Spanyol menggunakan OCR yang dipercepat + GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: id +og_description: Tutorial OCR Python yang memandu Anda melalui pengenalan teks gambar, + OCR resolusi tinggi, dan mengekstrak teks bahasa Spanyol dengan percepatan GPU. +og_title: Tutorial OCR Python – Pengenalan Teks Dipercepat GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Tutorial OCR Python – Mengenali Teks Gambar dengan Akselerasi GPU +url: /id/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial OCR Python – Mengenali Teks Gambar dengan Akselerasi GPU + +Pernah bertanya-tanya bagaimana cara **mengenali teks gambar** dalam skrip Python tanpa menghabiskan berjam-jam mengatur pengaturan? Anda bukan satu-satunya. Dalam **python ocr tutorial** ini kami akan menunjukkan cara yang bersih, end‑to‑end untuk mengekstrak teks Spanyol dari gambar beresolusi tinggi, dan kami akan menambahkan akselerasi GPU sehingga proses berjalan sangat cepat. + +Anggap ini sebagai demo singkat saat istirahat kopi yang dapat Anda kembangkan menjadi pipeline produksi nantinya. Pada akhir panduan ini Anda akan memiliki program yang dapat dijalankan yang melakukan **high resolution OCR**, memanfaatkan GPU yang mendukung CUDA, dan menghasilkan karakter Spanyol yang tepat yang Anda butuhkan. + +## Apa yang Akan Anda Pelajari + +- Cara menginstal dan mengimpor perpustakaan OCR modern yang mendukung akselerasi GPU. +- Cara membuat instance mesin OCR dan mengaturnya untuk **recognize image text** dalam bahasa Spanyol. +- Cara mengaktifkan **gpu accelerated OCR** untuk peningkatan kecepatan besar pada file beresolusi tinggi. +- Cara menangani kasus tepi seperti driver CUDA yang hilang atau fallback ke CPU. +- Tips untuk meningkatkan akurasi ketika Anda perlu **extract spanish text** dari pemindaian yang berisik. + +### Prasyarat + +- Python 3.9+ (kode ini juga berfungsi pada 3.10 dan yang lebih baru). +- GPU yang kompatibel dengan CUDA (opsional tetapi sangat disarankan). +- Pemahaman dasar tentang pip dan lingkungan virtual. + +Jika Anda tidak memiliki salah satu dari ini, tutorial tetap berfungsi—cukup lewati langkah GPU dan perpustakaan akan otomatis fallback ke CPU. + +--- + +## Tutorial OCR Python: Instal Paket yang Diperlukan + +Pertama-tama, kita membutuhkan mesin OCR yang solid. Untuk tutorial ini kami akan menggunakan paket sumber terbuka **`easyocr`**, yang dilengkapi dengan dukungan GPU bawaan ketika perangkat yang kompatibel terdeteksi. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Jika Anda sudah menginstal PyTorch, pastikan versinya cocok dengan versi CUDA Anda (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Versi yang tidak cocok adalah sumber umum kesalahan “GPU not found”. + +--- + +## Langkah 1: Buat Instance Mesin OCR + +Sekarang kita memulai mesin. EasyOCR menyebut kelas utamanya `Reader`. Konstruktor menerima daftar kode bahasa; kita akan memberikan `"es"` untuk bahasa Spanyol. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Mengapa ini penting:* Dengan mendeklarasikan bahasa di awal, mesin hanya memuat bobot jaringan saraf yang diperlukan, yang menghemat memori dan mempercepat inferensi—terutama berguna ketika Anda menangani **high resolution OCR** nanti. + +--- + +## Langkah 2: Siapkan Gambar Beresolusi Tinggi + +Gambar beresolusi tinggi memberikan model lebih banyak piksel untuk diproses, yang biasanya menghasilkan pengenalan karakter yang lebih baik. Mari kita asumsikan Anda memiliki file bernama `high_res_spanish.png` yang berada di folder bernama `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Jika Anda tidak memiliki contoh beresolusi tinggi, Anda dapat mengunduh yang gratis dari Unsplash atau menghasilkan gambar sintetis dengan Pillow. Kuncinya adalah menjaga DPI di atas 300 untuk hasil terbaik. + +--- + +## Langkah 3: Aktifkan Akselerasi GPU (Opsional tetapi Disarankan) + +EasyOCR sudah mencoba menggunakan GPU ketika Anda mengatur `gpu=True`. Namun, merupakan praktik yang baik untuk memverifikasi bahwa perangkat memang sedang digunakan, terutama pada sistem multi‑GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Mengapa memeriksa ini?* Jika skrip secara diam-diam beralih ke CPU, Anda mungkin bertanya-tanya mengapa operasi 5‑detik tiba-tiba memakan 30 detik. Pemeriksaan kecil ini membuat perilaku menjadi transparan dan menjaga pipeline **gpu accelerated OCR** Anda tetap dapat diprediksi. + +--- + +## Langkah 4: Lakukan OCR Beresolusi Tinggi dan Kenali Teks Gambar + +Sekarang bagian yang menyenangkan—memang membaca teks. Metode `readtext` dari EasyOCR mengembalikan daftar tuple yang berisi kotak pembatas, string yang dikenali, dan skor kepercayaan. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Jika Anda membutuhkan string mentah tanpa koordinat, atur `detail=0`. Untuk kebanyakan kasus penggunaan **recognize image text**, default (`detail=1`) memberikan cukup konteks untuk diproses lebih lanjut nanti. + +--- + +## Langkah 5: Ekstrak Teks Spanyol dan Bersihkan Output + +Karena kami meminta EasyOCR untuk bahasa Spanyol, string yang dikembalikan sudah dalam bahasa tersebut. Namun, Anda mungkin ingin menggabungkannya, menghapus spasi, atau menyaring deteksi dengan kepercayaan rendah. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Bagaimana jika kepercayaan rendah?** Anda dapat menurunkan ambang batas (dengan risiko noise) atau melakukan pra‑pemrosesan gambar (meningkatkan kontras, binarisasi, atau meluruskan). Trik tersebut umum saat menangani **high resolution OCR** pada dokumen yang dipindai. + +--- + +## Langkah 6: Menangani Kasus Tepi dan Penyesuaian Kinerja + +Bahkan model yang paling terlatih sekalipun mengalami kesulitan pada beberapa skenario. Berikut beberapa perbaikan cepat yang dapat Anda tempelkan ke dalam skrip. + +### 6.1 Fallback Ketika Tidak Ada GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling Gambar Sangat Besar + +Jika gambar Anda lebih besar dari 4000 × 4000 px, Anda mungkin kehabisan memori GPU. Lakukan down‑sample secara proporsional sambil mempertahankan DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Potongan kode ini menjaga skrip tetap kuat, baik Anda menjalankannya di workstation maupun laptop sederhana. + +--- + +## Contoh Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut skrip lengkap yang dapat Anda salin‑tempel dan jalankan langsung: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Output yang diharapkan (contoh):** + + + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Ekstrak Teks dari Gambar dengan Aspose OCR – Panduan Langkah‑per‑Langkah](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Cara OCR Teks Gambar dengan Bahasa Menggunakan Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Cara Mengenali Persegi Panjang Halaman untuk Pengenalan Teks OCR di Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/indonesian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..3e0472f85 --- /dev/null +++ b/ocr/indonesian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-06 +description: Mengenali teks dari gambar menggunakan mesin OCR Python. Pelajari cara + mengonfigurasi mesin OCR Python dan mengekstrak teks dari gambar dengan pemrosesan + cloud dalam hitungan menit. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: id +og_description: Mengenali teks dari gambar dengan mesin OCR Python. Panduan ini menunjukkan + cara mengonfigurasi mesin OCR Python dan mengekstrak teks dari gambar secara efisien. +og_title: Mengenali teks dari gambar dengan Python – Tutorial Pengaturan Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Mengenali Teks dari Gambar di Python – Panduan Lengkap Penyiapan Mesin OCR +url: /id/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# mengenali teks dari gambar dengan Python – Tutorial Pengaturan Lengkap + +Pernah bertanya-tanya bagaimana cara **mengenali teks dari gambar** hanya dengan beberapa baris kode Python? Anda tidak sendirian. Baik Anda sedang membuat pemindai struk, digitalisasi dokumen, atau proyek hobi sederhana, kemampuan untuk mengekstrak teks dari gambar adalah keterampilan yang cepat memberi hasil. + +Dalam tutorial ini kami akan membimbing Anda melalui seluruh proses—dimulai dari pengaturan **konfigurasi mesin OCR python**, melanjutkan ke otentikasi cloud, dan akhirnya menunjukkan cara **mengekstrak teks dari gambar** dengan hasil yang dapat diandalkan. Tidak ada sulap, hanya langkah‑langkah jelas yang dapat Anda salin‑tempel dan jalankan hari ini. + +## What You’ll Learn + +- Cara menginstal dan mengimpor pustaka OCR yang diperlukan. +- Perintah tepat untuk **konfigurasi mesin OCR python** untuk pemrosesan cloud. +- Skrip lengkap yang dapat dijalankan yang **mengenali teks dari gambar** dan mencetak output. +- Tips menangani jebakan umum seperti kunci API yang hilang atau format gambar yang tidak didukung. +- Ide tingkat lanjut seperti pemrosesan batch dan fallback lokal. + +### Prerequisites + +- Python 3.8+ terinstal di mesin Anda. +- Koneksi internet (contoh menggunakan layanan OCR berbasis cloud). +- Kunci API yang valid dari penyedia OCR (Anda akan melihat di mana memasangnya). + +Jika Anda sudah memiliki semua itu, mari kita mulai—tanpa basa‑basi, hanya panduan praktis yang berfungsi. + +--- + +## Step 1: Install the OCR Library and Import It + +Sebelum Anda dapat **konfigurasi mesin OCR python**, Anda memerlukan pustaka yang berkomunikasi dengan layanan cloud. Pada contoh kami akan menggunakan paket fiktif namun representatif bernama `ocrcloud`. Ganti dengan paket nyata yang Anda gunakan (misalnya `easyocr`, `google-cloud-vision`, dll). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Why this matters:** Mengimpor kelas memberi Anda akses ke metode seperti `use_cloud()` dan `set_api_key()`. Tanpa impor, sisa skrip akan menghasilkan `NameError`. + +*Pro tip:* Tetapkan versi di `requirements.txt` Anda (`ocrcloud==2.1.0`) untuk menghindari perubahan yang merusak secara tak terduga di kemudian hari. + +--- + +## Step 2: Create and **configure OCR engine python** for Cloud Mode + +Sekarang kita benar‑benarnya **konfigurasi mesin OCR python**. Mesin dimulai dalam mode lokal secara default; beralih ke mode cloud memungkinkan Anda memindahkan analisis gambar yang berat ke server yang kuat. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explanation:** +- `OcrEngine()` membuat objek mesin baru—anggaplah sebagai kanvas kosong Anda. +- `use_cloud(True)` mengaktifkan saklar, memberi tahu mesin untuk mengirim gambar melalui HTTPS alih‑alih memprosesnya secara lokal. Ini penting untuk hasil akurasi tinggi pada font kompleks atau foto beresolusi rendah. + +--- + +## Step 3: Authenticate with Your Cloud API Key + +Sebagian besar layanan OCR cloud memerlukan kunci API. Langkah ini menunjukkan cara menyuntikkan kredensial dengan aman. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Security note:** Jangan pernah menuliskan kunci secara langsung di repositori publik. Pada produksi Anda akan mengambilnya dari variabel lingkungan: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Step 4: **recognize text from image** – Send a Remote Image for Processing + +Dengan mesin yang sudah dikonfigurasi, kita akhirnya dapat **mengenali teks dari gambar**. Metode `recognize_image()` menerima jalur atau URL dan mengembalikan objek yang berisi teks yang diekstrak. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**What happens under the hood?** Byte gambar diunggah ke endpoint penyedia, diproses oleh model deep‑learning, dan hasil teks biasa dikirim kembali. Jika gambar berukuran besar, layanan dapat secara otomatis menurunkan resolusi untuk mempercepat proses. + +--- + +## Step 5: Output the **extract text from image** Result + +Setelah layanan OCR menyelesaikan tugasnya, kami cukup mencetak teks tersebut. Pada aplikasi nyata Anda mungkin menyimpannya ke basis data atau meneruskannya ke fungsi lain. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Expected output:** (example) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Jika output terlihat berantakan, periksa kembali bahwa gambar jelas dan Anda telah memilih model bahasa yang tepat (banyak layanan memungkinkan Anda menentukan `engine.set_language("en")`). + +--- + +## Handling Edge Cases & Common Pitfalls + +### 1. Missing or Invalid API Key +Jika Anda melihat kesalahan otentikasi, pastikan: +- Kunci aktif dan belum kedaluwarsa. +- Kunci dibaca dari lingkungan dengan benar. +- Jaringan Anda mengizinkan lalu lintas HTTPS keluar. + +### 2. Unsupported Image Formats +Sebagian besar API OCR menerima JPEG, PNG, dan PDF. Mencoba BMP atau TIFF dapat memicu respons “format tidak didukung”. Konversi dengan Pillow jika diperlukan: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Rate Limits +Layanan cloud sering membatasi jumlah permintaan per menit. Jika Anda mencapai batas, terapkan back‑off eksponensial: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Fallback to Local OCR +Jika cloud sedang tidak tersedia, Anda dapat beralih kembali: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Memiliki fallback menjaga aplikasi Anda tetap tahan banting. + +--- + +## Full Working Example + +Menggabungkan semuanya, berikut skrip yang dapat Anda jalankan sekarang (cukup ganti nilai placeholder). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Run it:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Anda harus melihat teks yang diekstrak dicetak ke konsol, mengonfirmasi bahwa Anda telah berhasil **mengenali teks dari gambar** dan **mengekstrak teks dari gambar** menggunakan alur kerja **konfigurasi mesin OCR python** yang tepat. + +--- + +## Conclusion + +Kami baru saja melewati proses lengkap end‑to‑end yang memungkinkan Anda **mengenali teks dari gambar** dengan Python, mulai dari menginstal pustaka hingga mengautentikasi layanan cloud dan akhirnya **mengekstrak teks dari gambar** dengan satu panggilan fungsi. Dengan **konfigurasi mesin OCR python** yang tepat, Anda memperoleh fleksibilitas (cloud vs. lokal) dan keandalan (penanganan error yang tepat). + +Apa selanjutnya? Coba proses batch folder struk, tambahkan deteksi bahasa, atau bereksperimen dengan PDF sebagai input. Langit adalah batasnya setelah Anda menguasai dasar‑dasarnya. + +Selamat coding, dan jangan ragu mengajukan pertanyaan di kolom komentar—tidak ada yang mengalahkan belajar bersama! + +## What Should You Learn Next? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Ekstrak Teks dari Gambar dengan Aspose OCR – Panduan Langkah‑per‑Langkah](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Ekstrak Teks dari Gambar – Mengenali Garis dengan Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Cara Mengekstrak Teks dari Gambar dengan Menyiapkan Persegi Panjang di OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..cc9761f42 --- /dev/null +++ b/ocr/indonesian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-06-06 +description: Jalankan OCR pada gambar menggunakan Python dan lihat skor kepercayaan. + Pelajari cara memfilter kata dengan kepercayaan rendah, mengatur ambang batas, dan + menangani kasus tepi. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: id +og_description: Jalankan OCR pada gambar di Python, periksa tingkat kepercayaan, dan + saring kata‑kata dengan kepercayaan rendah. Tutorial ini memandu Anda melalui contoh + lengkap yang dapat dijalankan. +og_title: Jalankan OCR pada Gambar dengan Python – Panduan Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Jalankan OCR pada Gambar dengan Python – Panduan Lengkap Langkah demi Langkah +url: /id/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jalankan OCR pada Gambar dengan Python – Panduan Lengkap Langkah‑per‑Langkah + +Pernahkah Anda **menjalankan OCR pada gambar** tetapi tidak yakin bagaimana cara mendapatkan teks yang dapat diandalkan darinya? Anda tidak sendirian—banyak pengembang mengalami hal yang sama ketika kata‑kata yang diekstrak tampak tidak stabil dan nilai skor kepercayaan menjadi misteri. + +Dalam panduan ini kami akan langsung menyajikan solusi yang dapat bekerja: Anda akan melihat cara **menjalankan OCR pada gambar**, membaca nilai kepercayaan keseluruhan, dan mengekstrak kata‑kata dengan kepercayaan rendah yang mungkin memerlukan peninjauan manual. Pada akhir tutorial Anda akan memiliki skrip yang dapat digunakan kembali, memahami mengapa setiap baris penting, dan mengetahui cara menyesuaikan ambang kepercayaan untuk proyek Anda sendiri. + +## Apa yang Dibahas dalam Tutorial Ini + +Kami akan menelusuri seluruh alur kerja—dari memuat gambar hingga mencetak laporan rapi tentang kata‑kata yang berada di bawah ambang kepercayaan 80 %. Sepanjang perjalanan kami akan membahas: + +* Memilih mesin OCR yang solid (kami akan menggunakan **EasyOCR**, sebuah perpustakaan OCR Python yang populer) +* Menafsirkan atribut `confidence` yang dikembalikan oleh setiap hasil OCR +* Menyaring kata‑kata dengan **ambang kepercayaan OCR** khusus +* Memperluas skrip untuk pemrosesan batch atau mesin alternatif seperti **pytesseract** + +Tidak diperlukan pengalaman OCR sebelumnya, cukup familiar dengan Python dan lingkungan kerja (Python 3.9+ disarankan). + +Siap mengubah tangkapan layar yang buram menjadi teks bersih yang dapat dicari? Mari kita mulai. + +--- + +## ## Cara Menjalankan OCR pada Gambar dengan Python + +Inti tutorial adalah potongan kode tiga langkah yang mencerminkan kode yang sudah Anda lihat. Di bawah ini kami akan memecah setiap baris, menjelaskan alasannya, dan kemudian memberikan skrip lengkap yang siap disalin‑tempel. + +### Langkah 1: Instal dan Impor Mesin OCR + +Pertama, pastikan perpustakaan OCR tersedia. **EasyOCR** bekerja langsung untuk banyak bahasa dan memberikan nilai kepercayaan per kata. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Mengapa EasyOCR?* Ia menyertakan model deep‑learning yang telah dilatih pada dataset beragam, sehingga Anda biasanya mendapatkan nilai kepercayaan lebih tinggi dibandingkan mesin Tesseract yang lebih lama, terutama pada gambar dengan kualitas campuran. + +> **Pro tip:** Jika Anda berada di lingkungan terbatas (misalnya, kontainer Docker kecil), `pytesseract` mungkin lebih ringan, tetapi Anda akan kehilangan sebagian akurasi modern yang diberikan EasyOCR. + +### Langkah 2: Jalankan OCR pada Gambar + +Sekarang kita benar‑benarnya **menjalankan OCR pada gambar**. Metode `recognize_image` dari contoh asli digantikan dengan pemanggilan `readtext` milik EasyOCR, yang mengembalikan daftar tuple `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Setiap entri dalam `ocr_results` terlihat seperti: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Elemen ketiga (`0.92` pada contoh) adalah nilai kepercayaan yang berkisar antara 0 hingga 1. + +### Langkah 3: Ringkas Kepercayaan Keseluruhan + +Berbeda dengan potongan kode sebelumnya yang mencetak satu atribut `confidence`, EasyOCR memberikan kepercayaan per kata. Untuk mendapatkan gambaran keseluruhan, kami akan menghitung rata‑rata nilai tersebut: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Mengapa rata‑rata?* Ini memberi Anda cek kesehatan cepat—jika kepercayaan keseluruhan di bawah, misalnya, 70 %, Anda mungkin perlu meningkatkan kualitas gambar (pencahayaan lebih baik, pra‑pemrosesan, dll.). + +### Langkah 4: Daftar Kata‑kata dengan Kepercayaan Rendah + +Berikutnya adalah bagian yang secara langsung menjawab permintaan “daftar kata yang kepercayaan nya di bawah ambang yang diinginkan”. Kami akan menetapkan **ambang kepercayaan OCR** sebesar 0.80 (80 %) secara default, tetapi Anda dapat menyesuaikannya. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Loop ini mencetak setiap kata yang tidak lolos, bersamaan dengan persentase kepercayaannya. Ini adalah analog tepat dari loop asli `for recognized_word in recognition_result.words`, tetapi kini bekerja dengan format keluaran EasyOCR. + +--- + +## ## Memahami Skor Kepercayaan OCR + +Kepercayaan bukanlah angka ajaib; itu adalah perkiraan model tentang seberapa yakin ia terhadap transkripsi tertentu. Berikut beberapa hal yang perlu diingat: + +| Situasi | Kepercayaan Umum | Apa yang Harus Dilakukan | +|-----------|-------------------|------------| +| Pemindaian jelas beresolusi tinggi | 0.95 – 1.00 | Tidak perlu pekerjaan tambahan | +| Sedikit blur atau pencahayaan tidak merata | 0.80 – 0.94 | Pertimbangkan pra‑pemrosesan ringan (peningkatan kontras) | +| Noise berat, teks miring | < 0.70 | Terapkan pra‑pemrosesan gambar (deskew, denoise) atau beralih ke mesin OCR lain | + +> **Waspada:** Beberapa bahasa (misalnya tulisan tangan kursif) secara alami menghasilkan skor lebih rendah. Sesuaikan ambang sesuai kebutuhan. + +### Kasus Pinggir & Variasi + +1. **Pemrosesan Batch** – Jika Anda perlu **menjalankan OCR pada gambar** secara massal, bungkus logika di atas dalam loop yang mengiterasi sebuah direktori. +2. **Banyak Bahasa** – Berikan daftar seperti `['en', 'fr']` ke `easyocr.Reader` dan mesin akan mendeteksi keduanya. +3. **Mesin Alternatif** – Ingin mencoba **pytesseract**? Ganti blok pembaca dengan: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Anda kemudian harus mengagregasi kepercayaan per‑karakter menjadi nilai per‑kata—sedikit lebih rumit tetapi memungkinkan. + +4. **Trik Pra‑pemrosesan** – Menerapkan filter OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) dapat meningkatkan kepercayaan pada pemindaian yang berisik. + +--- + +## ## Skrip Lengkap Siap‑Jalankan + +Berikut adalah file Python lengkap yang dapat Anda letakkan dalam proyek. Simpan sebagai `ocr_report.py` dan jalankan dengan `python ocr_report.py`. Pastikan jalur gambar mengarah ke berkas yang nyata. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Output yang diharapkan** (angka Anda akan berbeda): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Jika setiap kata melewati ambang 80 % Anda akan melihat pesan ramah “All words meet the confidence threshold.” sebagai gantinya. + +--- + +## ## Pertanyaan yang Sering Diajukan (FAQ) + +**T: Apakah ini bekerja dengan PDF?** +J: Tidak secara langsung. Konversi setiap halaman PDF menjadi gambar terlebih dahulu (misalnya dengan `pdf2image`) lalu masukkan PNG/JPEG ke dalam skrip. + +**T: Nilai kepercayaan saya semua rendah—apa yang bisa saya lakukan?** +J: Coba pra‑pemrosesan gambar: tingkatkan kontras, hilangkan noise latar, atau putar gambar ke posisi horizontal. EasyOCR juga menerima parameter `contrast_ths` yang dapat Anda sesuaikan. + +**T: Bisakah saya mengekspor hasil ke CSV?** +J: Tentu. Setelah loop kata‑kata berkepercayaan rendah, tulis `ocr_results` ke `csv.DictWriter` dimana setiap baris berisi `text`, `confidence`, dan koordinat bounding‑box. + +**T: Apakah ada versi yang dipercepat GPU?** +J: EasyOCR secara otomatis menggunakan CUDA jika GPU yang kompatibel dan PyTorch terpasang. Verifikasi dengan `torch.cuda.is_available()` sebelum menjalankan skrip. + +--- + +## Kesimpulan + +Kami baru saja **menjalankan OCR pada gambar** menggunakan Python, memeriksa kepercayaan keseluruhan, dan memisahkan kata‑kata berkepercayaan rendah yang memerlukan peninjauan manual. + +## Apa yang Harus Anda Pelajari Selanjutnya? + + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑per‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Menetapkan Nilai Ambang pada Pengakuan Gambar OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Cara Menggunakan Aspose OCR untuk Hasil JSON dalam Pengakuan Gambar](/ocr/english/net/text-recognition/get-result-as-json/) +- [Ekstrak Teks dari Gambar – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/italian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..f4aec43b0 --- /dev/null +++ b/ocr/italian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Estrai testo da un'immagine con OCR in Python in pochi minuti. Scopri + l'OCR multilingue per immagini, il rilevamento automatico della lingua e come estrarre + il testo OCR con precisione. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: it +og_description: Estrai testo da immagini con OCR in Python rapidamente. Scopri l'OCR + multilingue per immagini, il rilevamento automatico della lingua e come estrarre + il testo OCR passo dopo passo. +og_title: Estrai il testo da un'immagine usando OCR Python – Guida completa +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Estrai il testo da un'immagine usando OCR Python – Guida completa +url: /it/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Estrai testo da immagine usando Python OCR – Guida completa + +Ti è mai capitato di dover **estrarre testo da un'immagine** ma non eri sicuro quale libreria potesse gestire più lingue automaticamente? Non sei solo: gli sviluppatori chiedono continuamente *come estrarre testo OCR* quando si tratta di documenti internazionali, ricevute o volantini scansionati. In questo tutorial percorreremo un esempio pratico in Python che non solo estrae testo da un'immagine ma **rileva anche la lingua** al volo, rendendo l'OCR multilingue un gioco da ragazzi. + +Copriamo tutto, dall'installazione del pacchetto OCR all'abilitazione del **rilevamento automatico della lingua OCR**, all'esecuzione del motore su un'immagine di esempio e, infine, alla stampa sia della lingua rilevata sia della stringa estratta. Alla fine avrai uno snippet riutilizzabile da inserire in qualsiasi progetto, sia che tu stia costruendo una pipeline di traduzione o un servizio di ingestione dati. + +## Estrarre testo da immagine – Configurare l'ambiente + +Prima di immergerci nel codice, assicurati che la tua postazione soddisfi questi requisiti minimi: + +- Python 3.8 o successivo (la libreria utilizza type hints che le versioni più vecchie ignorano) +- `pip` per la gestione dei pacchetti +- Un file immagine che contenga testo in almeno due lingue diverse (ad es., inglese + spagnolo) + +Avrai inoltre bisogno della libreria OCR che alimenta questa demo. Per il presente tutorial useremo il pacchetto fittizio `ocr`, che rispecchia strumenti reali popolari come Tesseract o EasyOCR ma offre un'API Python pulita. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Suggerimento:** Se incontri errori di permessi, anteponi il comando con `python -m` o usa un ambiente virtuale—mantiene ordinati i tuoi site‑packages globali. + +## Crea un'istanza del motore OCR + +Ora che la libreria è pronta, il primo passo logico è **creare un'istanza del motore OCR**. Pensa al motore come a uno scanner intelligente che puoi configurare prima di alimentarlo con le immagini. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Perché istanziamo il motore separatamente invece di chiamare un metodo statico? L'oggetto motore conserva lo stato di configurazione (come le preferenze di lingua) che potresti voler riutilizzare su molte immagini, risparmiandoti il sovraccarico di reinizializzarlo ogni volta. + +## Abilita il rilevamento automatico della lingua OCR + +La maggior parte degli strumenti OCR richiede di specificare un codice lingua—`eng` per l'inglese, `spa` per lo spagnolo, ecc. Indovinare manualmente la lingua vanifica lo scopo di un flusso di lavoro **OCR multilingue per immagini**. Fortunatamente, il pacchetto `ocr` offre una modalità *auto detect language OCR* che analizza l'immagine e seleziona il modello linguistico più adatto in background. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Abilitare **detect language OCR** in questo modo significa che non dovrai mantenere una lunga lista di codici lingua. Il motore cercherà di corrispondere allo script rilevato—Latino, Cirillico, Han, ecc.—e caricherà automaticamente il modello appropriato. + +## Esegui OCR multilingue su immagine + +Con il motore pronto, è il momento di **estrarre testo da un'immagine**. Il metodo `recognize_image` accetta un percorso file e restituisce un oggetto risultato contenente sia il testo grezzo sia la lingua rilevata. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Se ti chiedi *come estrarre testo OCR* da un PDF invece che da un PNG, lo stesso motore offre `recognize_pdf`—basta cambiare il nome del metodo. La logica di rilevamento sottostante rimane identica, così benefici della stessa funzionalità **auto detect language OCR**. + +## Visualizza lingua rilevata e testo estratto + +Infine, mostriamo ciò che il motore ha scoperto. L'oggetto risultato espone `detected_language` (un tag BCP‑47 come `en` o `es`) e `text`, che contiene l'output OCR grezzo. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Eseguendo lo script sulla nostra immagine di esempio dovrebbe produrre qualcosa di simile a: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Nota come il motore abbia identificato correttamente l'inglese come lingua principale, ma abbia comunque catturato la riga in spagnolo—esattamente ciò che ti aspetti da una soluzione **OCR multilingue per immagini** robusta. + +### Cosa succede se il rilevamento fallisce? + +A volte il motore OCR può ricadere su una lingua predefinita (di solito l'inglese) se l'immagine è sfocata o lo script è troppo esotico. In questi casi puoi forzare una lista di lingue: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Ma ricorda, forzare le lingue vanifica la comodità del **auto detect language OCR**, quindi usalo solo quando hai un sottoinsieme di lingue noto. + +## Problemi comuni e come estrarre testo OCR in modo affidabile + +Anche con l'auto‑rilevamento, alcuni intoppi possono ostacolarti: + +1. **Immagini a bassa risoluzione** – L'accuratezza OCR diminuisce drasticamente sotto i 150 dpi. Upscale o richiedi una scansione a risoluzione più alta. +2. **Rumore e artefatti di compressione** – Applica un semplice filtro di soglia (`opencv` o `Pillow`) prima di fornire l'immagine al motore. +3. **Script misti in una pagina** – Alcuni motori hanno difficoltà con caratteri latini e CJK simultanei. Dividi la pagina in regioni ed esegui riconoscimenti separati se necessario. + +Affrontare questi problemi migliora notevolmente la qualità del processo di **estrazione di testo da immagine**, specialmente quando si trattano documenti reali e multilingue. + +## Esempio completo funzionante + +Di seguito trovi lo script completo, pronto da eseguire, che combina tutti i passaggi discussi. Salvalo come `multilingual_ocr.py` ed eseguilo dalla riga di comando. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Output previsto** (supponendo che l'immagine di esempio contenga testo in inglese e spagnolo): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Sentiti libero di sostituire `multilang_page.png` con qualsiasi immagine che contenga testo in altre lingue—grazie al **auto detect language OCR**, lo script ti fornirà comunque un tag lingua sensato e il testo corrispondente. + +![Esempio di estrazione di testo da immagine](https://example.com/ocr-sample.png "Estrai testo da immagine") + +## Conclusione + +Ora sai esattamente **come estrarre testo OCR** da un'immagine, come abilitare **auto detect language OCR** e come gestire scenari **OCR multilingue per immagini** con un codice minimo. Creando un'istanza del motore OCR, attivando il rilevamento automatico della lingua e chiamando `recognize_image`, puoi estrarre in modo affidabile sia l'identificatore della lingua sia il testo grezzo. + +Cosa fare dopo? Prova a inviare le stringhe estratte a un'API di traduzione, archiviarle in un database ricercabile o combinare più pagine in un unico report PDF. Puoi anche sperimentare con diversi back‑end OCR (Tesseract, EasyOCR, Google Vision) mantenendo lo stesso flusso di lavoro ad alto livello—grazie all'interfaccia coerente **detect language OCR**. + +Se incontri qualche stranezza, rivedi la sezione “Problemi comuni” o modifica i passaggi di pre‑elaborazione dell'immagine. Buon coding, e che il tuo prossimo progetto sia pieno di testo correttamente rilevato e perfettamente estratto! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/italian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..39c93e462 --- /dev/null +++ b/ocr/italian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Estrai il testo da PDF di immagini usando OCR in Python. Scopri come + convertire rapidamente documenti scansionati in testo con riconoscimento batch asincrono. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: it +og_description: Estrai il testo da immagini PDF con Python. Questa guida passo passo + mostra come convertire i documenti scansionati in testo usando OCR asincrono. +og_title: Estrai testo da PDF di immagini – Tutorial OCR in Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Estrai testo da PDF di immagini – Guida Python per convertire documenti scansionati + in testo +url: /it/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Estrai Testo da PDF Immagini – Guida Python per Convertire Documenti Scansionati in Testo + +Hai mai avuto bisogno di **estrarre testo da PDF immagini** senza passare ore a riscrivere? In questa guida ti mostreremo come **convertire documenti scansionati in testo** usando un semplice flusso di lavoro OCR asincrono in Python. + +Se ti sei mai trovato davanti a una pila di PDF scansionati e hai pensato: “Deve esserci un modo più veloce”, sei nel posto giusto. Esamineremo ogni riga di codice, spiegheremo perché ogni pezzo è importante e tratteremo anche alcuni casi limite che potresti incontrare. + +## Cosa Imparerai + +- Come avviare un motore OCR e impostare la lingua di riconoscimento. +- La meccanica di alimentare un elenco misto di PNG e PDF in un riconoscitore batch. +- Eseguire il lavoro OCR in modo asincrono così la tua app rimane reattiva. +- Recuperare i risultati, abbinarli ai file di origine e stampare un output pulito. + +**Prerequisiti**: Python 3.8+, una conoscenza di base di `asyncio` o `concurrent.futures`, e una libreria OCR che esponga una classe `OcrEngine` simile a quella dell’esempio (ad es., Aspose.OCR, wrapper Tesseract, o un wrapper personalizzato). Nessuna configurazione complessa—basta installare la libreria e sei pronto a partire. + +![estrai testo da PDF immagini](https://example.com/placeholder.png "Screenshot dell'output OCR – estrai testo da PDF immagini") + +## Estrai Testo da PDF Immagini – Configurare il Motore OCR + +La prima cosa di cui hai bisogno è un'istanza del motore OCR configurata per la lingua dei tuoi documenti. Nel nostro caso useremo il francese, ma puoi sostituirla con qualsiasi lingua supportata. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Perché è importante**: impostare la lingua in anticipo migliora drasticamente la precisione. Il motore utilizza dizionari e modelli di caratteri specifici per lingua; fornire la lingua sbagliata è una causa comune di output confuso. + +## Preparare l'Elenco dei File – Immagini e PDF Insieme + +Il nostro riconoscitore batch può gestire sia immagini raster (`.png`, `.jpg`) sia contenitori PDF. Basta fornire una semplice lista Python di percorsi file. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Suggerimento**: mantieni la lista piatta; il motore estrarrà internamente ogni pagina PDF in immagini prima del riconoscimento. Se hai migliaia di file, considera di suddividere la lista in batch più piccoli per evitare picchi di memoria. + +## Avviare il Riconoscimento Batch Asincrono + +Invece di bloccare il thread principale, avviamo il lavoro OCR in background. Il metodo restituisce un `Future` che conterrà eventualmente una lista di oggetti `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Come funziona**: sotto il cofano il motore avvia un pool di thread (o un task asincrono, a seconda dell'implementazione). Questo ti permette di continuare a fare altre cose—come aggiornare un’interfaccia, scaricare altri file o registrare l’avanzamento—mentre il lavoro pesante avviene altrove. + +## Fai Qualcosa di Utile Mentre l'OCR è in Esecuzione + +Un errore comune è stare inattivi e interrogare il future in un ciclo stretto. Invece, puoi eseguire qualsiasi lavoro non correlato. Per dimostrazione, stamperemo semplicemente una riga di stato. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Raccogliere i Risultati Una Volta che il Future è Completo + +Quando sei pronto a raccogliere l'output OCR, usa `as_completed` da `concurrent.futures`. Questo schema funziona sia con un future sia con molti. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Ciò che vedrai**: ogni percorso file seguito dalla rappresentazione di testo semplice estratta. Per i PDF, `result.text` contiene il testo concatenato di tutte le pagine. + +### Output Atteso (esempio) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Se noti caratteri mancanti, verifica che la lingua impostata corrisponda a quella del documento e considera di pre‑processare le immagini (raddrizzare, aumentare il contrasto) prima di passarle al motore. + +## Gestire i Casi Limite e le Trappole Comuni + +| Situazione | Cosa Fare | +|------------|-----------| +| **Lingue miste** | Esegui prima una fase di rilevamento della lingua, poi istanzia motori separati per ciascuna lingua. | +| **PDF di grandi dimensioni (> 100 MB)** | Dividi il PDF in pagine individuali su disco (ad es., usando `PyPDF2`) e alimentale come voci separate. | +| **Script non latini** | Assicurati che la libreria OCR includa il pacchetto linguistico necessario; alcune librerie richiedono il download di file dati aggiuntivi. | +| **Collo di bottiglia delle prestazioni** | Aumenta la dimensione del pool di thread (`engine.set_thread_pool_size(8)`) o passa a un backend accelerato da GPU se disponibile. | +| **Testo mancante in immagini a bassa risoluzione** | Pre‑processa con OpenCV: `cv2.resize`, `cv2.threshold` e `cv2.medianBlur` per migliorare la leggibilità. | + +## Esempio Completo Funzionante (Pronto per Copia‑Incolla) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Salva questo file come `extract_text_async.py`, sostituisci `YOUR_DIRECTORY` con il percorso dei tuoi file, installa il pacchetto OCR (`pip install your-ocr-lib`) ed esegui `python extract_text_async.py`. Dovresti vedere l'output console illustrato in precedenza. + +## Prossimi Passi – Oltre l'Estrazione Base + +- **Post‑elaborazione**: rimuovi spazi bianchi extra, normalizza Unicode (`unicodedata.normalize`) o esegui un correttore ortografico per pulire il rumore OCR. +- **Output strutturato**: esporta i risultati in CSV, JSON o direttamente in un database per ricerche successive. +- **Batch paralleli**: se hai centinaia di file, avvia più future e usa una coda per tenere occupata la CPU senza sovraccaricare la memoria. +- **Integrare con framework web**: collega questo script a un endpoint Flask o FastAPI per fornire OCR on‑demand come servizio. + +--- + +### TL;DR + +Ora sai come **estrarre testo da PDF immagini** con uno script Python minimale che esegue OCR in modo asincrono, permettendoti di **convertire documenti scansionati in testo** mentre il tuo programma resta reattivo. Gioca con le impostazioni della lingua, le dimensioni dei batch e le tecniche di pre‑processamento per ottenere la massima precisione possibile. + +Hai un trucco da condividere—magari OCR su note scritte a mano o un servizio basato su cloud? Lascia un commento e buona programmazione! + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Estrai Testo da Immagine con Aspose OCR – Guida Passo‑Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Estrai Testo da Immagini Usando l'Operazione OCR su Cartelle](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Estrai Testo da Immagini Usando Aspose.OCR – Caratteri Consentiti](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/italian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..450457e16 --- /dev/null +++ b/ocr/italian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Come eseguire l'OCR di un PDF con Python, estrarre testo da PDF, convertire + il testo di PDF scansionati e cambiare la lingua dell'OCR in poche righe di codice. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: it +og_description: 'Come fare OCR di PDF con Python: una guida pratica che ti mostra + come estrarre testo da PDF, convertire il testo di PDF scansionati e cambiare la + lingua dell''OCR senza sforzo.' +og_title: Come fare OCR di PDF in Python – Tutorial completo di programmazione +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Come fare OCR di PDF in Python – Guida completa passo passo +url: /it/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come fare OCR su PDF in Python – Guida completa passo‑passo + +Ti sei mai chiesto **come fare OCR su PDF** senza pagare costosi strumenti SaaS? Non sei l'unico. Che tu stia digitalizzando vecchi libri, estraendo dati da fatture, o semplicemente abbia bisogno di testo ricercabile da un report scansionato, padroneggiare l'OCR di PDF in Python può farti risparmiare ore di copia manuale. + +In questo tutorial percorreremo un esempio conciso e funzionante che **estrae testo da PDF**, ti mostrerà come **convertire il testo di PDF scansionati** in stringhe modificabili, e dimostrerà anche come **cambiare la lingua dell'OCR** se il tuo documento non è in inglese. Alla fine avrai uno snippet riutilizzabile da inserire in qualsiasi progetto. + +## Prerequisiti & Configurazione + +Prima di immergerci, assicurati di avere: + +- Python 3.8+ installato (il codice funziona su 3.9, 3.10 e versioni successive) +- Il pacchetto `ocr` che fornisce la classe `OcrEngine` (puoi installarlo via `pip install ocr-lib` – sostituisci con il nome reale del pacchetto che usi) +- Un file PDF da elaborare; per la demo useremo `high_res_book.pdf` collocato in una cartella chiamata `YOUR_DIRECTORY` + +Se utilizzi un ambiente virtuale (altamente consigliato), attivalo prima: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Consiglio professionale:** Tieni i tuoi file PDF in una directory dedicata `data/` per evitare problemi legati ai percorsi in seguito. + +## Passo 1: Creare un'Istanza del Motore OCR (Come fare OCR su PDF – Inizializzazione) + +La prima cosa da fare quando vuoi **eseguire OCR su PDF** è istanziare il motore. Pensa al motore come al cervello che leggerà ogni pagina, interpreterà i glifi e ti restituirà testo semplice. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Perché è importante: senza un motore non hai contesto per le impostazioni della lingua, le opzioni di rendering o la gestione del PDF. L'oggetto `OcrEngine` contiene tutti questi valori predefiniti e ti permette di modificarli in seguito. + +## Passo 2: Impostare la Lingua di Riconoscimento (Cambia Lingua OCR) + +La maggior parte delle librerie OCR usa l'inglese come predefinito, ma cosa succede se il tuo documento è in francese, tedesco o addirittura giapponese? Cambiare lingua è semplice come chiamare `set_recognition_language`. Questo soddisfa il requisito **cambia lingua OCR** e garantisce una maggiore accuratezza. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Perché potresti averne bisogno:** Un archivio multilingue contiene spesso pagine con lingue miste. Cambiare lingua al volo evita il riconoscimento errato di caratteri come “ß” o “ñ”. + +## Passo 3: Configurare le Opzioni di Rendering del PDF (Convertire Efficacemente il Testo di PDF Scansionati) + +Quando si lavora con PDF scansionati, la risoluzione e la modalità colore influenzano drasticamente la qualità dell'OCR. Renderizzare a 300 DPI in scala di grigi è un buon compromesso per la maggior parte dei documenti—abbastanza alto da catturare i dettagli, ma sufficientemente basso da mantenere ragionevole l'uso della memoria. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Le chiamate concatenate possono sembrare eleganti, ma sono semplicemente un'API fluida che restituisce lo stesso oggetto opzioni ogni volta. Se ti serve il colore (ad esempio per diagrammi a colori), sostituisci `"grayscale"` con `"color"`. + +## Passo 4: Riconoscere il PDF e Ottenere il Testo della Prima Pagina (Estrarre Testo da PDF) + +Ora arriva il cuore di **come fare OCR su PDF**: fornire al motore il percorso del file e prelevare il testo riconosciuto. Il metodo restituisce una lista di risultati per pagina; ogni risultato contiene un attributo `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Se ti serve l'intero documento, itera su `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### E se il PDF è Criptato? + +Alcuni PDF sono protetti da password. In tal caso puoi passare la password a `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Il motore decritterà al volo prima di eseguire l'OCR—nessun passaggio aggiuntivo necessario. + +## Passo 5: Post‑Processing del Testo Estratto (Rifinire l'Estrazione del Testo da PDF) + +L'output grezzo dell'OCR contiene spesso interruzioni di riga, spazi extra o occasionali caratteri riconosciuti in modo errato. Una rapida routine di pulizia rende la stringa estratta pronta per l'elaborazione successiva (indicizzazione, archiviazione in database, ecc.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Ora puoi **estrarre testo da PDF** e inviarlo a qualsiasi pipeline NLP, motore di ricerca o semplice operazione `open(...).write()`. + +## Bonus: Elaborazione Batch di Più PDF (Scalare l'Esecuzione OCR su PDF) + +Se hai una cartella piena di PDF scansionati, avvolgi la logica in un ciclo: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Questo snippet mostra come **eseguire OCR su PDF** in blocco, una necessità comune nei progetti di digitalizzazione. + +## Output Atteso + +Eseguire l'esempio a pagina singola (Passo 4) dovrebbe stampare qualcosa del genere: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Se hai elaborato un libro a più pagine, la console mostrerà il testo pulito di ogni pagina, e lo script batch lascerà un file `.txt` accanto a ciascun PDF. + +## Problemi Comuni & Come Evitarli + +| Problema | Sintomi | Soluzione | +|----------|----------|-----------| +| PDF sorgente a bassa risoluzione | Caratteri illeggibili, parole mancanti | Aumenta DPI (`set_dpi(400)` o superiore) | +| Lingua impostata errata | Molti simboli sconosciuti, specialmente caratteri accentati | Usa `engine.set_recognition_language(ocr.Language.FRENCH)` o l'enumerazione appropriata | +| PDF grande che causa errore di memoria | `MemoryError` o crash dopo alcune pagine | Processa le pagine a blocchi (`engine.recognize_pdf(..., max_pages=10)`) | +| Font mancanti nel PDF | Output vuoto per alcune pagine | Assicurati che il PDF contenga effettivamente immagini raster; alcuni PDF sono solo vettoriali e richiedono una gestione diversa | + +## Illustrazione + +Di seguito una rapida visuale del flusso di lavoro. Il testo alternativo è deliberatamente SEO‑friendly. + +![diagramma del flusso di lavoro per OCR di PDF che mostra l'inizializzazione del motore, impostazione della lingua, opzioni di rendering, riconoscimento e estrazione del testo](/images/ocr-workflow.png) + +*Il diagramma non è necessario per l'esecuzione del codice, ma aiuta gli apprendisti visivi a vedere dove si inserisce ogni passo.* + +## Conclusione + +Abbiamo coperto **come fare OCR su PDF** in Python dall'inizio alla fine: creazione di un motore OCR, **cambio della lingua OCR**, configurazione del rendering per **convertire il testo di PDF scansionati**, e infine **estrazione del testo da PDF** per usi successivi. L'esempio completo, eseguibile, è pronto per essere inserito in qualsiasi progetto, e lo script batch opzionale mostra come scalare la soluzione. + +Prossimamente potresti voler esplorare: + +- Aggiungere **esecuzione OCR su PDF** per archivi multilingue iterando su una lista di lingue. +- Integrare il testo estratto con Elasticsearch per la ricerca full‑text. +- Usare l'OCR per creare PDF ricercabili incorporando il livello di testo nel file originale (molte librerie espongono un metodo `save_as_searchable_pdf`). + +Sentiti libero di sperimentare, modificare le impostazioni DPI, o passare a un backend OCR diverso. I fondamenti rimangono gli stessi, e ora hai una solida base su cui costruire. + +Buon coding, e che i tuoi documenti scansionati diventino finalmente ricercabili! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/italian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..b021f1190 --- /dev/null +++ b/ocr/italian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-06 +description: Come fare OCR di PDF e creare file PDF ricercabili da immagini usando + Python. Impara ad aggiungere testo ricercabile e convertire l'immagine in PDF/A + in pochi minuti. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: it +og_description: Come fare OCR di un PDF passo dopo passo. Impara ad aggiungere testo + ricercabile e a convertire l'immagine in PDF/A usando un semplice script Python. +og_title: Come fare OCR su PDF – Guida rapida per creare PDF ricercabili +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Come fare OCR di PDF in Python – Creare PDF ricercabili da immagini +url: /it/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come fare OCR su PDF – Trasformare le Immagini Scansionate in PDF Ricercabili + +Ti sei mai chiesto **come fare OCR su PDF** quando tutto ciò che hai è un'immagine scansionata di una fattura o di una ricevuta? Non sei l'unico. In molti uffici la documentazione in arrivo arriva come PNG o JPEG piatti, e il passo successivo—rendere quel contenuto ricercabile—sembra una scatola nera. + +La buona notizia? Con poche righe di Python puoi **creare PDF ricercabili**, **aggiungere testo ricercabile**, e persino **convertire immagini in PDF/A** per l'archiviazione a lungo termine. In questo tutorial percorreremo ogni passaggio, spiegheremo perché è importante e ti forniremo uno script pronto all'uso da inserire in qualsiasi progetto. + +> **Consiglio professionale:** Lo stesso approccio funziona per scansioni multi‑pagina; basta iterare sui file e il motore si occupa del lavoro pesante. + +--- + +## Cosa ti servirà + +Prima di immergerci, assicurati di avere quanto segue sulla tua macchina: + +| Requisito | Perché è importante | +|-------------|----------------| +| Python 3.9 o più recente | Sintassi moderna e migliore supporto alle librerie | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Gestisce sia il riconoscimento delle immagini che la generazione di PDF/A | +| Un file immagine (PNG, JPEG, TIFF) che desideri trasformare in un PDF ricercabile | La fonte del testo | +| Permesso di scrittura sulla cartella di destinazione | Affinché lo script possa salvare il nuovo PDF | + +Se non hai ancora installato l'SDK OCR, esegui: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +È tutto—nessuna dipendenza di sistema complessa, solo un'installazione pip. + +## Come fare OCR su PDF – Panoramica + +A livello alto il processo consiste in tre azioni semplici: + +1. **Riconoscere** il testo all'interno dell'immagine mantenendo intatta la grafica originale. +2. **Esportare** il risultato OCR insieme all'immagine originale come **PDF/A ricercabile** (la variante PDF adatta all'archiviazione). +3. **Convalidare** che il file risultante contenga testo selezionabile e ricercabile sovrapposto all'immagine originale. + +Di seguito vedrai ogni passaggio in codice, con spiegazioni del *perché* dietro i comandi. + +## Passo 1: Riconoscere il Testo dall'Immagine + +Per prima cosa chiediamo al motore OCR di leggere i pixel e restituire un oggetto risultato che contiene sia l'immagine grezza sia il testo estratto. Pensalo come il motore che “legge” la fattura per te. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Perché è importante + +- **Preservare la grafica** significa che il layout visivo (tabelle, loghi, timbri) rimane esattamente come è stato acquisito dallo scanner. +- L'oggetto `result` tipicamente contiene un livello di testo nascosto che inseriremo successivamente nel PDF. +- Usare `recognize_image` invece di `recognize_pdf` evita un passaggio di conversione aggiuntivo, velocizzando l'elaborazione per immagini a pagina singola. + +#### Varianti comuni + +- Se hai un **TIFF multi‑pagina**, passa direttamente il percorso del file; la maggior parte dei motori tratterà ogni pagina come un'immagine separata. +- Per i PDF che contengono già immagini, puoi chiamare `engine.recognize_pdf("file.pdf")` e saltare completamente questo passaggio. + +## Passo 2: Esportare il Risultato OCR come PDF/A Ricercabile + +Ora prendiamo il `result` dal passo 1 e diciamo al motore di scrivere un nuovo file. Il flag chiave qui è *PDF/A*—la versione standard ISO del PDF progettata per la conservazione a lungo termine. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Perché è importante + +- **PDF ricercabile**: Il file di output contiene un livello di testo nascosto e selezionabile. Ora puoi usare Ctrl + F sul documento. +- **Conformità PDF/A**: Alcune organizzazioni (legale, finanziaria) richiedono PDF/A per le tracce di audit; questo passaggio soddisfa automaticamente tale requisito. +- Il metodo aggiunge anche **testo ricercabile** senza appiattire l'immagine, così la fedeltà visiva rimane perfetta. + +#### Caso limite: Hai bisogno di un PDF normale invece? + +Se non ti interessa il PDF/A, sostituisci `save_as_pdfa` con `save_as_pdf`. Il resto del flusso di lavoro rimane invariato. + +## Passo 3: Verificare il PDF Ricercabile + +Un rapido controllo di sanità ti salva da bug misteriosi in seguito. Apri il file generato in qualsiasi visualizzatore PDF, prova a selezionare una parola e usa la funzione di ricerca. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Output previsto + +Quando esegui lo script, la console stampa: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Aprendo il file, dovresti vedere l'immagine originale della fattura con un leggero livello di testo invisibile. Evidenzia qualsiasi parola e noterai che è selezionabile—**questo è il testo ricercabile** che hai appena aggiunto. + +## Aggiungere Testo Ricercabile a PDF Esistenti (Bonus) + +A volte hai già un PDF ma devi **aggiungere testo ricercabile**. Lo stesso motore può sovrapporre i risultati OCR a un PDF esistente: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Qui `apply_to` unisce il livello nascosto con le pagine originali, permettendoti di **creare PDF ricercabili** senza dover riscanalizzare. + +## Problemi Comuni e Consigli + +| Problema | Come evitarlo | +|----------|-----------------| +| **Immagini sorgente a bassa risoluzione** (< 150 dpi) | Aumenta la risoluzione o richiedi una scansione a risoluzione più alta; la precisione dell'OCR diminuisce drasticamente sotto i 150 dpi. | +| **Dati di lingua mancanti** | Installa i pacchetti di lingua appropriati per il tuo motore OCR (`pip install pdfocr[eng,spa]`). | +| **Cartella di output non scrivibile** | Esegui lo script con permessi sufficienti o scegli una directory diversa. | +| **Validazione PDF/A fallita** | Assicurati di non incorporare font non supportati o JavaScript; la maggior parte degli SDK gestisce automaticamente questo quando usi `save_as_pdfa`. | + +## Script Completo – Soluzione in Un Solo File + +Di seguito trovi uno script autonomo che collega tutti i passaggi. Copialo, sostituisci i percorsi segnaposto e sei pronto a **convertire immagini in PDF/A** in pochi secondi. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Cosa fa questo script:** +1. Carica il motore OCR. +2. Legge l'immagine selezionata ed estrae il testo. +3. Scrive un **PDF/A ricercabile** che puoi subito distribuire o archiviare. + +Sentiti libero di racchiudere la logica `main` in una funzione che processa un'intera cartella—basta iterare su `os.listdir()` e ripetere i tre passaggi per ogni file. + +## Prossimi Passi e Argomenti Correlati + +Ora che hai padroneggiato **come fare OCR su PDF**, considera di esplorare queste idee successive: + +- **Elaborazione batch:** Usa `concurrent.futures` per fare OCR a decine di fatture in parallelo. +- **Iniezione di metadati:** Aggiungi date di creazione o numeri di fattura ai metadati del PDF per indicizzazioni più semplici. +- **PDF ibridi:** Combina testo ricercabile con immagini originali incorporate per un “gemello digitale” del documento cartaceo. +- **Uscite alternative:** Esporta in **DOCX** o **HTML** se i sistemi a valle richiedono formati modificabili. + +Ognuna di queste si basa sui concetti fondamentali appena appresi—riconoscere, esportare, verificare. + +## Conclusione + +In sintesi, ora sai **come fare OCR su PDF** trasformando una semplice immagine in un **PDF/A ricercabile** con sole tre righe di Python. Lo script gestisce il lavoro pesante, preserva la grafica originale e ti fornisce un documento conforme agli standard che puoi cercare, archiviare o condividere. + +Provalo con le tue fatture, ricevute o contratti scansionati. Se incontri difficoltà, lascia un commento qui sotto o consulta la documentazione ufficiale dell'SDK—di solito è ricca di esempi aggiuntivi. Buona programmazione e goditi la nuova capacità di rendere qualsiasi immagine immediatamente ricercabile! + +![Esempio di Come fare OCR su PDF che mostra l'immagine originale e la sovrapposizione del PDF ricercabile](placeholder.png "Esempio di Come fare OCR su PDF") + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come fare OCR su PDF in .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Riconoscere Testo PDF – Operazioni OCR con Aspose.OCR per Java](/ocr/english/java/ocr-operations/) +- [Convertire Immagini in PDF C# – Salva Risultato OCR Multi‑pagina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/italian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..3af6c079f --- /dev/null +++ b/ocr/italian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Come fare OCR di PDF con Aspose OCR Cloud. Impara a estrarre il testo + da PDF, convertire le pagine PDF in PNG e salvare le immagini delle pagine PDF in + Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: it +og_description: Come eseguire OCR su PDF con Aspose OCR Cloud. Questa guida mostra + come estrarre il testo semplice da un PDF, convertire le pagine PDF in PNG e salvare + le immagini delle pagine PDF. +og_title: Come fare OCR di PDF con Aspose OCR Cloud – Passo dopo passo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Come eseguire l'OCR di PDF con Aspose OCR Cloud – Guida completa +url: /it/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come fare OCR su PDF con Aspose OCR Cloud – Guida completa + +Ti sei mai chiesto **come fare OCR su PDF** senza lottare con strumenti desktop ingombranti? Non sei solo—molti sviluppatori si trovano di fronte a questo ostacolo quando hanno bisogno di un modo rapido e programmatico per estrarre il testo da documenti scansionati. La buona notizia? Con Aspose OCR Cloud puoi **estrarre testo da PDF**, trasformare ogni pagina in un PNG e persino **salvare le immagini delle pagine PDF** per un uso successivo, il tutto da un pulito script Python. + +In questo tutorial percorreremo tutto ciò che devi sapere: dall'installazione dell'SDK, alla licenza del motore, al riconoscimento di PDF multi‑pagina, fino all'estrazione di testo semplice, alla conversione delle pagine in PNG e al salvataggio di queste immagini su disco. Alla fine avrai uno snippet riutilizzabile da inserire in qualsiasi progetto che necessiti di funzionalità **come fare OCR su PDF**. + +## Cosa ti servirà + +- **Python 3.8+** (il codice funziona anche su 3.10 e versioni successive) +- Un account Aspose OCR Cloud – otterrai un file di licenza di prova gratuito (`Aspose.OCR.lic`) +- Il pacchetto `asposeocrcloud` (`pip install asposeocrcloud`) +- Un PDF scansionato, multi‑pagina che desideri elaborare + +È tutto. Nessun binario aggiuntivo, nessuna dipendenza nativa, solo puro Python. + +## Come fare OCR su PDF – Configurazione e Licenza + +Prima di poter chiamare qualsiasi metodo OCR, devi indicare all'SDK chi sei. Aspose utilizza un file di licenza leggero che devi posizionare in un luogo accessibile al tuo script. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Consiglio:* Se salti il passaggio della licenza, l'SDK funzionerà comunque ma inserirà una piccola filigrana nelle immagini di output. Non è ideale per la produzione. + +## Passo 2: Installa l'SDK Python di Aspose OCR Cloud + +Apri un terminale ed esegui: + +```bash +pip install asposeocrcloud +``` + +Il pacchetto scarica tutte le dipendenze necessarie (requests, pillow, ecc.) così non devi cercare nient'altro. + +## Passo 3: Crea un motore OCR e scegli una lingua + +Il motore è il cuore dell'operazione. Puoi specificare qualsiasi lingua supportata da Aspose; l'inglese funziona nella maggior parte dei casi. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Perché impostare la lingua? Perché il motore OCR utilizza dizionari specifici per lingua per migliorare l'accuratezza. Se stai elaborando PDF in francese, basta sostituire `ENGLISH` con `FRENCH`. + +## Passo 4: Indica il tuo PDF multi‑pagina + +Fornisci al motore il percorso completo del file che desideri elaborare. I percorsi relativi vanno bene finché risolvono correttamente dalla directory di lavoro dello script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Assicurati che il file sia leggibile; altrimenti vedrai un `FileNotFoundError`. + +## Passo 5: Esegui OCR – Ottieni una lista di risultati + +Chiamare `recognize_pdf` restituisce una lista in cui ogni elemento corrisponde a una pagina del PDF di origine. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Ogni `OcrResult` contiene due utili proprietà: + +* `text` – la rappresentazione in testo semplice della pagina (ottimo per **estrarre testo semplice da pdf**) +* `image` – un oggetto `Image` di Pillow della pagina renderizzata (perfetto per **convertire pagina pdf in png**) + +## Passo 6: Estrarre testo da PDF e convertire le pagine in PNG + +Ora iteriamo sui risultati, stampiamo il testo estratto e salviamo una versione PNG di ogni pagina. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Output previsto nella console + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Troverai anche `page_1.png`, `page_2.png`, … nella cartella `YOUR_DIRECTORY`. Queste sono le immagini rasterizzate delle pagine che puoi inserire in pipeline di elaborazione immagini successive. + +## Passo 7: Salva le immagini delle pagine PDF (Post‑processing opzionale) + +Se ti servono solo le immagini e non il testo, puoi saltare la riga `print(res.text)`. Al contrario, se vuoi salvare il testo in file `.txt` separati, aggiungi una piccola scrittura: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Questa piccola aggiunta dimostra quanto sia semplice **salvare le immagini delle pagine PDF** mantenendo anche il contenuto estratto. + +## Esempio completo funzionante + +Mettendo tutto insieme, ecco lo script completo che puoi copiare‑incollare in `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Eseguilo con: + +```bash +python ocr_pdf.py +``` + +Dovresti vedere nella console il dump del testo di ogni pagina e una serie di file PNG + +## Cosa dovresti imparare dopo? + +I tutorial seguenti coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/italian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..0c0bb9375 --- /dev/null +++ b/ocr/italian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-06-06 +description: Come pre‑processare le immagini per OCR usando Python. Impara a binarizzare + l'immagine con Otsu, a raddrizzare i documenti scansionati e a migliorare l'accuratezza + OCR per il testo tedesco. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: it +og_description: Come pre-elaborare le immagini per l'OCR in Python. Questo tutorial + mostra come binarizzare l'immagine usando Otsu, come raddrizzare i documenti scannerizzati + e come migliorare l'accuratezza dell'OCR per immagini tedesche. +og_title: Come preelaborare le immagini per OCR – Guida completa Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Come preelaborare le immagini per OCR – Guida completa in Python +url: /it/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come Preprocessare le Immagini per OCR – Guida Completa in Python + +Ti sei mai chiesto **come preprocessare le immagini per OCR** in modo che il testo risulti cristallino? Non sei l’unico. I documenti scansionati—soprattutto le pagine tedesche rumorose—possono essere un incubo per qualsiasi motore OCR. La buona notizia? Alcuni passaggi intelligenti di preprocessing possono trasformare una scansione sfocata e macchiata in un’immagine pulita e leggibile dalla macchina. + +In questo tutorial percorreremo un esempio pratico che mostra **come preprocessare le immagini per OCR** usando Python. Imparerai a **binarizzare l’immagine usando Otsu**, **come correggere l’inclinazione dei documenti scansionati**, e in generale **come migliorare la precisione OCR** quando devi **estrarre testo da file immagine in tedesco**. Niente fronzoli, solo uno script funzionante che puoi copiare‑incollare oggi. + +## Cosa Ti Serve + +- **Python 3.9+** (qualsiasi versione recente va bene) +- Una libreria OCR che espone una classe `OcrEngine` – per la demo assumiamo un pacchetto generico `ocr`. Installala con `pip install ocr-lib`. +- Una scansione tedesca rumorosa (`noisy_german_scan.tif`) su cui vuoi testare. +- Una conoscenza di base delle funzioni Python (se hai già scritto un `def`, sei a posto). + +> **Consiglio professionale:** Se usi un SDK OCR diverso (ad esempio Tesseract tramite `pytesseract`), i concetti rimangono gli stessi—basta adattare i nomi dei metodi. + +## Panoramica della Soluzione + +1. **Creare un’istanza del motore OCR.** +2. **Impostare la lingua di riconoscimento su tedesco.** +3. **Costruire una pipeline di preprocessing personalizzata** che includa correzione dell’inclinazione, denoising, binarizzazione (Otsu) e stretching del contrasto. +4. **Collegare la pipeline al motore** così ogni immagine la attraversa automaticamente. +5. **Eseguire l’OCR** su una scansione tedesca rumorosa. +6. **Stampare il testo estratto** per verificare il risultato. + +Di seguito scomponiamo ogni passaggio, spieghiamo **perché** è importante e mostriamo il codice esatto di cui hai bisogno. + +![come preprocessare le immagini per OCR esempio](image.png "come preprocessare le immagini per OCR esempio") + +## Step 1: Creare un’Istanza del Motore OCR + +Prima di tutto—senza un motore, non succede nulla. L’oggetto `OcrEngine` è il punto di ingresso che coordina tutti i successivi processi. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Perché è importante:* Inizializzare il motore configura le risorse interne (come i modelli linguistici) e ti fornisce una base pulita a cui collegare una pipeline personalizzata in seguito. + +## Step 2: Impostare la Lingua di Riconoscimento su Tedesco + +La precisione OCR dipende molto dalla lingua. Indicando al motore di aspettarsi il tedesco, attivi il set di caratteri corretto e il modello linguistico appropriato. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Se salti questo passaggio, il motore potrebbe usare l’inglese di default, riconoscendo male le umlaut (ä, ö, ü) e il carattere ß—trappole comuni quando si lavora con scansioni tedesche. + +## Step 3: Costruire una Pipeline di Preprocessing Personalizzata + +Questo è il cuore di **come preprocessare le immagini per OCR**. Concatenamo quattro trasformazioni: + +| Trasformazione | Cosa fa | Perché è utile | +|----------------|---------|----------------| +| **Deskew** | Ruota l’immagine nuovamente in orizzontale (max 5°) | Le scansioni raramente sono perfettamente allineate; la correzione dell’inclinazione elimina la slant che confonde la segmentazione dei caratteri. | +| **Denoise** | Riduce i punti casuali (intensità 0.7) | Il rumore crea bordi falsi che il motore OCR può interpretare come caratteri. | +| **Binarize (Otsu)** | Converte in bianco‑nero usando il metodo di Otsu | Un’immagine binaria pulita fornisce al motore un contrasto netto tra primo piano (testo) e sfondo. | +| **Contrast Stretch** | Espande la gamma dinamica | Migliora la leggibilità di tratti deboli, specialmente su documenti vecchi. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Come Correggere l’Inclinazione dei Documenti Scansionati + +La chiamata `deskew` sopra è la risposta concreta a **come correggere l’inclinazione dei documenti scansionati**. Internamente stima l’angolo dominante delle linee di testo tramite trasformata di Hough e ruota l’immagine indietro. Se i tuoi documenti sono ruotati più di 5°, aumenta `max_angle`, ma fai attenzione agli artefatti di sovra‑rotazione. + +### Binarizzare l’Immagine Usando Otsu + +La riga `binarize(method="otsu")` risponde direttamente alla query **binarizzare immagine usando otsu**. L’algoritmo di Otsu calcola una soglia che minimizza la varianza intra‑classe, perfetta per documenti con istogrammi bimodali (testo scuro vs. sfondo chiaro). + +## Step 4: Collegare la Pipeline al Motore + +Ora diciamo al motore OCR di eseguire ogni immagine in ingresso attraverso la pipeline appena creata. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Perché è importante:* Senza la registrazione, il motore elaborerebbe la scansione grezza, ignorando tutta la pulizia che abbiamo configurato. Questo passaggio garantisce **come migliorare la precisione OCR** applicando lo stesso preprocessing in modo coerente. + +## Step 5: Riconoscere il Testo da una Scansione Tedesca Rumorosa + +È il momento di mettere tutto insieme. Forniamo al motore un’immagine tedesca rumorosa e lasciamo che faccia il lavoro pesante. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Se sei curioso delle prestazioni, puoi cronometrarne la chiamata: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Step 6: Stampare il Testo Riconosciuto + +Infine, stampiamo la stringa estratta. Questa è la risposta diretta a **estrarre testo da immagine tedesca**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Output Atteso + +Supponendo che la scansione di esempio contenga la frase “Die schnelle braune Füchsin springt über den faulen Hund.” dovresti vedere qualcosa di simile: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Se l’output contiene ancora caratteri illeggibili, considera di regolare la forza del `denoise` o aumentare `max_angle` per la correzione dell’inclinazione. + +## Problemi Comuni & Come Affrontarli + +- **Modello linguistico mancante:** Dimenticare `set_recognition_language(Language.GERMAN)` porta spesso a perdere le umlaut. Controlla la chiamata. +- **Over‑denoising:** Una forza superiore a 0.9 può cancellare tratti sottili, specialmente in font più vecchi. Mantieni 0.5‑0.7 nella maggior parte dei casi. +- **Formato file errato:** Alcuni motori OCR non gestiscono TIFF multi‑pagina. Se hai un documento multi‑pagina, dividilo in file singoli prima. +- **Ordine della pipeline:** L’ordine mostrato (deskew → denoise → binarize → contrast) è intenzionale. Binarizzare prima del denoising può fissare il rumore; denoise sempre per primo. + +## Estendere la Pipeline (Cosa Viene Dopo?) + +Ora che hai una solida base, potresti voler: + +- **Aggiungere un’apertura morfologica** per pulire piccoli blob (`.morph_open(kernel=3)`). +- **Integrare un modello linguistico** per la correzione post‑processo (`ocr_engine.apply_spellcheck()`). +- **Parallelizzare l’elaborazione batch** per grandi dataset usando `concurrent.futures`. + +Tutte queste sono estensioni naturali che mantengono intatta l’idea di **come preprocessare le immagini per OCR** mentre potenziano **come migliorare la precisione OCR** ancora di più. + +## Conclusione + +Abbiamo appena coperto **come preprocessare le immagini per OCR** dall’inizio alla fine: creare un motore, impostare la lingua tedesca, costruire una pipeline che **binarizza l’immagine usando Otsu**, **come correggere l’inclinazione dei documenti scansionati**, e infine **estrarre testo da immagine tedesca** con maggiore fiducia. Seguendo i sei passaggi sopra vedrai un salto notevole nella qualità del riconoscimento—niente più correzioni manuali infinite. + +Prova lo script con le tue scansioni, sperimenta i parametri e lascia che i risultati parlino da soli. Hai domande su un particolare aggiustamento di preprocessing? Lascia un commento e approfondiremo insieme. + +Buona programmazione, e che il tuo OCR sia sempre preciso! + +## Cosa Dovresti Imparare Dopo? + + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Estrarre testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Come Impostare il Valore di Soglia nel Riconoscimento Immagine OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Come Eseguire OCR su Immagine – Eseguire OCR su Immagine nel Riconoscimento Immagine OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/italian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..185a1a25f --- /dev/null +++ b/ocr/italian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-06 +description: OCR di immagini PNG con Python – impara come estrarre il testo dall’immagine, + esegui un esempio di OCR in Python e leggi facilmente anche testi in greco antico. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: it +og_description: OCR di immagini PNG in Python spiegato. Questa guida mostra come estrarre + testo dall'immagine, eseguire un esempio di OCR in Python e leggere il greco antico + con facilità. +og_title: OCR immagine PNG in Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR di immagine PNG in Python – Guida completa passo passo +url: /it/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image in Python – Guida Completa Passo‑Passo + +Ti sei mai chiesto come **OCR PNG image** file direttamente da uno script Python? Forse hai una cartella piena di manoscritti antichi scansionati e hai bisogno di **extract text from image** file senza digitare tutto manualmente. La buona notizia è che non ti serve un dottorato in computer vision—basta qualche riga di codice e la libreria giusta, e leggerai greco antico in pochi secondi. + +In questo tutorial percorreremo un **python OCR example** che riconosce il testo da un PNG, imposta la lingua al greco politonico e stampa il risultato. Alla fine saprai esattamente come **recognize image text**, gestire le insidie comuni e adattare lo script ad altre lingue o formati di immagine. + +## Cosa Imparerai + +- Installa e configura una libreria Python OCR (pytesseract + Tesseract OCR) +- Crea un'istanza del motore OCR e carica un file PNG +- Imposta la lingua di riconoscimento al greco politonico così potrai **read ancient greek** +- Stampa il testo riconosciuto e risolvi i problemi tipici +- Estendi lo script per elaborare in batch più PNG o cambiare lingua + +### Prerequisiti + +| Requisito | Perché è importante | +|-------------|----------------| +| Python 3.8+ | Sintassi moderna e type hints | +| `pytesseract` package | Leggera interfaccia attorno al motore Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Il motore reale che esegue il lavoro pesante | +| Greek language data (`grc.traineddata`) | Necessario per **read ancient greek** correttamente | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Il nostro obiettivo per la demo **ocr png image** | + +Puoi installare la parte Python con: + +```bash +pip install pytesseract Pillow +``` + +E su Ubuntu/macOS aggiungeresti il motore stesso: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Non dimenticare di scaricare i dati di addestramento greco politonico: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Il percorso può differire; regola `TESSDATA_PREFIX` se necessario.)* + +## OCR PNG Image: Crea l'Istanza del Motore + +La prima cosa di cui abbiamo bisogno è un oggetto che comunica con Tesseract. In `pytesseract` il motore è accessibile tramite funzioni a livello di modulo, ma per chiarezza lo avvolgeremo in una piccola classe. Questo rispecchia il concetto di “engine” che hai visto nello snippet originale. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Perché avvolgerlo?** +- Mantiene l'API pubblica identica allo snippet di partenza, rendendo la migrazione indolore. +- Ci permette di aggiungere logging o gestione degli errori in seguito senza toccare il flusso principale. +- Dimostra una buona pratica OOP—qualcosa che gli sviluppatori senior apprezzano. + +## Estrai Testo dall'Immagine: Imposta la Lingua al Greco Politonico + +Ora che abbiamo un motore, dobbiamo dirgli quale lingua aspettarsi. Il greco politonico utilizza diacritici che non sono coperti dai dati “greek” standard, quindi indirizziamo Tesseract al file di addestramento `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Se vuoi **extract text from image** file in un'altra lingua, basta sostituire `"grc"` con `"eng"` per l'inglese, `"fra"` per il francese, ecc. La stessa riga funziona per qualsiasi lingua installata. + +## Riconosci Testo nell'Immagine: Esegui l'OCR su un PNG + +Con la lingua impostata, forniamo il PNG al motore. L'esempio originale usava un percorso hard‑coded; lo renderemo un po' più flessibile usando oggetti `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Suggerimenti & Casi Limite** + +- **File not found** – avvolgi la chiamata in un `try/except FileNotFoundError` per fornire un messaggio amichevole. +- **Low‑resolution PNG** – considera il pre‑processing (es., ridimensionamento, binarizzazione) con Pillow prima dell'OCR. +- **Non‑Greek text** – Tesseract proverà comunque a decodificare, ma l'accuratezza cala drasticamente. Assicurati sempre di corrispondere alla lingua. + +## Stampa il Testo Riconosciuto + +Infine, stampiamo il risultato. In un progetto reale potresti scrivere su un database, un CSV, o anche inserirlo in una pipeline di traduzione. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Quando esegui lo script su una scansione chiara di un'iscrizione greca antica, dovresti vedere qualcosa del genere: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Se l'output appare confuso, ricontrolla che il file **greek.traineddata** sia nella cartella corretta e che il PNG non sia troppo rumoroso. + +## Esempio Completo Funzionante (Tutti i Passaggi in Un Solo Script) + +Di seguito il programma completo, pronto per l'esecuzione. Salvalo come `ocr_greek.py` ed esegui `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Output atteso** (troncato per brevità): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Se vedi i corretti caratteri greci, congratulazioni—hai eseguito con successo un'operazione **ocr png image** in Python! + +## Domande Frequenti & Consigli Pro + +### Come migliorare l'accuratezza su un PNG rumoroso? + +- Converti l'immagine in scala di grigi: `img = img.convert('L')` +- Applica una soglia binaria: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Ingrandisci con `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Questi passaggi spesso trasformano un incubo di **recognize image text** in un risultato pulito. + +### Posso elaborare un'intera cartella di PNG? + +Assolutamente. Avvolgi la chiamata `recognize_image` in un ciclo `for` su `Path.glob("*.png")`. Salva ogni risultato in un dizionario o scrivilo in un CSV per analisi successive. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### E se ho bisogno di estrarre solo numeri? + +Passa una stringa **config** personalizzata a `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +In questo modo puoi **extract text from image** file che contengono tabelle, numeri di serie o timestamp. + +### Esiste un modo per ottenere i punteggi di confidenza? + +Sì—usa `pytesseract.image_to_data` che restituisce un TSV con la confidenza per parola. Puoi filtrare i token a bassa confidenza prima di assemblare la stringa finale. + +## Estendere il Tutorial + +Ora che hai padroneggiato le basi, considera di esplorare questi argomenti correlati: + +- **Batch OCR with multiprocessing** – velocizza grandi corpora di PNG. +- **Hybrid OCR + NLP pipelines** – traduci automaticamente il greco antico estratto in inglese moderno. +- **Alternative engines** – prova `easyocr` o metodi basati su `opencv` per casi d'uso specifici. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, o AWS Textract per scalabilità serverless. + +Ognuno di questi si basa sul core **python ocr example** che abbiamo appena trattato, così ti sentirai a tuo agio ad approfondire. + +## Conclusione + +Abbiamo preso uno snippet semplice e lo abbiamo trasformato in un flusso di lavoro robusto **ocr png image** in Python. Creando un `OcrEngine`, impostando la lingua al greco politonico, fornendo un PNG e stampando il risultato, ora sai come **extract text from image** file, **recognize image text**, e persino **read ancient greek**. + +## Cosa Dovresti Imparare Dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Estrai Testo da Immagine con Aspose OCR – Guida Passo‑Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Come Impostare il Valore di Soglia nel Riconoscimento OCR di Immagini](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Riconosci testo immagine con Aspose OCR per più lingue](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/italian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..ed8d4256a --- /dev/null +++ b/ocr/italian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-06 +description: Tutorial OCR in Python che mostra come riconoscere il testo nelle immagini, + eseguire OCR ad alta risoluzione ed estrarre testo spagnolo usando OCR accelerato + da GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: it +og_description: Tutorial OCR in Python che ti guida nel riconoscere il testo nelle + immagini, OCR ad alta risoluzione e nell'estrazione di testo spagnolo con accelerazione + GPU. +og_title: Tutorial OCR in Python – Riconoscimento del testo accelerato da GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Tutorial OCR Python – Riconosci il testo delle immagini con accelerazione GPU +url: /it/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Riconoscere il Testo nelle Immagini con Accelerazione GPU + +Ti sei mai chiesto come **riconoscere il testo nelle immagini** in uno script Python senza passare ore a regolare le impostazioni? Non sei l'unico. In questo **python ocr tutorial** ti mostreremo un modo pulito, end‑to‑end, per estrarre testo spagnolo da un'immagine ad alta risoluzione, e aggiungeremo l'accelerazione GPU così il processo sarà fulmineo. + +Pensalo come una dimostrazione veloce da fare durante una pausa caffè, che potrai poi espandere in una pipeline di livello produzione. Alla fine di questa guida avrai un programma eseguibile che esegue **OCR ad alta risoluzione**, sfrutta una GPU con supporto CUDA e restituisce i caratteri spagnoli esatti di cui hai bisogno. + +## Cosa Imparerai + +- Come installare e importare una libreria OCR moderna che supporta l'accelerazione GPU. +- Come creare un'istanza del motore OCR e impostarla per **riconoscere il testo nelle immagini** in spagnolo. +- Come abilitare **OCR accelerato da GPU** per guadagni di velocità massicci su file ad alta risoluzione. +- Come gestire casi limite come driver CUDA mancanti o fallback alla CPU. +- Consigli per migliorare l'accuratezza quando devi **estrarre testo spagnolo** da scansioni rumorose. + +### Prerequisiti + +- Python 3.9+ (il codice funziona anche su 3.10 e versioni successive). +- Una GPU compatibile con CUDA (opzionale ma altamente consigliata). +- Familiarità di base con pip e gli ambienti virtuali. + +Se ti manca qualcuno di questi, il tutorial funziona comunque—basta saltare il passaggio GPU e la libreria tornerà automaticamente alla CPU. + +--- + +## Python OCR Tutorial: Installa i Pacchetti Necessari + +Prima di tutto, ci serve un motore OCR solido. Per questo tutorial useremo il pacchetto open‑source **`easyocr`**, che include il supporto GPU integrato quando viene rilevato un dispositivo compatibile. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Se hai già installato PyTorch, assicurati che corrisponda alla tua versione CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Versioni non allineate sono una causa comune di errori “GPU not found”. + +--- + +## Passo 1: Crea un'Istanza del Motore OCR + +Ora avviamo il motore. EasyOCR chiama la sua classe principale `Reader`. Il costruttore accetta una lista di codici lingua; noi passeremo `"es"` per lo spagnolo. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Perché è importante:* Dichiarando la lingua in anticipo, il motore carica solo i pesi della rete neurale necessari, risparmiando memoria e velocizzando l'inferenza—particolarmente utile quando si tratta di **OCR ad alta risoluzione** più avanti. + +--- + +## Passo 2: Prepara un'Immagine ad Alta Risoluzione + +Le immagini ad alta risoluzione forniscono al modello più pixel su cui lavorare, il che di solito si traduce in un riconoscimento dei caratteri migliore. Supponiamo tu abbia un file chiamato `high_res_spanish.png` in una cartella denominata `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Se non hai a disposizione un campione ad alta risoluzione, puoi scaricarne uno gratuito da Unsplash o generare un'immagine sintetica con Pillow. La chiave è mantenere i DPI sopra 300 per ottenere i migliori risultati. + +--- + +## Passo 3: Abilita l'Accelerazione GPU (Opzionale ma Raccomandata) + +EasyOCR tenta già di usare la GPU quando imposti `gpu=True`. Tuttavia, è buona pratica verificare che il dispositivo sia effettivamente utilizzato, soprattutto su configurazioni con più GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Perché controllare?* Se lo script ricade silenziosamente sulla CPU, potresti chiederti perché un'operazione di 5 secondi improvvisamente richiede 30 secondi. Questo piccolo controllo rende il comportamento trasparente e mantiene la tua pipeline **OCR accelerato da GPU** prevedibile. + +--- + +## Passo 4: Esegui OCR ad Alta Risoluzione e Riconosci il Testo nell'Immagine + +Ora la parte divertente—leggere effettivamente il testo. Il metodo `readtext` di EasyOCR restituisce una lista di tuple contenenti il bounding box, la stringa riconosciuta e un punteggio di confidenza. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Se ti serve la stringa grezza senza coordinate, imposta `detail=0`. Per la maggior parte dei casi d'uso di **riconoscere il testo nelle immagini**, il valore predefinito (`detail=1`) ti offre abbastanza contesto per una post‑elaborazione successiva. + +--- + +## Passo 5: Estrarre il Testo Spagnolo e Pulire l'Output + +Poiché abbiamo chiesto a EasyOCR lo spagnolo, le stringhe restituite sono già in quella lingua. Tuttavia, potresti volerle concatenare, rimuovere spazi bianchi o filtrare le rilevazioni a bassa confidenza. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**E se la confidenza è bassa?** Puoi abbassare la soglia (rischiando più rumore) o pre‑processare l'immagine (aumentare il contrasto, binarizzare o correggere l'inclinazione). Questi trucchi sono comuni quando si affronta **OCR ad alta risoluzione** su documenti scansionati. + +--- + +## Passo 6: Gestire i Casi Limite e Ottimizzazioni di Prestazioni + +Anche i modelli meglio addestrati inciampano in alcuni scenari. Di seguito trovi un paio di correzioni rapide da incollare nello script. + +### 6.1 Fallback Quando Non C'è GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling di Immagini Molto Grandi + +Se la tua immagine supera i 4000 × 4000 px, potresti esaurire la memoria GPU. Esegui un down‑sampling proporzionale mantenendo i DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Questi snippet mantengono lo script robusto, sia che tu lo esegua su una workstation sia su un laptop modesto. + +--- + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco lo script completo che puoi copiare‑incollare ed eseguire subito: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Output previsto (esempio):** + + + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/italian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..03301e859 --- /dev/null +++ b/ocr/italian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-06 +description: Riconosci il testo da un'immagine usando il motore OCR Python. Scopri + come configurare il motore OCR in Python ed estrarre il testo da un'immagine con + l'elaborazione cloud in pochi minuti. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: it +og_description: Riconosci il testo da un'immagine con il motore OCR Python. Questa + guida mostra come configurare il motore OCR in Python ed estrarre il testo dall'immagine + in modo efficiente. +og_title: Riconosci il testo da un'immagine in Python – Tutorial completo di configurazione +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Riconoscere il testo da un'immagine in Python – Guida completa alla configurazione + del motore OCR +url: /it/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# riconoscere testo da immagine in Python – Tutorial completo di configurazione + +Ti sei mai chiesto come **riconoscere testo da immagine** usando solo poche righe di Python? Non sei l’unico. Che tu stia costruendo uno scanner per ricevute, un digitalizzatore di documenti o un semplice progetto hobby, saper estrarre testo da un’immagine è una competenza che paga rapidamente. + +In questo tutorial percorreremo l’intero processo—dalla configurazione dello **OCR engine python**, passando per l’autenticazione cloud, fino a mostrarti come **estrarre testo da immagine** con un risultato affidabile. Niente magia, solo passaggi chiari che puoi copiare‑incollare ed eseguire oggi. + +## Cosa imparerai + +- Come installare e importare la libreria OCR necessaria. +- I comandi esatti per **configure OCR engine python** per l’elaborazione cloud. +- Uno script completo, eseguibile, che **recognize text from image** e stampa l’output. +- Consigli per gestire problemi comuni come chiavi API mancanti o formati immagine non supportati. +- Idee avanzate come elaborazione batch e fallback locale. + +### Prerequisiti + +- Python 3.8+ installato sulla tua macchina. +- Una connessione a Internet (l’esempio utilizza un servizio OCR basato su cloud). +- Una chiave API valida dal provider OCR (vedrai dove inserirla). + +Se hai tutto questo, tuffiamoci—senza fronzoli, solo una guida pratica che funziona. + +--- + +## Passo 1: Installa la libreria OCR e importala + +Prima di poter **configure OCR engine python**, ti serve la libreria che comunica con il servizio cloud. Nel nostro esempio useremo un pacchetto fittizio ma rappresentativo chiamato `ocrcloud`. Sostituiscilo con il pacchetto reale che stai usando (ad es. `easyocr`, `google-cloud-vision`, ecc.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Perché è importante:** L’importazione della classe ti dà accesso a metodi come `use_cloud()` e `set_api_key()`. Senza l’importazione, il resto dello script genererebbe un `NameError`. + +*Consiglio esperto:* Blocca la versione nel tuo `requirements.txt` (`ocrcloud==2.1.0`) per evitare cambiamenti inattesi in futuro. + +--- + +## Passo 2: Crea e **configure OCR engine python** per la Modalità Cloud + +Ora configuriamo effettivamente **configure OCR engine python**. L’engine parte in modalità locale per impostazione predefinita; passare alla modalità cloud ti permette di delegare l’analisi pesante delle immagini a server potenti. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Spiegazione:** +- `OcrEngine()` crea un nuovo oggetto engine—pensalo come una tela vuota. +- `use_cloud(True)` attiva un interruttore, dicendo all’engine di inviare le immagini via HTTPS invece di elaborarle localmente. Questo è cruciale per risultati ad alta precisione su caratteri complessi o foto a bassa risoluzione. + +--- + +## Passo 3: Autenticati con la tua chiave API Cloud + +La maggior parte dei servizi OCR cloud richiede una chiave API. Questo passo mostra come inserire la credenziale in modo sicuro. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Nota di sicurezza:** Non inserire mai la chiave in un repository pubblico. In produzione la prenderesti da una variabile d’ambiente: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Passo 4: **recognize text from image** – Invia un’immagine remota per l’elaborazione + +Con l’engine configurato, possiamo finalmente **recognize text from image**. Il metodo `recognize_image()` accetta un percorso o un URL e restituisce un oggetto contenente il testo estratto. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Cosa succede dietro le quinte?** +I byte dell’immagine vengono caricati sul endpoint del provider, elaborati da un modello di deep‑learning, e il risultato in plain‑text viene restituito in streaming. Se l’immagine è grande, il servizio può ridimensionarla automaticamente per velocizzare il lavoro. + +--- + +## Passo 5: Stampa il risultato di **extract text from image** + +Ora che il servizio OCR ha completato il lavoro, stampiamo semplicemente il testo. In applicazioni reali potresti salvarlo in un database o passarne il risultato a un’altra funzione. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Output previsto:** (esempio) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Se l’output appare confuso, verifica che l’immagine sia nitida e che tu abbia selezionato il modello linguistico corretto (molti servizi consentono di specificare `engine.set_language("en")`). + +--- + +## Gestione dei casi limite e problemi comuni + +### 1. Chiave API mancante o non valida +Se visualizzi un errore di autenticazione, assicurati che: +- La chiave sia attiva e non scaduta. +- Venga letta correttamente dalla variabile d’ambiente. +- La tua rete consenta traffico HTTPS in uscita. + +### 2. Formati immagine non supportati +La maggior parte delle API OCR accetta JPEG, PNG e PDF. Provare con BMP o TIFF può generare una risposta “format not supported”. Converti con Pillow se necessario: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Limiti di velocità +I servizi cloud spesso limitano le richieste per minuto. Se raggiungi il limite, implementa un back‑off esponenziale: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Fallback a OCR locale +Se il cloud è inattivo, puoi tornare alla modalità locale: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Avere un fallback mantiene la tua app resiliente. + +--- + +## Esempio completo funzionante + +Mettendo tutto insieme, ecco uno script che puoi eseguire subito (sostituisci i valori segnaposto). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Eseguilo:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Dovresti vedere il testo estratto stampato sulla console, confermando che hai **recognize text from image** e **extract text from image** usando un workflow **configure OCR engine python** correttamente impostato. + +--- + +## Conclusione + +Abbiamo appena percorso un processo completo, end‑to‑end, che ti permette di **recognize text from image** in Python, dall’installazione della libreria all’autenticazione di un servizio cloud e infine **extract text from image** con una singola chiamata di funzione. Configurando **configure OCR engine python** nel modo giusto, ottieni sia flessibilità (cloud vs. locale) sia affidabilità (gestione corretta degli errori). + +Cosa fare dopo? Prova a processare in batch una cartella di ricevute, aggiungi il rilevamento della lingua, o sperimenta con PDF come input. Il cielo è il limite una volta che hai padroneggiato le basi. + +Buon coding, e sentiti libero di lasciare domande nei commenti—niente batte l’apprendimento condiviso! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Estrai testo da immagine con Aspose OCR – Guida passo‑passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Estrai testo da immagine – Riconosci la linea con Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Come estrarre testo da immagine preparando rettangoli in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/italian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..cc1878d94 --- /dev/null +++ b/ocr/italian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Esegui OCR su un'immagine usando Python e visualizza i punteggi di confidenza. + Scopri come filtrare le parole a bassa confidenza, impostare soglie e gestire i + casi limite. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: it +og_description: Esegui OCR su un'immagine in Python, controlla i livelli di confidenza + e filtra le parole a bassa confidenza. Questo tutorial ti guida attraverso un esempio + completo e funzionante. +og_title: Esegui OCR su immagine con Python – Guida completa +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Esegui OCR su un'immagine con Python – Guida completa passo passo +url: /it/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esegui OCR su Immagine con Python – Guida Completa Passo‑Passo + +Hai mai dovuto **eseguire OCR su file immagine** ma non sapevi come ottenere testo affidabile? Non sei solo: molti sviluppatori si trovano di fronte a parole estratte instabili e a un punteggio di confidenza misterioso. + +In questa guida entreremo subito in una soluzione funzionante: vedrai come eseguire OCR su immagine, leggere la confidenza complessiva e estrarre le parole a bassa confidenza che potrebbero richiedere una revisione manuale. Alla fine avrai uno script riutilizzabile, comprenderai perché ogni riga è importante e saprai come regolare la soglia di confidenza per i tuoi progetti. + +## Cosa Copre Questo Tutorial + +Percorreremo l’intero flusso di lavoro—dal caricamento di un’immagine alla stampa di un report ordinato delle parole che sono scese sotto l’80 % di confidenza. Lungo il percorso discuteremo di: + +* Scegliere un motore OCR solido (useremo **EasyOCR**, una popolare libreria OCR per Python) +* Interpretare l’attributo `confidence` che ogni risultato OCR restituisce +* Filtrare le parole con una **soglia di confidenza OCR** personalizzata +* Estendere lo script per l’elaborazione batch o per motori alternativi come **pytesseract** + +Non è necessaria alcuna esperienza pregressa con OCR, basta una familiarità di base con Python e un ambiente di lavoro funzionante (Python 3.9+ consigliato). + +Pronto a trasformare screenshot sfocati in testo pulito e ricercabile? Iniziamo. + +--- + +## ## Come Eseguire OCR su Immagine con Python + +Il cuore del tutorial è uno snippet a tre passaggi che rispecchia il codice che hai già visto. Di seguito analizzeremo ogni riga, spiegheremo il perché e poi ti forniremo uno script completo pronto da copiare‑incollare. + +### Passo 1: Installa e Importa il Motore OCR + +Per prima cosa, assicurati che la libreria OCR sia disponibile. **EasyOCR** funziona subito per molte lingue e fornisce un punteggio di confidenza per parola. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Perché EasyOCR?* Include un modello di deep‑learning addestrato su dataset diversificati, quindi ottieni tipicamente valori di confidenza più alti rispetto al vecchio motore Tesseract, soprattutto su immagini di qualità mista. + +> **Consiglio professionale:** Se lavori in un ambiente limitato (ad es. un piccolo container Docker), `pytesseract` potrebbe essere più leggero, ma perderai parte della precisione moderna offerta da EasyOCR. + +### Passo 2: Esegui OCR sull'Immagine + +Ora **eseguiamo OCR su immagine**. Il metodo `recognize_image` dell’esempio originale è sostituito dalla chiamata `readtext` di EasyOCR, che restituisce una lista di tuple `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Ogni voce in `ocr_results` appare così: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Il terzo elemento (`0.92` nell’esempio) è il punteggio di confidenza, compreso tra 0 e 1. + +### Passo 3: Riassumi la Confidenza Complessiva + +Diversamente dallo snippet precedente che stampava un singolo attributo `confidence`, EasyOCR fornisce una confidenza per parola. Per avere una panoramica generale, ne calcoleremo la media: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Perché la media?* Ti dà un rapido controllo di salute—se la confidenza complessiva è sotto, ad esempio, il 70 %, probabilmente dovrai migliorare l’immagine (migliore illuminazione, pre‑elaborazione, ecc.). + +### Passo 4: Elenca le Parole a Bassa Confidenza + +Ora arriva la parte che risponde direttamente alla richiesta “elencare le parole la cui confidenza è inferiore alla soglia desiderata”. Imposteremo una **soglia di confidenza OCR** di 0.80 (80 %) per impostazione predefinita, ma potrai modificarla. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Il ciclo stampa ogni parola che non ha superato la soglia, insieme alla sua percentuale di confidenza. Questo è l’esatto analogo del ciclo originale `for recognized_word in recognition_result.words`, ma ora funziona con il formato di output di EasyOCR. + +--- + +## ## Comprendere i Punteggi di Confidenza OCR + +La confidenza non è un numero magico; è la stima del modello su quanto sia sicuro della trascrizione specifica. Ecco alcune cose da tenere a mente: + +| Situazione | Confidenza Tipica | Cosa Fare | +|------------|-------------------|-----------| +| Scansione chiara ad alta risoluzione | 0.95 – 1.00 | Nessun lavoro aggiuntivo necessario | +| Leggero sfocamento o illuminazione non uniforme | 0.80 – 0.94 | Considera una leggera pre‑elaborazione (aumento contrasto) | +| Rumore intenso, testo ruotato | < 0.70 | Applica pre‑elaborazione (deskew, denoise) o passa a un motore OCR diverso | + +> **Attenzione:** Alcune lingue (ad es. scrittura corsiva) producono naturalmente punteggi più bassi. Regola la soglia di conseguenza. + +### Casi Limite e Varianti + +1. **Elaborazione Batch** – Se devi **eseguire OCR su file immagine** in blocco, avvolgi la logica sopra in un ciclo che itera su una directory. +2. **Molteplici Lingue** – Passa una lista come `['en', 'fr']` a `easyocr.Reader` e il motore rileverà entrambe. +3. **Motori Alternativi** – Vuoi provare **pytesseract**? Sostituisci il blocco del lettore con: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Dovrai poi aggregare le confidenze per carattere in valori per parola—un po' più di lavoro ma fattibile. + +4. **Trucchi di Pre‑elaborazione** – L’applicazione di filtri OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) può aumentare la confidenza per scansioni rumorose. + +--- + +## ## Script Completo, Pronto‑All‑Uso + +Di seguito trovi il file Python completo che puoi inserire nel tuo progetto. Salvalo come `ocr_report.py` ed esegui `python ocr_report.py`. Assicurati che il percorso dell’immagine punti a un file reale. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Output previsto** (i numeri varieranno): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Se ogni parola supera la soglia dell’80 % vedrai il messaggio amichevole “All words meet the confidence threshold.” al posto. + +--- + +## ## Domande Frequenti (FAQ) + +**D: Funziona con i PDF?** +R: Non direttamente. Converti ogni pagina PDF in immagine prima (ad es. con `pdf2image`) e poi passa il PNG/JPEG allo script. + +**D: I miei numeri di confidenza sono tutti bassi—cosa posso fare?** +R: Prova la pre‑elaborazione dell’immagine: aumenta il contrasto, rimuovi il rumore di fondo o ruota l’immagine su una linea orizzontale. EasyOCR accetta anche un parametro `contrast_ths` che puoi regolare. + +**D: Posso esportare i risultati in CSV?** +R: Assolutamente. Dopo il ciclo delle parole a bassa confidenza, scrivi `ocr_results` in un `csv.DictWriter` dove ogni riga contiene `text`, `confidence` e le coordinate del bounding‑box. + +**D: Esiste una versione accelerata da GPU?** +R: EasyOCR utilizza automaticamente CUDA se è presente una GPU compatibile e PyTorch è installato. Verifica con `torch.cuda.is_available()` prima di eseguire lo script. + +--- + +## Conclusione + +Abbiamo appena **eseguito OCR su immagine** usando Python, ispezionato la confidenza complessiva e isolato le parole a bassa confidenza che necessitano di revisione manuale. + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/japanese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..87e1ece61 --- /dev/null +++ b/ocr/japanese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-06-06 +description: 数分でPython OCRを使って画像からテキストを抽出できます。多言語画像OCRや自動言語検出OCR、そしてOCRテキストを正確に抽出する方法をご紹介します。 +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: ja +og_description: Python OCRで画像からテキストをすばやく抽出しましょう。多言語画像OCR、言語自動検出OCR、そしてOCRテキストの抽出手順をステップバイステップで学びます。 +og_title: Python OCRで画像からテキストを抽出する – 完全ガイド +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Python OCRで画像からテキストを抽出する – 完全ガイド +url: /ja/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR を使用した画像からのテキスト抽出 – 完全ガイド + +画像から **テキストを抽出** したいが、複数言語を自動で処理できるライブラリが分からない…という経験はありませんか?開発者は国際文書、領収書、スキャンしたチラシを扱う際に、*OCR テキストを抽出する方法* を頻繁に質問します。このチュートリアルでは、画像からテキストを抽出するだけでなく、**言語を自動検出** する実用的な Python の例を順を追って解説します。これにより、多言語画像 OCR が簡単になります。 + +OCR パッケージのインストールから **自動言語検出 OCR** の有効化、サンプル画像でエンジンを実行し、検出された言語と抽出された文字列の両方を出力するまでを網羅します。最後まで読めば、翻訳パイプラインやデータインジェストサービスを構築する際に、どのプロジェクトにもすぐに組み込める再利用可能なスニペットが手に入ります。 + +## 画像からテキスト抽出 – 環境構築 + +コードに入る前に、作業環境が以下の最低要件を満たしていることを確認してください。 + +- Python 3.8 以上(ライブラリは型ヒントを使用しており、古いバージョンでは無視されます) +- `pip` によるパッケージ管理 +- 少なくとも 2 種類の言語(例:英語 + スペイン語)が混在したテキストを含む画像ファイル + +このデモで使用する OCR ライブラリも必要です。本ガイドでは、実際のツール(Tesseract や EasyOCR)に似た架空の `ocr` パッケージを使用しますが、同様の API を持つ実際のライブラリでも置き換えて利用できます。 + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **プロのコツ:** 権限エラーが出た場合はコマンドの先頭に `python -m` を付けるか、仮想環境を使用してください。グローバルの site‑packages が汚染されません。 + +## OCR エンジンインスタンスの作成 + +ライブラリの準備ができたら、最初のステップは **OCR エンジンインスタンスを作成** することです。エンジンは画像を投入する前に設定できるスマートスキャナと考えてください。 + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +なぜ静的メソッドを直接呼び出さずにエンジンをインスタンス化するのか?エンジンオブジェクトは言語設定などの構成状態を保持します。これにより、複数の画像に対して同じ設定を再利用でき、毎回の初期化オーバーヘッドを削減できます。 + +## 自動言語検出 OCR の有効化 + +多くの OCR ツールは言語コード(英語は `eng`、スペイン語は `spa` など)を指定する必要があります。手動で言語を推測すると、**多言語画像 OCR** の本来の目的が失われます。幸い、`ocr` パッケージは *auto detect language OCR* モードを提供しており、画像を解析して最適な言語モデルを自動的に選択します。 + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +このように **detect language OCR** を有効にすれば、長大な言語コードリストを管理する必要がなくなります。エンジンは Latin、Cyrillic、Han などの文字体系を検出し、適切なモデルを自動でロードします。 + +## 多言語画像 OCR の実行 + +エンジンの準備ができたら、いよいよ **画像からテキストを抽出** します。`recognize_image` メソッドはファイルパスを受け取り、抽出されたテキストと検出された言語の両方を含む結果オブジェクトを返します。 + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +PDF から *OCR テキストを抽出* したい場合は、同じエンジンの `recognize_pdf` を使用すれば OK です。内部ロジックは同一なので、**自動言語検出 OCR** 機能もそのまま利用できます。 + +## 検出された言語と抽出テキストの表示 + +最後に、エンジンが見つけた情報を出力します。結果オブジェクトは `detected_language`(例: `en` や `es` の BCP‑47 タグ)と、OCR の生データを保持する `text` を公開します。 + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +サンプル画像でスクリプトを実行すると、次のような出力が得られるはずです。 + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +エンジンが英語を主要言語として正しく認識しつつ、スペイン語の行も正確に取得していることが分かります。これこそが堅牢な **多言語画像 OCR** ソリューションが提供すべき結果です。 + +### 検出が失敗した場合は? + +画像がぼやけていたり、文字体系が極端に珍しい場合、OCR エンジンはデフォルト言語(通常は英語)にフォールバックすることがあります。その際は言語リストを強制指定できます。 + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +ただし、言語を強制すると **auto detect language OCR** の利便性が失われるため、限定された言語セットが分かっている場合にのみ使用してください。 + +## よくある落とし穴と信頼性の高い OCR テキスト抽出方法 + +自動検出を利用しても、以下のような問題でつまずくことがあります。 + +1. **低解像度画像** – 150 dpi 未満では OCR 精度が急激に低下します。画像を拡大するか、より高解像度のスキャンを依頼してください。 +2. **ノイズ・圧縮アーティファクト** – 画像をエンジンに渡す前に、シンプルな閾値フィルタ(`opencv` や `Pillow`)で前処理すると効果的です。 +3. **1 ページに混在するスクリプト** – Latin と CJK 文字が同時に存在すると一部エンジンは苦手です。必要に応じてページを領域ごとに分割し、別々に認識させてください。 + +これらの対策を講じることで、**画像からテキストを抽出** するプロセスの品質が大幅に向上し、実務での多言語文書処理が格段に楽になります。 + +## 完全動作サンプル + +以下に、これまで説明したすべての手順を組み合わせた実行可能なスクリプトを示します。`multilingual_ocr.py` という名前で保存し、コマンドラインから実行してください。 + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**期待される出力**(サンプル画像に英語とスペイン語が含まれている場合): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +`multilang_page.png` を、他の言語が混在した任意の画像に差し替えても構いません。**自動言語検出 OCR** が有効なので、適切な言語タグと対応するテキストが得られます。 + +![画像からテキストを抽出する例](https://example.com/ocr-sample.png "画像からテキストを抽出する例") + +## 結論 + +これで **画像から OCR テキストを抽出** する方法、**自動言語検出 OCR** を有効にする手順、そして最小限のコードで **多言語画像 OCR** シナリオに対応する方法がマスターできました。OCR エンジンインスタンスを作成し、言語自動検出をオンにし、`recognize_image` を呼び出すだけで、言語識別子と生テキストの両方を確実に取得できます。 + +次のステップは?抽出した文字列を翻訳 API に渡す、検索可能なデータベースに保存する、または複数ページを 1 つの PDF レポートにまとめる、などです。Tesseract、EasyOCR、Google Vision など別の OCR バックエンドに切り替えても、同じ高レベルワークフローが使えるのが **detect language OCR** インターフェースの強みです。 + +問題が発生したら「よくある落とし穴」セクションを再確認するか、画像前処理のパラメータを調整してください。コーディングを楽しみながら、正しく検出・抽出されたテキストが次のプロジェクトで活躍することを願っています! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースは完全なコード例とステップバイステップの解説を含んでおり、API の追加機能習得や別実装アプローチの探求に役立ちます。 + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/japanese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..b7d3d7f2b --- /dev/null +++ b/ocr/japanese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR を使用して画像 PDF からテキストを抽出します。非同期バッチ認識でスキャンした文書を迅速にテキストに変換する方法を学びましょう。 +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: ja +og_description: Pythonで画像PDFからテキストを抽出する。ステップバイステップのガイドで、非同期OCRを使用してスキャンした文書をテキストに変換する方法を示します。 +og_title: 画像PDFからテキストを抽出 – Python OCRチュートリアル +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: 画像PDFからテキストを抽出 – スキャンした文書をテキストに変換するPythonガイド +url: /ja/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 画像PDFからテキスト抽出 – スキャンした文書をテキストに変換するPythonガイド + +何度も **画像PDFからテキストを抽出** したくて、何時間も手入力するのに疲れたことはありませんか?このガイドでは、シンプルな非同期OCRワークフローを使って **スキャンした文書をテキストに変換** する方法をPythonで紹介します。 + +スキャンしたPDFが山積みで「もっと速くできないか?」と思ったことがあるなら、ここがその答えです。コードを一行ずつ解説し、各部分がなぜ重要かを説明し、遭遇しうるいくつかのエッジケースも取り上げます。 + +## 学べること + +- OCRエンジンを起動し、認識言語を設定する方法。 +- PNGとPDFを混在させたリストをバッチ認識器に渡す仕組み。 +- OCRジョブを非同期で実行し、アプリの応答性を保つ方法。 +- 結果を取得し、元ファイルと組み合わせて、きれいに出力する方法。 + +**前提条件**: Python 3.8以上、`asyncio` または `concurrent.futures` の基本的な理解、そして例で使用しているような `OcrEngine` クラスを提供するOCRライブラリ(例: Aspose.OCR、Tesseractラッパー、またはカスタムラッパー)。重いセットアップは不要で、ライブラリをインストールすればすぐに使用できます。 + +![画像PDFからテキスト抽出](https://example.com/placeholder.png "OCR出力のスクリーンショット – 画像PDFからテキスト抽出") + +## 画像PDFからテキスト抽出 – OCRエンジンの設定 + +最初に必要なのは、文書の言語に合わせて設定されたOCRエンジンのインスタンスです。ここではフランス語を使用しますが、任意のサポートされている言語に変更可能です。 + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**なぜ重要か**: 言語を事前に設定することで精度が大幅に向上します。エンジンは言語固有の辞書と文字モデルを使用するため、誤った言語を指定すると文字化けした出力になることがよくあります。 + +## ファイルリストの準備 – 画像とPDFを同時に扱う + +バッチ認識器はラスタ画像(`.png`、`.jpg`)とPDFコンテナの両方を処理できます。ファイルパスの普通のPythonリストを渡すだけです。 + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**ヒント**: リストはフラットに保ちます。エンジンは内部で各PDFページを画像に展開してから認識します。ファイルが数千件ある場合は、メモリ使用量の急増を防ぐためにリストを小さなバッチに分割すると良いでしょう。 + +## 非同期バッチ認識の開始 + +メインスレッドをブロックせずに、OCRジョブをバックグラウンドで起動します。このメソッドは最終的に `OcrResult` オブジェクトのリストを保持する `Future` を返します。 + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**動作概要**: エンジンは内部でスレッドプール(または実装に応じた非同期タスク)を生成します。これにより、重い処理が別スレッドで行われている間に、UIの更新やファイルの取得、進捗のロギングなど他の作業を続けられます。 + +## OCR実行中に有用な処理を行う + +一般的なミスは、何もしないでFutureを頻繁にポーリングすることです。その代わりに、無関係な作業を実行できます。デモとして、ステータス行を出力するだけにします。 + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Future完了後に結果を取得する + +OCR出力を取得する準備ができたら、`concurrent.futures` の `as_completed` を使用します。このパターンは、1つでも複数でも機能します。 + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**出力例**: 各ファイルパスの後に抽出されたプレーンテキストが表示されます。PDFの場合、`result.text` には全ページのテキストが結合された形で含まれます。 + +### 期待される出力(例) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +文字が抜けている場合は、設定した言語が文書の言語と一致しているか再確認し、エンジンに渡す前に画像の前処理(傾き補正、コントラスト向上)を検討してください。 + +## エッジケースと一般的な落とし穴の対処 + +| 状況 | 対策 | +|-----------|------------| +| **混在言語** | まず言語検出を行い、言語ごとに別々のエンジンをインスタンス化します。 | +| **巨大PDF(> 100 MB)** | PDFをディスク上でページ単位に分割(例: `PyPDF2` 使用)し、個別エントリとして渡します。 | +| **非ラテン文字** | OCRライブラリに必要な言語パックが含まれていることを確認します。ライブラリによっては追加データファイルのダウンロードが必要です。 | +| **パフォーマンスボトルネック** | スレッドプールサイズを増やす(`engine.set_thread_pool_size(8)`)か、利用可能ならGPUアクセラレートバックエンドに切り替えます。 | +| **低解像度画像でテキスト欠損** | OpenCVで前処理(`cv2.resize`、`cv2.threshold`、`cv2.medianBlur`)を行い、可読性を向上させます。 | + +## 完全動作例(コピー&ペースト可能) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +`extract_text_async.py` として保存し、`YOUR_DIRECTORY` をファイルがあるパスに置き換え、OCRパッケージをインストール(`pip install your-ocr-lib`)して、`python extract_text_async.py` を実行します。先ほど示したコンソール出力が表示されるはずです。 + +## 次のステップ – 基本抽出を超えて + +- **ポストプロセッシング**: 余分な空白を除去し、Unicode正規化(`unicodedata.normalize`)やスペルチェッカーを実行してOCRノイズを除去します。 +- **構造化出力**: 結果をCSV、JSON、またはデータベースに直接エクスポートし、下流検索に利用します。 +- **並列バッチ**: 数百ファイルある場合は複数のFutureを立ち上げ、キューを使ってCPUを稼働させつつメモリ過負荷を防ぎます。 +- **ウェブフレームワークとの統合**: このスクリプトをFlaskやFastAPIのエンドポイントに組み込み、オンデマンドOCRサービスを提供します。 + +--- + +### TL;DR + +これで、OCRを非同期で実行する最小限のPythonスクリプトを使って **画像PDFからテキストを抽出** し、プログラムを応答性のまま **スキャンした文書をテキストに変換** できるようになりました。言語設定やバッチサイズ、前処理のテクニックを試して、文字精度を最大限に引き出してください。 + +手書きノートのOCRやクラウドベースのサービスなど、独自の工夫があればぜひ共有してください。コメントを残して、楽しいコーディングを! + +## 次に学ぶべきこと + +以下のチュートリアルは本ガイドで示した手法を基にした、密接に関連するトピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、追加のAPI機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [Aspose OCR を使用した画像からのテキスト抽出 – ステップバイステップガイド](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [フォルダー上での OCR 操作を使用して画像からテキストを抽出](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Aspose.OCR を使用した画像からのテキスト抽出 – 許可文字](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..b0a947536 --- /dev/null +++ b/ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: PythonでPDFをOCRし、PDFからテキストを抽出し、スキャンしたPDFのテキストを変換し、数行のコードでOCR言語を変更する方法。 +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: ja +og_description: PythonでPDFをOCRする方法:PDFからテキストを抽出し、スキャンしたPDFのテキストを変換し、OCR言語を簡単に変更できる実践的ガイド。 +og_title: PythonでPDFをOCRする方法 – 完全プログラミングチュートリアル +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: PythonでPDFをOCRする方法 – 完全ステップバイステップガイド +url: /ja/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PythonでPDFをOCRする方法 – 完全ステップバイステップガイド + +高価なSaaSツールに払わずに **PDFをOCRする方法** を知りたくありませんか? あなたは一人ではありません。古い本をデジタル化したり、請求書からデータを抽出したり、スキャンしたレポートから検索可能なテキストが必要だったりする場合、PythonでPDF OCRをマスターすれば手作業のコピーに費やす時間を大幅に削減できます。 + +このチュートリアルでは、**PDFからテキストを抽出** する簡潔で動作する例を順に解説し、**スキャンしたPDFテキストを編集可能な文字列に変換** する方法、さらに文書が英語でない場合に **OCR言語を変更** する方法も示します。最後まで読めば、どのプロジェクトにもすぐに組み込める再利用可能なスニペットが手に入ります。 + +## 前提条件とセットアップ + +始める前に以下を用意してください。 + +- Python 3.8+ がインストール済み(コードは 3.9、3.10、以降でも動作します) +- `ocr` パッケージ(`OcrEngine` クラスを提供)※ `pip install ocr-lib` でインストールできます(実際に使用しているパッケージ名に置き換えてください) +- 処理したい PDF ファイル;デモでは `high_res_book.pdf` を `YOUR_DIRECTORY` フォルダーに置きます + +仮想環境を使用している場合(強く推奨)、まずそれをアクティベートしてください: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **プロのコツ:** 後でパス関連のトラブルを防ぐため、PDF ファイルは専用の `data/` ディレクトリに置いておくと便利です。 + +## Step 1: OCR エンジンインスタンスの作成(How to OCR PDF – Initialization) + +**PDFに対してOCRを実行** したいときに最初に行うべきことは、エンジンをインスタンス化することです。エンジンは各ページを読み取り、文字形状を解釈し、プレーンテキストを返す「脳」のようなものです。 + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +なぜ重要かというと、エンジンがなければ言語設定やレンダリングオプション、PDF の取り扱いに関するコンテキストがありません。`OcrEngine` オブジェクトはこれらのデフォルトを保持し、後から調整できるようにします。 + +## Step 2: 認識言語の設定(Change OCR Language) + +多くの OCR ライブラリはデフォルトで英語ですが、文書がフランス語、ドイツ語、あるいは日本語の場合はどうでしょうか? 言語を変更するのは `set_recognition_language` を呼び出すだけです。これにより **OCR言語の変更** 要件を満たし、精度が向上します。 + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **この設定が必要になる理由:** 多言語アーカイブには混在した言語のページが含まれることが多いです。実行時に言語を切り替えることで「ß」や「ñ」などの文字が誤認識されるのを防げます。 + +## Step 3: PDF レンダリングオプションの構成(Convert Scanned PDF Text Effectively) + +スキャンした PDF を扱う際、解像度とカラーモードは OCR の品質に大きく影響します。300 DPI のグレースケールはほとんどの文書にとって最適なバランスで、ディテールを十分に捉えつつメモリ使用量も抑えられます。 + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +チェーン形式の呼び出しは見た目が派手ですが、同じオプションオブジェクトを返す流暢な API に過ぎません。カラー画像(例:カラー図表)が必要な場合は `"grayscale"` を `"color"` に置き換えてください。 + +## Step 4: PDF を認識し、最初のページのテキストを取得(Extract Text from PDF) + +ここが **PDFに対してOCRを実行** する核心部分です。エンジンにファイルパスを渡し、認識されたテキストを取得します。メソッドはページ結果のリストを返し、各結果は `text` 属性を持ちます。 + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +文書全体が必要な場合は `results` をイテレートします: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### PDF が暗号化されている場合は? + +一部の PDF はパスワードで保護されています。その場合は `recognize_pdf` にパスワードを渡すだけです: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +エンジンは OCR を実行する前にオンザフライで復号化するので、追加の手順は不要です。 + +## Step 5: 抽出テキストの後処理(Fine‑Tuning Extract Text from PDF) + +生の OCR 出力には改行や余分なスペース、時折の誤認識文字が含まれがちです。簡単なクリーンアップルーチンを実行すれば、抽出した文字列を検索インデックスやデータベース保存、その他の下流処理にすぐ使える形に整えられます。 + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +これで **PDFからテキストを抽出** でき、任意の NLP パイプラインや検索エンジン、あるいはシンプルな `open(...).write()` 操作に渡すことができます。 + +## Bonus: 複数 PDF のバッチ処理(Scaling Perform OCR on PDF) + +スキャンした PDF が多数ある場合は、ロジックをループで包みます: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +このスニペットは **PDFに対してOCRを実行** するバルク処理の方法を示しており、デジタル化プロジェクトでよく求められるニーズに応えます。 + +## Expected Output + +単ページの例(Step 4)を実行すると、次のような出力がコンソールに表示されます: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +複数ページの書籍を処理した場合、各ページのクリーンテキストがコンソールに表示され、バッチスクリプトは各 PDF の横に `.txt` ファイルを生成します。 + +## Common Pitfalls & How to Avoid Them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Low‑resolution source PDF | 文字化け、単語欠落 | DPI を上げる(`set_dpi(400)` 以上) | +| Wrong language set | 多数の不明シンボル、特にアクセント文字が誤認識 | `engine.set_recognition_language(ocr.Language.FRENCH)` など適切な enum を使用 | +| Large PDF causing memory error | `MemoryError` または数ページ後のクラッシュ | ページをチャンクで処理(`engine.recognize_pdf(..., max_pages=10)`) | +| Missing fonts in the PDF | 特定ページで空出力 | PDF が実際にラスタ画像を含んでいるか確認。ベクタのみの場合は別の処理が必要 | + +## Image Illustration + +以下はワークフローの簡易ビジュアルです。代替テキストは SEO を意識して作成しています。 + +![how to ocr pdf workflow diagram showing engine initialization, language setting, rendering options, recognition, and text extraction](/images/ocr-workflow.png) + +*この図はコード実行に必須ではありませんが、視覚的に各ステップの位置付けを理解したい学習者に役立ちます。* + +## Conclusion + +Python で **PDFに対してOCRを実行** する方法を、エンジン作成、**OCR言語の変更**、**スキャンしたPDFテキストの変換**、そして最終的な **PDFからテキストを抽出** まで一通り解説しました。完全に実行可能なサンプルはどのプロジェクトにもすぐに組み込め、オプションのバッチスクリプトでソリューションをスケールさせる方法も示しました。 + +次に試したいこと: + +- 言語リストをループして **PDFに対してOCRを実行** する多言語アーカイブ対応 +- 抽出テキストを Elasticsearch に統合し全文検索を実現 +- OCR で生成したテキストレイヤーを元のファイルに埋め込み、検索可能な PDF を作成(多くのライブラリは `save_as_searchable_pdf` メソッドを提供) + +自由に実験し、DPI 設定を調整したり、別の OCR バックエンドに切り替えたりしてみてください。基本は変わりませんので、これでしっかりとした土台ができました。 + +Happy coding, and may your scanned documents finally become searchable! + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能を習得したり、別の実装アプローチを自分のプロジェクトで試したりするのに役立ちます。 + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..76dd752f4 --- /dev/null +++ b/ocr/japanese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-06 +description: Python を使って PDF を OCR し、画像から検索可能な PDF ファイルを作成する方法。数分で検索可能なテキストを追加し、画像を + PDF/A に変換する方法を学びましょう。 +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: ja +og_description: PDFをステップバイステップでOCRする方法。シンプルなPythonスクリプトを使って検索可能なテキストを追加し、画像をPDF/Aに変換する方法を学びましょう。 +og_title: PDFをOCRする方法 – 検索可能なPDFを作成するクイックガイド +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: PythonでPDFをOCRする方法 – 画像から検索可能なPDFを作成 +url: /ja/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF を OCR する方法 – スキャン画像を検索可能な PDF に変換 + +請求書や領収書のスキャン画像しかないとき、**PDF を OCR する方法**を知りたくありませんか? あなただけではありません。多くのオフィスでは、受信した書類が PNG や JPEG のフラット画像として届き、次のステップである「内容を検索可能にする」作業がブラックボックスのように感じられます。 + +朗報です! Python の数行のコードで **検索可能な PDF** を作成し、**検索可能なテキストを追加**、さらには **PDF/A に変換** して長期保存も可能です。このチュートリアルでは、各ステップを順に解説し、すぐに実行できるスクリプトを提供します。 + +> **プロのコツ:** 同じアプローチは複数ページのスキャンでも機能します。ファイルをループさせるだけで、エンジンが重い処理を自動で行います。 + +--- + +## 必要なもの + +作業を始める前に、以下がマシンに揃っていることを確認してください。 + +| 必要条件 | 重要な理由 | +|----------|------------| +| Python 3.9 以上 | 最新構文と豊富なライブラリサポート | +| `pdfium` ベースの OCR エンジン(例: `pdfocr` または商用 SDK) | 画像認識と PDF/A 生成の両方を処理 | +| 検索可能な PDF に変換したい画像ファイル(PNG、JPEG、TIFF) | テキスト抽出元 | +| 出力フォルダへの書き込み権限 | スクリプトが新しい PDF を保存できるように | + +OCR SDK がまだインストールされていない場合は、以下を実行してください。 + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +これだけです—複雑なシステム依存は不要で、pip インストールだけです。 + +--- + +## PDF を OCR する方法 – 概要 + +全体の流れは大きく 3 つのシンプルなアクションで構成されます。 + +1. **画像内のテキストを認識**し、元のグラフィックを保持する。 +2. **OCR 結果と元画像を組み合わせて検索可能な PDF/A**(アーカイブ向け PDF)としてエクスポート。 +3. **生成されたファイルに、元画像上に選択可能で検索可能なテキスト層があることを検証**。 + +以下にコードとともに、各コマンドの *なぜ* を解説します。 + +--- + +## ステップ 1: 画像からテキストを認識 + +まず OCR エンジンにピクセルを読み取らせ、元画像と抽出テキストの両方を保持した結果オブジェクトを取得します。請求書をエンジンが「読む」イメージです。 + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### なぜ重要か + +- **グラフィックの保持** により、レイアウト(表、ロゴ、スタンプ)がスキャナが捉えたまま正確に残ります。 +- `result` オブジェクトには、後で PDF に埋め込む隠れたテキスト層が通常含まれます。 +- `recognize_image` を使用することで、`recognize_pdf` に比べて余分な変換ステップが省かれ、単ページ画像の処理が高速化します。 + +#### よくあるバリエーション + +- **マルチページ TIFF** がある場合はファイルパスを直接渡してください。ほとんどのエンジンは各ページを別々の画像として扱います。 +- 画像をすでに含む PDF がある場合は `engine.recognize_pdf("file.pdf")` を呼び出せば、このステップは不要です。 + +--- + +## ステップ 2: OCR 結果を検索可能な PDF/A としてエクスポート + +ステップ 1 の `result` を受け取り、エンジンに新しいファイルを書き出させます。ここで重要なのは *PDF/A* フラグ—長期保存向けに設計された ISO 標準の PDF バージョンです。 + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### なぜ重要か + +- **検索可能な PDF**: 出力ファイルには隠れた選択可能テキスト層が含まれます。これで文書内を Ctrl + F で検索できます。 +- **PDF/A 準拠**: 法務や財務など、一部の組織は監査証跡のために PDF/A を必須としています。このステップで自動的に要件を満たします。 +- 画像をフラット化せずに **検索可能なテキストを追加** できるため、視覚的な忠実度が保たれます。 + +#### エッジケース: 通常の PDF が欲しい場合 + +PDF/A が不要なら `save_as_pdfa` を `save_as_pdf` に置き換えてください。残りのワークフローは同じです。 + +--- + +## ステップ 3: 検索可能な PDF を検証 + +簡単なサニティチェックで、後々の不思議なバグを防げます。生成されたファイルを任意の PDF ビューアで開き、単語を選択して検索機能を試してください。 + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### 期待される出力 + +スクリプト実行時、コンソールに次のように表示されます。 + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +ファイルを開くと、元の請求書画像の上に薄く見えないテキスト層があるはずです。任意の単語をハイライトすると選択可能になっていることが確認できます—**これが先ほど追加した検索可能テキスト**です。 + +--- + +## 既存 PDF に検索可能テキストを追加する(ボーナス) + +既に PDF があり、そこに **検索可能テキストを追加** したいケースがあります。同じエンジンで OCR 結果を既存 PDF にオーバーレイできます。 + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +ここで `apply_to` が隠れ層と元ページをマージし、**再スキャンせずに検索可能な PDF** を作成します。 + +--- + +## よくある落とし穴と対策 + +| 落とし穴 | 回避策 | +|----------|--------| +| **低解像度の画像** (< 150 dpi) | 解像度を上げるか、より高解像度のスキャンを依頼。150 dpi 未満では OCR 精度が大幅に低下します。 | +| **言語データが欠如** | OCR エンジン用の言語パックをインストール(例: `pip install pdfocr[eng,spa]`)。 | +| **出力フォルダが書き込み不可** | 十分な権限でスクリプトを実行するか、別ディレクトリを指定。 | +| **PDF/A 検証に失敗** | 非対応フォントや JavaScript を埋め込んでいないか確認。`save_as_pdfa` を使用すれば多くの SDK が自動で対処します。 | + +--- + +## フルスクリプト – ワンファイルソリューション + +以下はすべてをまとめた自己完結型スクリプトです。プレースホルダーのパスを差し替えるだけで、**画像を PDF/A に変換**できるようになります。 + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**スクリプトの流れ:** +1. OCR エンジンをロード。 +2. 指定画像を読み取り、テキストを抽出。 +3. **検索可能な PDF/A** を生成し、すぐに配布またはアーカイブ可能。 + +フォルダ全体を処理したい場合は、`main` ロジックを関数化し、`os.listdir()` でイテレートして各ファイルに対して同じ 3 ステップを繰り返すだけです。 + +--- + +## 次のステップ & 関連トピック + +**OCR PDF** をマスターした今、以下の応用アイデアを検討してください。 + +- **バッチ処理:** `concurrent.futures` を使って数十件の請求書を並列 OCR。 +- **メタデータ注入:** 作成日や請求書番号を PDF メタデータに追加し、インデックス化を容易に。 +- **ハイブリッド PDF:** 検索可能テキストと元画像を組み合わせ、紙文書の「デジタルツイン」を実現。 +- **代替出力:** 下流システムが編集可能形式を必要とする場合は **DOCX** や **HTML** へエクスポート。 + +これらはすべて、今回学んだ「認識 → エクスポート → 検証」のコア概念に基づいています。 + +--- + +## まとめ + +要するに、**画像を検索可能な PDF/A に変換**する方法を 3 行の Python で実装できるようになりました。スクリプトは重い処理を担い、元のグラフィックを保持し、標準準拠の文書を即座に検索・保存・共有できます。 + +自分の請求書、領収書、スキャンした契約書で試してみてください。問題があればコメントを残すか、SDK の公式ドキュメントを確認してください。コードを書いて楽しく検索可能な画像を作りましょう! + +![元画像と検索可能な PDF オーバーレイを示す OCR PDF の例](placeholder.png "How to OCR PDF example showing original image and searchable PDF overlay") + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを基にした、密接に関連するトピックを扱っています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能を習得したり、独自プロジェクトで代替実装アプローチを探求したりするのに役立ちます。 + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/japanese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..e372c0ae6 --- /dev/null +++ b/ocr/japanese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-06-06 +description: Aspose OCR Cloud を使用した PDF の OCR 方法。PDF からテキストを抽出し、PDF ページを PNG に変換し、Python + で PDF ページ画像を保存する方法を学びます。 +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: ja +og_description: Aspose OCR Cloud を使用して PDF を OCR する方法。このガイドでは、プレーンテキスト PDF の抽出、PDF + ページを PNG に変換、PDF ページ画像の保存方法を示します。 +og_title: Aspose OCR CloudでPDFをOCRする方法 – ステップバイステップ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Aspose OCR CloudでPDFをOCRする方法 – 完全ガイド +url: /ja/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR CloudでPDFをOCRする方法 – 完全ガイド + +重いデスクトップツールと格闘せずに **PDFをOCRする方法** を考えたことはありませんか? あなたは一人ではありません—スキャンした文書からテキストを素早くプログラム的に抽出する必要がある開発者は多く、この壁にぶつかります。良いニュースは、Aspose OCR Cloudを使えば **PDFからテキストを抽出** でき、各ページをPNGに変換し、さらには **PDFページ画像を保存** して後で利用することも、きれいなPythonスクリプトだけで実現できます。 + +このチュートリアルでは、SDKのインストール、エンジンのライセンス設定、マルチページPDFの認識から、プレーンテキストの抽出、ページのPNG変換、画像のディスクへの永続化まで、必要なすべての手順を解説します。最後まで読めば、**PDFをOCRする方法** の機能を必要とする任意のプロジェクトに組み込める再利用可能なスニペットが手に入ります。 + +## What You’ll Need + +- **Python 3.8+**(コードは3.10以降でも動作します) +- Aspose OCR Cloud アカウント – 無料トライアルのライセンスファイル(`Aspose.OCR.lic`)が取得できます +- `asposeocrcloud` パッケージ(`pip install asposeocrcloud`) +- 処理したいスキャン済みのマルチページPDF + +## How to OCR PDF – Setup and License + +OCR メソッドを呼び出す前に、SDK に自分が誰かを知らせる必要があります。Aspose は軽量なライセンスファイルを使用し、スクリプトからアクセス可能な場所に配置します。 + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* ライセンス手順を省略すると、SDK は動作しますが出力画像に小さな透かしが埋め込まれます。実運用には適しません。 + +## Step 2: Install the Aspose OCR Cloud Python SDK + +ターミナルを開き、以下を実行します: + +```bash +pip install asposeocrcloud +``` + +このパッケージは必要な依存関係(requests、pillow など)をすべて自動で取得するため、別途探す必要はありません。 + +## Step 3: Create an OCR Engine and Choose a Language + +エンジンは処理の中心です。Aspose がサポートする任意の言語を指定できます。英語はほとんどの場合で機能します。 + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +言語を設定する理由は、OCR エンジンが言語固有の辞書を使用して精度を向上させるためです。フランス語のPDFを処理する場合は、`ENGLISH` を `FRENCH` に置き換えるだけです。 + +## Step 4: Point to Your Multi‑Page PDF + +エンジンに処理したいファイルへのフルパスを指定します。相対パスでも、スクリプトの作業ディレクトリから解決できれば問題ありません。 + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +ファイルが読み取り可能であることを確認してください。そうでない場合は `FileNotFoundError` が発生します。 + +## Step 5: Run OCR – You Get a List of Results + +`recognize_pdf` を呼び出すと、元のPDFの各ページに対応する要素が含まれるリストが返されます。 + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +各 `OcrResult` には便利なプロパティが2つあります: + +* `text` – ページのプレーンテキスト表現(**extract plain text pdf** に最適) +* `image` – レンダリングされたページの Pillow `Image` オブジェクト(**convert pdf page png** に最適) + +## Step 6: Extract Text from PDF and Convert Pages to PNG + +ここでは結果をループし、抽出したテキストを出力し、各ページの PNG バージョンを保存します。 + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Expected Console Output + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +`page_1.png`、`page_2.png` … が `YOUR_DIRECTORY` に生成されます。これらは下流の画像処理パイプラインに渡せるラスタライズされたページ画像です。 + +## Step 7: Save PDF Page Images (Optional Post‑Processing) + +画像だけが必要でテキストが不要な場合は `print(res.text)` 行を省略できます。逆にテキストを別々の `.txt` ファイルに保存したい場合は、以下のように小さな書き出しを追加するだけです: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +この小さな追加により、**PDFページ画像を保存**しつつ抽出したコンテンツを永続化するのがいかに簡単かが分かります。 + +## Full Working Example + +すべてをまとめると、`ocr_pdf.py` にコピー&ペーストできる完全なスクリプトは以下の通りです: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +以下のコマンドで実行します: + +```bash +python ocr_pdf.py +``` + +各ページのテキストがコンソールに出力され、PNG ファイルが一連で生成されるはずです。 + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示した手法を基にした関連トピックを扱っています。各リソースには、ステップバイステップの解説付きの完全なコード例が含まれており、追加の API 機能を習得したり、独自プロジェクトで代替実装アプローチを検討したりするのに役立ちます。 + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/japanese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..64edacb75 --- /dev/null +++ b/ocr/japanese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-06-06 +description: Python を使った OCR 用画像の前処理方法。Otsu 法で画像を二値化する方法、スキャンした文書の傾きを補正する方法、そしてドイツ語テキストの + OCR 精度を向上させる方法を学びます。 +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: ja +og_description: PythonでOCR用に画像を前処理する方法。このチュートリアルでは、Otsu法を用いた画像の二値化、スキャンした文書の傾き補正、そしてドイツ語画像のOCR精度を向上させる方法を示します。 +og_title: OCR用画像の前処理方法 – 完全Pythonガイド +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: OCRのための画像前処理方法 – 完全Pythonガイド +url: /ja/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 用画像前処理の完全ガイド(Python) + +画像を OCR 用に **前処理する方法** を知りたくありませんか?テキストがくっきりと抽出できるようにしたいですよね。特にノイズが多いドイツ語のスキャンページは、どの OCR エンジンにとっても悪夢です。朗報です!数ステップの賢い前処理で、ぼやけた斑点だらけのスキャンを、機械が読み取りやすいクリーンな画像に変えることができます。 + +このチュートリアルでは、Python を使って **画像を OCR 用に前処理する方法** を実例で解説します。**Otsu による二値化**、**スキャン文書の傾き補正(デスキュー)**、そして **ドイツ語画像からテキストを抽出** する際の **OCR 精度向上** のポイントを学びます。余計な説明は省き、すぐにコピー&ペーストできる実働スクリプトを提供します。 + +## 必要なもの + +- **Python 3.9+**(最近のバージョンならどれでも可) +- `OcrEngine` クラスを提供する OCR ライブラリ – デモでは汎用的な `ocr` パッケージを想定しています。`pip install ocr-lib` でインストールしてください。 +- テスト用のノイズが多いドイツ語スキャン画像(`noisy_german_scan.tif`) +- Python 関数の基本的な理解(`def` が書ければ問題なし) + +> **プロのコツ:** 別の OCR SDK(例: `pytesseract` 経由の Tesseract)を使う場合でも、概念は同じです。メソッド名だけ置き換えてください。 + +## ソリューションの概要 + +1. **OCR エンジンのインスタンスを作成** +2. **認識言語をドイツ語に設定** +3. **デスキュー、デノイズ、二値化(Otsu)、コントラスト伸長を含むカスタム前処理パイプラインを構築** +4. **パイプラインをエンジンに登録** して、すべての画像が自動的に通過するようにする +5. **ノイズの多いドイツ語スキャンに対して OCR を実行** +6. **抽出されたテキストを出力** して結果を確認 + +以下で各ステップを分解し、**なぜ重要か** を説明しながら、必要なコードを示します。 + +![how to preprocess images for OCR example](image.png "how to preprocess images for OCR example") + +## ステップ 1: OCR エンジンのインスタンスを作成 + +まずはエンジンがなければ何も起きません。`OcrEngine` オブジェクトは、以降のすべての処理を統括するエントリーポイントです。 + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*重要ポイント:* エンジンの初期化で内部リソース(言語モデルなど)が確保され、後からカスタムパイプラインを付けられるクリーンな状態になります。 + +## ステップ 2: 認識言語をドイツ語に設定 + +OCR の精度は言語に大きく依存します。エンジンにドイツ語を期待させることで、正しい文字セットとモデルが有効になります。 + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +この設定を省くと、エンジンはデフォルトで英語になる可能性があり、ウムラウト(ä, ö, ü)や ß が正しく認識されません。ドイツ語スキャンではよくある落とし穴です。 + +## ステップ 3: カスタム前処理パイプラインを構築 + +ここが **画像を OCR 用に前処理する方法** の核心です。4 つの変換をチェーンします。 + +| 変換 | 内容 | 効果 | +|------|------|------| +| **Deskew** | 画像を水平に回転させる(最大 5°) | スキャンは完璧に揃っていることは稀です。傾きを除去することで文字分割が容易になります。 | +| **Denoise** | ランダムな斑点を低減(強度 0.7) | ノイズは偽のエッジを生み、OCR が文字と誤認する原因になります。 | +| **Binarize (Otsu)** | Otsu 法で白黒二値化 | クリーンな二値画像は、前景(文字)と背景のコントラストを最大化します。 | +| **Contrast Stretch** | ダイナミックレンジを拡張 | 薄い筆跡や古い文書の可読性が向上します。 | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### スキャン文書の傾き補正(デスキュー)の方法 + +上記の `deskew` 呼び出しが **スキャン文書の傾き補正(デスキュー)** の具体例です。内部ではハフ変換で支配的なテキストライン角度を推定し、画像を回転させます。回転角が 5° を超える場合は `max_angle` を上げてください。ただし過度な回転はアーティファクトの原因になるので注意が必要です。 + +### Otsu による二値化 + +`binarize(method="otsu")` 行は **Otsu による二値化** の直接的な回答です。Otsu のアルゴリズムはクラス間分散を最小化する閾値を算出し、暗い文字と明るい背景という二峰性ヒストグラムに最適です。 + +## ステップ 4: パイプラインをエンジンに登録 + +ここで作成したパイプラインを OCR エンジンに結び付け、すべての入力画像が自動的に前処理されるようにします。 + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*重要ポイント:* 登録しなければエンジンは生のスキャンをそのまま処理し、先ほど設定したクリーニングは無視されます。このステップが **OCR 精度を向上させる方法** の鍵です。 + +## ステップ 5: ノイズの多いドイツ語スキャンからテキストを認識 + +すべてを組み合わせます。エンジンにノイズの多いドイツ語画像を渡し、重い処理を任せます。 + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +パフォーマンスが気になる場合は、呼び出し時間を測定できます。 + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## ステップ 6: 認識結果を出力 + +最後に抽出された文字列を表示します。これが **ドイツ語画像からテキストを抽出** する直接的な答えです。 + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### 期待される出力例 + +サンプルスキャンに「Die schnelle braune Füchsin springt über den faulen Hund.」という文が含まれていると仮定すると、次のような出力が得られるはずです。 + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +出力にまだ文字化けが残る場合は、`denoise` の強度を調整するか、`max_angle` を大きくしてデスキューを強化してください。 + +## よくある落とし穴と対処法 + +- **言語モデルが欠如:** `set_recognition_language(Language.GERMAN)` を忘れるとウムラウトが抜け落ちます。呼び出しを必ず確認してください。 +- **過度なデノイズ:** 強度が 0.9 を超えると細い筆跡が消えてしまいます。多くの場合は 0.5‑0.7 が安全です。 +- **ファイル形式の不一致:** マルチページ TIFF に弱いエンジンがあります。マルチページ文書は単ページファイルに分割してから処理しましょう。 +- **パイプラインの順序:** 示した順序(デスキュー → デノイズ → 二値化 → コントラスト伸長)は意図的です。二値化を先に行うとノイズが固定化され、後から除去できません。必ずデノイズを先に実行してください。 + +## パイプラインの拡張(次のステップは?) + +ベースラインができたら、以下のような拡張を検討できます。 + +- **形態学的オープニング**で微小ブロブを除去(`.morph_open(kernel=3)`) +- **言語モデル統合**で事後補正(`ocr_engine.apply_spellcheck()`) +- **バッチ処理の並列化**(`concurrent.futures`)で大規模データセットを高速化 + +これらはすべて **画像を OCR 用に前処理する方法** の核を保ちつつ、**OCR 精度を向上させる方法** をさらに強化します。 + +## 結論 + +本稿では **画像を OCR 用に前処理する方法** を、エンジン作成・ドイツ語設定・Otsu による二値化・スキャン文書の傾き補正・テキスト抽出という 6 ステップで網羅しました。これらを実行すれば、認識品質が目に見えて向上し、手作業での修正が激減します。 + +ぜひ自分のスキャンでスクリプトを試し、パラメータを調整して結果を確かめてみてください。特定の前処理に関する質問があればコメントで教えてください。一緒に深掘りしていきましょう。 + +Happy coding, and may your OCR be ever accurate! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示した手法を応用した関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全なコード例が含まれているので、API の追加機能習得や別実装への展開に役立ちます。 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..926a43e69 --- /dev/null +++ b/ocr/japanese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-06-06 +description: PythonでPNG画像のOCR – 画像からテキストを抽出する方法を学び、PythonのOCRサンプルを実行し、さらには古代ギリシャ語のテキストまで簡単に読むことができます。 +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: ja +og_description: PythonでのOCR PNG画像の解説。このガイドでは、画像からテキストを抽出する方法、PythonのOCR例を実行する方法、そして古代ギリシャ語を簡単に読む方法を示します。 +og_title: PythonでPNG画像のOCR – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: PythonでPNG画像のOCR – 完全ステップバイステップガイド +url: /ja/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PythonでOCR PNG画像 – 完全ステップバイステップガイド + +Pythonスクリプトだけで **OCR PNG image** ファイルを処理する方法を考えたことはありませんか?スキャンした古代写本がたくさん入ったフォルダーがあり、**extract text from image** ファイルを手作業で入力せずに取得したいかもしれません。良いニュースは、コンピュータビジョンの博士号は不要で、数行のコードと適切なライブラリさえあれば、数秒で古代ギリシャ語を読むことができるということです。 + +このチュートリアルでは、PNG からテキストを認識し、言語をギリシャ語(ポリトニック)に設定して結果を出力する **python OCR example** を順を追って解説します。最後まで読むと、**recognize image text** のやり方、一般的な落とし穴の対処法、他の言語や画像形式へのスクリプトの拡張方法が正確に分かります。 + +## What You’ll Learn + +- Python OCR ライブラリ(pytesseract + Tesseract OCR)のインストールと設定方法 +- OCR エンジンのインスタンス作成と PNG ファイルの読み込み +- 言語をギリシャ語ポリトニックに設定して **read ancient greek** を実現する方法 +- 認識結果の出力と典型的な問題のトラブルシューティング +- 複数の PNG をバッチ処理したり、別の言語に切り替える方法の拡張 + +### Prerequisites + +| 要件 | 重要な理由 | +|------|------------| +| Python 3.8+ | モダンな構文と型ヒント | +| `pytesseract` パッケージ | Tesseract エンジンの薄いラッパー | +| Tesseract OCR バイナリ(≥ 5.0) | 実際に重い処理を行うエンジン本体 | +| Greek language data (`grc.traineddata`) | **read ancient greek** を正しく行うために必要 | +| 解析したい PNG 画像(例: `ancient_greek.png`) | **ocr png image** デモの対象 | + +Python 側は次のコマンドでインストールできます: + +```bash +pip install pytesseract Pillow +``` + +Ubuntu/macOS ではエンジン本体を次のように追加します: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Greek ポリトニックの学習データのダウンロードを忘れずに: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(パスは環境により異なる場合があります。必要に応じて `TESSDATA_PREFIX` を調整してください。)* + +--- + +## OCR PNG Image: Create the Engine Instance + +最初に必要なのは Tesseract とやり取りするオブジェクトです。`pytesseract` ではモジュールレベルの関数でエンジンにアクセスしますが、分かりやすさのために小さなクラスでラップします。これは元のスニペットで見た「エンジン」概念を模倣したものです。 + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**ラップする理由** +- 元のスニペットと同じ公開 API を保ち、移行をスムーズにするため。 +- 後からロギングやエラーハンドリングを追加しやすくするため。 +- 上級開発者が評価する良い OOP 実践を示すため。 + +--- + +## Extract Text from Image: Set the Language to Greek Polytonic + +エンジンが用意できたら、どの言語を認識させるかを指定します。ギリシャ語ポリトニックは標準の “greek” データではカバーできないアクセントがあるため、`grc` の学習ファイルを指す必要があります。 + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +別の言語で **extract text from image** を行いたい場合は、`"grc"` を `"eng"`(英語)や `"fra"`(フランス語)など、インストール済みの言語コードに置き換えるだけです。同じ行がどの言語でも機能します。 + +--- + +## Recognize Image Text: Run the OCR on a PNG + +言語設定が済んだら PNG をエンジンに渡します。元の例はハードコードされたパスでしたが、ここでは `Path` オブジェクトを使って柔軟性を持たせます。 + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tips & Edge Cases** + +- **File not found** – `try/except FileNotFoundError` でラップし、分かりやすいメッセージを出す。 +- **Low‑resolution PNG** – OCR 前に Pillow でリサイズや二値化など前処理を検討。 +- **Non‑Greek text** – 言語が合わないと精度が大幅に低下します。必ず対象言語を合わせましょう。 + +--- + +## Output the Recognized Text + +最後に結果を出力します。実際のプロジェクトではデータベースや CSV、あるいは翻訳パイプラインに渡すこともあるでしょう。 + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +クリアな古代ギリシャ語の碑文をスキャンした画像でスクリプトを実行すると、以下のような出力が得られます: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +出力が文字化けしている場合は、**greek.traineddata** が正しいフォルダーにあるか、PNG がノイズ過多でないかを再確認してください。 + +--- + +## Full Working Example (All Steps in One Script) + +以下は完成形のスクリプトです。`ocr_greek.py` として保存し、`python ocr_greek.py` で実行してください。 + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Expected output**(抜粋): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +正しくギリシャ文字が表示されれば、Python で **ocr png image** を実行できたことになります。おめでとうございます! + +--- + +## Common Questions & Pro Tips + +### How do I improve accuracy on a noisy PNG? + +- 画像をグレースケールに変換: `img = img.convert('L')` +- 二値化し閾値を適用: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` で拡大 + +これらの手順で **recognize image text** の失敗ケースをクリーンな結果に変えることができます。 + +### Can I process a whole folder of PNGs? + +もちろんです。`recognize_image` 呼び出しを `Path.glob("*.png")` のループで包み、結果を辞書に格納するか CSV に書き出すだけです。 + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### What if I need to extract numbers only? + +`image_to_string` にカスタム **config** 文字列を渡します: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +これでテーブルやシリアル番号、タイムスタンプなど数字だけを含む **extract text from image** が可能になります。 + +### Is there a way to get confidence scores? + +はい、`pytesseract.image_to_data` を使うと単語ごとの信頼度(confidence)を含む TSV が返ります。低信頼度のトークンを除外して最終文字列を組み立てることができます。 + +--- + +## Extending the Tutorial + +基本をマスターしたら、以下の関連トピックにも挑戦してみてください。 + +- **Batch OCR with multiprocessing** – 大量の PNG コーパスを高速化 +- **Hybrid OCR + NLP pipelines** – 抽出した古代ギリシャ語を自動で現代英語に翻訳 +- **Alternative engines** – `easyocr` や `opencv` ベースの手法を特定ユースケースで試す +- **Cloud OCR services** – Google Vision、Azure Computer Vision、AWS Textract でサーバーレスにスケール + +これらはすべて、今回扱った **python ocr example** を土台にしているので、次のステップへスムーズに進めます。 + +--- + +## Conclusion + +シンプルなスニペットを、Python で堅牢な **ocr png image** ワークフローに変換しました。`OcrEngine` を作成し、言語をギリシャ語ポリトニックに設定し、PNG を読み込んで結果を出力することで、**extract text from image**、**recognize image text**、さらには **read ancient greek** まで実現できました。 + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで学んだテクニックを応用した関連トピックを扱っています。各リソースには完全なコード例とステップバイステップの解説が含まれており、API の追加機能習得や代替実装アプローチの探求に役立ちます。 + +- [画像からテキストを抽出する Aspose OCR – ステップバイステップガイド](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [OCR 画像認識でしきい値を設定する方法](/ocr/english/net/ocr-settings/set-threshold-value/) +- [複数言語に対応した Aspose OCR でテキスト画像を認識する](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/japanese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..5f2d6ef85 --- /dev/null +++ b/ocr/japanese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-06 +description: Python OCRチュートリアルでは、画像テキストの認識、ハイレゾリューションOCRの実行、GPUアクセラレートされたOCRを使用したスペイン語テキストの抽出方法を示します。 +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: ja +og_description: 画像テキストの認識、高解像度OCR、GPUアクセラレーションによるスペイン語テキスト抽出を段階的に解説するPython OCRチュートリアル。 +og_title: Python OCRチュートリアル – GPUアクセラレーションによるテキスト認識 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCRチュートリアル – GPUアクセラレーションで画像テキストを認識する +url: /ja/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR チュートリアル – GPU 加速で画像テキストを認識する + +Python スクリプトで設定をいちいち調整することなく **画像テキストを認識** したことがありますか? あなただけではありません。この **python ocr tutorial** では、高解像度画像からスペイン語テキストを抽出するクリーンでエンドツーエンドな方法を示し、さらに GPU 加速を組み合わせて処理を超高速にします。 + +これは、後で本番レベルのパイプラインに拡張できる手軽なコーヒーブレイクデモと考えてください。このガイドの最後までに、**high resolution OCR** を実行し、CUDA 対応 GPU を活用し、必要なスペイン語文字を正確に出力する実行可能なプログラムが手に入ります。 + +## 学べること + +- GPU 加速をサポートする最新の OCR ライブラリのインストールとインポート方法。 +- OCR エンジンインスタンスを作成し、スペイン語で **画像テキストを認識** するように設定する方法。 +- **gpu accelerated OCR** を有効にして、高解像度ファイルで大幅な速度向上を実現する方法。 +- CUDA ドライバが見つからない場合や CPU にフォールバックする場合など、エッジケースの処理方法。 +- ノイズの多いスキャンから **extract spanish text** を抽出する際の精度向上のヒント。 + +### 前提条件 + +- Python 3.9+(コードは 3.10 以降でも動作します)。 +- CUDA 対応 GPU(任意ですが強く推奨)。 +- pip と仮想環境の基本的な知識。 + +これらが揃っていなくてもチュートリアルは動作します—GPU の手順をスキップすれば、ライブラリは自動的に CPU にフォールバックします。 + +--- + +## Python OCR チュートリアル: 必要なパッケージのインストール + +まず最初に、堅牢な OCR エンジンが必要です。このチュートリアルでは、互換性のあるデバイスが検出された場合に組み込みの GPU サポートを備えたオープンソース **`easyocr`** パッケージを使用します。 + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** すでに PyTorch がインストールされている場合は、CUDA バージョンと一致していることを確認してください(`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`)。バージョンが合わないことは “GPU not found” エラーの一般的な原因です。 + +## ステップ 1: OCR エンジンインスタンスの作成 + +それではエンジンを起動します。EasyOCR のメインクラスは `Reader` です。コンストラクタは言語コードのリストを受け取りますので、スペイン語には `"es"` を渡します。 + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* 言語を事前に宣言することで、エンジンは必要なニューラルネットワークの重みだけをロードし、メモリを節約し推論を高速化します—特に後で **high resolution OCR** を扱う際に有用です。 + +## ステップ 2: 高解像度画像の準備 + +高解像度画像はモデルにより多くのピクセルを提供し、通常は文字認識精度の向上につながります。`samples` フォルダに `high_res_spanish.png` というファイルがあると仮定しましょう。 + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +高解像度のサンプルが手元にない場合は、Unsplash から無料でダウンロードするか、Pillow で合成画像を生成できます。ベストな結果を得るためには DPI を 300 以上に保つことが重要です。 + +## ステップ 3: GPU 加速の有効化(任意だが推奨) + +`gpu=True` を設定すると EasyOCR は自動的に GPU の使用を試みます。ただし、特にマルチ GPU 環境では、実際にデバイスが使用されているか確認することがベストプラクティスです。 + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* スクリプトが静かに CPU にフォールバックすると、5 秒の処理がなぜか 30 秒かかると疑問に思うかもしれません。この小さなチェックにより動作が明示的になり、**gpu accelerated OCR** パイプラインの予測可能性が保たれます。 + +## ステップ 4: 高解像度 OCR の実行と画像テキストの認識 + +さあ楽しいパートです—実際にテキストを読み取ります。EasyOCR の `readtext` メソッドは、バウンディングボックス、認識された文字列、信頼度スコアを含むタプルのリストを返します。 + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +座標なしで生の文字列だけが必要な場合は `detail=0` を設定してください。ほとんどの **recognize image text** ユースケースでは、デフォルト(`detail=1`)で後処理に十分なコンテキストが得られます。 + +## ステップ 5: スペイン語テキストの抽出と出力のクリーンアップ + +EasyOCR にスペイン語を指定したので、返される文字列はすでにその言語です。それでも、文字列を結合したり、空白を除去したり、低信頼度の検出結果を除外したりしたい場合があります。 + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** 信頼度が低い場合は、しきい値を下げる(ノイズが増えるリスクあり)か、画像を前処理(コントラスト増加、二値化、傾き補正)してください。これらのテクニックは、スキャンした文書で **high resolution OCR** を行う際に一般的です。 + +## ステップ 6: エッジケースの処理とパフォーマンス調整 + +最も訓練されたモデルでもいくつかのシナリオでは失敗します。以下に、スクリプトに貼り付けられる簡単な修正をいくつか示します。 + +### 6.1 GPU が存在しない場合のフォールバック + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 超大サイズ画像のダウンサンプリング + +画像が 4000 × 4000 px を超える場合、GPU メモリが不足する可能性があります。DPI を保ちつつ比例的にダウンサンプリングしてください: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +これらのスニペットにより、ワークステーションでも控えめなノートパソコンでもスクリプトが堅牢に動作します。 + +## 完全な動作例 + +すべてをまとめると、すぐにコピー&ペーストして実行できる完全なスクリプトは以下の通りです: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**期待される出力(例):** + + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを取り上げています。各リソースには、ステップバイステップの解説とともに完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/japanese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..06155e95c --- /dev/null +++ b/ocr/japanese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-06 +description: PythonのOCRエンジンを使用して画像からテキストを認識します。OCRエンジンの設定方法と、クラウド処理で数分で画像からテキストを抽出する方法を学びましょう。 +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: ja +og_description: Python OCRエンジンで画像からテキストを認識します。このガイドでは、OCRエンジンをPythonで設定し、画像から効率的にテキストを抽出する方法を示します。 +og_title: Pythonで画像からテキストを認識する – 完全セットアップチュートリアル +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Pythonで画像からテキストを認識する – 完全OCRエンジン設定ガイド +url: /ja/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonで画像からテキストを認識する – 完全セットアップチュートリアル + +画像からテキストを **認識** したいと思ったことはありませんか?数行の Python だけで実現できます。レシートスキャナー、文書デジタライザー、シンプルな趣味プロジェクトなど、画像からテキストを抽出できるスキルはすぐに役立ちます。 + +このチュートリアルでは、**configure OCR engine python** の設定から始め、クラウド認証を行い、最終的に **extract text from image** を確実に取得する手順をすべて解説します。魔法はありません。今日すぐにコピー&ペーストして実行できる明快な手順だけです。 + +## 学べること + +- 必要な OCR ライブラリのインストールとインポート方法 +- クラウド処理用に **configure OCR engine python** する正確なコマンド +- **recognize text from image** して出力を表示する、実行可能な完全スクリプト +- API キーがない、画像形式が未対応などの一般的な落とし穴への対処法 +- バッチ処理やローカルフォールバックといった次のレベルのアイデア + +### 前提条件 + +- Python 3.8+ がインストールされていること +- インターネット接続(例ではクラウドベースの OCR サービスを使用) +- OCR プロバイダーから取得した有効な API キー(どこに差し込むかは後述) + +これらが揃っていれば、余計な説明は省き実践的なガイドに入ります。 + +--- + +## Step 1: OCR ライブラリをインストールしてインポート + +**configure OCR engine python** を行う前に、クラウドサービスと通信するライブラリが必要です。ここでは架空ですが代表的なパッケージ `ocrcloud` を例にします。実際に使用しているパッケージ(例:`easyocr`、`google-cloud-vision` など)に置き換えてください。 + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**重要ポイント:** クラスをインポートすると `use_cloud()` や `set_api_key()` といったメソッドが利用可能になります。インポートが無いとスクリプト全体が `NameError` を起こします。 + +*プロ tip:* `requirements.txt` でバージョンを固定(`ocrcloud==2.1.0`)して、予期せぬ破壊的変更を防ぎましょう。 + +--- + +## Step 2: **configure OCR engine python** を Cloud モードに設定 + +ここで実際に **configure OCR engine python** を行います。エンジンはデフォルトでローカルモードです。クラウドモードに切り替えることで、重い画像解析を強力なサーバーにオフロードできます。 + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**解説:** +- `OcrEngine()` は新しいエンジンオブジェクトを生成します。空のキャンバスと考えてください。 +- `use_cloud(True)` はスイッチを入れ、ローカルではなく HTTPS 経由で画像を送信するよう指示します。複雑なフォントや低解像度写真でも高精度を得るために重要です。 + +--- + +## Step 3: クラウド API キーで認証 + +ほとんどのクラウド OCR サービスは API キーが必要です。このステップでは安全に認証情報を注入する方法を示します。 + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**セキュリティ注意:** 公開リポジトリにキーをハードコードしないでください。本番環境では環境変数から取得します。 + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Step 4: **recognize text from image** – リモート画像を送信して処理 + +エンジンが設定できたので、やっと **recognize text from image** が可能です。`recognize_image()` メソッドはパスまたは URL を受け取り、抽出されたテキストを含むオブジェクトを返します。 + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**内部で何が起きているか:** +画像バイトがプロバイダーのエンドポイントにアップロードされ、ディープラーニングモデルで処理され、プレーンテキスト結果がストリームで返されます。画像が大きい場合、サービス側で自動的にダウンサンプリングされ、処理が高速化されることがあります。 + +--- + +## Step 5: **extract text from image** の結果を出力 + +OCR サービスが処理を終えたら、テキストをそのまま出力します。実際のアプリではデータベースに保存したり、別の関数に渡したりすることが多いでしょう。 + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**期待される出力例:**(サンプル) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +出力が文字化けしている場合は、画像が鮮明かつ正しい言語モデルが選択されているか確認してください(多くのサービスは `engine.set_language("en")` のように言語を指定できます)。 + +--- + +## エッジケースと一般的な落とし穴の対処 + +### 1. API キーがない、または無効 +認証エラーが出たら以下を確認してください。 +- キーが有効で期限切れでないこと +- 環境変数から正しく読み込まれていること +- ネットワークが外部 HTTPS 通信を許可していること + +### 2. 未対応の画像形式 +多くの OCR API は JPEG、PNG、PDF を受け付けます。BMP や TIFF は「format not supported」エラーになることがあります。必要なら Pillow で変換してください。 + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. レートリミット +クラウドサービスは分あたりのリクエスト数を制限することが多いです。制限に達したら指数バックオフを実装しましょう。 + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. ローカル OCR へのフォールバック +クラウドがダウンした場合はローカルに切り替えられます。 + +```python +engine.use_cloud(False) # revert to local mode +``` + +フォールバックを持つことでアプリの耐障害性が向上します。 + +--- + +## 完全動作サンプル + +すべてをまとめたスクリプトです。プレースホルダーだけ差し替えればすぐに実行できます。 + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**実行方法:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +コンソールに抽出されたテキストが表示されれば、**recognize text from image** と **extract text from image** を **configure OCR engine python** ワークフローで正しく実行できたことになります。 + +--- + +## まとめ + +Python で画像からテキストを **recognize text from image** するための、ライブラリのインストールからクラウド認証、最終的に **extract text from image** を単一関数呼び出しで取得するまでのエンドツーエンドプロセスを解説しました。**configure OCR engine python** を正しく設定すれば、クラウドとローカルの柔軟な切り替えと、堅牢なエラーハンドリングが手に入ります。 + +次は何をしますか?レシートフォルダをバッチ処理したり、言語検出を追加したり、PDF を入力に試したりしてみましょう。基本をマスターすれば、可能性は無限です。 + +楽しいコーディングを!質問があればコメントでどうぞ—一緒に学ぶことほど価値のあるものはありません。 + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能をマスターしたり、別の実装アプローチを自分のプロジェクトに取り入れたりするのに役立ちます。 + +- [Aspose OCR で画像からテキストを抽出 – ステップバイステップガイド](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose.OCR で画像からテキストを抽出 – 行認識](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [OCR で矩形を準備して画像からテキストを抽出する方法](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3d64714ea --- /dev/null +++ b/ocr/japanese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-06-06 +description: Python を使って画像の OCR を実行し、信頼度スコアを確認します。信頼度の低い単語をフィルタリングする方法、しきい値の設定、エッジケースの処理方法を学びます。 +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: ja +og_description: Pythonで画像にOCRを実行し、信頼度レベルを確認して低信頼度の単語をフィルタリングします。このチュートリアルでは、完全な実行可能な例を順を追って解説します。 +og_title: Pythonで画像のOCRを実行する ― 完全ガイド +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Pythonで画像のOCRを実行する – 完全ステップバイステップガイド +url: /ja/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonで画像のOCRを実行する – 完全ステップバイステップガイド + +画像ファイルに対して **run OCR on image** を実行したいと思ったことはありませんか?しかし、信頼できるテキストを取得する方法が分からないこともあるでしょう。あなたは一人ではありません—抽出された単語が不安定に見え、confidenceスコアが謎のままになる壁に、多くの開発者がぶつかっています。 + +このガイドでは、実用的な解決策にすぐに取り掛かります。**run OCR on image** の方法、全体の confidence を読み取り、手動で確認が必要になる低 confidence の単語を抽出する方法を紹介します。最後まで読むと、再利用可能なスクリプトが手に入り、各行がなぜ重要か理解でき、プロジェクトに合わせて confidence の閾値を調整する方法が分かります。 + +## このチュートリアルでカバーする内容 + +- 堅牢な OCR エンジンの選択(ここでは **EasyOCR**、人気の Python OCR ライブラリを使用します) +- すべての OCR 結果が返す `confidence` 属性の解釈 +- カスタム **OCR confidence threshold** による単語のフィルタリング +- バッチ処理や **pytesseract** などの代替エンジンへの拡張 + +OCR の事前経験は不要です。Python の基本的な知識と動作環境(Python 3.9+ 推奨)があれば始められます。 + +ぼやけたスクリーンショットをクリーンで検索可能なテキストに変換する準備はできましたか?さあ、始めましょう。 + +--- + +## ## Pythonで画像のOCRを実行する方法 + +チュートリアルの核心は、すでに見たコードと同様の 3 ステップスニペットです。以下で各行を分解し、理由を説明し、コピー&ペーストで使える完全なスクリプトを提供します。 + +### ステップ 1: OCRエンジンのインストールとインポート + +まず、OCR ライブラリが利用可能であることを確認します。**EasyOCR** は多くの言語に対してすぐに使える上、単語ごとに confidence スコアを提供します。 + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Why EasyOCR?* 多様なデータセットで学習されたディープラーニングモデルをバンドルしているため、特に品質が混在した画像では、従来の Tesseract エンジンよりも高い confidence 値が得られることが多いです。 + +> **Pro tip:** 制約のある環境(例: 小さな Docker コンテナ)で作業している場合、`pytesseract` の方が軽量ですが、EasyOCR が提供する最新の精度の一部は失われます。 + +### ステップ 2: 画像に対して OCR を実行する + +ここで実際に **run OCR on image** を行います。元の例の `recognize_image` メソッドは EasyOCR の `readtext` 呼び出しに置き換えられ、`(bbox, text, confidence)` のタプルのリストが返ります。 + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +`ocr_results` の各エントリは次のようになります: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +3 番目の要素(例では `0.92`)が 0 から 1 の範囲の confidence スコアです。 + +### ステップ 3: 全体の confidence を要約する + +以前のスニペットが単一の `confidence` 属性を出力したのとは異なり、EasyOCR は単語ごとに confidence を提供します。全体像を把握するために、これらを平均します: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Why average?* 迅速なヘルスチェックが可能になります。たとえば全体の confidence が 70 % 未満であれば、画像の照明改善や前処理などが必要になる可能性が高いです。 + +### ステップ 4: 低 confidence の単語を一覧表示 + +ここが「confidence が所定の閾値以下の単語をリストアップする」要件に直接応える部分です。デフォルトで **OCR confidence threshold** を 0.80(80 %)に設定しますが、必要に応じて調整できます。 + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +このループは基準に達しなかった各単語とそのパーセンテージ confidence を出力します。これは元の `for recognized_word in recognition_result.words` ループと同等ですが、EasyOCR の出力形式に合わせて動作します。 + +--- + +## ## OCR confidence スコアの理解 + +confidence は魔法の数値ではなく、特定の文字起こしに対するモデルの確信度の推定です。覚えておくべきポイントをいくつか紹介します。 + +| 状況 | 典型的な信頼度 | 対策 | +|-----------|-------------------|------------| +| 明瞭で高解像度のスキャン | 0.95 – 1.00 | 追加作業不要 | +| わずかなぼやけや不均一な照明 | 0.80 – 0.94 | 軽度の前処理(コントラスト強化)を検討 | +| 大きなノイズや回転したテキスト | < 0.70 | 画像前処理(デスキュー、ノイズ除去)または別の OCR エンジンに切り替え | + +> **Watch out:** 手書きの筆記体など、一部の言語は自然に低いスコアを出すことがあります。閾値はそれに合わせて調整してください。 + +### Edge Cases & Variations + +1. **Batch Processing** – 大量の **run OCR on image** ファイルを処理する必要がある場合、上記ロジックをディレクトリを走査するループでラップします。 +2. **Multiple Languages** – `easyocr.Reader` に `['en', 'fr']` のようなリストを渡すと、エンジンは両方の言語を検出します。 +3. **Alternative Engines** – **pytesseract** を試したいですか?リーダーブロックを次のように置き換えます: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + その後、文字単位の confidence を単語単位に集計する必要があります。少し手間はかかりますが実現可能です。 + +4. **Pre‑processing Tricks** – OpenCV フィルタ(`cv2.threshold`, `cv2.GaussianBlur`)を適用すると、ノイズの多いスキャンでも confidence を向上させられます。 + +--- + +## ## 完全版・すぐに実行できるスクリプト + +以下はプロジェクトにそのまま組み込める Python ファイルです。`ocr_report.py` として保存し、`python ocr_report.py` を実行してください。画像パスは実際のファイルを指すように設定してください。 + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**期待される出力**(数値は環境により異なります): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +すべての単語が 80 % の基準をクリアすれば、代わりに「All words meet the confidence threshold.」というフレンドリーなメッセージが表示されます。 + +--- + +## ## Frequently Asked Questions (FAQ) + +**Q: Does this work with PDFs?** +A: 直接は対応していません。まず `pdf2image` などで各 PDF ページを画像に変換し、PNG/JPEG をスクリプトに渡してください。 + +**Q: My confidence numbers are all low—what can I do?** +A: 画像前処理を試みてください。コントラストを上げる、背景ノイズを除去する、画像を水平に回転させるなど。EasyOCR では `contrast_ths` パラメータも調整可能です。 + +**Q: Can I export the results to CSV?** +A: もちろんです。低 confidence ループの後で、`ocr_results` を `csv.DictWriter` に書き出し、各行に `text`、`confidence`、バウンディングボックス座標を含めれば完了です。 + +**Q: Is there a GPU‑accelerated version?** +A: EasyOCR は、互換性のある GPU と PyTorch がインストールされていれば自動的に CUDA を使用します。スクリプト実行前に `torch.cuda.is_available()` で確認してください。 + +--- + +## Conclusion + +私たちは Python を使って **run OCR on image** を実行し、全体の confidence を検査し、手動レビューが必要な低 confidence の単語を抽出しました。 + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示した手法を基にした、密接に関連するトピックをカバーしています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得したり、独自プロジェクトで代替実装アプローチを探求したりするのに役立ちます。 + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/korean/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..24cdf1fdc --- /dev/null +++ b/ocr/korean/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR로 이미지를 몇 분 안에 텍스트로 추출하세요. 다국어 이미지 OCR, 자동 언어 감지 OCR, 그리고 OCR + 텍스트를 정확하게 추출하는 방법을 알아보세요. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: ko +og_description: Python OCR을 사용해 이미지를 빠르게 텍스트로 추출하세요. 다국어 이미지 OCR, 자동 언어 감지 OCR, 그리고 + 단계별 OCR 텍스트 추출 방법을 배워보세요. +og_title: Python OCR을 사용하여 이미지에서 텍스트 추출 – 완전 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Python OCR로 이미지에서 텍스트 추출 – 완전 가이드 +url: /ko/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 텍스트 추출하기 (Python OCR) – 완전 가이드 + +이미지를 **텍스트로 추출**해야 하는데 여러 언어를 자동으로 처리할 수 있는 라이브러리를 몰라 고민한 적 있나요? 여러분만 그런 것이 아닙니다—개발자들은 국제 문서, 영수증, 스캔한 전단지를 다룰 때 *OCR 텍스트를 어떻게 추출하나요* 라는 질문을 자주 합니다. 이번 튜토리얼에서는 이미지에서 텍스트를 추출할 뿐만 아니라 **언어를 자동으로 감지**하는 실용적인 Python 예제를 단계별로 살펴보겠습니다. 다국어 이미지 OCR을 손쉽게 구현할 수 있습니다. + +설치부터 **자동 언어 감지 OCR** 활성화, 샘플 이미지에 엔진 적용, 감지된 언어와 추출된 문자열 출력까지 모두 다룹니다. 튜토리얼을 마치면 번역 파이프라인이든 데이터 수집 서비스든 어느 프로젝트에든 바로 삽입할 수 있는 재사용 가능한 스니펫을 얻게 됩니다. + +## 이미지에서 텍스트 추출 – 환경 설정 + +코드 작성을 시작하기 전에 워크스테이션이 다음 최소 요구 사항을 충족하는지 확인하세요: + +- Python 3.8 이상 (라이브러리가 타입 힌트를 사용하므로 구버전에서는 무시됩니다) +- `pip` 패키지 관리 도구 +- 최소 두 개 이상의 언어(예: 영어 + 스페인어)가 포함된 이미지 파일 + +데모에 사용할 OCR 라이브러리도 필요합니다. 여기서는 실제 도구인 Tesseract나 EasyOCR와 유사하지만 깔끔한 Python API를 제공하는 가상의 `ocr` 패키지를 사용합니다. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** 권한 오류가 발생하면 명령 앞에 `python -m`을 붙이거나 가상 환경을 사용하세요—전역 site‑packages를 깔끔하게 유지할 수 있습니다. + +## OCR 엔진 인스턴스 생성 + +라이브러리가 준비되었으니 **OCR 엔진 인스턴스를 생성**하는 것이 첫 번째 논리적 단계입니다. 엔진은 이미지를 전달하기 전에 구성할 수 있는 스마트 스캐너와 같습니다. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +왜 정적 메서드 대신 엔진을 별도로 인스턴스화할까요? 엔진 객체는 언어 선호도와 같은 설정 상태를 보관하므로 여러 이미지에 걸쳐 재사용할 수 있어 매번 초기화하는 오버헤드를 줄여줍니다. + +## 자동 언어 감지 OCR 활성화 + +대부분의 OCR 도구는 언어 코드를 지정해야 합니다—영어는 `eng`, 스페인어는 `spa` 등. 언어를 수동으로 추측하면 **다국어 이미지 OCR** 워크플로의 의미가 사라집니다. 다행히 `ocr` 패키지는 이미지 내용을 분석해 최적의 언어 모델을 자동으로 선택하는 *자동 언어 감지 OCR* 모드를 제공합니다. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +이렇게 **언어 감지 OCR**을 활성화하면 긴 언어 코드 목록을 관리할 필요가 없습니다. 엔진이 라틴 문자, 키릴 문자, 한자 등 스크립트를 자동으로 인식하고 적절한 모델을 로드합니다. + +## 다국어 이미지 OCR 수행 + +엔진이 준비되었으니 이제 **이미지에서 텍스트를 추출**할 차례입니다. `recognize_image` 메서드는 파일 경로를 받아 원시 텍스트와 감지된 언어를 모두 포함하는 결과 객체를 반환합니다. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +PDF에서 OCR 텍스트를 추출하고 싶다면 `recognize_pdf` 메서드로 이름만 바꾸면 됩니다. 내부 감지 로직은 동일하므로 **자동 언어 감지 OCR** 기능을 그대로 활용할 수 있습니다. + +## 감지된 언어와 추출된 텍스트 출력 + +마지막으로 엔진이 발견한 내용을 출력합니다. 결과 객체는 `detected_language`(예: `en`, `es`와 같은 BCP‑47 태그)와 `text`(원시 OCR 출력)를 제공합니다. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +샘플 이미지를 대상으로 스크립트를 실행하면 다음과 유사한 결과가 나타납니다: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +엔진이 영어를 주요 언어로 정확히 식별하면서도 스페인어 라인을 놓치지 않은 것을 확인할 수 있습니다—강력한 **다국어 이미지 OCR** 솔루션이 기대하는 바로 그 모습입니다. + +### 감지가 실패하면 어떻게 하나요? + +이미지가 흐리거나 스크립트가 너무 이색적인 경우 엔진이 기본 언어(보통 영어)로 되돌아갈 수 있습니다. 이때는 언어 목록을 강제로 지정할 수 있습니다: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +하지만 언어를 강제로 지정하면 **자동 언어 감지 OCR**의 편리함이 사라지므로, 알려진 언어 집합이 있을 때만 사용하세요. + +## 흔히 발생하는 문제와 안정적인 OCR 텍스트 추출 방법 + +자동 감지를 사용하더라도 몇 가지 함정에 걸릴 수 있습니다: + +1. **저해상도 이미지** – 150 dpi 이하에서는 OCR 정확도가 급격히 떨어집니다. 해상도를 높이거나 업스케일링하세요. +2. **노이즈 및 압축 아티팩트** – 이미지를 엔진에 전달하기 전에 간단한 임계값 필터(`opencv` 또는 `Pillow`)를 적용하세요. +3. **한 페이지에 혼합 스크립트** – 일부 엔진은 라틴 문자와 CJK 문자를 동시에 처리하기 어렵습니다. 페이지를 영역별로 나누어 별도 인식을 수행하세요. + +이러한 문제를 해결하면 특히 실제 다국어 문서를 다룰 때 **이미지에서 텍스트 추출** 과정의 품질이 크게 향상됩니다. + +## 전체 작업 예제 + +아래는 앞서 설명한 모든 단계를 하나로 합친 완전 실행 가능한 스크립트입니다. `multilingual_ocr.py`라는 파일명으로 저장한 뒤 커맨드 라인에서 실행하세요. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**예상 출력**(샘플 이미지에 영어와 스페인어 텍스트가 포함된 경우): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +`multilang_page.png`를 다른 언어가 포함된 이미지로 교체해도 **자동 언어 감지 OCR** 덕분에 적절한 언어 태그와 해당 텍스트를 얻을 수 있습니다. + +![이미지에서 텍스트 추출 예시](https://example.com/ocr-sample.png "이미지에서 텍스트 추출") + +## 결론 + +이제 **이미지에서 OCR 텍스트를 추출**하는 방법, **자동 언어 감지 OCR**을 활성화하는 방법, 그리고 최소한의 코드로 **다국어 이미지 OCR** 시나리오를 처리하는 방법을 정확히 알게 되었습니다. OCR 엔진 인스턴스를 만들고, 자동 언어 감지를 켜고, `recognize_image`를 호출하면 언어 식별자와 원시 텍스트를 안정적으로 얻을 수 있습니다. + +다음 단계는 무엇일까요? 추출한 문자열을 번역 API에 전달하거나 검색 가능한 데이터베이스에 저장하고, 여러 페이지를 하나의 PDF 보고서로 결합해 보세요. 또한 동일한 고수준 워크플로를 유지하면서 Tesseract, EasyOCR, Google Vision 등 다양한 OCR 백엔드로 실험해 볼 수도 있습니다—**언어 감지 OCR** 인터페이스가 일관되게 제공되기 때문입니다. + +문제가 발생하면 “흔히 발생하는 문제” 섹션을 다시 확인하거나 이미지 전처리 단계를 조정해 보세요. 즐거운 코딩 되시고, 다음 프로젝트에서도 정확히 감지되고 완벽히 추출된 텍스트를 많이 활용하시길 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이번 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 심도 있게 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 마스터하고 다양한 구현 방식을 직접 프로젝트에 적용할 수 있도록 도와줍니다. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/korean/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..377bcb874 --- /dev/null +++ b/ocr/korean/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR을 사용하여 이미지 PDF에서 텍스트를 추출합니다. 비동기 배치 인식을 통해 스캔한 문서를 빠르게 텍스트로 + 변환하는 방법을 배워보세요. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: ko +og_description: Python으로 이미지 PDF에서 텍스트 추출하기. 이 단계별 가이드는 비동기 OCR을 사용하여 스캔한 문서를 텍스트로 + 변환하는 방법을 보여줍니다. +og_title: 이미지 PDF에서 텍스트 추출 – 파이썬 OCR 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: 이미지 PDF에서 텍스트 추출 – 스캔한 문서를 텍스트로 변환하는 파이썬 가이드 +url: /ko/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지 PDF에서 텍스트 추출 – 스캔된 문서를 텍스트로 변환하는 Python 가이드 + +시간을 들여 다시 타이핑하지 않고 **이미지 PDF에서 텍스트를 추출**해야 했던 적이 있나요? 이 가이드에서는 Python에서 간단한 비동기 OCR 워크플로를 사용해 **스캔된 문서를 텍스트로 변환**하는 방법을 보여드립니다. + +스캔된 PDF가 쌓여 있는 모습을 보며 “더 빠른 방법이 없을까?”라고 생각한 적이 있다면, 바로 여기가 맞습니다. 코드 한 줄 한 줄을 자세히 살펴보고, 각 부분이 왜 중요한지 설명하며, 마주칠 수 있는 몇 가지 엣지 케이스까지 다룹니다. + +## 배울 내용 + +- OCR 엔진을 시작하고 인식 언어를 설정하는 방법 +- PNG와 PDF가 섞인 리스트를 배치 인식기로 전달하는 메커니즘 +- 앱이 응답성을 유지하도록 OCR 작업을 비동기적으로 실행하는 방법 +- 결과를 가져와 원본 파일과 매핑하고 깔끔하게 출력하는 방법 + +**전제 조건**: Python 3.8 이상, `asyncio` 또는 `concurrent.futures`에 대한 기본 이해, 그리고 예제와 유사한 `OcrEngine` 클래스를 제공하는 OCR 라이브러리(예: Aspose.OCR, Tesseract 래퍼, 혹은 커스텀 래퍼). 별도의 복잡한 설정은 필요 없으며, 라이브러리만 설치하면 바로 시작할 수 있습니다. + +![이미지 PDF에서 텍스트 추출](https://example.com/placeholder.png "OCR 출력 스크린샷 – 이미지 PDF에서 텍스트 추출") + +## 이미지 PDF에서 텍스트 추출 – OCR 엔진 설정하기 + +먼저 문서 언어에 맞게 구성된 OCR 엔진 인스턴스가 필요합니다. 여기서는 프랑스어를 사용하지만, 지원되는 언어라면 어떤 것이든 교체할 수 있습니다. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**왜 중요한가**: 언어를 미리 설정하면 정확도가 크게 향상됩니다. 엔진은 언어별 사전과 문자 모델을 사용하므로, 잘못된 언어를 지정하면 출력이 엉망이 되는 흔한 원인입니다. + +## 파일 리스트 준비 – 이미지와 PDF를 함께 + +우리 배치 인식기는 래스터 이미지(`.png`, `.jpg`)와 PDF 컨테이너를 모두 처리할 수 있습니다. 파일 경로를 담은 일반 Python 리스트만 전달하면 됩니다. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**팁**: 리스트는 평평하게 유지하세요; 엔진이 내부적으로 각 PDF 페이지를 이미지로 풀어낸 뒤 인식합니다. 파일 수가 수천 개에 달한다면 메모리 급증을 방지하기 위해 리스트를 작은 배치로 나누는 것을 고려하세요. + +## 비동기 배치 인식 시작하기 + +메인 스레드를 차단하지 않고 OCR 작업을 백그라운드에서 실행합니다. 이 메서드는 결국 `OcrResult` 객체 리스트를 담게 될 `Future`를 반환합니다. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**작동 방식**: 엔진은 내부적으로 스레드 풀(또는 async 태스크)을 생성합니다(구현에 따라 다름). 이를 통해 UI 업데이트, 파일 추가 가져오기, 진행 상황 로깅 등 다른 작업을 동시에 수행할 수 있습니다. + +## OCR이 실행되는 동안 유용한 작업 수행하기 + +많은 사람들이 미래 객체를 빡빡한 루프에서 폴링하며 대기합니다. 대신 전혀 관련 없는 작업을 수행하세요. 예시로 상태 라인을 출력해 보겠습니다. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Future가 완료되면 결과 모으기 + +OCR 출력을 수집할 준비가 되면 `concurrent.futures`의 `as_completed`를 사용합니다. 이 패턴은 하나의 Future든 여러 개든 동일하게 동작합니다. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**출력 예시**: 각 파일 경로 뒤에 추출된 순수 텍스트가 표시됩니다. PDF의 경우 `result.text`에 모든 페이지 텍스트가 연결되어 들어 있습니다. + +### 예상 출력 (예시) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +문자 누락이 보이면 설정한 언어가 문서 언어와 일치하는지 다시 확인하고, 엔진에 전달하기 전에 이미지를 전처리(디스큐, 대비 증가)하는 것을 고려하세요. + +## 엣지 케이스 및 흔히 발생하는 함정 처리 + +| 상황 | 해결 방법 | +|-----------|------------| +| **혼합 언어** | 먼저 언어 감지(pass)를 수행한 뒤, 언어별로 별도 엔진을 인스턴스화합니다. | +| **대용량 PDF (> 100 MB)** | `PyPDF2` 등으로 PDF를 페이지 단위 파일로 분할하고 각각을 별도 엔트리로 전달합니다. | +| **비라틴 문자** | OCR 라이브러리에 해당 언어 팩이 포함되어 있는지 확인합니다; 일부 라이브러리는 추가 데이터 파일을 다운로드해야 합니다. | +| **성능 병목** | 스레드 풀 크기를 늘리세요(`engine.set_thread_pool_size(8)`) 또는 GPU 가속 백엔드가 있으면 전환합니다. | +| **저해상도 이미지에서 텍스트 누락** | OpenCV로 전처리: `cv2.resize`, `cv2.threshold`, `cv2.medianBlur` 등을 사용해 가독성을 높입니다. | + +## 전체 작동 예제 (복사‑붙여넣기 가능) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +위 코드를 `extract_text_async.py` 파일로 저장하고, `YOUR_DIRECTORY`를 파일이 있는 경로로 바꾸고, OCR 패키지를 설치(`pip install your-ocr-lib`)한 뒤 `python extract_text_async.py`를 실행하세요. 앞서 보여드린 콘솔 출력이 나타날 것입니다. + +## 다음 단계 – 기본 추출을 넘어서는 활용 + +- **후처리**: 불필요한 공백 제거, 유니코드 정규화(`unicodedata.normalize`), 혹은 맞춤법 검사기로 OCR 노이즈 정리 +- **구조화된 출력**: 결과를 CSV, JSON, 혹은 직접 데이터베이스에 저장해 다운스트림 검색에 활용 +- **병렬 배치**: 수백 개 파일이 있다면 여러 Future를 띄우고 큐를 사용해 CPU를 지속적으로 활용하되 메모리 과부하를 방지 +- **웹 프레임워크와 통합**: Flask 또는 FastAPI 엔드포인트에 스크립트를 연결해 온디맨드 OCR 서비스를 제공 + +--- + +### TL;DR + +이제 **이미지 PDF에서 텍스트를 추출**하는 최소한의 Python 스크립트를 사용해 OCR을 비동기적으로 실행하고, **스캔된 문서를 텍스트로 변환**하면서 프로그램이 응답성을 유지하는 방법을 알게 되었습니다. 언어 설정, 배치 크기, 전처리 기법을 조정해 정확도를 최대한 끌어올려 보세요. + +특별히 공유하고 싶은 팁—예를 들어 손글씨 노트 OCR이나 클라우드 기반 서비스—이 있다면 댓글로 알려 주세요. 즐거운 코딩 되세요! + +## 다음에 배워야 할 내용은? + + +다음 튜토리얼들은 이 가이드에서 소개한 기술을 기반으로 하며, 관련 주제를 깊이 있게 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공해 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 도와줍니다. + +- [Aspose OCR으로 이미지에서 텍스트 추출 – 단계별 가이드](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [폴더에서 OCR 작업으로 이미지에서 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Aspose.OCR으로 이미지에서 텍스트 추출 – 허용 문자 지정](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/korean/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..fb20f3040 --- /dev/null +++ b/ocr/korean/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: Python을 사용하여 PDF를 OCR하고, PDF에서 텍스트를 추출하며, 스캔된 PDF 텍스트를 변환하고, 몇 줄의 코드만으로 + OCR 언어를 변경하는 방법. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: ko +og_description: 'Python으로 PDF OCR하기: PDF에서 텍스트를 추출하고, 스캔된 PDF 텍스트를 변환하며, OCR 언어를 손쉽게 + 변경하는 방법을 보여주는 실용 가이드.' +og_title: Python에서 PDF OCR하는 방법 – 전체 프로그래밍 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Python에서 PDF OCR 하는 방법 – 완전 단계별 가이드 +url: /ko/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 PDF OCR 하는 방법 – 완전 단계별 가이드 + +비싼 SaaS 도구에 비용을 지불하지 않고 **PDF를 OCR 하는 방법**이 궁금하셨나요? 당신만 그런 것이 아닙니다. 오래된 책을 디지털화하거나, 청구서에서 데이터를 추출하거나, 스캔된 보고서에서 검색 가능한 텍스트가 필요할 때, Python으로 PDF OCR을 마스터하면 수작업 복사를 몇 시간씩 절약할 수 있습니다. + +이 튜토리얼에서는 **PDF에서 텍스트를 추출**하는 간결하고 작동하는 예제를 단계별로 살펴보고, **스캔된 PDF 텍스트를** 편집 가능한 문자열로 변환하는 방법, 그리고 문서가 영어가 아닐 경우 **OCR 언어를 변경**하는 방법을 보여줍니다. 마지막까지 따라오시면 어떤 프로젝트에도 바로 넣어 사용할 수 있는 재사용 가능한 스니펫을 얻게 됩니다. + +## 사전 요구 사항 및 설정 + +시작하기 전에 다음이 준비되어 있는지 확인하세요. + +- Python 3.8+ 설치 (코드는 3.9, 3.10 및 최신 버전에서도 작동) +- `OcrEngine` 클래스를 제공하는 `ocr` 패키지 (`pip install ocr-lib` 로 설치 – 실제 사용 중인 패키지 이름으로 교체) +- 처리하려는 PDF 파일; 데모에서는 `YOUR_DIRECTORY` 폴더에 위치한 `high_res_book.pdf` 를 사용합니다. + +가상 환경을 사용하고 있다면(강력히 권장) 먼저 활성화하세요: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** PDF 파일은 나중에 경로 문제를 피하기 위해 전용 `data/` 디렉터리 아래에 보관하세요. + +## Step 1: OCR 엔진 인스턴스 생성 (How to OCR PDF – Initialization) + +**PDF에 OCR을 수행**하려면 가장 먼저 해야 할 일은 엔진을 인스턴스화하는 것입니다. 엔진은 각 페이지를 읽고, 글리프를 해석하고, 순수 텍스트를 반환하는 두뇌와 같습니다. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +왜 중요한가요: 엔진이 없으면 언어 설정, 렌더링 옵션, PDF 처리와 같은 컨텍스트가 없습니다. `OcrEngine` 객체는 이러한 기본값을 보관하고 나중에 조정할 수 있게 해줍니다. + +## Step 2: 인식 언어 설정 (Change OCR Language) + +대부분의 OCR 라이브러리는 기본값이 영어이지만, 문서가 프랑스어, 독일어, 혹은 일본어라면 어떻게 할까요? 언어를 변경하는 것은 `set_recognition_language` 를 호출하는 것만큼 간단합니다. 이는 **OCR 언어 변경** 요구 사항을 충족시키며 정확도를 높여줍니다. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **왜 필요할 수 있나요:** 다국어 아카이브에는 혼합 언어 페이지가 자주 등장합니다. 실행 중에 언어를 전환하면 “ß”나 “ñ” 같은 문자를 오인식하는 일을 방지할 수 있습니다. + +## Step 3: PDF 렌더링 옵션 구성 (Convert Scanned PDF Text Effectively) + +스캔된 PDF를 다룰 때 해상도와 색상 모드는 OCR 품질에 큰 영향을 미칩니다. 대부분의 문서에 대해 300 DPI, 그레이스케일 렌더링이 최적의 균형을 이룹니다—세부 사항을 충분히 포착하면서 메모리 사용량은 적당합니다. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +연쇄 호출은 보기엔 화려해 보이지만, 매번 같은 옵션 객체를 반환하는 유창한 API일 뿐입니다. 컬러 다이어그램이 필요하면 `"grayscale"` 을 `"color"` 로 바꾸면 됩니다. + +## Step 4: PDF 인식 및 첫 페이지 텍스트 추출 (Extract Text from PDF) + +이제 **PDF에 OCR을 수행**하는 핵심 단계가 나옵니다: 엔진에 파일 경로를 전달하고 인식된 텍스트를 받아옵니다. 메서드는 페이지 결과 리스트를 반환하며, 각 결과는 `text` 속성을 포함합니다. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +전체 문서가 필요하면 `results` 를 순회하세요: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### PDF가 암호화된 경우는? + +일부 PDF는 비밀번호로 보호됩니다. 이 경우 `recognize_pdf` 에 비밀번호를 전달하면 됩니다: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +엔진이 OCR을 수행하기 전에 즉시 복호화하므로 별도의 단계가 필요 없습니다. + +## Step 5: 추출된 텍스트 후처리 (Fine‑Tuning Extract Text from PDF) + +원시 OCR 결과물은 줄 바꿈, 불필요한 공백, 혹은 가끔씩 잘못 인식된 문자들을 포함합니다. 간단한 정리 루틴을 적용하면 추출된 문자열을 다운스트림 처리(검색 인덱싱, 데이터베이스 저장 등)에 바로 사용할 수 있습니다. + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +이제 **PDF에서 텍스트를 추출**하고 이를 어떤 NLP 파이프라인, 검색 엔진, 혹은 간단한 `open(...).write()` 작업에 안전하게 전달할 수 있습니다. + +## Bonus: 여러 PDF 일괄 처리 (Scaling Perform OCR on PDF) + +스캔된 PDF가 가득한 폴더가 있다면 로직을 루프에 감싸면 됩니다: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +이 스니펫은 **PDF에 OCR을 수행**하는 작업을 대량으로 처리하는 방법을 보여주며, 디지털화 프로젝트에서 흔히 요구됩니다. + +## Expected Output + +단일 페이지 예제(Step 4)를 실행하면 다음과 유사한 출력이 표시됩니다: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +다중 페이지 책을 처리하면 콘솔에 각 페이지의 정제된 텍스트가 출력되고, 배치 스크립트는 각 PDF 옆에 `.txt` 파일을 생성합니다. + +## Common Pitfalls & How to Avoid Them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Low‑resolution source PDF | Garbled characters, missing words | Increase DPI (`set_dpi(400)` or higher) | +| Wrong language set | Many unknown symbols, especially accented characters | Use `engine.set_recognition_language(ocr.Language.FRENCH)` or the appropriate enum | +| Large PDF causing memory error | `MemoryError` or crash after a few pages | Process pages in chunks (`engine.recognize_pdf(..., max_pages=10)`) | +| Missing fonts in the PDF | Blank output for certain pages | Ensure the PDF actually contains raster images; some PDFs are vector‑only and need different handling | + +## Image Illustration + +아래는 워크플로우를 한눈에 보여주는 간단한 시각 자료입니다. 대체 텍스트는 SEO 친화적으로 작성되었습니다. + +![how to ocr pdf workflow diagram showing engine initialization, language setting, rendering options, recognition, and text extraction](/images/ocr-workflow.png) + +*다이어그램 자체가 코드 실행에 필수적인 것은 아니지만, 시각 학습자에게 각 단계가 어디에 해당하는지 이해시키는 데 도움이 됩니다.* + +## Conclusion + +Python에서 **PDF에 OCR을 수행**하는 전체 과정을 다뤘습니다: OCR 엔진 생성, **OCR 언어 변경**, **스캔된 PDF 텍스트 변환**을 위한 렌더링 설정, 그리고 최종적으로 **PDF에서 텍스트 추출**까지. 완전하고 실행 가능한 예제는 어떤 프로젝트에도 바로 삽입할 수 있으며, 선택적인 배치 스크립트는 솔루션을 확장하는 방법을 보여줍니다. + +다음 단계로 고려해볼 내용: + +- 다국어 아카이브를 위해 언어 리스트를 순회하며 **PDF에 OCR을 수행**하기 +- 추출된 텍스트를 Elasticsearch와 연동해 전체 텍스트 검색 구현 +- OCR을 사용해 원본 파일에 텍스트 레이어를 삽입해 검색 가능한 PDF 만들기(`save_as_searchable_pdf` 메서드를 제공하는 라이브러리 다수) + +실험하고, DPI 설정을 조정하고, 다른 OCR 백엔드로 교체해 보세요. 기본 원리는 동일하며, 이제 튼튼한 기반을 갖추셨습니다. + +행복한 코딩 되시고, 스캔된 문서가 마침내 검색 가능해지길 바랍니다! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/korean/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..f399d0671 --- /dev/null +++ b/ocr/korean/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-06 +description: Python을 사용하여 PDF를 OCR하고 이미지에서 검색 가능한 PDF 파일을 만드는 방법. 몇 분 안에 검색 가능한 텍스트를 + 추가하고 이미지를 PDF/A로 변환하는 방법을 배워보세요. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: ko +og_description: PDF를 단계별로 OCR하는 방법. 간단한 파이썬 스크립트를 사용해 검색 가능한 텍스트를 추가하고 이미지를 PDF/A로 + 변환하는 방법을 배워보세요. +og_title: PDF OCR 방법 – 검색 가능한 PDF 만들기 빠른 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Python으로 PDF OCR하기 – 이미지에서 검색 가능한 PDF 만들기 +url: /ko/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF를 OCR하는 방법 – 스캔된 이미지를 검색 가능한 PDF로 변환하기 + +청구서나 영수증의 스캔 이미지만 있을 때 **PDF를 OCR하는 방법**을 궁금해 본 적 있나요? 당신만 그런 것이 아닙니다. 많은 사무실에서 들어오는 서류는 평면 PNG나 JPEG 형태로 도착하고, 그 다음 단계인 콘텐츠를 검색 가능하게 만드는 작업은 마치 블랙박스처럼 느껴집니다. + +좋은 소식은? 몇 줄의 Python 코드만으로 **검색 가능한 PDF** 파일을 **생성하고**, **검색 가능한 텍스트를 추가**하며, 장기 보관을 위해 **이미지를 PDF/A로 변환**할 수 있습니다. 이 튜토리얼에서는 각 단계를 자세히 살펴보고, 왜 중요한지 설명한 뒤, 어떤 프로젝트에도 바로 넣어 사용할 수 있는 실행 가능한 스크립트를 제공하겠습니다. + +> **프로 팁:** 동일한 방법이 다중 페이지 스캔에도 적용됩니다; 파일들을 반복하면 엔진이 무거운 작업을 처리합니다. + +--- + +## What You’ll Need + +작업을 시작하기 전에 다음 항목이 머신에 준비되어 있는지 확인하세요: + +| 요구 사항 | 왜 중요한가 | +|-------------|----------------| +| Python 3.9 or newer | 최신 구문과 향상된 라이브러리 지원 | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | 이미지 인식과 PDF/A 생성 모두 처리 | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | 텍스트의 원본 | +| Write permission to the output folder | 스크립트가 새 PDF를 저장할 수 있도록 | + +OCR SDK를 아직 설치하지 않았다면 다음을 실행하세요: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +그게 전부—복잡한 시스템 의존성 없이 pip 설치만 하면 됩니다. + +--- + +## How to OCR PDF – Overview + +전체 흐름은 크게 세 가지 간단한 작업으로 구성됩니다: + +1. **Recognize**: 원본 그래픽을 보존하면서 이미지 안의 텍스트를 인식합니다. +2. **Export**: OCR 결과와 원본 이미지를 함께 **searchable PDF/A**(보관 친화적인 PDF 형식)로 내보냅니다. +3. **Validate**: 생성된 파일에 원본 사진 위에 선택 가능하고 검색 가능한 텍스트 레이어가 포함되어 있는지 확인합니다. + +아래에서는 각 단계를 코드와 함께 보여주고, 명령 뒤에 숨은 *왜*에 대한 설명을 덧붙입니다. + +--- + +## Step 1: Recognize Text from the Image + +먼저 OCR 엔진에 픽셀을 읽도록 요청하고, 원본 이미지와 추출된 텍스트를 모두 담은 결과 객체를 반환받습니다. 엔진이 청구서를 “읽어주는” 것이라고 생각하면 됩니다. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Why this matters + +- **Preserving graphics**: 시각 레이아웃(표, 로고, 도장 등)이 스캐너가 캡처한 그대로 유지됩니다. +- `result` 객체에는 나중에 PDF에 삽입할 숨겨진 텍스트 레이어가 일반적으로 포함됩니다. +- `recognize_image`를 사용하면 `recognize_pdf`보다 추가 변환 단계가 없어 단일 페이지 이미지 처리 속도가 빨라집니다. + +#### Common variations + +- **멀티 페이지 TIFF**가 있는 경우 파일 경로를 직접 전달하면 대부분의 엔진이 각 페이지를 별도 이미지로 처리합니다. +- 이미 이미지가 포함된 PDF의 경우 `engine.recognize_pdf("file.pdf")`를 호출해 이 단계를 완전히 건너뛸 수 있습니다. + +--- + +## Step 2: Export OCR Result as Searchable PDF/A + +이제 1단계에서 얻은 `result`를 사용해 엔진에게 새 파일을 쓰도록 지시합니다. 여기서 핵심 플래그는 *PDF/A*—장기 보존을 위해 설계된 ISO 표준 PDF 버전입니다. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Why this matters + +- **Searchable PDF**: 출력 파일에 숨겨진 선택 가능한 텍스트 레이어가 포함됩니다. 이제 문서 내에서 Ctrl + F로 검색할 수 있습니다. +- **PDF/A compliance**: 일부 조직(법무, 재무 등)은 감사 추적을 위해 PDF/A를 요구합니다; 이 단계가 자동으로 해당 규칙을 만족시킵니다. +- 이미지 자체를 평탄화하지 않고 **searchable text**를 추가하므로 시각적 충실도가 완벽하게 유지됩니다. + +#### Edge case: Need a regular PDF instead? + +PDF/A가 필요 없으면 `save_as_pdfa`를 `save_as_pdf`로 교체하면 됩니다. 나머지 워크플로는 동일하게 유지됩니다. + +--- + +## Step 3: Verify the Searchable PDF + +간단한 정상 확인을 통해 나중에 발생할 수 있는 신비한 버그를 예방할 수 있습니다. 생성된 파일을 PDF 뷰어에서 열고, 단어를 선택해 보며 검색 기능을 사용해 보세요. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Expected output + +스크립트를 실행하면 콘솔에 다음과 같이 출력됩니다: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +파일을 열면 원본 청구서 이미지 위에 희미하고 보이지 않는 텍스트 레이어가 보일 것입니다. 아무 단어든 강조 표시하면 선택 가능함을 확인할 수 있습니다—**바로 방금 추가한 검색 가능한 텍스트**입니다. + +--- + +## Adding Searchable Text to Existing PDFs (Bonus) + +이미 PDF가 존재하지만 **검색 가능한 텍스트를 추가**해야 할 때가 있습니다. 같은 엔진을 사용해 OCR 결과를 기존 PDF에 오버레이할 수 있습니다: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +여기서 `apply_to`는 숨겨진 레이어를 원본 페이지와 병합해 **재스캔 없이도 searchable PDF**를 만들 수 있게 해줍니다. + +--- + +## Common Pitfalls and Tips + +| Pitfall | How to avoid it | +|---------|-----------------| +| **Low‑resolution source images** (< 150 dpi) | 해상도를 높이거나 고해상도 스캔을 요청하세요; 150 dpi 이하에서는 OCR 정확도가 크게 떨어집니다. | +| **Missing language data** | OCR 엔진에 맞는 언어 팩을 설치하세요 (`pip install pdfocr[eng,spa]`). | +| **Output folder not writable** | 충분한 권한으로 스크립트를 실행하거나 다른 디렉터리를 선택하세요. | +| **PDF/A validation fails** | 지원되지 않는 글꼴이나 JavaScript를 삽입하지 않도록 하세요; 대부분의 SDK는 `save_as_pdfa` 사용 시 자동으로 처리합니다. | + +--- + +## Full Script – One‑File Solution + +아래는 모든 과정을 하나로 묶은 독립 실행형 스크립트입니다. 복사‑붙여넣기 후 플레이스홀더 경로만 교체하면 **이미지를 PDF/A로 변환**하는 작업을 몇 초 안에 수행할 수 있습니다. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**What this script does:** +1. OCR 엔진을 로드합니다. +2. 선택한 이미지를 읽고 텍스트를 추출합니다. +3. 즉시 배포하거나 보관할 수 있는 **searchable PDF/A**를 작성합니다. + +전체 폴더를 처리하도록 `main` 로직을 함수로 감싸고 `os.listdir()`을 순회하면서 각 파일에 대해 세 단계를 반복하면 됩니다. + +--- + +## Next Steps & Related Topics + +이제 **PDF를 OCR하는 방법**을 마스터했으니 다음 아이디어들을 살펴보세요: + +- **Batch processing:** `concurrent.futures`를 사용해 수십 개의 청구서를 병렬로 OCR합니다. +- **Metadata injection:** PDF 메타데이터에 생성일이나 청구서 번호를 추가해 인덱싱을 용이하게 합니다. +- **Hybrid PDFs:** 검색 가능한 텍스트와 원본 이미지를 결합해 종이 문서의 “디지털 트윈”을 만듭니다. +- **Alternative outputs:** 하위 시스템에서 편집 가능한 형식이 필요하면 **DOCX** 또는 **HTML**로 내보냅니다. + +이 모든 내용은 방금 배운 핵심 개념—인식, 내보내기, 검증—위에 기반합니다. + +--- + +## Wrap‑Up + +요약하면, 이제 몇 줄의 Python 코드만으로 간단한 이미지를 **searchable PDF/A**로 변환하는 **PDF OCR** 방법을 알게 되었습니다. 스크립트가 무거운 작업을 처리하고 원본 그래픽을 보존하며, 검색·보관·공유가 가능한 표준 준수 문서를 제공합니다. + +직접 청구서, 영수증, 스캔된 계약서를 가지고 실행해 보세요. 문제가 발생하면 아래에 댓글을 남기거나 SDK 공식 문서를 확인하세요—보통 추가 예제가 풍부하게 제공됩니다. 즐거운 코딩 되시고, 이제 어떤 이미지든 즉시 검색 가능하게 만드는 새로운 능력을 마음껏 활용하세요! + +![원본 이미지와 검색 가능한 PDF 오버레이를 보여주는 OCR PDF 예시](placeholder.png "How to OCR PDF example") + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하며, 밀접하게 연관된 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 포함해 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 돕습니다. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/korean/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..bfca5eb73 --- /dev/null +++ b/ocr/korean/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-06-06 +description: Aspose OCR Cloud를 사용하여 PDF를 OCR하는 방법. PDF에서 텍스트를 추출하고, PDF 페이지를 PNG로 + 변환하며, Python에서 PDF 페이지 이미지를 저장하는 방법을 배웁니다. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: ko +og_description: Aspose OCR Cloud를 사용하여 PDF를 OCR하는 방법. 이 가이드는 일반 텍스트 PDF를 추출하고, PDF + 페이지를 PNG로 변환하며, PDF 페이지 이미지를 저장하는 방법을 보여줍니다. +og_title: Aspose OCR Cloud로 PDF OCR 하는 방법 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Aspose OCR Cloud로 PDF OCR하는 방법 – 완전 가이드 +url: /ko/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Cloud를 사용한 PDF OCR 방법 – 완전 가이드 + +무거운 데스크톱 도구와 씨름하지 않고 **PDF를 OCR하는 방법**을 궁금해 본 적 있나요? 당신만 그런 것이 아닙니다—많은 개발자들이 스캔된 문서에서 텍스트를 빠르게 프로그래밍 방식으로 추출해야 할 때 이 문제에 부딪힙니다. 좋은 소식은? Aspose OCR Cloud를 사용하면 **PDF에서 텍스트를 추출**하고, 각 페이지를 PNG로 변환하며, 심지어 **PDF 페이지 이미지를** 나중에 사용할 수 있도록 저장할 수 있습니다. 모두 깔끔한 Python 스크립트 하나로 가능합니다. + +이 튜토리얼에서는 SDK 설치, 엔진 라이선스 적용, 다중 페이지 PDF 인식부터 순수 텍스트 추출, 페이지를 PNG로 변환, 그리고 이미지들을 디스크에 저장하는 방법까지 알아야 할 모든 것을 단계별로 안내합니다. 마지막까지 진행하면 **PDF OCR 방법**이 필요한 어떤 프로젝트에도 삽입할 수 있는 재사용 가능한 코드 조각을 얻을 수 있습니다. + +## 필요한 것 + +- **Python 3.8+** (코드는 3.10 및 그 이후 버전에서도 작동합니다) +- Aspose OCR Cloud 계정 – 무료 체험 라이선스 파일(`Aspose.OCR.lic`)을 받게 됩니다 +- `asposeocrcloud` 패키지 (`pip install asposeocrcloud`) +- 처리하려는 스캔된 다중 페이지 PDF + +그게 전부입니다. 별도의 바이너리나 네이티브 종속성 없이 순수 Python만 있으면 됩니다. + +## PDF OCR – 설정 및 라이선스 + +OCR 메서드를 호출하기 전에 SDK에 본인을 알려야 합니다. Aspose는 스크립트가 접근할 수 있는 위치에 배치하는 가벼운 라이선스 파일을 사용합니다. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*팁:* 라이선스 단계를 건너뛰면 SDK는 여전히 동작하지만 출력 이미지에 작은 워터마크가 삽입됩니다. 프로덕션 환경에는 적합하지 않습니다. + +## Step 2: Install the Aspose OCR Cloud Python SDK + +터미널을 열고 다음을 실행합니다: + +```bash +pip install asposeocrcloud +``` + +패키지는 필요한 모든 종속성(requests, pillow 등)을 자동으로 가져오므로 별도로 찾아 설치할 필요가 없습니다. + +## Step 3: Create an OCR Engine and Choose a Language + +엔진은 작업의 핵심입니다. Aspose에서 지원하는 모든 언어를 지정할 수 있으며, 대부분의 경우 영어가 작동합니다. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +언어를 설정하는 이유는? OCR 엔진이 언어별 사전을 사용해 정확도를 높이기 때문입니다. 프랑스어 PDF를 처리한다면 `ENGLISH`를 `FRENCH`로 바꾸기만 하면 됩니다. + +## Step 4: Point to Your Multi‑Page PDF + +엔진에 처리하려는 파일의 전체 경로를 제공하세요. 상대 경로도 스크립트 작업 디렉터리에서 올바르게 해석된다면 문제 없습니다. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +파일이 읽기 가능한지 확인하세요; 그렇지 않으면 `FileNotFoundError`가 발생합니다. + +## Step 5: Run OCR – You Get a List of Results + +`recognize_pdf`를 호출하면 원본 PDF의 각 페이지에 해당하는 요소를 가진 리스트가 반환됩니다. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +각 `OcrResult`는 두 가지 유용한 속성을 포함합니다: + +* `text` – 페이지의 순수 텍스트 표현( **extract plain text pdf**에 적합) +* `image` – 렌더링된 페이지의 Pillow `Image` 객체(**convert pdf page png**에 완벽) + +## Step 6: Extract Text from PDF and Convert Pages to PNG + +이제 결과를 순회하면서 추출된 텍스트를 출력하고, 각 페이지의 PNG 버전을 저장합니다. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### 예상 콘솔 출력 + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +`page_1.png`, `page_2.png`, … 파일이 `YOUR_DIRECTORY`에 생성된 것을 확인할 수 있습니다. 이들은 후속 이미지 처리 파이프라인에 사용할 수 있는 래스터화된 페이지 이미지입니다. + +## Step 7: Save PDF Page Images (Optional Post‑Processing) + +이미지만 필요하고 텍스트가 필요 없으면 `print(res.text)` 라인을 생략하면 됩니다. 반대로 텍스트를 별도의 `.txt` 파일에 저장하고 싶다면 작은 쓰기 코드를 추가하면 됩니다: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +이 작은 추가 코드는 **PDF 페이지 이미지를 저장**하면서 추출된 내용을 동시에 보존하는 것이 얼마나 쉬운지 보여줍니다. + +## Full Working Example + +모든 내용을 종합하면, `ocr_pdf.py`에 복사해 넣을 수 있는 전체 스크립트는 다음과 같습니다: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +다음과 같이 실행합니다: + +```bash +python ocr_pdf.py +``` + +각 페이지의 텍스트와 일련의 PNG 파일이 콘솔에 출력되는 것을 확인할 수 있습니다. + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 동작 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/korean/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..5c0f77ced --- /dev/null +++ b/ocr/korean/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-06 +description: Python을 사용하여 OCR을 위한 이미지 전처리 방법. Otsu 방법으로 이미지를 이진화하고, 스캔한 문서의 기울기를 보정하는 + 방법, 그리고 독일어 텍스트에 대한 OCR 정확도를 향상시키는 방법을 배웁니다. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: ko +og_description: Python에서 OCR을 위한 이미지 전처리 방법. 이 튜토리얼에서는 Otsu를 사용한 이미지 이진화, 스캔한 문서의 + 기울기 보정 방법, 그리고 독일어 이미지의 OCR 정확도를 향상시키는 방법을 보여줍니다. +og_title: OCR을 위한 이미지 전처리 방법 – 완전한 파이썬 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: OCR을 위한 이미지 전처리 방법 – 완전한 파이썬 가이드 +url: /ko/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR을 위한 이미지 전처리 방법 – 완전한 파이썬 가이드 + +OCR을 위한 이미지 전처리 방법이 궁금했던 적 있나요? 텍스트가 선명하게 나오도록 말이죠. 당신만 그런 것이 아닙니다. 스캔한 문서—특히 잡음이 많은 독일어 페이지—는 어떤 OCR 엔진에게도 악몽이 될 수 있습니다. 좋은 소식은? 몇 가지 스마트한 전처리 단계만으로 흐릿하고 잡음이 섞인 스캔을 깨끗하고 기계가 읽을 수 있는 이미지로 바꿀 수 있다는 것입니다. + +이 튜토리얼에서는 Python을 사용해 **OCR을 위한 이미지 전처리 방법**을 보여주는 실용적인 예제를 단계별로 살펴봅니다. **Otsu를 이용한 이미지 이진화**, **스캔 문서 디스키유 방법**, 그리고 **OCR 정확도 향상 방법**을 배워 **독일어 이미지 파일에서 텍스트 추출**하는 방법을 익히게 됩니다. 불필요한 내용은 없으며, 오늘 바로 복사‑붙여넣기 할 수 있는 작동 스크립트만 제공합니다. + +## 필요한 것들 + +- **Python 3.9+** (최근 버전이면 모두 작동합니다) +- `OcrEngine` 클래스를 제공하는 OCR 라이브러리 – 데모에서는 일반적인 `ocr` 패키지를 가정합니다. `pip install ocr-lib` 로 설치하세요. +- 테스트할 잡음이 많은 독일어 스캔(`noisy_german_scan.tif`) +- Python 함수에 대한 기본적인 이해 (이미 `def`를 작성해 본 적이 있다면 충분합니다) + +> **팁:** 다른 OCR SDK(예: `pytesseract`를 통한 Tesseract)를 사용한다면 개념은 동일합니다—메서드 이름만 해당 SDK에 맞게 바꾸면 됩니다. + +## 솔루션 개요 + +1. **OCR 엔진 인스턴스를 생성합니다.** +2. **인식 언어를 독일어로 설정합니다.** +3. **디스키유, 노이즈 제거, 이진화(Otsu), 대비 스트레칭을 포함하는 맞춤 전처리 파이프라인을 구축합니다.** +4. **파이프라인을 엔진에 연결하여 모든 이미지가 자동으로 통과하도록 합니다.** +5. **잡음이 많은 독일어 스캔에 OCR을 실행합니다.** +6. **추출된 텍스트를 출력하여 결과를 확인합니다.** + +아래에서 각 단계를 자세히 나누고, **왜** 중요한지 설명하며, 필요한 정확한 코드를 보여드립니다. + +![OCR을 위한 이미지 전처리 예시](image.png "OCR을 위한 이미지 전처리 예시") + +## 단계 1: OCR 엔진 인스턴스 생성 + +먼저 엔진이 없으면 아무 일도 일어나지 않습니다. `OcrEngine` 객체는 이후 모든 처리를 조정하는 진입점입니다. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Why this matters:* 엔진을 초기화하면 내부 리소스(예: 언어 모델)가 설정되고, 나중에 맞춤 파이프라인을 연결할 수 있는 깨끗한 상태가 됩니다. + +## 단계 2: 인식 언어를 독일어로 설정 + +OCR 정확도는 언어에 크게 의존합니다. 엔진에 독일어를 기대하도록 알려주면 올바른 문자 집합과 언어 모델이 활성화됩니다. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +이 단계를 건너뛰면 엔진이 기본값으로 영어를 사용하게 되어 움라우트(ä, ö, ü)와 ß 문자를 잘못 인식하는 일반적인 함정을 겪게 됩니다. + +## 단계 3: 맞춤 전처리 파이프라인 구축 + +이것이 **OCR을 위한 이미지 전처리 방법**의 핵심입니다. 네 가지 변환을 순차적으로 연결합니다: + +| 변환 | 동작 | 도움이 되는 이유 | +|------|------|-------------------| +| **Deskew** | 이미지를 수평으로 회전시킴 (최대 5°) | 스캔은 거의 완벽하게 정렬되지 않으며, 디스키유는 문자 분할을 혼란스럽게 하는 기울기를 제거합니다. | +| **Denoise** | 무작위 잡음을 감소시킴 (강도 0.7) | 노이즈는 OCR 엔진이 문자로 오인할 수 있는 잘못된 경계를 생성합니다. | +| **Binarize (Otsu)** | Otsu 방법을 사용해 흑백으로 변환 | 깨끗한 이진 이미지는 전경(텍스트)과 배경 사이에 선명한 대비를 제공합니다. | +| **Contrast Stretch** | 다이내믹 레인지를 확장 | 특히 오래된 문서에서 옅은 획의 가독성을 향상시킵니다. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### 스캔 문서 디스키유 방법 + +위 `deskew` 호출은 **스캔 문서 디스키유 방법**에 대한 구체적인 답변입니다. 내부적으로 Hough 변환을 통해 주요 텍스트 라인 각도를 추정하고 이미지를 회전시킵니다. 문서가 5° 이상 회전되어 있다면 `max_angle` 값을 높이되, 과도한 회전 아티팩트에 주의하세요. + +### Otsu를 이용한 이미지 이진화 + +`binarize(method="otsu")` 라인은 **Otsu를 이용한 이미지 이진화** 질문에 직접적인 답변을 제공합니다. Otsu 알고리즘은 클래스 내 분산을 최소화하는 임계값을 계산해, 어두운 텍스트와 밝은 배경이라는 이중 피크 히스토그램에 최적입니다. + +## 단계 4: 파이프라인을 엔진에 연결 + +이제 방금 만든 파이프라인을 OCR 엔진에 등록하여 모든 입력 이미지가 자동으로 전처리되도록 합니다. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Why this matters:* 등록하지 않으면 엔진이 원본 스캔을 그대로 처리해 우리가 설정한 모든 정리를 무시하게 됩니다. 이 단계는 **OCR 정확도 향상 방법**을 일관되게 적용하도록 보장합니다. + +## 단계 5: 잡음이 많은 독일어 스캔에서 텍스트 인식 + +이제 모든 것을 합칩니다. 엔진에 잡음이 많은 독일어 이미지를 전달하고 무거운 작업을 수행하게 합니다. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +성능이 궁금하다면 호출 시간을 측정할 수 있습니다: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## 단계 6: 인식된 텍스트 출력 + +마지막으로 추출된 문자열을 출력합니다. 이는 **독일어 이미지에서 텍스트 추출**에 대한 직접적인 답변입니다. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### 예상 출력 + +샘플 스캔에 “Die schnelle braune Füchsin springt über den faulen Hund.” 라는 문장이 포함되어 있다고 가정하면 다음과 같은 결과가 나타납니다: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +출력이 여전히 깨진 문자로 나타난다면 `denoise` 강도를 조정하거나 디스키유를 위해 `max_angle` 값을 늘려보세요. + +## 흔히 발생하는 문제와 해결 방법 + +- **언어 모델 누락:** `set_recognition_language(Language.GERMAN)` 호출을 잊으면 움라우트가 누락될 수 있습니다. 호출을 다시 확인하세요. +- **과도한 노이즈 제거:** 강도가 0.9 이상이면 특히 오래된 글꼴에서 얇은 획이 사라질 수 있습니다. 대부분의 경우 0.5‑0.7을 유지하세요. +- **잘못된 파일 형식:** 일부 OCR 엔진은 다중 페이지 TIFF를 처리하지 못합니다. 다중 페이지 문서가 있다면 먼저 단일 페이지 파일로 분할하세요. +- **파이프라인 순서:** 표시된 순서(디스키유 → 노이즈 제거 → 이진화 → 대비)는 의도된 것입니다. 이진화를 먼저 하면 노이즈가 고정될 수 있으니 항상 먼저 노이즈를 제거하세요. + +## 파이프라인 확장 (다음 단계?) + +기본 베이스가 마련됐으니 다음과 같은 확장을 고려해볼 수 있습니다: + +- **형태학적 오프닝**을 추가하여 작은 블롭을 정리합니다 (`.morph_open(kernel=3)`). +- **언어 모델 통합**을 통해 후처리 교정(`ocr_engine.apply_spellcheck()`). +- `concurrent.futures`를 사용해 대규모 데이터셋에 대한 배치 처리를 병렬화합니다. + +이 모든 확장은 **OCR을 위한 이미지 전처리 방법**의 핵심 아이디어를 유지하면서 **OCR 정확도 향상 방법**을 더욱 강화합니다. + +## 결론 + +우리는 **OCR을 위한 이미지 전처리 방법**을 처음부터 끝까지 다뤘습니다: 엔진 생성, 독일어 언어 설정, **Otsu를 이용한 이미지 이진화**, **스캔 문서 디스키유 방법**을 포함한 파이프라인 구축, 그리고 최종적으로 **독일어 이미지에서 텍스트 추출**까지. 위의 여섯 단계를 따르면 인식 품질이 눈에 띄게 향상됩니다—더 이상 끝없는 수동 교정이 필요하지 않습니다. + +직접 스캔 파일로 스크립트를 실행해 보고, 파라미터를 실험해 보며 결과를 확인해 보세요. 특정 전처리 조정에 대한 질문이 있나요? 댓글을 남겨 주시면 함께 깊이 파고들겠습니다. + +행복한 코딩 되시고, OCR이 언제나 정확하기를 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 자세히 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 돕습니다. + +- [Aspose.OCR을 사용한 언어 선택 C# 이미지 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [OCR 이미지 인식에서 임계값 설정 방법](/ocr/english/net/ocr-settings/set-threshold-value/) +- [이미지 OCR 방법 – OCR 이미지 인식에서 이미지에 OCR 수행](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/korean/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..5e6cfa9b4 --- /dev/null +++ b/ocr/korean/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-06-06 +description: Python으로 PNG 이미지 OCR – 이미지에서 텍스트를 추출하는 방법을 배우고, 파이썬 OCR 예제를 실행하며, 고대 + 그리스어 텍스트까지 쉽게 읽어보세요. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: ko +og_description: Python에서 OCR PNG 이미지 사용법을 설명합니다. 이 가이드는 이미지에서 텍스트를 추출하고, 파이썬 OCR 예제를 + 실행하며, 고대 그리스를 손쉽게 읽는 방법을 보여줍니다. +og_title: Python에서 PNG 이미지 OCR – 완전 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python에서 PNG 이미지 OCR – 전체 단계별 가이드 +url: /ko/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 OCR PNG 이미지 – 전체 단계별 가이드 + +Python 스크립트만으로 **OCR PNG image** 파일을 처리하는 방법이 궁금하셨나요? 스캔한 고대 원고가 가득한 폴더가 있고, **extract text from image** 파일을 일일이 타이핑하지 않고 추출하고 싶을 때가 있죠. 좋은 소식은 컴퓨터 비전 박사 학위가 필요 없다는 겁니다—몇 줄의 코드와 올바른 라이브러리만 있으면 몇 초 만에 고대 그리스를 읽을 수 있습니다. + +이 튜토리얼에서는 PNG에서 텍스트를 인식하고, 언어를 Greek polytonic으로 설정한 뒤 결과를 출력하는 **python OCR example**을 단계별로 살펴봅니다. 끝까지 읽으면 **recognize image text** 방법을 정확히 이해하고, 흔히 발생하는 문제들을 해결하며, 다른 언어와 이미지 포맷에 스크립트를 적용하는 방법을 알게 됩니다. + +## What You’ll Learn + +- Python OCR 라이브러리(pytesseract + Tesseract OCR) 설치 및 설정 +- OCR 엔진 인스턴스를 만들고 PNG 파일 로드 +- 언어를 Greek polytonic으로 설정하여 **read ancient greek** 가능하게 만들기 +- 인식된 텍스트 출력 및 일반적인 문제 해결 +- 여러 PNG를 배치 처리하거나 다른 언어로 전환하는 방법 확장 + +### Prerequisites + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | 현대 문법 및 타입 힌트 | +| `pytesseract` package | Tesseract 엔진을 감싸는 얇은 래퍼 | +| Tesseract OCR binaries (≥ 5.0) | 실제 OCR 엔진 자체 | +| Greek language data (`grc.traineddata`) | **read ancient greek** 를 정확히 인식하기 위해 필요 | +| 분석하려는 PNG 이미지 (예: `ancient_greek.png`) | **ocr png image** 데모의 대상 파일 | + +Python 쪽은 다음과 같이 설치할 수 있습니다: + +```bash +pip install pytesseract Pillow +``` + +Ubuntu/macOS에서는 엔진 자체를 추가로 설치합니다: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Greek polytonic 학습 데이터를 다운로드하는 것을 잊지 마세요: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(경로는 시스템에 따라 다를 수 있으니 `TESSDATA_PREFIX` 를 필요에 맞게 조정하세요.)* + +--- + +## OCR PNG Image: Create the Engine Instance + +먼저 Tesseract와 통신할 객체가 필요합니다. `pytesseract`에서는 모듈 수준 함수로 엔진에 접근하지만, 명확성을 위해 작은 클래스로 감싸겠습니다. 이는 원본 스니펫에서 보던 “engine” 개념을 그대로 반영합니다. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**왜 래핑하나요?** +- 시작할 때 사용한 스니펫과 동일한 공개 API를 유지해 마이그레이션이 쉬워집니다. +- 나중에 로깅이나 오류 처리를 추가해도 메인 흐름을 건드릴 필요가 없습니다. +- 좋은 OOP 실천을 보여줍니다—시니어 개발자들이 선호하는 방식이죠. + +--- + +## Extract Text from Image: Set the Language to Greek Polytonic + +엔진을 만든 뒤에는 어떤 언어를 인식할지 알려줘야 합니다. Greek polytonic은 표준 “greek” 데이터에 포함되지 않은 부호가 있으므로, `grc` 학습 파일을 지정합니다. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +다른 언어로 **extract text from image** 하고 싶다면 `"grc"` 를 `"eng"`(영어), `"fra"`(프랑스어) 등으로 바꾸면 됩니다. 설치된 언어라면 동일한 한 줄로 동작합니다. + +--- + +## Recognize Image Text: Run the OCR on a PNG + +언어를 설정했으니 PNG를 엔진에 전달합니다. 원본 예제는 하드코딩된 경로를 사용했지만, 여기서는 `Path` 객체를 활용해 약간 더 유연하게 만들었습니다. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**팁 & 엣지 케이스** + +- **File not found** – `try/except FileNotFoundError` 로 감싸 친절한 메시지를 제공하세요. +- **Low‑resolution PNG** – OCR 전에 Pillow로 리사이징·이진화 같은 전처리를 고려하세요. +- **Non‑Greek text** – Tesseract가 여전히 시도하지만 정확도가 크게 떨어집니다. 항상 언어를 맞춰 주세요. + +--- + +## Output the Recognized Text + +마지막으로 결과를 출력합니다. 실제 프로젝트에서는 데이터베이스, CSV, 혹은 번역 파이프라인에 전달할 수도 있습니다. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +깨끗한 고대 그리스 비문을 스캔한 파일을 실행하면 다음과 비슷한 출력이 나타납니다: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +출력이 깨져 보이면 **greek.traineddata** 파일이 올바른 폴더에 있는지, PNG가 너무 노이즈가 없는지 다시 확인하세요. + +--- + +## Full Working Example (All Steps in One Script) + +아래는 완전한 실행 가능한 프로그램 전체입니다. `ocr_greek.py` 로 저장하고 `python ocr_greek.py` 로 실행하세요. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**예상 출력** (일부만 발췌): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +올바른 그리스 문자들이 보이면 축하합니다—Python에서 **ocr png image** 작업을 성공적으로 수행한 것입니다! + +--- + +## Common Questions & Pro Tips + +### How do I improve accuracy on a noisy PNG? + +- 이미지를 그레이스케일로 변환: `img = img.convert('L')` +- 이진 임계값 적용: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` 로 확대 + +이 단계들은 **recognize image text** 를 악몽에서 깨끗한 결과로 바꾸는 데 자주 도움이 됩니다. + +### Can I process a whole folder of PNGs? + +물론입니다. `recognize_image` 호출을 `Path.glob("*.png")` 로 순회하는 `for` 루프로 감싸면 됩니다. 결과를 딕셔너리에 저장하거나 CSV로 기록해 나중에 분석하세요. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### What if I need to extract numbers only? + +`image_to_string` 에 커스텀 **config** 문자열을 전달하면 됩니다: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +이렇게 하면 표, 일련 번호, 타임스탬프 등 숫자만 포함된 **extract text from image** 파일에서도 원하는 결과를 얻을 수 있습니다. + +### Is there a way to get confidence scores? + +네—`pytesseract.image_to_data` 를 사용하면 단어별 신뢰도 점수가 포함된 TSV를 반환합니다. 최종 문자열을 만들기 전에 낮은 신뢰도의 토큰을 필터링할 수 있습니다. + +--- + +## Extending the Tutorial + +기본을 마스터했으니 다음 주제들을 탐구해 보세요: + +- **Batch OCR with multiprocessing** – 대량 PNG 코퍼스 처리 속도 향상 +- **Hybrid OCR + NLP pipelines** – 추출한 고대 그리스를 현대 영어로 자동 번역 +- **Alternative engines** – 특정 상황에 맞는 `easyocr` 혹은 `opencv` 기반 방법 시도 +- **Cloud OCR services** – 서버리스 확장을 위한 Google Vision, Azure Computer Vision, AWS Textract 등 + +이 모든 내용은 방금 다룬 **python ocr example** 을 기반으로 하므로, 더 깊이 파고들어도 자연스럽게 이해할 수 있습니다. + +--- + +## Conclusion + +간단한 스니펫을 견고한 **ocr png image** 워크플로우로 확장했습니다. `OcrEngine` 을 만들고, 언어를 Greek polytonic 으로 설정하고, PNG를 입력해 결과를 출력함으로써 이제 **extract text from image** 파일, **recognize image text**, 그리고 **read ancient greek** 를 수행하는 방법을 알게 되었습니다. + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 배운 기술을 확장하는 데 도움이 되는 관련 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공하므로, 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있습니다. + +- [이미지에서 텍스트 추출 – Aspose OCR 단계별 가이드](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [OCR 이미지 인식에서 임계값 설정 방법](/ocr/english/net/ocr-settings/set-threshold-value/) +- [다국어를 위한 Aspose OCR 텍스트 인식](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/korean/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..ebdb12508 --- /dev/null +++ b/ocr/korean/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-06 +description: 'Python OCR 튜토리얼: 이미지 텍스트를 인식하고, 고해상도 OCR을 수행하며, GPU 가속 OCR을 사용해 스페인어 + 텍스트를 추출하는 방법을 보여줍니다.' +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: ko +og_description: 이미지 텍스트 인식, 고해상도 OCR 및 GPU 가속을 통한 스페인어 텍스트 추출을 단계별로 안내하는 Python OCR + 튜토리얼. +og_title: Python OCR 튜토리얼 – GPU 가속 텍스트 인식 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR 튜토리얼 – GPU 가속으로 이미지 텍스트 인식 +url: /ko/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR 튜토리얼 – GPU 가속을 이용한 이미지 텍스트 인식 + +Python 스크립트에서 설정을 조정하는 데 몇 시간을 들이지 않고 **이미지 텍스트를 인식**하는 방법이 궁금했나요? 당신만 그런 것이 아닙니다. 이 **python ocr tutorial**에서는 고해상도 사진에서 스페인어 텍스트를 추출하는 깔끔하고 엔드‑투‑엔드 방식을 보여드리며, GPU 가속을 결합해 프로세스가 번개처럼 빠르게 실행되도록 합니다. + +잠깐의 커피 브레이크 데모라고 생각하고, 나중에 프로덕션 급 파이프라인으로 확장할 수 있습니다. 이 가이드를 끝까지 따라오면 **high resolution OCR**을 수행하고 CUDA 지원 GPU를 활용하며, 필요한 정확한 스페인어 문자를 출력하는 실행 가능한 프로그램을 얻게 됩니다. + +## 배울 내용 + +- GPU 가속을 지원하는 최신 OCR 라이브러리를 설치하고 가져오는 방법. +- OCR 엔진 인스턴스를 생성하고 스페인어로 **이미지 텍스트를 인식**하도록 설정하는 방법. +- 고해상도 파일에서 **gpu accelerated OCR**을 활성화해 대규모 속도 향상을 얻는 방법. +- CUDA 드라이버가 없거나 CPU로 폴백하는 경우와 같은 엣지 케이스를 처리하는 방법. +- 노이즈가 많은 스캔에서 **extract spanish text**를 추출할 때 정확도를 높이는 팁. + +### 사전 요구 사항 + +- Python 3.9+ (코드는 3.10 및 그 이후 버전에서도 작동합니다). +- CUDA 호환 GPU (선택 사항이지만 강력히 권장). +- pip 및 가상 환경에 대한 기본적인 이해. + +이 중 하나라도 없으면 튜토리얼은 여전히 작동합니다—GPU 단계를 건너뛰면 라이브러리가 자동으로 CPU로 폴백합니다. + +--- + +## Python OCR 튜토리얼: 필요한 패키지 설치 + +우선 탄탄한 OCR 엔진이 필요합니다. 이번 튜토리얼에서는 호환 가능한 장치를 감지하면 내장 GPU 지원을 제공하는 오픈소스 **`easyocr`** 패키지를 사용할 것입니다. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** 이미 PyTorch가 설치되어 있다면 CUDA 버전과 일치하도록 (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`) 확인하세요. 버전이 맞지 않으면 “GPU not found” 오류가 흔히 발생합니다. + +## Step 1: Create an OCR Engine Instance + +이제 엔진을 시작합니다. EasyOCR은 주요 클래스를 `Reader`라고 부릅니다. 생성자는 언어 코드 리스트를 받으며, 여기서는 스페인어를 의미하는 `"es"`를 전달합니다. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* 언어를 미리 선언하면 엔진이 필요한 신경망 가중치만 로드하므로 메모리를 절약하고 추론 속도가 빨라집니다—특히 **high resolution OCR**을 다룰 때 유용합니다. + +## Step 2: Prepare a High‑Resolution Image + +고해상도 이미지는 모델이 더 많은 픽셀을 활용하게 해 주어 일반적으로 문자 인식 정확도가 향상됩니다. `samples` 폴더에 `high_res_spanish.png` 파일이 있다고 가정해 보겠습니다. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +고해상도 샘플이 없으면 Unsplash에서 무료 이미지를 다운로드하거나 Pillow로 합성 이미지를 생성할 수 있습니다. 최상의 결과를 위해 DPI를 300 이상으로 유지하는 것이 핵심입니다. + +## Step 3: Enable GPU Acceleration (Optional but Recommended) + +`gpu=True`로 설정하면 EasyOCR이 자동으로 GPU 사용을 시도합니다. 다중 GPU 환경에서는 실제로 장치가 사용 중인지 확인하는 것이 좋은 습관입니다. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* 스크립트가 조용히 CPU로 폴백하면 5초 걸리던 작업이 갑자기 30초가 될 수 있습니다. 이 작은 확인을 통해 동작을 투명하게 만들고 **gpu accelerated OCR** 파이프라인을 예측 가능하게 유지할 수 있습니다. + +## Step 4: Perform High‑Resolution OCR and Recognize Image Text + +이제 본격적으로 텍스트를 읽는 단계입니다. EasyOCR의 `readtext` 메서드는 경계 상자, 인식된 문자열, 신뢰도 점수를 포함하는 튜플 리스트를 반환합니다. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +좌표 없이 순수 문자열만 필요하면 `detail=0`으로 설정하세요. 대부분의 **recognize image text** 사용 사례에서는 기본값(`detail=1`)이 후처리를 위한 충분한 컨텍스트를 제공합니다. + +## Step 5: Extract Spanish Text and Clean the Output + +EasyOCR에 스페인어를 요청했기 때문에 반환된 문자열은 이미 해당 언어입니다. 그래도 문자열을 연결하거나 공백을 제거하고, 신뢰도가 낮은 결과를 필터링하고 싶을 수 있습니다. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** 임계값을 낮춰 노이즈를 허용하거나 이미지 전처리(대비 증가, 이진화, 기울기 보정)를 수행할 수 있습니다. 이러한 트릭은 스캔 문서에서 **high resolution OCR**을 할 때 흔히 사용됩니다. + +## Step 6: Handling Edge Cases and Performance Tweaks + +최고 수준의 모델이라도 몇몇 상황에서는 어려움을 겪습니다. 아래는 스크립트에 바로 붙여넣을 수 있는 간단한 해결책 몇 가지입니다. + +### 6.1 Fallback When No GPU Is Present + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling Very Large Images + +이미지가 4000 × 4000 px보다 크면 GPU 메모리가 부족할 수 있습니다. DPI를 유지하면서 비율에 맞게 다운샘플링하세요: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +이 스니펫들은 워크스테이션이든 보통 노트북이든 스크립트를 견고하게 유지해 줍니다. + +## Full Working Example + +전체 코드를 한 번에 정리했습니다. 바로 복사‑붙여넣기하고 실행해 보세요: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Expected output (example):** + + + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 탐색하는 데 도움이 됩니다. + +- [Aspose OCR을 사용한 이미지 텍스트 추출 – 단계별 가이드](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose.OCR을 사용한 언어별 이미지 텍스트 OCR 방법](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR에서 OCR 텍스트 인식을 위한 페이지 사각형 인식 방법](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/korean/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..070b78fda --- /dev/null +++ b/ocr/korean/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR 엔진을 사용하여 이미지에서 텍스트를 인식합니다. OCR 엔진을 Python에 설정하고 클라우드 처리로 몇 + 분 안에 이미지에서 텍스트를 추출하는 방법을 배워보세요. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: ko +og_description: Python OCR 엔진으로 이미지에서 텍스트를 인식합니다. 이 가이드는 OCR 엔진을 Python에 설정하고 이미지를 + 효율적으로 텍스트로 추출하는 방법을 보여줍니다. +og_title: Python으로 이미지에서 텍스트 인식 – 완전 설정 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python에서 이미지 텍스트 인식 – 전체 OCR 엔진 설정 가이드 +url: /ko/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 텍스트 인식하기 (Python) – 전체 설정 튜토리얼 + +Python 몇 줄만으로 **이미지에서 텍스트 인식**하는 방법이 궁금하셨나요? 당신만 그런 것이 아닙니다. 영수증 스캐너, 문서 디지털화, 혹은 간단한 취미 프로젝트를 만들든, 이미지에서 텍스트를 추출할 수 있는 능력은 빠르게 큰 도움이 됩니다. + +이 튜토리얼에서는 전체 과정을 단계별로 안내합니다—**configure OCR engine python** 스타일 설정부터 시작해 클라우드 인증을 거치고, 마지막으로 **extract text from image**를 신뢰할 수 있는 결과와 함께 보여드립니다. 마법은 없고, 오늘 바로 복사‑붙여넣기해서 실행할 수 있는 명확한 단계만 제공합니다. + +## 배울 내용 + +- 필요한 OCR 라이브러리를 설치하고 import 하는 방법. +- **configure OCR engine python**을 사용해 클라우드 처리하는 정확한 명령어. +- **recognize text from image**를 수행하고 출력하는 완전한 실행 가능한 스크립트. +- 누락된 API 키나 지원되지 않는 이미지 형식과 같은 일반적인 함정 처리 팁. +- 배치 처리 및 로컬 폴백과 같은 차세대 아이디어. + +### 사전 요구 사항 + +- 머신에 Python 3.8+이 설치되어 있어야 합니다. +- 인터넷 연결(예제는 클라우드 기반 OCR 서비스를 사용합니다). +- OCR 제공업체에서 발급받은 유효한 API 키(삽입 위치는 아래에서 확인). + +위 조건을 갖추셨다면 바로 시작해봅시다—불필요한 내용 없이 실제로 동작하는 실용적인 가이드입니다. + +--- + +## 1단계: OCR 라이브러리 설치 및 Import + +**configure OCR engine python**을 수행하기 전에 클라우드 서비스와 통신하는 라이브러리가 필요합니다. 예제에서는 가상의 대표 패키지 `ocrcloud`를 사용합니다. 실제 사용하는 패키지(e.g., `easyocr`, `google-cloud-vision` 등)로 교체하세요. + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**왜 중요한가:** 클래스를 import 하면 `use_cloud()`와 `set_api_key()` 같은 메서드에 접근할 수 있습니다. import가 없으면 스크립트 나머지는 `NameError`를 발생시킵니다. +*프로 팁:* 나중에 예상치 못한 깨지는 변경을 방지하려면 `requirements.txt`에 버전을 고정하세요(`ocrcloud==2.1.0`). + +--- + +## 2단계: **configure OCR engine python**을 생성하고 클라우드 모드로 설정 + +이제 실제로 **configure OCR engine python**을 수행합니다. 엔진은 기본적으로 로컬 모드에서 시작하며, 클라우드 모드로 전환하면 무거운 이미지 분석을 강력한 서버에 위임할 수 있습니다. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**설명:** +- `OcrEngine()`은 새로운 엔진 객체를 생성합니다—빈 캔버스와 같습니다. +- `use_cloud(True)`는 스위치를 전환하여 엔진이 이미지를 로컬에서 처리하는 대신 HTTPS를 통해 전송하도록 합니다. 이는 복잡한 글꼴이나 저해상도 사진에서도 높은 정확도의 결과를 얻는 데 중요합니다. + +--- + +## 3단계: 클라우드 API 키 인증 + +대부분의 클라우드 OCR 서비스는 API 키가 필요합니다. 이 단계에서는 자격 증명을 안전하게 주입하는 방법을 보여줍니다. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**보안 주의:** 공개 저장소에 키를 하드코딩하지 마세요. 실제 운영에서는 환경 변수에서 가져옵니다: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## 4단계: **recognize text from image** – 원격 이미지 전송 및 처리 + +엔진이 설정되었으니 이제 **recognize text from image**를 수행할 수 있습니다. `recognize_image()` 메서드는 경로나 URL을 받아 추출된 텍스트를 포함한 객체를 반환합니다. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**내부 동작:** +이미지 바이트가 제공자의 엔드포인트로 업로드되고, 딥러닝 모델에 의해 처리된 뒤 순수 텍스트 결과가 스트리밍됩니다. 이미지가 크면 서비스가 자동으로 다운스케일하여 작업 속도를 높일 수 있습니다. + +--- + +## 5단계: **extract text from image** 결과 출력 + +OCR 서비스가 작업을 마쳤으니 텍스트를 단순히 출력합니다. 실제 애플리케이션에서는 데이터베이스에 저장하거나 다른 함수에 전달할 수 있습니다. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**예상 출력:** (예시) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +출력이 깨져 보인다면 이미지가 선명한지와 올바른 언어 모델을 선택했는지 확인하세요(많은 서비스에서 `engine.set_language("en")`와 같이 지정할 수 있습니다). + +--- + +## 엣지 케이스 및 일반적인 함정 처리 + +### 1. 누락되었거나 잘못된 API 키 + +인증 오류가 발생한다면 다음을 확인하세요: +- 키가 활성화되어 있고 만료되지 않았는지. +- 환경 변수에서 올바르게 읽히는지. +- 네트워크가 외부 HTTPS 트래픽을 허용하는지. + +### 2. 지원되지 않는 이미지 형식 + +대부분의 OCR API는 JPEG, PNG, PDF를 지원합니다. BMP나 TIFF를 시도하면 “지원되지 않는 형식” 응답이 발생할 수 있습니다. 필요하면 Pillow로 변환하세요: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. 요청 제한(Rate Limits) + +클라우드 서비스는 분당 요청 수를 제한하는 경우가 많습니다. 제한에 걸리면 지수 백오프를 구현하세요: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. 로컬 OCR 폴백 + +클라우드가 다운되면 로컬로 전환할 수 있습니다: + +```python +engine.use_cloud(False) # revert to local mode +``` + +폴백을 두면 애플리케이션이 회복력을 유지합니다. + +--- + +## 전체 작동 예제 + +전체를 합치면, 지금 바로 실행할 수 있는 스크립트가 여기 있습니다(플레이스홀더 값을 교체하면 됩니다). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**실행 방법:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +콘솔에 추출된 텍스트가 출력될 것이며, 이를 통해 **configure OCR engine python** 워크플로우를 올바르게 사용해 **recognize text from image**와 **extract text from image**를 성공적으로 수행했음을 확인할 수 있습니다. + +--- + +## 결론 + +우리는 이제 Python에서 **recognize text from image**를 수행하는 전체 엔드‑투‑엔드 과정을 살펴보았습니다. 라이브러리 설치부터 클라우드 서비스 인증, 마지막으로 단일 함수 호출로 **extract text from image**까지. **configure OCR engine python**을 올바르게 설정하면 유연성(클라우드 vs. 로컬)과 신뢰성(적절한 오류 처리)을 모두 얻을 수 있습니다. + +다음은? 영수증 폴더를 배치 처리해보거나, 언어 감지를 추가하거나, PDF를 입력으로 실험해보세요. 기본을 마스터하면 가능성은 무한합니다. + +코딩을 즐기세요, 그리고 댓글에 언제든 질문을 남겨 주세요—함께 배우는 것보다 좋은 것은 없습니다! + +--- + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료는 완전한 코드 예제와 단계별 설명을 포함해 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하도록 돕습니다. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/korean/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2dc8a1f7a --- /dev/null +++ b/ocr/korean/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,337 @@ +--- +category: general +date: 2026-06-06 +description: Python을 사용해 이미지에 OCR을 실행하고 신뢰도 점수를 확인하세요. 낮은 신뢰도의 단어를 필터링하고, 임계값을 설정하며, + 엣지 케이스를 처리하는 방법을 배워보세요. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: ko +og_description: Python에서 이미지에 OCR을 실행하고, 신뢰도 수준을 확인한 뒤 신뢰도가 낮은 단어를 필터링합니다. 이 튜토리얼은 + 완전하고 실행 가능한 예제를 단계별로 안내합니다. +og_title: Python으로 이미지에서 OCR 실행 – 전체 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Python으로 이미지에서 OCR 실행 – 완전한 단계별 가이드 +url: /ko/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python으로 이미지에서 OCR 실행 – 완전 단계별 가이드 + +이미지 파일에서 **run OCR on image** 해야 할 때, 신뢰할 수 있는 텍스트를 추출하는 방법을 몰라 고민한 적 있나요? 당신만 그런 것이 아닙니다—많은 개발자들이 추출된 단어가 흐릿하게 보이고 confidence 점수가 이해되지 않아 같은 벽에 부딪히곤 합니다. + +이 가이드에서는 바로 사용할 수 있는 솔루션을 살펴봅니다: **run OCR on image** 하는 방법, 전체 confidence를 읽는 방법, 그리고 수동 검토가 필요할 수 있는 low‑confidence 단어들을 추출하는 방법을 보여드립니다. 끝까지 읽으면 재사용 가능한 스크립트를 얻고, 각 라인이 왜 중요한지 이해하며, 프로젝트에 맞게 confidence threshold를 조정하는 방법을 알게 됩니다. + +## 이 튜토리얼에서 다루는 내용 + +이미지를 로드하는 단계부터 80 % confidence 이하인 단어들을 깔끔하게 보고하는 단계까지 전체 워크플로를 단계별로 살펴보겠습니다. 진행하면서 다음을 논의합니다: + +* 견고한 OCR 엔진 선택 (우리는 **EasyOCR**이라는 인기 있는 Python OCR 라이브러리를 사용할 것입니다) +* 모든 OCR 결과가 반환하는 `confidence` 속성 해석하기 +* 사용자 정의 **OCR confidence threshold** 로 단어 필터링하기 +* 배치 처리 또는 **pytesseract**와 같은 대체 엔진을 위한 스크립트 확장하기 + +사전 OCR 경험은 필요 없으며, Python에 대한 기본적인 이해와 작업 환경만 있으면 됩니다 (Python 3.9+ 권장). + +흐릿한 스크린샷을 깔끔하고 검색 가능한 텍스트로 바꿀 준비가 되셨나요? 시작해봅시다. + +--- + +## ## Python으로 이미지에서 OCR 실행 방법 + +튜토리얼의 핵심은 앞서 본 코드를 그대로 반영한 3단계 스니펫입니다. 아래에서 각 라인을 자세히 살펴보고 이유를 설명한 뒤, 완전한 복사‑붙여넣기 가능한 스크립트를 제공하겠습니다. + +### Step 1: OCR 엔진 설치 및 임포트 + +먼저 OCR 라이브러리가 사용 가능한지 확인하세요. **EasyOCR**는 다수의 언어를 바로 지원하며 단어별 confidence 점수를 제공합니다. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Why EasyOCR?* 다양한 데이터셋으로 학습된 딥러닝 모델을 포함하고 있어, 특히 품질이 혼합된 이미지에서 오래된 Tesseract 엔진보다 일반적으로 더 높은 confidence 값을 얻을 수 있습니다. + +> **Pro tip:** 제한된 환경(예: 작은 Docker 컨테이너)에서 작업한다면 `pytesseract`가 더 가벼울 수 있지만, EasyOCR가 제공하는 최신 정확도 중 일부를 잃게 됩니다. + +### Step 2: 이미지에서 OCR 실행 + +이제 실제로 **run OCR on image** 를 수행합니다. 원본 예제의 `recognize_image` 메서드는 EasyOCR의 `readtext` 호출로 대체되며, 이는 `(bbox, text, confidence)` 튜플 리스트를 반환합니다. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +`ocr_results`의 각 항목은 다음과 같습니다: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +세 번째 요소(`0.92` 예시)는 0에서 1 사이의 confidence 점수입니다. + +### Step 3: 전체 confidence 요약 + +이전 스니펫이 단일 `confidence` 속성을 출력한 것과 달리, EasyOCR는 단어별 confidence를 제공합니다. 전체적인 감을 잡기 위해 평균을 구해보겠습니다: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Why average?* 빠른 상태 점검을 할 수 있습니다—전체 confidence가 예를 들어 70 % 이하라면 이미지(조명 개선, 전처리 등)를 개선해야 할 가능성이 높습니다. + +### Step 4: Low‑Confidence 단어 목록 + +이제 “confidence가 원하는 임계값 이하인 단어를 나열” 요구사항을 직접 만족시키는 부분입니다. 기본값으로 **OCR confidence threshold** 를 0.80(80 %)으로 설정하지만, 필요에 따라 조정할 수 있습니다. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +루프는 기준에 미달한 각 단어와 해당 confidence 퍼센트를 출력합니다. 이는 원래 `for recognized_word in recognition_result.words` 루프와 정확히 동일하지만, 이제 EasyOCR의 출력 형식에 맞게 동작합니다. + +--- + +## ## OCR confidence 점수 이해하기 + +Confidence는 마법 같은 숫자가 아니라, 특정 전사에 대해 모델이 얼마나 확신하는지를 추정한 값입니다. 기억해두면 좋은 몇 가지 사항은 다음과 같습니다: + +| 상황 | 일반적인 Confidence | 조치 | +|-----------|-------------------|------------| +| 선명하고 고해상도 스캔 | 0.95 – 1.00 | 추가 작업 필요 없음 | +| 약간의 흐림 또는 고르지 않은 조명 | 0.80 – 0.94 | 약간의 전처리(대비 향상) 고려 | +| 많은 노이즈, 회전된 텍스트 | < 0.70 | 이미지 전처리(디스큐, 노이즈 제거) 적용 또는 다른 OCR 엔진으로 전환 | + +> **Watch out:** 일부 언어(예: 필기체)에서는 자연스럽게 낮은 점수가 나올 수 있습니다. 그에 맞게 임계값을 조정하세요. + +### 엣지 케이스 및 변형 + +1. **Batch Processing** – 대량으로 **run OCR on image** 파일을 처리해야 한다면, 위 로직을 디렉터리를 순회하는 루프로 감싸세요. +2. **Multiple Languages** – `easyocr.Reader`에 `['en', 'fr']`와 같은 리스트를 전달하면 엔진이 두 언어를 모두 감지합니다. +3. **Alternative Engines** – **pytesseract**를 사용해 보고 싶나요? 리더 블록을 다음과 같이 교체하세요: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + 그런 다음 문자별 confidence를 단어별 값으로 집계해야 합니다—조금 더 작업이 필요하지만 가능합니다. + +4. **Pre‑processing Tricks** – OpenCV 필터(`cv2.threshold`, `cv2.GaussianBlur`)를 적용하면 노이즈가 많은 스캔의 confidence를 높일 수 있습니다. + +--- + +## ## 완전 실행 가능한 스크립트 + +아래는 프로젝트에 바로 넣을 수 있는 완전한 Python 파일입니다. `ocr_report.py`로 저장하고 `python ocr_report.py`를 실행하세요. 이미지 경로가 실제 파일을 가리키는지 확인하십시오. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Expected output** (당신의 결과는 다를 수 있습니다): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +모든 단어가 80 % 기준을 통과하면 친절한 “All words meet the confidence threshold.” 메시지가 표시됩니다. + +--- + +## ## 자주 묻는 질문 (FAQ) + +**Q: Does this work with PDFs?** +A: 직접적으로는 지원되지 않습니다. 각 PDF 페이지를 먼저 이미지(PNG/JPEG)로 변환(`pdf2image` 등)한 뒤 스크립트에 전달하세요. + +**Q: My confidence numbers are all low—what can I do?** +A: 이미지 전처리를 시도해 보세요: 대비를 높이고, 배경 노이즈를 제거하거나 이미지를 수평 기준으로 회전합니다. EasyOCR는 조정 가능한 `contrast_ths` 파라미터도 지원합니다. + +**Q: Can I export the results to CSV?** +A: 물론 가능합니다. low‑confidence 루프 이후에 `ocr_results`를 `csv.DictWriter`에 기록하면 각 행에 `text`, `confidence`, 그리고 bounding‑box 좌표가 포함됩니다. + +**Q: Is there a GPU‑accelerated version?** +A: 호환 가능한 GPU와 PyTorch가 설치되어 있으면 EasyOCR가 자동으로 CUDA를 사용합니다. 스크립트를 실행하기 전에 `torch.cuda.is_available()`로 확인하세요. + +--- + +## 결론 + +우리는 방금 Python을 사용해 **run OCR on image** 를 수행하고, 전체 confidence를 검사했으며, 낮은 confidence를 가진 단어들을 분리했습니다. + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료는 단계별 설명과 함께 완전한 동작 코드 예제를 제공하여 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움을 줍니다. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/polish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..60f1e8cd0 --- /dev/null +++ b/ocr/polish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Wyodrębnij tekst z obrazu za pomocą Python OCR w kilka minut. Odkryj + wielojęzyczne OCR obrazów, automatyczne wykrywanie języka w OCR oraz jak dokładnie + wyodrębnić tekst z OCR. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: pl +og_description: Szybko wyodrębnij tekst z obrazu za pomocą OCR w Pythonie. Poznaj + wielojęzyczne OCR obrazów, automatyczne wykrywanie języka w OCR oraz krok po kroku, + jak wyodrębniać tekst OCR. +og_title: Wyodrębnianie tekstu z obrazu przy użyciu OCR w Pythonie – kompletny przewodnik +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Wyodrębnianie tekstu z obrazu przy użyciu OCR w Pythonie – Kompletny przewodnik +url: /pl/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wyodrębnianie tekstu z obrazu przy użyciu Python OCR – Kompletny przewodnik + +Kiedykolwiek potrzebowałeś **wyodrębnić tekst z obrazu**, ale nie byłeś pewien, która biblioteka potrafi automatycznie obsłużyć wiele języków? Nie jesteś sam — deweloperzy często pytają *jak wyodrębnić tekst OCR*, gdy mają do czynienia z międzynarodowymi dokumentami, paragonami czy zeskanowanymi ulotkami. W tym tutorialu przejdziemy przez praktyczny przykład w Pythonie, który nie tylko wyodrębnia tekst z obrazu, ale także **wykrywa język** w locie, czyniąc wielojęzyczne OCR obrazów dziecinnie proste. + +Omówimy wszystko, od instalacji pakietu OCR po włączenie **automatycznego wykrywania języka OCR**, uruchomienie silnika na przykładowym zdjęciu oraz wypisanie zarówno wykrytego języka, jak i wyodrębnionego ciągu znaków. Po zakończeniu będziesz mieć gotowy fragment kodu, który możesz wstawić do dowolnego projektu, niezależnie od tego, czy budujesz pipeline tłumaczeniowy, czy usługę ingestowania danych. + +## Wyodrębnianie tekstu z obrazu – przygotowanie środowiska + +Zanim zanurkujemy w kod, upewnij się, że Twój komputer spełnia następujące minimalne wymagania: + +- Python 3.8 lub nowszy (biblioteka używa podpowiedzi typów, które starsze wersje ignorują) +- `pip` do zarządzania pakietami +- Plik obrazu zawierający tekst w co najmniej dwóch różnych językach (np. angielski + hiszpański) + +Będziesz także potrzebował biblioteki OCR, która napędza tę demonstrację. Dla potrzeb tego przewodnika użyjemy fikcyjnego pakietu `ocr`, który odzwierciedla popularne rzeczywiste narzędzia, takie jak Tesseract czy EasyOCR, ale oferuje czyste API w Pythonie. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Wskazówka:** Jeśli napotkasz błędy uprawnień, poprzedź polecenie `python -m` lub użyj wirtualnego środowiska — utrzyma to Twoje globalne pakiety w porządku. + +## Utworzenie instancji silnika OCR + +Teraz, gdy biblioteka jest gotowa, pierwszym logicznym krokiem jest **utworzenie instancji silnika OCR**. Pomyśl o silniku jako o inteligentnym skanerze, który możesz skonfigurować przed podaniem mu obrazów. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Dlaczego tworzymy instancję silnika osobno, zamiast wywoływać metodę statyczną? Obiekt silnika przechowuje stan konfiguracji (np. preferencje językowe), który możesz chcieć ponownie wykorzystać przy wielu obrazach, oszczędzając koszt ponownego inicjowania przy każdym wywołaniu. + +## Włączenie automatycznego wykrywania języka OCR + +Większość narzędzi OCR wymaga podania kodu języka — `eng` dla angielskiego, `spa` dla hiszpańskiego itd. Ręczne zgadywanie języka podważa sens **wielojęzycznego OCR obrazu**. Na szczęście pakiet `ocr` oferuje tryb *auto detect language OCR*, który analizuje obraz i automatycznie wybiera najlepszy model językowy w tle. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Włączenie **detect language OCR** w ten sposób oznacza, że nie będziesz musiał utrzymywać długiej listy kodów językowych. Silnik spróbuje dopasować widoczny skrypt — łaciński, cyrylica, han itp. — i automatycznie załaduje odpowiedni model. + +## Wykonanie wielojęzycznego OCR obrazu + +Gdy silnik jest już przygotowany, czas naprawdę **wyodrębnić tekst z obrazu**. Metoda `recognize_image` przyjmuje ścieżkę do pliku i zwraca obiekt wyniku zawierający zarówno surowy tekst, jak i wykryty język. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Jeśli zastanawiasz się *jak wyodrębnić tekst OCR* z PDF zamiast PNG, ten sam silnik oferuje `recognize_pdf` — po prostu zamień nazwę metody. Logika wykrywania pozostaje identyczna, więc korzystasz z tej samej funkcji **auto detect language OCR**. + +## Wyświetlenie wykrytego języka i wyodrębnionego tekstu + +Na koniec wypisujemy to, co silnik odkrył. Obiekt wyniku udostępnia `detected_language` (znacznik BCP‑47, np. `en` lub `es`) oraz `text`, który zawiera surowy wynik OCR. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Uruchomienie skryptu na naszym przykładowym obrazie powinno dać coś podobnego do: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Zauważ, że silnik poprawnie zidentyfikował angielski jako język główny, a jednocześnie uchwycił hiszpańską linię — dokładnie to, czego oczekujesz od solidnego **wielojęzycznego OCR obrazu**. + +### Co zrobić, gdy wykrywanie zawiedzie? + +Czasami silnik OCR może przejść na język domyślny (zwykle angielski), jeśli obraz jest rozmazany lub skrypt jest zbyt egzotyczny. W takich przypadkach możesz wymusić listę języków: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Jednak pamiętaj, że wymuszanie języków podważa wygodę **auto detect language OCR**, więc używaj tego tylko wtedy, gdy znasz ograniczony zestaw języków. + +## Typowe pułapki i jak niezawodnie wyodrębniać tekst OCR + +Nawet przy automatycznym wykrywaniu może pojawić się kilka problemów: + +1. **Obrazy o niskiej rozdzielczości** – dokładność OCR gwałtownie spada poniżej 150 dpi. Zwiększ rozdzielczość lub poproś o skan w wyższej jakości. +2. **Szum i artefakty kompresji** – zastosuj prosty filtr progowy (`opencv` lub `Pillow`) przed przekazaniem obrazu do silnika. +3. **Mieszane skrypty na jednej stronie** – niektóre silniki mają trudności z jednoczesnym rozpoznawaniem znaków łacińskich i CJK. Podziel stronę na regiony i uruchom oddzielne rozpoznawanie w razie potrzeby. + +Rozwiązanie tych problemów znacząco podnosi jakość procesu **extract text from image**, szczególnie przy pracy z rzeczywistymi, wielojęzycznymi dokumentami. + +## Pełny działający przykład + +Poniżej znajduje się kompletny, gotowy do uruchomienia skrypt, który łączy wszystkie omawiane kroki. Zapisz go jako `multilingual_ocr.py` i uruchom z wiersza poleceń. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Oczekiwany wynik** (zakładając, że przykładowy obraz zawiera tekst po angielsku i hiszpańsku): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Śmiało zamień `multilang_page.png` na dowolny obraz zawierający tekst w innych językach — dzięki **auto detect language OCR** skrypt nadal zwróci sensowny znacznik języka oraz odpowiadający mu tekst. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Zakończenie + +Teraz wiesz dokładnie **jak wyodrębnić tekst OCR** z obrazu, jak włączyć **auto detect language OCR** oraz jak radzić sobie z **wielojęzycznym OCR obrazu** przy minimalnym kodzie. Tworząc instancję silnika OCR, włączając automatyczne wykrywanie języka i wywołując `recognize_image`, możesz niezawodnie uzyskać zarówno identyfikator języka, jak i surowy tekst. + +Co dalej? Spróbuj przekazać wyodrębnione ciągi do API tłumaczeniowego, zapisać je w przeszukiwalnej bazie danych lub połączyć wiele stron w jeden raport PDF. Możesz także eksperymentować z różnymi backendami OCR (Tesseract, EasyOCR, Google Vision), zachowując tę samą wysokopoziomową logikę — dzięki spójnemu interfejsowi **detect language OCR**. + +Jeśli napotkasz jakiekolwiek problemy, wróć do sekcji „Typowe pułapki” lub dostosuj kroki wstępnego przetwarzania obrazu. Powodzenia w kodowaniu i niech Twój kolejny projekt będzie pełen poprawnie wykrytego i perfekcyjnie wyodrębnionego tekstu! + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz krok po kroku wyjaśnienia, pomagające opanować dodatkowe funkcje API i eksplorować alternatywne podejścia w własnych projektach. + +- [Konwertuj obraz na tekst – wykonaj OCR na obrazie z URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Wyodrębnianie tekstu z obrazu – optymalizacja OCR z Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [rozpoznawanie tekstu na obrazie przy użyciu Aspose OCR dla wielu języków](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/polish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..bcd6291f5 --- /dev/null +++ b/ocr/polish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-06-06 +description: Wyodrębnij tekst z obrazów PDF przy użyciu OCR w Pythonie. Dowiedz się, + jak szybko konwertować zeskanowane dokumenty na tekst przy użyciu asynchronicznego + rozpoznawania wsadowego. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: pl +og_description: Wyodrębnij tekst z obrazów PDF przy użyciu Pythona. Ten przewodnik + krok po kroku pokazuje, jak konwertować zeskanowane dokumenty na tekst przy użyciu + asynchronicznego OCR. +og_title: Wyodrębnianie tekstu z obrazów PDF – samouczek OCR w Pythonie +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Wyodrębnij tekst z obrazów PDF – Przewodnik Pythona do konwersji zeskanowanych + dokumentów na tekst +url: /pl/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wyodrębnianie tekstu z obrazów PDF – Przewodnik Pythona do konwertowania zeskanowanych dokumentów na tekst + +Czy kiedykolwiek potrzebowałeś **wyodrębnić tekst z obrazów pdf** bez spędzania godzin na przepisywaniu? W tym przewodniku pokażemy, jak **przekształcić zeskanowane dokumenty na tekst** przy użyciu prostego asynchronicznego przepływu pracy OCR w Pythonie. + +Jeśli kiedykolwiek patrzyłeś na stos zeskanowanych PDF‑ów i pomyślałeś: „Musi istnieć szybszy sposób”, jesteś we właściwym miejscu. Przejdziemy przez każdy wiersz kodu, wyjaśnimy, dlaczego każdy element ma znaczenie, i omówimy kilka przypadków brzegowych, na które możesz natrafić. + +## Czego się nauczysz + +- Jak uruchomić silnik OCR i ustawić język rozpoznawania. +- Mechanikę podawania mieszanej listy PNG‑ów i PDF‑ów do rozpoznawania wsadowego. +- Uruchamianie zadania OCR asynchronicznie, aby Twoja aplikacja pozostała responsywna. +- Pobieranie wyników, łączenie ich z plikami źródłowymi i wyświetlanie czystego wyjścia. + +**Wymagania wstępne**: Python 3.8+, podstawowa znajomość `asyncio` lub `concurrent.futures` oraz biblioteka OCR udostępniająca klasę `OcrEngine` podobną do tej w przykładzie (np. Aspose.OCR, wrapper Tesseract lub własny wrapper). Nie wymaga skomplikowanej konfiguracji — wystarczy zainstalować bibliotekę i możesz zaczynać. + +![wyodrębnić tekst z obrazów pdf](https://example.com/placeholder.png "Zrzut ekranu wyniku OCR – wyodrębnić tekst z obrazów pdf") + +## Wyodrębnianie tekstu z obrazów PDF – Konfiguracja silnika OCR + +Pierwszą rzeczą, której potrzebujesz, jest instancja silnika OCR skonfigurowana na język Twoich dokumentów. W naszym przypadku użyjemy francuskiego, ale możesz zamienić go na dowolny obsługiwany język. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Dlaczego to ma znaczenie**: Ustawienie języka z góry znacząco zwiększa dokładność. Silnik korzysta ze słowników i modeli znaków specyficznych dla języka; podanie niewłaściwego języka jest częstym źródłem zniekształconego wyjścia. + +## Przygotowanie listy plików – obrazy i PDF‑y razem + +Nasz rozpoznawacz wsadowy radzi sobie zarówno z obrazami rastrowymi (`.png`, `.jpg`), jak i kontenerami PDF. Wystarczy podać zwykłą listę ścieżek plików w Pythonie. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Wskazówka**: Trzymaj listę płaską; silnik wewnętrznie rozpakowuje każdą stronę PDF‑a na obrazy przed rozpoznaniem. Jeśli masz tysiące plików, rozważ podzielenie listy na mniejsze partie, aby uniknąć skoków pamięci. + +## Rozpoczęcie asynchronicznego rozpoznawania wsadowego + +Zamiast blokować główny wątek, uruchamiamy zadanie OCR w tle. Metoda zwraca `Future`, który ostatecznie będzie zawierał listę obiektów `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Jak to działa**: Pod maską silnik tworzy pulę wątków (lub zadanie async, w zależności od implementacji). Dzięki temu możesz kontynuować inne czynności — np. aktualizować interfejs UI, pobierać kolejne pliki lub logować postęp — podczas gdy ciężka praca odbywa się w tle. + +## Zrób coś pożytecznego, gdy OCR działa + +Częstym błędem jest bezczynne czekanie i ciągłe odpytywanie `Future` w ciasnej pętli. Zamiast tego możesz wykonywać dowolne niezwiązane zadania. Dla demonstracji po prostu wypiszemy linię statusu. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Zbierz wyniki po zakończeniu `Future` + +Kiedy będziesz gotowy, aby zebrać wynik OCR, użyj `as_completed` z `concurrent.futures`. Ten wzorzec działa zarówno przy jednym, jak i wielu `Future`. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Co zobaczysz**: Każda ścieżka pliku, po której następuje wyodrębniona reprezentacja tekstowa. Dla PDF‑ów `result.text` zawiera połączony tekst ze wszystkich stron. + +### Oczekiwane wyjście (przykład) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Jeśli zauważysz brakujące znaki, sprawdź, czy ustawiony język odpowiada językowi dokumentu i rozważ wstępne przetworzenie obrazów (prostowanie, zwiększenie kontrastu) przed podaniem ich silnikowi. + +## Obsługa przypadków brzegowych i typowych pułapek + +| Sytuacja | Co zrobić | +|-----------|------------| +| **Mixed languages** | Najpierw wykonaj wykrywanie języka, a następnie utwórz osobne silniki dla każdego języka. | +| **Huge PDFs (> 100 MB)** | Podziel PDF na pojedyncze strony na dysku (np. przy użyciu `PyPDF2`) i podawaj je jako oddzielne wpisy. | +| **Non‑Latin scripts** | Upewnij się, że biblioteka OCR zawiera wymagany pakiet językowy; niektóre biblioteki wymagają pobrania dodatkowych plików danych. | +| **Performance bottleneck** | Zwiększ rozmiar puli wątków (`engine.set_thread_pool_size(8)`) lub przełącz na backend przyspieszony GPU, jeśli jest dostępny. | +| **Missing text in low‑resolution images** | Wstępnie przetwórz obraz za pomocą OpenCV: `cv2.resize`, `cv2.threshold` i `cv2.medianBlur`, aby poprawić czytelność. | + +## Pełny działający przykład (gotowy do kopiowania) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Zapisz to jako `extract_text_async.py`, zamień `YOUR_DIRECTORY` na ścieżkę do swoich plików, zainstaluj pakiet OCR (`pip install your-ocr-lib`) i uruchom `python extract_text_async.py`. Powinieneś zobaczyć w konsoli wyjście przedstawione wcześniej. + +## Kolejne kroki – wyjście poza podstawowe wyodrębnianie + +- **Post‑processing**: Usuń zbędne białe znaki, normalizuj Unicode (`unicodedata.normalize`) lub uruchom korektor ortograficzny, aby oczyścić szumy OCR. +- **Structured output**: Eksportuj wyniki do CSV, JSON lub bezpośrednio do bazy danych w celu dalszego wyszukiwania. +- **Parallel batches**: Jeśli masz setki plików, uruchom wiele `Future` i użyj kolejki, aby utrzymać CPU zajęte bez przeciążania pamięci. +- **Integrate with web frameworks**: Podłącz ten skrypt do endpointu Flask lub FastAPI, aby udostępniać OCR na żądanie jako usługę. + +--- + +### TL;DR + +Teraz wiesz, jak **wyodrębnić tekst z obrazów pdf** przy użyciu minimalnego skryptu Pythona, który uruchamia OCR asynchronicznie, pozwalając **przekształcić zeskanowane dokumenty na tekst**, podczas gdy Twój program pozostaje responsywny. Eksperymentuj z ustawieniami języka, rozmiarami partii i trikami wstępnego przetwarzania, aby wydobyć maksymalną dokładność. + +Masz własny pomysł, który chciałbyś podzielić — może OCR na notatkach odręcznych lub usługa w chmurze? Dodaj komentarz i powodzenia w kodowaniu! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki dotyczą ściśle powiązanych tematów, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz wyjaśnienia krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Wyodrębnianie tekstu z obrazu przy użyciu Aspose OCR – przewodnik krok po kroku](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Wyodrębnianie tekstu z obrazów przy użyciu operacji OCR na folderach](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Wyodrębnianie tekstu z obrazów przy użyciu Aspose.OCR – dozwolone znaki](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/polish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..cb57d5b60 --- /dev/null +++ b/ocr/polish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Jak zrobić OCR PDF w Pythonie, wyodrębnić tekst z PDF, przetworzyć tekst + zeskanowanego PDF i zmienić język OCR w kilku linijkach kodu. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: pl +og_description: 'Jak wykonać OCR PDF w Pythonie: praktyczny przewodnik, który pokazuje, + jak wyodrębnić tekst z PDF, konwertować zeskanowany tekst PDF oraz łatwo zmienić + język OCR.' +og_title: Jak zrobić OCR PDF w Pythonie – Pełny samouczek programistyczny +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Jak wykonać OCR PDF w Pythonie – Kompletny przewodnik krok po kroku +url: /pl/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak wykonać OCR PDF w Pythonie – Kompletny przewodnik krok po kroku + +Zastanawiałeś się kiedyś, **jak wykonać OCR PDF** bez płacenia za drogie narzędzia SaaS? Nie jesteś sam. Niezależnie od tego, czy digitalizujesz stare książki, wyciągasz dane z faktur, czy po prostu potrzebujesz przeszukiwalnego tekstu ze zeskanowanego raportu, opanowanie OCR PDF w Pythonie może zaoszczędzić Ci godziny ręcznego kopiowania. + +W tym tutorialu przeprowadzimy Cię przez zwięzły, działający przykład, który **wyodrębnia tekst z PDF**, pokazuje, jak **przekształcić zeskanowany tekst PDF** w edytowalne ciągi znaków oraz demonstruje, jak **zmienić język OCR**, jeśli dokument nie jest po angielsku. Po zakończeniu będziesz mieć gotowy fragment kodu, który możesz wkleić do dowolnego projektu. + +## Wymagania wstępne i konfiguracja + +Zanim zaczniemy, upewnij się, że masz: + +- Python 3.8+ zainstalowany (kod działa na 3.9, 3.10 i nowszych) +- Pakiet `ocr` udostępniający klasę `OcrEngine` (możesz go zainstalować poleceniem `pip install ocr-lib` – zamień na rzeczywistą nazwę pakietu, którego używasz) +- Plik PDF, który chcesz przetworzyć; w demonstracji użyjemy `high_res_book.pdf` umieszczonego w folderze o nazwie `YOUR_DIRECTORY` + +Jeśli używasz wirtualnego środowiska (bardzo zalecane), najpierw je aktywuj: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** Trzymaj pliki PDF w dedykowanym katalogu `data/`, aby uniknąć problemów ze ścieżkami później. + +## Krok 1: Utworzenie instancji silnika OCR (How to OCR PDF – Initialization) + +Pierwszą rzeczą, którą musisz zrobić, aby **wykonać OCR na PDF** jest zainicjowanie silnika. Pomyśl o silniku jako o mózgu, który odczyta każdą stronę, zinterpretuje glify i zwróci czysty tekst. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Dlaczego to ważne: bez silnika nie masz kontekstu dla ustawień języka, opcji renderowania ani obsługi PDF. Obiekt `OcrEngine` przechowuje wszystkie domyślne wartości i pozwala je później modyfikować. + +## Krok 2: Ustawienie języka rozpoznawania (Change OCR Language) + +Większość bibliotek OCR domyślnie używa języka angielskiego, ale co zrobić, gdy dokument jest po francusku, niemiecku lub nawet po japońsku? Zmiana języka jest tak prosta, jak wywołanie `set_recognition_language`. Spełnia to wymóg **change OCR language** i zapewnia wyższą dokładność. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Dlaczego możesz tego potrzebować:** Archiwum wielojęzyczne często zawiera strony w różnych językach. Przełączanie języka w locie zapobiega błędnemu rozpoznawaniu znaków takich jak „ß” czy „ñ”. + +## Krok 3: Konfiguracja opcji renderowania PDF (Convert Scanned PDF Text Effectively) + +Przy skanowanych PDF‑ach rozdzielczość i tryb kolorów mają ogromny wpływ na jakość OCR. Renderowanie w 300 DPI w trybie szarości to optymalny punkt dla większości dokumentów – wystarczająco wysokie, aby uchwycić szczegóły, a jednocześnie na tyle niskie, aby zużycie pamięci było rozsądne. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Łańcuchowe wywołania mogą wyglądać efektownie, ale to po prostu płynne API, które za każdym razem zwraca ten sam obiekt opcji. Jeśli potrzebujesz koloru (np. dla kolorowych diagramów), zamień `"grayscale"` na `"color"`. + +## Krok 4: Rozpoznanie PDF i pobranie tekstu z pierwszej strony (Extract Text from PDF) + +Teraz przechodzi do sedna **jak wykonać OCR PDF**: przekazujemy silnikowi ścieżkę do pliku i wyciągamy rozpoznany tekst. Metoda zwraca listę wyników stron; każdy wynik zawiera atrybut `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Jeśli potrzebujesz całego dokumentu, iteruj po `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Co zrobić, gdy PDF jest zaszyfrowany? + +Niektóre PDF‑y są chronione hasłem. W takim wypadku możesz przekazać hasło do `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Silnik odszyfruje plik w locie przed wykonaniem OCR – nie są potrzebne dodatkowe kroki. + +## Krok 5: Post‑processing wyodrębnionego tekstu (Fine‑Tuning Extract Text from PDF) + +Surowy wynik OCR często zawiera podziały linii, dodatkowe spacje lub sporadyczne błędnie rozpoznane znaki. Krótka procedura czyszczenia przygotowuje wyodrębniony ciąg do dalszego przetwarzania (indeksowanie, przechowywanie w bazie danych itp.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Teraz możesz bezpiecznie **wyodrębnić tekst z PDF** i przekazać go do dowolnego potoku NLP, silnika wyszukiwania lub po prostu zapisać przy pomocy `open(...).write()`. + +## Bonus: Przetwarzanie wsadowe wielu PDF‑ów (Scaling Perform OCR on PDF) + +Jeśli masz folder pełen zeskanowanych PDF‑ów, owiń logikę w pętlę: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Ten fragment pokazuje, jak **wykonać OCR na PDF** w trybie wsadowym – częsta potrzeba w projektach digitalizacji. + +## Oczekiwany wynik + +Uruchomienie przykładu jednokolumnowego (Krok 4) powinno wypisać coś w stylu: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Jeśli przetworzyłeś książkę wielostronicową, konsola wyświetli wyczyszczony tekst każdej strony, a skrypt wsadowy utworzy plik `.txt` obok każdego PDF‑a. + +## Typowe problemy i jak ich unikać + +| Problem | Objawy | Rozwiązanie | +|---------|--------|--------------| +| PDF o niskiej rozdzielczości | Zniekształcone znaki, brakujące słowa | Zwiększ DPI (`set_dpi(400)` lub wyżej) | +| Nieprawidłowy język | Wiele nieznanych symboli, zwłaszcza znaków akcentowanych | Użyj `engine.set_recognition_language(ocr.Language.FRENCH)` lub odpowiedniego enumu | +| Duży PDF powodujący błąd pamięci | `MemoryError` lub awaria po kilku stronach | Przetwarzaj strony w partiach (`engine.recognize_pdf(..., max_pages=10)`) | +| Brak czcionek w PDF | Puste wyjście dla niektórych stron | Upewnij się, że PDF rzeczywiście zawiera obrazy rastrowe; niektóre PDF‑y są wyłącznie wektorowe i wymagają innego podejścia | + +## Ilustracja + +Poniżej szybka wizualizacja przepływu pracy. Tekst alternatywny jest celowo przyjazny SEO. + +![jak wykonać OCR PDF diagram przepływu pokazujący inicjalizację silnika, ustawienie języka, opcje renderowania, rozpoznanie i wyodrębnianie tekstu](/images/ocr-workflow.png) + +*Diagram nie jest niezbędny do działania kodu, ale pomaga osobom uczącym się wizualnie zobaczyć, gdzie każdy krok się wpisuje.* + +## Zakończenie + +Omówiliśmy **jak wykonać OCR PDF** w Pythonie od początku do końca: tworzenie silnika OCR, **zmianę języka OCR**, konfigurację renderowania w celu **konwersji zeskanowanego tekstu PDF** oraz w końcu **wyodrębnianie tekstu z PDF** do dalszego wykorzystania. Pełny, gotowy do uruchomienia przykład jest gotowy do wklejenia w dowolny projekt, a opcjonalny skrypt wsadowy pokazuje, jak skalować rozwiązanie. + +Następnie możesz rozważyć: + +- Dodanie **perform OCR on PDF** dla archiwów wielojęzycznych poprzez iterację po liście języków. +- Integrację wyodrębnionego tekstu z Elasticsearch w celu pełnotekstowego wyszukiwania. +- Użycie OCR do tworzenia przeszukiwalnych PDF‑ów poprzez osadzenie warstwy tekstowej z powrotem w oryginalnym pliku (wiele bibliotek udostępnia metodę `save_as_searchable_pdf`). + +Śmiało eksperymentuj, modyfikuj ustawienia DPI lub przełącz się na inny backend OCR. Fundamenty pozostają takie same, a Ty masz solidną bazę do dalszego rozwoju. + +Miłego kodowania i niech Twoje zeskanowane dokumenty w końcu staną się przeszukiwalne! + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz wyjaśnienia krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Rozpoznawanie tekstu PDF – operacje OCR z Aspose.OCR dla Javy](/ocr/english/java/ocr-operations/) +- [Jak wykonać OCR obrazu z wyborem języka przy użyciu Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Jak wykonać OCR PDF w .NET z Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/polish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..fb0b2a06a --- /dev/null +++ b/ocr/polish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-06 +description: Jak wykonać OCR PDF i tworzyć przeszukiwalne pliki PDF z obrazów przy + użyciu Pythona. Dowiedz się, jak dodać przeszukiwalny tekst i w kilka minut przekonwertować + obraz na PDF/A. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: pl +og_description: Jak przeprowadzić OCR PDF krok po kroku. Dowiedz się, jak dodać tekst + przeszukiwalny i przekonwertować obraz na PDF/A przy użyciu prostego skryptu w Pythonie. +og_title: Jak zrobić OCR PDF – szybki przewodnik tworzenia przeszukiwalnych PDF‑ów +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Jak wykonać OCR PDF w Pythonie – Utwórz przeszukiwalny PDF z obrazów +url: /pl/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak OCR-ować PDF – Zamień zeskanowane obrazy w przeszukiwalne PDFy + +Zastanawiałeś się kiedyś **jak OCR-ować PDF** gdy jedyne, co masz, to zeskanowany obraz faktury lub paragonu? Nie jesteś jedyny. W wielu biurach przychodząca dokumentacja pojawia się jako płaskie pliki PNG lub JPEG, a kolejny krok — uczynienie tej treści przeszukiwalną — wydaje się czarną skrzynką. + +The good news? With just a few lines of Python you can **create searchable PDF** files, **add searchable text**, and even **convert image to PDF/A** for long‑term archiving. In this tutorial we’ll walk through each step, explain why it matters, and give you a ready‑to‑run script that you can drop into any project. + +> **Porada:** To samo podejście działa dla skanów wielostronicowych; po prostu iteruj po plikach, a silnik wykona ciężką pracę. + +--- + +## Czego będziesz potrzebować + +Before we dive in, make sure you have the following on your machine: + +| Wymaganie | Dlaczego jest ważne | +|-------------|----------------| +| Python 3.9 or newer | Nowoczesna składnia i lepsze wsparcie bibliotek | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Obsługuje zarówno rozpoznawanie obrazu, jak i generowanie PDF/A | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | Plik obrazu (PNG, JPEG, TIFF), który chcesz zamienić w przeszukiwalny PDF | +| Write permission to the output folder | Uprawnienia zapisu do folderu wyjściowego | + +If you haven’t installed the OCR SDK yet, run: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +That’s it—no complex system dependencies, just a pip install. + +## Jak OCR-ować PDF – Przegląd + +At a high level the process consists of three simple actions: + +1. **Recognize** the text inside the image while preserving the original graphics. +2. **Export** the OCR result together with the original image as a **searchable PDF/A** (the archival‑friendly PDF flavour). +3. **Validate** that the resulting file contains selectable, searchable text layered over the original picture. + +Below you’ll see each step in code, with explanations of the *why* behind the commands. + +## Krok 1: Rozpoznaj tekst z obrazu + +First we ask the OCR engine to read the pixels and return a result object that holds both the raw image and the extracted text. Think of it as the engine “reading” the invoice for you. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Dlaczego to ważne + +- **Zachowanie grafiki** oznacza, że układ wizualny (tabele, loga, pieczęcie) pozostaje dokładnie taki, jak zeskanowano. +- Obiekt `result` zazwyczaj zawiera ukrytą warstwę tekstową, którą później wstawimy do PDF. +- Użycie `recognize_image` zamiast `recognize_pdf` unika dodatkowego kroku konwersji, co przyspiesza przetwarzanie jednopostaciowych obrazów. + +#### Typowe warianty + +- Jeśli masz **wielostronicowy TIFF**, przekaż bezpośrednio ścieżkę do pliku; większość silników potraktuje każdą stronę jako osobny obraz. +- Dla PDF‑ów, które już zawierają obrazy, możesz wywołać `engine.recognize_pdf("file.pdf")` i pominąć ten krok całkowicie. + +## Krok 2: Eksportuj wynik OCR jako przeszukiwalny PDF/A + +Now we take the `result` from step 1 and tell the engine to write a new file. The key flag here is *PDF/A*—the ISO‑standard version of PDF designed for long‑term preservation. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Dlaczego to ważne + +- **Przeszukiwalny PDF**: Plik wyjściowy zawiera ukrytą, wybieralną warstwę tekstową. Teraz możesz używać Ctrl + F w dokumencie. +- **Zgodność z PDF/A**: Niektóre organizacje (prawne, finansowe) wymagają PDF/A do ścieżek audytu; ten krok spełnia ten wymóg automatycznie. +- Metoda także **dodaje przeszukiwalny tekst** bez spłaszczania obrazu, więc wierność wizualna pozostaje idealna. + +#### Edge case: Need a regular PDF instead? + +If you don’t care about PDF/A, replace `save_as_pdfa` with `save_as_pdf`. The rest of the workflow stays the same. + +## Krok 3: Zweryfikuj przeszukiwalny PDF + +A quick sanity check saves you from mysterious bugs later. Open the generated file in any PDF viewer, try selecting a word, and use the search function. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Expected output + +When you run the script, the console prints: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Opening the file, you should see the original invoice image with a faint, invisible text layer. Highlight any word and you’ll notice it’s selectable—**that’s the searchable text** you just added. + +## Dodawanie przeszukiwalnego tekstu do istniejących PDF‑ów (Bonus) + +Sometimes you already have a PDF but need to **add searchable text** to it. The same engine can overlay OCR results onto an existing PDF: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Here `apply_to` merges the hidden layer with the original pages, letting you **create searchable PDF** without re‑scanning. + +## Częste pułapki i wskazówki + +| Pułapka | Jak tego uniknąć | +|---------|-----------------| +| **Obrazy źródłowe o niskiej rozdzielczości** (< 150 dpi) | Zwiększ rozdzielczość lub poproś o skan w wyższej rozdzielczości; dokładność OCR drastycznie spada poniżej 150 dpi. | +| **Brak danych językowych** | Zainstaluj odpowiednie pakiety językowe dla swojego silnika OCR (`pip install pdfocr[eng,spa]`). | +| **Folder wyjściowy nie jest zapisywalny** | Uruchom skrypt z odpowiednimi uprawnieniami lub wybierz inny katalog. | +| **Walidacja PDF/A nie powiodła się** | Upewnij się, że nie osadzasz nieobsługiwanych czcionek ani JavaScript; większość SDK automatycznie radzi sobie z tym przy użyciu `save_as_pdfa`. | + +## Pełny skrypt – rozwiązanie jednoplikowe + +Below is a self‑contained script that ties everything together. Copy‑paste it, replace the placeholder paths, and you’re ready to **convert image to PDF/A** in seconds. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Co robi ten skrypt:** +1. Ładuje silnik OCR. +2. Odczytuje wybrany obraz i wyodrębnia tekst. +3. Zapisuje **przeszukiwalny PDF/A**, który możesz od razu rozpowszechniać lub archiwizować. + +Feel free to wrap the `main` logic in a function that processes a whole folder—just iterate over `os.listdir()` and repeat the three steps for each file. + +## Kolejne kroki i powiązane tematy + +Now that you’ve mastered **how to OCR PDF**, consider exploring these follow‑up ideas: + +- **Przetwarzanie wsadowe:** Użyj `concurrent.futures`, aby OCR‑ować dziesiątki faktur równolegle. +- **Wstrzykiwanie metadanych:** Dodaj daty utworzenia lub numery faktur do metadanych PDF, aby ułatwić indeksowanie. +- **Hybrydowe PDFy:** Połącz przeszukiwalny tekst z osadzonymi oryginalnymi obrazami, tworząc „cyfrowego bliźniaka” dokumentu papierowego. +- **Alternatywne formaty wyjściowe:** Eksportuj do **DOCX** lub **HTML**, jeśli systemy downstream potrzebują edytowalnych formatów. + +Each of these builds on the core concepts you just learned—recognize, export, verify. + +## Podsumowanie + +In a nutshell, you now know **how to OCR PDF** files by turning a simple image into a **searchable PDF/A** with just three lines of Python. The script handles the heavy lifting, preserves the original graphics, and gives you a standards‑compliant document that you can search, archive, or share. + +Give it a spin with your own invoices, receipts, or scanned contracts. If you hit any snags, drop a comment below or check the SDK’s official docs—they’re usually packed with extra examples. Happy coding, and enjoy the newfound ability to make any image instantly searchable! + +![Przykład OCR PDF pokazujący oryginalny obraz i nakładkę przeszukiwalnego PDF](placeholder.png "Przykład OCR PDF") + +## Co warto nauczyć się dalej? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Jak OCR-ować PDF w .NET z Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Rozpoznawanie tekstu PDF – operacje OCR z Aspose.OCR dla Javy](/ocr/english/java/ocr-operations/) +- [Konwertowanie obrazów do PDF C# – zapisywanie wyniku OCR wielostronicowego](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/polish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..d3b9c51f0 --- /dev/null +++ b/ocr/polish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Jak wykonać OCR pliku PDF przy użyciu Aspose OCR Cloud. Dowiedz się, + jak wyodrębnić tekst z PDF, przekonwertować stronę PDF na PNG oraz zapisać obrazy + stron PDF w Pythonie. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: pl +og_description: Jak wykonać OCR PDF za pomocą Aspose OCR Cloud. Ten przewodnik pokazuje, + jak wyodrębnić zwykły tekst z PDF, konwertować stronę PDF na PNG oraz zapisać obrazy + stron PDF. +og_title: Jak wykonać OCR PDF za pomocą Aspose OCR Cloud – krok po kroku +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Jak wykonać OCR PDF przy użyciu Aspose OCR Cloud – Kompletny przewodnik +url: /pl/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak wykonać OCR PDF przy użyciu Aspose OCR Cloud – Kompletny przewodnik + +Zastanawiałeś się kiedyś **jak wykonać OCR PDF** bez konieczności używania ciężkich narzędzi desktopowych? Nie jesteś sam — wielu programistów napotyka ten problem, gdy potrzebują szybkiego, programowego sposobu na wyodrębnienie tekstu ze skanowanych dokumentów. Dobra wiadomość? Dzięki Aspose OCR Cloud możesz **wyodrębnić tekst z PDF**, zamienić każdą stronę na PNG oraz **zapisać obrazy stron PDF** do późniejszego użycia, wszystko z jednego schludnego skryptu w Pythonie. + +W tym tutorialu przejdziemy krok po kroku przez wszystko, co musisz wiedzieć: od instalacji SDK, licencjonowania silnika i rozpoznawania wielostronicowych PDF‑ów, po wyodrębnianie czystego tekstu, konwersję stron na PNG oraz zapisywanie tych obrazów na dysku. Po zakończeniu będziesz mieć gotowy fragment kodu, który możesz wstawić do dowolnego projektu potrzebującego **jak wykonać OCR PDF**. + +## Co będzie potrzebne + +- **Python 3.8+** (kod działa również na 3.10 i nowszych) +- Konto Aspose OCR Cloud – otrzymasz darmowy plik licencyjny (`Aspose.OCR.lic`) +- Pakiet `asposeocrcloud` (`pip install asposeocrcloud`) +- Skanowany, wielostronicowy PDF, który chcesz przetworzyć + +To wszystko. Bez dodatkowych binarek, bez natywnych zależności, po prostu czysty Python. + +## Jak wykonać OCR PDF – konfiguracja i licencja + +Zanim będziesz mógł wywołać jakiekolwiek metody OCR, musisz poinformować SDK, kim jesteś. Aspose używa lekkiego pliku licencyjnego, który umieszczasz w miejscu dostępnym dla swojego skryptu. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Wskazówka:* Jeśli pominiesz krok z licencją, SDK nadal będzie działać, ale wstawia mały znak wodny do wygenerowanych obrazów. Nie jest to idealne rozwiązanie produkcyjne. + +## Krok 2: Instalacja SDK Aspose OCR Cloud dla Pythona + +Otwórz terminal i uruchom: + +```bash +pip install asposeocrcloud +``` + +Pakiet pobiera wszystkie wymagane zależności (requests, pillow itp.), więc nie musisz szukać niczego innego. + +## Krok 3: Utwórz silnik OCR i wybierz język + +Silnik jest sercem operacji. Możesz określić dowolny język obsługiwany przez Aspose; angielski działa w większości przypadków. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Dlaczego ustawia się język? Ponieważ silnik OCR używa słowników specyficznych dla języka, aby zwiększyć dokładność. Jeśli przetwarzasz francuskie PDF‑y, po prostu zamień `ENGLISH` na `FRENCH`. + +## Krok 4: Wskaż swój wielostronicowy PDF + +Podaj silnikowi pełną ścieżkę do pliku, który chcesz przetworzyć. Ścieżki względne są w porządku, o ile rozwiążą się względem katalogu roboczego skryptu. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Upewnij się, że plik jest czytelny; w przeciwnym razie zobaczysz błąd `FileNotFoundError`. + +## Krok 5: Uruchom OCR – otrzymasz listę wyników + +Wywołanie `recognize_pdf` zwraca listę, w której każdy element odpowiada jednej stronie źródłowego PDF‑a. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Każdy `OcrResult` zawiera dwie przydatne właściwości: + +* `text` – tekstowa reprezentacja strony (idealna do **extract plain text pdf**) +* `image` – obiekt Pillow `Image` przedstawiający wyrenderowaną stronę (idealny do **convert pdf page png**) + +## Krok 6: Wyodrębnij tekst z PDF i konwertuj strony na PNG + +Teraz przechodzimy przez wyniki, wypisujemy wyodrębniony tekst i zapisujemy wersję PNG każdej strony. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Oczekiwany wynik w konsoli + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Znajdziesz także pliki `page_1.png`, `page_2.png`, … w katalogu `YOUR_DIRECTORY`. Są to rasteryzowane obrazy stron, które możesz przekazać do dalszych potoków przetwarzania obrazu. + +## Krok 7: Zapisz obrazy stron PDF (opcjonalne przetwarzanie końcowe) + +Jeśli potrzebujesz tylko obrazów, a nie tekstu, możesz pominąć linię `print(res.text)`. Odwrotnie, jeśli chcesz przechowywać tekst w oddzielnych plikach `.txt`, wystarczy dodać małe zapisywanie: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +To małe rozszerzenie pokazuje, jak łatwo **save PDF page images** jednocześnie zachowując wyodrębnioną treść. + +## Pełny działający przykład + +Łącząc wszystko w całość, oto kompletny skrypt, który możesz skopiować do pliku `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Uruchom go poleceniem: + +```bash +python ocr_pdf.py +``` + +Powinieneś zobaczyć w konsoli wypisany tekst każdej strony oraz serię plików PNG. + +## Co warto poznać dalej? + +Poniższe tutoriale obejmują tematy blisko powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/polish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..1b087168a --- /dev/null +++ b/ocr/polish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-06 +description: Jak przygotować obrazy do OCR przy użyciu Pythona. Dowiedz się, jak binaryzować + obraz metodą Otsu, jak prostować zeskanowane dokumenty oraz jak poprawić dokładność + OCR dla tekstu niemieckiego. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: pl +og_description: Jak przygotować obrazy do OCR w Pythonie. Ten tutorial pokazuje, jak + binaryzować obraz przy użyciu metody Otsu, jak prostować zeskanowane dokumenty oraz + jak poprawić dokładność OCR dla obrazów w języku niemieckim. +og_title: Jak przygotować obrazy do OCR – Kompletny przewodnik w Pythonie +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Jak przygotować obrazy do OCR – Kompletny przewodnik w Pythonie +url: /pl/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak przetwarzać obrazy pod OCR – Kompletny przewodnik w Pythonie + +Zastanawiałeś się kiedyś **jak przetwarzać obrazy pod OCR**, aby tekst był krystalicznie czysty? Nie jesteś jedyny. Skanowane dokumenty — szczególnie zaszumione niemieckie strony — mogą być koszmarem dla każdego silnika OCR. Dobra wiadomość? Kilka sprytnych kroków przetwarzania może zamienić rozmyty, zaszpunowany skan w czysty, czytelny dla maszyny obraz. + +W tym samouczku przeprowadzimy praktyczny przykład, który pokazuje **jak przetwarzać obrazy pod OCR** przy użyciu Pythona. Nauczysz się **binarizować obraz metodą Otsu**, **jak prostować zeskanowane dokumenty**, oraz ogólnie **jak poprawić dokładność OCR**, gdy potrzebujesz **wyodrębnić tekst z niemieckich plików obrazów**. Bez zbędnych wstępów, tylko działający skrypt, który możesz skopiować‑wkleić już dziś. + +## Czego będziesz potrzebować + +- **Python 3.9+** (dowolna nowsza wersja) +- Biblioteka OCR udostępniająca klasę `OcrEngine` – w demonstracji przyjmiemy ogólny pakiet `ocr`. Zainstaluj go poleceniem `pip install ocr-lib`. +- Zaszumiony skan niemiecki (`noisy_german_scan.tif`), który chcesz przetestować. +- Podstawowa znajomość funkcji w Pythonie (jeśli już pisałeś `def`, jesteś gotowy). + +> **Pro tip:** Jeśli używasz innego SDK OCR (np. Tesseract przez `pytesseract`), koncepcje pozostają takie same — wystarczy dostosować nazwy metod. + +## Przegląd rozwiązania + +1. **Utwórz instancję silnika OCR.** +2. **Ustaw język rozpoznawania na niemiecki.** +3. **Zbuduj własny pipeline przetwarzania**, który obejmuje prostowanie, odszumianie, binarizację (Otsu) i rozciąganie kontrastu. +4. **Dołącz pipeline do silnika**, aby każde zdjęcie przechodziło przez niego automatycznie. +5. **Uruchom OCR** na zaszumionym niemieckim skanie. +6. **Wypisz wyodrębniony tekst**, aby zweryfikować wynik. + +![jak przetwarzać obrazy pod OCR przykład](image.png "jak przetwarzać obrazy pod OCR przykład") + +## Krok 1: Utwórz instancję silnika OCR + +Na początek — bez silnika nic się nie dzieje. Obiekt `OcrEngine` jest punktem wejścia, który koordynuje wszystkie późniejsze operacje. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Dlaczego to ważne:* Inicjalizacja silnika konfiguruje zasoby wewnętrzne (takie jak modele językowe) i daje czystą bazę do podłączenia własnego pipeline’u później. + +## Krok 2: Ustaw język rozpoznawania na niemiecki + +Dokładność OCR jest silnie zależna od języka. Informując silnik, że ma oczekiwać języka niemieckiego, aktywujesz odpowiedni zestaw znaków i model językowy. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Jeśli pominiesz ten krok, silnik może domyślnie używać angielskiego, co spowoduje błędne rozpoznawanie umlautów (ä, ö, ü) oraz znaku ß — typowe pułapki przy pracy z niemieckimi skanami. + +## Krok 3: Zbuduj własny pipeline przetwarzania + +To serce **jak przetwarzać obrazy pod OCR**. Połączymy cztery transformacje: + +| Transformacja | Co robi | Dlaczego pomaga | +|----------------|--------------|--------------| +| **Deskew** | Obraca obraz z powrotem do poziomu (maks 5°) | Skanowane dokumenty rzadko są idealnie wyrównane; prostowanie usuwa pochylenie, które myli segmentację znaków. | +| **Denoise** | Redukuje losowe plamki (siła 0.7) | Szum tworzy fałszywe krawędzie, które silnik OCR może zinterpretować jako znaki. | +| **Binarize (Otsu)** | Konwertuje do czerni‑i‑bieli metodą Otsu | Czysty obraz binarny zapewnia silnikowi wyraźny kontrast między pierwszym planem (tekst) a tłem. | +| **Contrast Stretch** | Rozciąga zakres dynamiczny | Poprawia czytelność słabych kresek, szczególnie w starych dokumentach. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Jak prostować zeskanowane dokumenty + +Wywołanie `deskew` powyżej jest konkretną odpowiedzią na **jak prostować zeskanowane dokumenty**. Wewnątrz szacuje dominujący kąt linii tekstu za pomocą transformacji Hougha i obraca obraz z powrotem. Jeśli Twoje dokumenty są obrócone o więcej niż 5°, zwiększ `max_angle`, ale uważaj na artefakty nadmiernego obracania. + +### Binarnizuj obraz metodą Otsu + +Linia `binarize(method="otsu")` bezpośrednio odpowiada na pytanie **binarizować obraz metodą Otsu**. Algorytm Otsu oblicza próg minimalizujący wariancję wewnątrz klas, co jest idealne dla dokumentów z dwumodalnym histogramem (ciemny tekst vs. jasne tło). + +## Krok 4: Dołącz pipeline do silnika + +Teraz informujemy silnik OCR, aby uruchamiał każdy przychodzący obraz przez właśnie zbudowany pipeline. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Dlaczego to ważne:* Bez rejestracji silnik przetworzyłby surowy skan, ignorując wszystkie przygotowane czyszczenia. Ten krok zapewnia **jak poprawić dokładność OCR** poprzez konsekwentne stosowanie tego samego przetwarzania. + +## Krok 5: Rozpoznaj tekst z zaszumionego niemieckiego skanu + +Czas połączyć wszystko. Przekazujemy silnikowi zaszumiony niemiecki obraz i pozwalamy mu wykonać ciężką pracę. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Jeśli interesuje Cię wydajność, możesz zmierzyć czas wywołania: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Krok 6: Wyświetl rozpoznany tekst + +Na koniec wypisujemy wyodrębniony ciąg znaków. To bezpośrednia odpowiedź na **wyodrębnić tekst z niemieckiego obrazu**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Oczekiwany wynik + +Zakładając, że przykładowy skan zawiera zdanie „Die schnelle braune Füchsin springt über den faulen Hund.”, powinieneś zobaczyć coś w stylu: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Jeśli wynik nadal zawiera zniekształcone znaki, rozważ dostosowanie siły `denoise` lub zwiększenie `max_angle` przy prostowaniu. + +## Częste pułapki i jak je rozwiązać + +- **Brak modelu językowego:** Zapomnienie o `set_recognition_language(Language.GERMAN)` często skutkuje brakującymi umlautami. Sprawdź, czy wywołanie jest obecne. +- **Nadmierne odszumianie:** Siła powyżej 0.9 może wymazać cienkie kreski, zwłaszcza w starszych czcionkach. Trzymaj się zakresu 0.5‑0.7 w większości przypadków. +- **Nieprawidłowy format pliku:** Niektóre silniki OCR nie radzą sobie z wielostronicowymi TIFF‑ami. Jeśli masz dokument wielostronicowy, podziel go najpierw na pojedyncze pliki. +- **Kolejność pipeline’u:** Pokazana kolejność (prostowanie → odszumianie → binarizacja → kontrast) jest zamierzona. Binarizacja przed odszumianiem może utrwalić szum; zawsze najpierw odszumiaj. + +## Rozszerzanie pipeline (Co dalej?) + +Teraz, gdy masz solidną bazę, możesz rozważyć: + +- **Dodanie otwarcia morfologicznego** w celu usunięcia drobnych plamek (`.morph_open(kernel=3)`). +- **Integrację modelu językowego** do korekcji po‑procesowej (`ocr_engine.apply_spellcheck()`). +- **Równoległe przetwarzanie wsadowe** dużych zbiorów danych przy użyciu `concurrent.futures`. + +Wszystkie te rozszerzenia zachowują główną ideę **jak przetwarzać obrazy pod OCR**, jednocześnie podnosząc **jak poprawić dokładność OCR** jeszcze bardziej. + +## Zakończenie + +Omówiliśmy **jak przetwarzać obrazy pod OCR** od początku do końca: utworzyliśmy silnik, ustawiliśmy język niemiecki, zbudowaliśmy pipeline, który **binarizuje obraz metodą Otsu**, **jak prostować zeskanowane dokumenty**, i w końcu **wyodrębnić tekst z niemieckiego obrazu** z większą pewnością. Stosując sześć opisanych kroków, zauważysz wyraźny wzrost jakości rozpoznawania — koniec z niekończącymi się ręcznymi poprawkami. + +Wypróbuj skrypt na własnych skanach, eksperymentuj z parametrami i pozwól wynikom przemówić. Masz pytania o konkretną technikę przetwarzania? Zostaw komentarz, a zagłębimy się razem. + +Powodzenia w kodowaniu i niech Twój OCR będzie zawsze precyzyjny! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz szczegółowe wyjaśnienia, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Wyodrębnij tekst z obrazu C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Jak ustawić wartość progu w rozpoznawaniu obrazu OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Jak wykonać OCR obrazu – Przeprowadź OCR na obrazie w rozpoznawaniu obrazu OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/polish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..a89d69da3 --- /dev/null +++ b/ocr/polish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,335 @@ +--- +category: general +date: 2026-06-06 +description: OCR obrazu PNG w Pythonie – dowiedz się, jak wyodrębnić tekst z obrazu, + uruchomić przykład OCR w Pythonie i nawet łatwo odczytać starogrecki tekst. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: pl +og_description: OCR obrazu PNG w Pythonie wyjaśnione. Ten przewodnik pokazuje, jak + wyodrębnić tekst z obrazu, uruchomić przykład OCR w Pythonie i z łatwością czytać + starogrecki. +og_title: OCR obrazu PNG w Pythonie – Kompletny poradnik +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR obrazu PNG w Pythonie – Kompletny przewodnik krok po kroku +url: /pl/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR obrazu PNG w Pythonie – Pełny przewodnik krok po kroku + +Zastanawiałeś się kiedyś, jak **OCR PNG image** pliki bezpośrednio z poziomu skryptu Pythona? Być może masz folder pełen zeskanowanych starożytnych rękopisów i potrzebujesz **extract text from image** plików bez ręcznego przepisywania wszystkiego. Dobra wiadomość: nie potrzebujesz doktoratu z widzenia komputerowego — wystarczy kilka linijek kodu i odpowiednia biblioteka, a w kilka sekund będziesz czytać starogrecki. + +W tym samouczku przeprowadzimy **python OCR example**, które rozpoznaje tekst z PNG, ustawia język na grecki politoniczny i wypisuje wynik. Po zakończeniu dokładnie będziesz wiedział, jak **recognize image text**, radzić sobie z typowymi pułapkami i dostosować skrypt do innych języków lub formatów obrazów. + +## Czego się nauczysz + +- Zainstalować i skonfigurować bibliotekę OCR dla Pythona (pytesseract + Tesseract OCR) +- Utworzyć instancję silnika OCR i wczytać plik PNG +- Ustawić język rozpoznawania na grecki politoniczny, aby móc **read ancient greek** +- Wyświetlić rozpoznany tekst i rozwiązać typowe problemy +- Rozszerzyć skrypt o przetwarzanie wsadowe wielu plików PNG lub przełączenie na inny język + +### Wymagania wstępne + +| Wymaganie | Dlaczego jest ważne | +|-------------|----------------| +| Python 3.8+ | Nowa składnia i wskazówki typów | +| `pytesseract` package | Cienka nakładka na silnik Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Rzeczywisty silnik, który wykonuje ciężką pracę | +| Greek language data (`grc.traineddata`) | Wymagane do poprawnego **read ancient greek** | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Nasz cel dla demonstracji **ocr png image** | + +Możesz zainstalować część Pythona za pomocą: + +```bash +pip install pytesseract Pillow +``` + +A na Ubuntu/macOS dodałbyś sam silnik: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Nie zapomnij pobrać danych treningowych greckiego politonicznego: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Ścieżka może się różnić; w razie potrzeby dostosuj `TESSDATA_PREFIX`.)* + +--- + +## OCR PNG Image: Utwórz instancję silnika + +Pierwszą rzeczą, której potrzebujemy, jest obiekt komunikujący się z Tesseract. W `pytesseract` silnik jest dostępny poprzez funkcje na poziomie modułu, ale dla przejrzystości opakujemy go w małą klasę. To odzwierciedla koncepcję „silnika”, którą widziałeś w oryginalnym fragmencie. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Dlaczego to opakować?** +- Utrzymuje publiczne API identyczne z fragmentem, od którego zaczynałeś, co ułatwia migrację. +- Umożliwia późniejsze dodanie logowania lub obsługi błędów bez modyfikacji głównego przepływu. +- Pokazuje dobrą praktykę OOP — coś, co doceniają starsi programiści. + +--- + +## Wyodrębnij tekst z obrazu: ustaw język na grecki politoniczny + +Teraz, gdy mamy silnik, musimy powiedzieć mu, jakiego języka się spodziewać. Grecki politoniczny używa znaków diakrytycznych, które nie są objęte standardowymi danymi „greek”, więc wskazujemy Tesseract na plik treningowy `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Jeśli kiedykolwiek zechcesz **extract text from image** plików w innym języku, po prostu zamień `"grc"` na `"eng"` dla angielskiego, `"fra"` dla francuskiego itd. Ten sam wiersz działa dla każdego zainstalowanego języka. + +--- + +## Rozpoznaj tekst obrazu: uruchom OCR na PNG + +Po ustawieniu języka podajemy PNG do silnika. Oryginalny przykład używał sztywno zakodowanej ścieżki; uczynimy to nieco bardziej elastycznym, używając obiektów `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Wskazówki i przypadki brzegowe** + +- **File not found** – otocz wywołanie w `try/except FileNotFoundError`, aby wyświetlić przyjazny komunikat. +- **Low‑resolution PNG** – rozważ wstępne przetworzenie (np. zmiana rozmiaru, binaryzacja) przy użyciu Pillow przed OCR. +- **Non‑Greek text** – Tesseract nadal spróbuje zdekodować, ale dokładność gwałtownie spada. Zawsze dopasowuj język. + +--- + +## Wyświetl rozpoznany tekst + +Na koniec wypisujemy wynik. W prawdziwym projekcie możesz zapisać go do bazy danych, pliku CSV lub nawet przekazać do potoku tłumaczeniowego. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Gdy uruchomisz skrypt na wyraźnym skanie starożytnego greckiego napisu, powinieneś zobaczyć coś podobnego do: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Jeśli wynik wygląda na zniekształcony, sprawdź ponownie, czy plik **greek.traineddata** znajduje się w odpowiednim folderze i czy PNG nie jest zbyt zaszumiony. + +--- + +## Pełny działający przykład (wszystkie kroki w jednym skrypcie) + +Poniżej znajduje się kompletny, gotowy do uruchomienia program. Zapisz go jako `ocr_greek.py` i uruchom `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Oczekiwany wynik** (skrócony dla zwięzłości): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Jeśli zobaczysz poprawne greckie znaki, gratulacje — pomyślnie wykonałeś operację **ocr png image** w Pythonie! + +--- + +## Częste pytania i profesjonalne wskazówki + +### Jak poprawić dokładność przy zaszumionym PNG? + +- Konwertuj obraz do odcieni szarości: `img = img.convert('L')` +- Zastosuj prog binarny: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Zwiększ rozdzielczość za pomocą `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Te kroki często zamieniają koszmar **recognize image text** w czysty wynik. + +### Czy mogę przetwarzać cały folder PNG‑ów? + +Oczywiście. Owiń wywołanie `recognize_image` w pętlę `for` iterującą po `Path.glob("*.png")`. Przechowaj każdy wynik w słowniku lub zapisz do CSV do późniejszej analizy. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Co zrobić, jeśli potrzebuję wyodrębnić tylko liczby? + +Przekaż własny ciąg **config** do `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +W ten sposób możesz **extract text from image** pliki zawierające tabele, numery seryjne lub znaczniki czasu. + +### Czy istnieje sposób na uzyskanie ocen pewności? + +Tak — użyj `pytesseract.image_to_data`, który zwraca TSV z poziomem pewności dla każdego słowa. Możesz odfiltrować tokeny o niskiej pewności przed złożeniem ostatecznego ciągu. + +--- + +## Rozszerzanie samouczka + +Teraz, gdy opanowałeś podstawy, rozważ zgłębienie następujących powiązanych tematów: + +- **Batch OCR with multiprocessing** – przyspiesz przetwarzanie dużych zbiorów PNG. +- **Hybrid OCR + NLP pipelines** – automatycznie przetłumacz wyodrębniony starogrecki na współczesny angielski. +- **Alternative engines** – wypróbuj `easyocr` lub metody oparte na `opencv` dla konkretnych przypadków użycia. +- **Cloud OCR services** – Google Vision, Azure Computer Vision lub AWS Textract do skalowania bezserwerowego. + +Każdy z nich opiera się na podstawowym **python ocr example**, który właśnie omówiliśmy, więc będziesz czuł się pewnie, zagłębiając się dalej. + +--- + +## Podsumowanie + +Przekształciliśmy prosty fragment w solidny przepływ pracy **ocr png image** w Pythonie. Tworząc `OcrEngine`, ustawiając język na grecki politoniczny, podając PNG i wypisując wynik, teraz wiesz, jak **extract text from image** pliki, **recognize image text**, a nawet **read ancient greek**. + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każde źródło zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i zbadać alternatywne podejścia implementacyjne w własnych projektach. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/polish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..968ee689c --- /dev/null +++ b/ocr/polish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-06 +description: Samouczek OCR w Pythonie, pokazujący, jak rozpoznawać tekst na obrazie, + wykonywać OCR w wysokiej rozdzielczości i wyodrębniać tekst hiszpański przy użyciu + przyspieszonego GPU OCR. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: pl +og_description: Samouczek OCR w Pythonie, który krok po kroku prowadzi przez rozpoznawanie + tekstu na obrazach, OCR w wysokiej rozdzielczości oraz wyodrębnianie hiszpańskiego + tekstu z przyspieszeniem GPU. +og_title: Samouczek OCR w Pythonie – Rozpoznawanie tekstu przyspieszone GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Samouczek OCR w Pythonie – Rozpoznawanie tekstu na obrazie z przyspieszeniem + GPU +url: /pl/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Samouczek Python OCR – Rozpoznawanie tekstu na obrazie z przyspieszeniem GPU + +Zastanawiałeś się kiedyś, jak **rozpoznawać tekst na obrazie** w skrypcie Pythona, nie spędzając godzin na dopasowywaniu ustawień? Nie jesteś jedyny. W tym **python ocr tutorial** pokażemy Ci czysty, kompleksowy sposób na wyodrębnienie hiszpańskiego tekstu z obrazu wysokiej rozdzielczości oraz dodamy przyspieszenie GPU, aby proces działał błyskawicznie. + +Pomyśl o tym jako szybkim demo przy kawie, które możesz później rozbudować do produkcyjnego pipeline’u. Po zakończeniu tego przewodnika będziesz mieć działający program, który wykonuje **high resolution OCR**, wykorzystuje GPU z obsługą CUDA i zwraca dokładne hiszpańskie znaki, których potrzebujesz. + +## Czego się nauczysz + +- Jak zainstalować i zaimportować nowoczesną bibliotekę OCR obsługującą przyspieszenie GPU. +- Jak utworzyć instancję silnika OCR i ustawić ją do **recognize image text** w języku hiszpańskim. +- Jak włączyć **gpu accelerated OCR** dla ogromnych przyspieszeń przy plikach wysokiej rozdzielczości. +- Jak radzić sobie z przypadkami brzegowymi, takimi jak brak sterowników CUDA lub przejście na CPU. +- Wskazówki dotyczące poprawy dokładności, gdy potrzebujesz **extract spanish text** z zaszumionych skanów. + +### Wymagania wstępne + +- Python 3.9+ (kod działa również na 3.10 i nowszych). +- GPU kompatybilne z CUDA (opcjonalne, ale bardzo zalecane). +- Podstawowa znajomość pip oraz środowisk wirtualnych. + +Jeśli brakuje Ci któregoś z nich, samouczek nadal działa — po prostu pomiń krok GPU, a biblioteka automatycznie przełączy się na CPU. + +--- + +## Samouczek Python OCR: Instalacja wymaganych pakietów + +Na początek potrzebujemy solidnego silnika OCR. W tym samouczku użyjemy otwarto‑źródłowego pakietu **`easyocr`**, który zawiera wbudowane wsparcie GPU, gdy wykryte zostanie kompatybilne urządzenie. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Jeśli masz już zainstalowany PyTorch, upewnij się, że jego wersja pasuje do wersji CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Niepasujące wersje są częstą przyczyną błędów „GPU not found”. + +--- + +## Krok 1: Utwórz instancję silnika OCR + +Teraz uruchamiamy silnik. EasyOCR nazywa swoją główną klasę `Reader`. Konstruktor przyjmuje listę kodów językowych; przekażemy `"es"` dla języka hiszpańskiego. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Dlaczego to ważne:* Deklarując język od razu, silnik ładuje tylko niezbędne wagi sieci neuronowej, co oszczędza pamięć i przyspiesza inferencję — szczególnie przydatne, gdy później pracujesz z **high resolution OCR**. + +--- + +## Krok 2: Przygotuj obraz wysokiej rozdzielczości + +Obrazy wysokiej rozdzielczości dostarczają modelowi więcej pikseli do analizy, co zazwyczaj przekłada się na lepsze rozpoznawanie znaków. Załóżmy, że masz plik o nazwie `high_res_spanish.png` w folderze `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Jeśli nie masz pod ręką próbki wysokiej rozdzielczości, możesz pobrać darmowy obraz z Unsplash lub wygenerować syntetyczny obraz przy użyciu Pillow. Kluczowe jest utrzymanie DPI powyżej 300, aby uzyskać najlepsze wyniki. + +--- + +## Krok 3: Włącz przyspieszenie GPU (opcjonalne, ale zalecane) + +EasyOCR już próbuje używać GPU, gdy ustawisz `gpu=True`. Jednak dobrą praktyką jest sprawdzenie, czy urządzenie jest rzeczywiście wykorzystywane, szczególnie w konfiguracjach z wieloma GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Dlaczego to sprawdzać?* Jeśli skrypt cicho przełączy się na CPU, możesz się zastanawiać, dlaczego operacja trwająca 5 sekund nagle zajmuje 30 sekund. To małe sprawdzenie czyni zachowanie przejrzystym i utrzymuje Twoją **gpu accelerated OCR** pipeline przewidywalną. + +--- + +## Krok 4: Wykonaj OCR wysokiej rozdzielczości i rozpoznaj tekst na obrazie + +Teraz najciekawsza część — faktyczne odczytanie tekstu. Metoda `readtext` EasyOCR zwraca listę krotek zawierających ramkę ograniczającą, rozpoznany ciąg znaków oraz współczynnik pewności. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Jeśli potrzebujesz surowego ciągu bez współrzędnych, ustaw `detail=0`. Dla większości przypadków użycia **recognize image text**, domyślna wartość (`detail=1`) dostarcza wystarczającego kontekstu do późniejszego przetwarzania. + +--- + +## Krok 5: Wyodrębnij hiszpański tekst i oczyść wynik + +Ponieważ poprosiliśmy EasyOCR o język hiszpański, zwrócone ciągi są już w tym języku. Nadal możesz chcieć je połączyć, usunąć białe znaki lub odfiltrować wykrycia o niskiej pewności. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Co zrobić, gdy pewność jest niska?** Możesz obniżyć próg (ryzykując szum) lub wstępnie przetworzyć obraz (zwiększyć kontrast, binaryzować lub prostować). Te sztuczki są powszechne przy pracy z **high resolution OCR** na zeskanowanych dokumentach. + +--- + +## Krok 6: Obsługa przypadków brzegowych i optymalizacje wydajności + +Nawet najlepiej wytrenowane modele potykają się o niektóre scenariusze. Poniżej znajdziesz kilka szybkich poprawek, które możesz wkleić do skryptu. + +### 6.1 Przejście na CPU, gdy brak GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling bardzo dużych obrazów + +Jeśli Twój obraz jest większy niż 4000 × 4000 px, możesz wyczerpać pamięć GPU. Down‑sample proporcjonalnie, zachowując DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Te fragmenty utrzymują skrypt w stabilnej formie, niezależnie od tego, czy uruchamiasz go na stacji roboczej, czy na skromnym laptopie. + +--- + +## Pełny działający przykład + +Łącząc wszystko razem, oto kompletny skrypt, który możesz skopiować i od razu uruchomić: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Oczekiwany wynik (przykład):** + + + +## Co warto się nauczyć dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Wyodrębnij tekst z obrazu przy użyciu Aspose OCR – przewodnik krok po kroku](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Jak rozpoznawać tekst obrazu w języku przy użyciu Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Jak rozpoznawać prostokąty stron dla rozpoznawania tekstu OCR w Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/polish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..da9494c28 --- /dev/null +++ b/ocr/polish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-06-06 +description: Rozpoznawaj tekst z obrazu przy użyciu silnika OCR w Pythonie. Dowiedz + się, jak skonfigurować silnik OCR w Pythonie i wyodrębnić tekst z obrazu przy użyciu + przetwarzania w chmurze w kilka minut. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: pl +og_description: rozpoznawaj tekst z obrazu za pomocą silnika OCR w Pythonie. Ten przewodnik + pokazuje, jak skonfigurować silnik OCR w Pythonie i efektywnie wyodrębniać tekst + z obrazu. +og_title: Rozpoznawanie tekstu z obrazu w Pythonie – Kompletny poradnik konfiguracji +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Rozpoznawanie tekstu z obrazu w Pythonie – Kompletny przewodnik konfiguracji + silnika OCR +url: /pl/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# rozpoznawanie tekstu z obrazu w Python – Kompletny przewodnik konfiguracji + +Zastanawiałeś się kiedyś, jak **rozpoznaj tekst z obrazu** przy użyciu zaledwie kilku linijek Pythona? Nie jesteś sam. Niezależnie od tego, czy tworzysz skaner paragonów, cyfrowy dokumentator, czy prosty projekt hobbystyczny, możliwość **wyodrębnij tekst z obrazu** to umiejętność, która szybko się opłaca. + +W tym samouczku przeprowadzimy Cię przez cały proces — zaczynając od **skonfiguruj silnik OCR w Pythonie** w stylu konfiguracji, przechodząc przez uwierzytelnianie w chmurze, a na końcu pokazując, jak **wyodrębnij tekst z obrazu** z niezawodnym wynikiem. Bez magii, tylko jasne kroki, które możesz skopiować‑wkleić i uruchomić już dziś. + +## Czego się nauczysz + +- Jak zainstalować i zaimportować wymaganą bibliotekę OCR. +- Dokładne polecenia do **skonfiguruj silnik OCR w Pythonie** dla przetwarzania w chmurze. +- Kompletny, uruchamialny skrypt, który **rozpoznaj tekst z obrazu** i wypisuje wynik. +- Wskazówki dotyczące radzenia sobie z typowymi problemami, takimi jak brakujące klucze API lub nieobsługiwane formaty obrazów. +- Pomysły na wyższy poziom, takie jak przetwarzanie wsadowe i lokalny fallback. + +### Wymagania wstępne + +- Python 3.8+ zainstalowany na Twoim komputerze. +- Połączenie internetowe (przykład używa usługi OCR w chmurze). +- Ważny klucz API od dostawcy OCR (zobaczysz, gdzie go wstawić). + +Jeśli masz to wszystko, zanurzmy się — bez zbędnych wstępów, tylko praktyczny przewodnik, który działa. + +--- + +## Krok 1: Zainstaluj bibliotekę OCR i zaimportuj ją + +Zanim będziesz mógł **skonfiguruj silnik OCR w Pythonie**, potrzebujesz biblioteki, która komunikuje się z usługą w chmurze. W naszym przykładzie użyjemy fikcyjnego, ale reprezentatywnego pakietu o nazwie `ocrcloud`. Zastąp go rzeczywistym pakietem, którego używasz (np. `easyocr`, `google-cloud-vision` itp.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Dlaczego to ważne:** Importowanie klasy daje dostęp do metod takich jak `use_cloud()` i `set_api_key()`. Bez importu reszta skryptu spowodowałaby błąd `NameError`. + +*Wskazówka:* Zablokuj wersję w pliku `requirements.txt` (`ocrcloud==2.1.0`), aby uniknąć nieoczekiwanych zmian łamiących w przyszłości. + +--- + +## Krok 2: Utwórz i **skonfiguruj silnik OCR w Pythonie** dla trybu chmurowego + +Teraz faktycznie **skonfiguruj silnik OCR w Pythonie**. Silnik domyślnie uruchamia się w trybie lokalnym; przełączenie na tryb chmurowy pozwala przenieść ciężką analizę obrazu na potężne serwery. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Wyjaśnienie:** +- `OcrEngine()` tworzy nowy obiekt silnika — wyobraź sobie go jako pustą płótno. +- `use_cloud(True)` przełącza przełącznik, informując silnik, aby wysyłał obrazy przez HTTPS zamiast przetwarzać je lokalnie. Jest to kluczowe dla wysokiej dokładności wyników przy skomplikowanych czcionkach lub zdjęciach o niskiej rozdzielczości. + +--- + +## Krok 3: Uwierzytelnij się przy użyciu klucza API w chmurze + +Większość usług OCR w chmurze wymaga klucza API. Ten krok pokazuje, jak bezpiecznie wstrzyknąć poświadczenie. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Uwaga dotycząca bezpieczeństwa:** Nigdy nie zapisuj klucza na stałe w publicznym repozytorium. W produkcji pobrałbyś go ze zmiennej środowiskowej: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Krok 4: **rozpoznaj tekst z obrazu** – Wyślij zdalny obraz do przetworzenia + +Po skonfigurowaniu silnika możemy w końcu **rozpoznaj tekst z obrazu**. Metoda `recognize_image()` przyjmuje ścieżkę lub URL i zwraca obiekt zawierający wyodrębniony tekst. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Co się dzieje w tle?** +Bajty obrazu są przesyłane do punktu końcowego dostawcy, przetwarzane przez model uczenia głębokiego, a wynik w postaci zwykłego tekstu jest zwracany. Jeśli obraz jest duży, usługa może automatycznie zmniejszyć jego rozmiar, aby przyspieszyć zadanie. + +--- + +## Krok 5: Wyświetl wynik **wyodrębnij tekst z obrazu** + +Teraz, gdy usługa OCR wykonała swoją pracę, po prostu wypisujemy tekst. W rzeczywistych aplikacjach możesz go przechowywać w bazie danych lub przekazać do innej funkcji. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Oczekiwany wynik:** (przykład) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Jeśli wynik wygląda na zniekształcony, sprawdź ponownie, czy obraz jest wyraźny i czy wybrałeś właściwy model językowy (wiele usług pozwala określić `engine.set_language("en")`). + +## Obsługa przypadków brzegowych i typowych pułapek + +### 1. Brakujący lub nieprawidłowy klucz API +Jeśli widzisz błąd uwierzytelnienia, upewnij się: +- Klucz jest aktywny i nie wygasł. +- Jest prawidłowo odczytywany ze zmiennej środowiskowej. +- Twoja sieć zezwala na wychodzący ruch HTTPS. + +### 2. Nieobsługiwane formaty obrazów +Większość API OCR akceptuje JPEG, PNG i PDF. Próba użycia BMP lub TIFF może spowodować odpowiedź „format nieobsługiwany”. W razie potrzeby konwertuj przy pomocy Pillow: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Limity szybkości +Usługi w chmurze często ograniczają liczbę żądań na minutę. Jeśli przekroczysz limit, zastosuj wykładniczy back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Fallback do OCR lokalnego +Jeśli chmura jest niedostępna, możesz przełączyć się z powrotem: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Posiadanie fallbacku utrzymuje aplikację odporną. + +## Pełny działający przykład + +Łącząc wszystko razem, oto skrypt, który możesz uruchomić od razu (wystarczy podmienić wartości zastępcze). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Uruchom go:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Powinieneś zobaczyć wyodrębniony tekst wypisany w konsoli, co potwierdza, że pomyślnie **rozpoznaj tekst z obrazu** i **wyodrębnij tekst z obrazu** używając prawidłowo **skonfiguruj silnik OCR w Pythonie** workflow. + +## Zakończenie + +Właśnie przeszliśmy przez kompletny proces od początku do końca, który pozwala **rozpoznaj tekst z obrazu** w Pythonie, od instalacji biblioteki po uwierzytelnienie usługi w chmurze i w końcu **wyodrębnij tekst z obrazu** za pomocą jednego wywołania funkcji. Poprzez **skonfiguruj silnik OCR w Pythonie** w odpowiedni sposób zyskujesz zarówno elastyczność (chmura vs. lokalnie), jak i niezawodność (właściwe obsługiwanie błędów). + +Co dalej? Spróbuj przetwarzać wsadowo folder z paragonami, dodaj wykrywanie języka lub eksperymentuj z PDF‑ami jako wejściem. Nie ma granic, gdy opanujesz podstawy. + +Szczęśliwego kodowania i nie wahaj się zadawać pytań w komentarzach — nic nie przebije wspólnej nauki! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Wyodrębnianie tekstu z obrazu przy użyciu Aspose OCR – przewodnik krok po kroku](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Wyodrębnianie tekstu z obrazu – Rozpoznawanie linii z Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Jak wyodrębnić tekst z obrazu poprzez przygotowanie prostokątów w OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/polish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1473ad235 --- /dev/null +++ b/ocr/polish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Uruchom OCR na obrazie przy użyciu Pythona i zobacz wyniki pewności. + Dowiedz się, jak filtrować słowa o niskiej pewności, ustawiać progi i radzić sobie + z przypadkami brzegowymi. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: pl +og_description: Uruchom OCR na obrazie w Pythonie, sprawdź poziomy pewności i odfiltruj + słowa o niskiej pewności. Ten tutorial przeprowadzi Cię przez kompletny, gotowy + do uruchomienia przykład. +og_title: Uruchom OCR na obrazie w Pythonie – pełny przewodnik +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Uruchom OCR na obrazie w Pythonie – Kompletny przewodnik krok po kroku +url: /pl/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Uruchom OCR na obrazie przy użyciu Pythona – Kompletny przewodnik krok po kroku + +Czy kiedykolwiek potrzebowałeś **uruchomić OCR na obrazie** i nie byłeś pewien, jak uzyskać wiarygodny tekst? Nie jesteś sam — wielu programistów napotyka ten sam problem, gdy wyodrębnione słowa wyglądają niepewnie, a współczynnik pewności jest zagadką. + +W tym przewodniku od razu przejdziemy do działającego rozwiązania: zobaczysz, jak **uruchomić OCR na obrazie**, odczytać ogólną pewność i wyodrębnić słowa o niskiej pewności, które mogą wymagać ręcznej weryfikacji. Po zakończeniu będziesz mieć skrypt wielokrotnego użytku, zrozumiesz, dlaczego każda linia ma znaczenie, i będziesz wiedział, jak dostosować próg pewności dla własnych projektów. + +## Co obejmuje ten tutorial + +Przejdziemy przez cały przepływ pracy — od wczytania obrazu po wydrukowanie schludnego raportu słów, które spadły poniżej progu 80 % pewności. Po drodze omówimy: + +* Wybór solidnego silnika OCR (użyjemy **EasyOCR**, popularnej biblioteki OCR w Pythonie) +* Interpretację atrybutu `confidence`, który zwraca każdy wynik OCR +* Filtrowanie słów przy użyciu własnego **progu pewności OCR** +* Rozszerzenie skryptu o przetwarzanie wsadowe lub alternatywne silniki, takie jak **pytesseract** + +Nie wymagana jest wcześniejsza znajomość OCR, wystarczy podstawowa znajomość Pythona i działające środowisko (zalecany Python 3.9+). + +Gotowy, aby zamienić rozmyte zrzuty ekranu w czysty, przeszukiwalny tekst? Zaczynajmy. + +--- + +## ## Jak uruchomić OCR na obrazie przy użyciu Pythona + +Sednem tutorialu jest trzyetapowy fragment kodu, który odzwierciedla kod, który już widziałeś. Poniżej rozłożymy każdą linię, wyjaśnimy dlaczego jest użyta i podamy kompletny, gotowy do kopiowania skrypt. + +### Krok 1: Zainstaluj i zaimportuj silnik OCR + +Najpierw upewnij się, że biblioteka OCR jest dostępna. **EasyOCR** działa od razu dla wielu języków i podaje współczynnik pewności dla każdego słowa. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Dlaczego EasyOCR?* Zawiera model uczenia głębokiego wytrenowany na różnorodnych zestawach danych, więc zazwyczaj uzyskujesz wyższe wartości pewności niż starszy silnik Tesseract, szczególnie przy obrazach o mieszanej jakości. + +> **Wskazówka:** Jeśli pracujesz w ograniczonym środowisku (np. mały kontener Docker), `pytesseract` może być lżejszy, ale utracisz część nowoczesnej dokładności, jaką zapewnia EasyOCR. + +### Krok 2: Uruchom OCR na obrazie + +Teraz faktycznie **uruchamiamy OCR na obrazie**. Metoda `recognize_image` z oryginalnego przykładu została zastąpiona wywołaniem `readtext` EasyOCR, które zwraca listę krotek `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Każdy wpis w `ocr_results` wygląda tak: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Trzeci element (`0.92` w przykładzie) to współczynnik pewności w zakresie od 0 do 1. + +### Krok 3: Podsumuj ogólną pewność + +W przeciwieństwie do wcześniejszego fragmentu, który drukował pojedynczy atrybut `confidence`, EasyOCR podaje pewność dla każdego słowa. Aby uzyskać ogólne wyobrażenie, obliczymy ich średnią: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Dlaczego średnia?* Daje szybki przegląd stanu — jeśli ogólna pewność jest poniżej, powiedzmy, 70 %, prawdopodobnie musisz poprawić obraz (lepsze oświetlenie, wstępne przetwarzanie itp.). + +### Krok 4: Lista słów o niskiej pewności + +Teraz następuje część, która bezpośrednio odpowiada wymaganiu „wypisz słowa, których pewność jest poniżej żądanego progu”. Ustawimy domyślnie **próg pewności OCR** na 0.80 (80 %), ale możesz go zmienić. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Pętla drukuje każde słowo, które nie przeszło progu, wraz z jego procentową pewnością. To dokładny odpowiednik oryginalnej pętli `for recognized_word in recognition_result.words`, ale teraz działa z formatem wyjściowym EasyOCR. + +--- + +## ## Zrozumienie współczynników pewności OCR + +Pewność nie jest magiczną liczbą; to szacunek modelu, jak bardzo jest pewny konkretnej transkrypcji. Oto kilka rzeczy, które warto mieć na uwadze: + +| Sytuacja | Typowa pewność | Co zrobić | +|-----------|-------------------|------------| +| Czyste, wysokiej rozdzielczości skanowanie | 0.95 – 1.00 | Nie wymaga dodatkowej pracy | +| Lekka rozmycie lub nierówne oświetlenie | 0.80 – 0.94 | Rozważ lekkie wstępne przetwarzanie (zwiększenie kontrastu) | +| Silny szum, obrócony tekst | < 0.70 | Zastosuj wstępne przetwarzanie obrazu (prostowanie, odszumianie) lub przejdź na inny silnik OCR | + +> **Uwaga:** Niektóre języki (np. pismo odręczne kursywą) naturalnie dają niższe wyniki. Dostosuj próg odpowiednio. + +### Przypadki brzegowe i warianty + +1. **Przetwarzanie wsadowe** – Jeśli potrzebujesz **uruchomić OCR na obrazie** w trybie masowym, otocz powyższą logikę pętlą iterującą po katalogu. +2. **Wiele języków** – Przekaż listę taką jak `['en', 'fr']` do `easyocr.Reader`, a silnik wykryje oba. +3. **Alternatywne silniki** – Chcesz wypróbować **pytesseract**? Zastąp blok czytnika następującym: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Następnie będziesz musiał zaggregować pewności poszczególnych znaków do wartości na słowo — trochę więcej pracy, ale wykonalne. + +4. **Triki wstępnego przetwarzania** – Zastosowanie filtrów OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) może zwiększyć pewność przy szumnych skanach. + +--- + +## ## Pełny, gotowy do uruchomienia skrypt + +Poniżej znajduje się kompletny plik Python, który możesz dodać do swojego projektu. Zapisz go jako `ocr_report.py` i uruchom `python ocr_report.py`. Upewnij się, że ścieżka do obrazu wskazuje na istniejący plik. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Oczekiwany wynik** (twoje liczby będą się różnić): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Jeśli każde słowo przekroczy próg 80 %, zobaczysz przyjazny komunikat „All words meet the confidence threshold.”. + +--- + +## ## Najczęściej zadawane pytania (FAQ) + +**Q: Czy to działa z PDF‑ami?** +A: Nie bezpośrednio. Najpierw przekonwertuj każdą stronę PDF na obraz (np. przy użyciu `pdf2image`), a następnie podaj PNG/JPEG do skryptu. + +**Q: Moje liczby pewności są wszystkie niskie — co mogę zrobić?** +A: Spróbuj wstępnego przetwarzania obrazu: zwiększ kontrast, usuń szumy tła lub obróć obraz do poziomej linii bazowej. EasyOCR akceptuje także parametr `contrast_ths`, który możesz dostosować. + +**Q: Czy mogę wyeksportować wyniki do CSV?** +A: Oczywiście. Po pętli niskiej pewności zapisz `ocr_results` przy użyciu `csv.DictWriter`, gdzie każdy wiersz zawiera `text`, `confidence` oraz współrzędne prostokąta ograniczającego. + +**Q: Czy istnieje wersja przyspieszona GPU?** +A: EasyOCR automatycznie używa CUDA, jeśli zainstalowano kompatybilny GPU i PyTorch. Sprawdź za pomocą `torch.cuda.is_available()` przed uruchomieniem skryptu. + +--- + +## Zakończenie + +**Uruchomiliśmy właśnie OCR na obrazie** przy użyciu Pythona, sprawdziliśmy ogólną pewność i wyodrębniliśmy wszystkie słowa o niskiej pewności, które wymagają + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/portuguese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..19804ead3 --- /dev/null +++ b/ocr/portuguese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extraia texto de imagens com OCR em Python em minutos. Descubra OCR de + imagens multilíngue, detecção automática de idioma no OCR e como extrair texto OCR + com precisão. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: pt +og_description: Extraia texto de imagens com OCR em Python rapidamente. Aprenda OCR + de imagens multilíngue, detecção automática de idioma no OCR e como extrair texto + OCR passo a passo. +og_title: Extrair Texto de Imagem Usando OCR em Python – Guia Completo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Extrair Texto de Imagem Usando OCR em Python – Guia Completo +url: /pt/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrair Texto de Imagem Usando Python OCR – Guia Completo + +Já precisou **extrair texto de imagem** mas não sabia qual biblioteca poderia lidar com vários idiomas automaticamente? Você não está sozinho—desenvolvedores perguntam constantemente *como extrair texto OCR* ao lidar com documentos internacionais, recibos ou folhetos escaneados. Neste tutorial vamos percorrer um exemplo prático em Python que não só extrai texto de uma imagem, mas também **detecta o idioma** em tempo real, tornando o OCR de imagem multilíngue muito simples. + +Cobriremos tudo, desde a instalação do pacote OCR até a habilitação do **auto detect language OCR**, execução do motor em uma imagem de exemplo e, por fim, impressão tanto do idioma detectado quanto da string extraída. Ao final, você terá um trecho reutilizável que pode ser inserido em qualquer projeto, seja para construir um pipeline de tradução ou um serviço de ingestão de dados. + +## Extrair Texto de Imagem – Configurando o Ambiente + +Antes de mergulharmos no código, certifique‑se de que sua estação de trabalho atende a estes requisitos mínimos: + +- Python 3.8 ou superior (a biblioteca usa type hints que versões mais antigas ignoram) +- `pip` para gerenciamento de pacotes +- Um arquivo de imagem que contenha texto em, pelo menos, dois idiomas diferentes (por exemplo, Inglês + Espanhol) + +Você também precisará da biblioteca OCR que alimenta esta demonstração. Para o propósito deste guia usaremos o fictício pacote `ocr`, que espelha ferramentas reais populares como Tesseract ou EasyOCR, mas oferece uma API Python limpa. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Dica profissional:** Se encontrar erros de permissão, prefixe o comando com `python -m` ou use um ambiente virtual—mantém seus site‑packages globais organizados. + +## Criar Instância do Motor OCR + +Agora que a biblioteca está pronta, o primeiro passo lógico é **criar uma instância do motor OCR**. Pense no motor como um scanner inteligente que você pode configurar antes de alimentá‑lo com imagens. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Por que instanciamos o motor separadamente ao invés de chamar um método estático? O objeto do motor mantém o estado de configuração (como preferências de idioma) que você pode querer reutilizar em várias imagens, economizando o custo de re‑inicializá‑lo a cada vez. + +## Habilitar Auto Detect Language OCR + +A maioria das ferramentas OCR exige que você especifique um código de idioma—`eng` para English, `spa` para Spanish, etc. Adivinhar manualmente o idioma derrota o propósito de um fluxo de trabalho **multilingual image OCR**. Felizmente, o pacote `ocr` oferece um modo *auto detect language OCR* que inspeciona a imagem e seleciona o melhor modelo de idioma nos bastidores. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Habilitar **detect language OCR** dessa forma significa que você não precisará manter uma longa lista de códigos de idioma. O motor tentará combinar o script que vê—Latim, Cirílico, Han, etc.—e carregará o modelo apropriado automaticamente. + +## Executar OCR de Imagem Multilíngue + +Com o motor preparado, é hora de realmente **extrair texto de imagem**. O método `recognize_image` aceita um caminho de arquivo e retorna um objeto de resultado contendo tanto o texto bruto quanto o idioma que foi detectado. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Se você está se perguntando *como extrair texto OCR* de um PDF em vez de um PNG, o mesmo motor oferece `recognize_pdf`—basta trocar o nome do método. A lógica de detecção subjacente permanece idêntica, então você se beneficia do mesmo recurso **auto detect language OCR**. + +## Exibir Idioma Detectado e Texto Extraído + +Por fim, exibimos o que o motor descobriu. O objeto de resultado expõe `detected_language` (uma tag BCP‑47 como `en` ou `es`) e `text`, que contém a saída bruta do OCR. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Executar o script na nossa imagem de exemplo deve produzir algo semelhante a: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Observe como o motor identificou corretamente o Inglês como idioma principal, mas ainda capturou a linha em Espanhol—exatamente o que se espera de uma solução robusta de **multilingual image OCR**. + +### E se a Detecção Falhar? + +Às vezes o motor OCR pode recair para um idioma padrão (geralmente Inglês) se a imagem estiver borrada ou o script for muito exótico. Nesses casos você pode forçar uma lista de idiomas: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Mas lembre‑se, forçar idiomas elimina a conveniência do **auto detect language OCR**, então use isso apenas quando souber um subconjunto específico de idiomas. + +## Armadilhas Comuns e Como Extrair Texto OCR de Forma Confiável + +Mesmo com auto‑detecção, alguns contratempos podem atrapalhar: + +1. **Imagens de baixa resolução** – A precisão do OCR cai drasticamente abaixo de 150 dpi. Aumente a escala ou solicite uma digitalização de maior resolução. +2. **Ruído e artefatos de compressão** – Aplique um filtro de limiar simples (`opencv` ou `Pillow`) antes de enviar a imagem ao motor. +3. **Scripts mistos em uma mesma página** – Alguns motores têm dificuldade com caracteres latinos e CJK simultâneos. Divida a página em regiões e execute reconhecimentos separados, se necessário. + +Abordar esses pontos melhora drasticamente a qualidade do processo **extract text from image**, especialmente ao lidar com documentos reais e multilíngues. + +## Exemplo Completo Funcional + +Abaixo está o script completo, pronto para ser executado, que combina todas as etapas que discutimos. Salve‑o como `multilingual_ocr.py` e execute-o a partir da linha de comando. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Saída esperada** (supondo que a imagem de exemplo contenha texto em Inglês e Espanhol): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Sinta‑se à vontade para substituir `multilang_page.png` por qualquer foto que contenha texto em outros idiomas—graças ao **auto detect language OCR**, o script ainda fornecerá uma tag de idioma coerente e o texto correspondente. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Conclusão + +Agora você sabe exatamente **como extrair texto OCR** de uma imagem, como habilitar **auto detect language OCR** e como lidar com cenários de **multilingual image OCR** com código mínimo. Ao criar uma instância do motor OCR, ativar a detecção automática de idioma e chamar `recognize_image`, você pode extrair de forma confiável tanto o identificador de idioma quanto o texto bruto. + +Qual o próximo passo? Experimente alimentar as strings extraídas em uma API de tradução, armazená‑las em um banco de dados pesquisável ou combinar várias páginas em um único relatório PDF. Você também pode experimentar diferentes back‑ends OCR (Tesseract, EasyOCR, Google Vision) mantendo o mesmo fluxo de trabalho de alto nível—graças à interface consistente de **detect language OCR**. + +Se encontrar alguma peculiaridade, revise a seção “Armadi­lhas Comuns” ou ajuste as etapas de pré‑processamento da imagem. Boa codificação, e que seu próximo projeto esteja repleto de texto corretamente detectado e perfeitamente extraído! + +## O Que Você Deve Aprender a Seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/portuguese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..929f0c779 --- /dev/null +++ b/ocr/portuguese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Extraia texto de PDFs de imagens usando OCR em Python. Aprenda como converter + documentos escaneados em texto rapidamente com reconhecimento em lote assíncrono. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: pt +og_description: Extrair texto de PDFs de imagens com Python. Este guia passo a passo + mostra como converter documentos escaneados em texto usando OCR assíncrono. +og_title: Extrair Texto de PDFs de Imagens – Tutorial de OCR em Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Extrair Texto de PDFs de Imagens – Guia Python para Converter Documentos Escaneados + em Texto +url: /pt/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrair Texto de PDFs de Imagens – Guia Python para Converter Documentos Escaneados em Texto + +Já precisou **extrair texto de PDFs de imagens** sem gastar horas digitando novamente? Neste guia, mostraremos como **converter documentos escaneados em texto** usando um fluxo de trabalho OCR assíncrono simples em Python. + +Se você já ficou encarando uma pilha de PDFs escaneados e pensou: “Tem que haver uma maneira mais rápida”, você está no lugar certo. Vamos percorrer cada linha de código, explicar por que cada parte importa e até cobrir alguns casos limites que você pode encontrar. + +## O que Você Vai Aprender + +- Como iniciar um motor OCR e definir o idioma de reconhecimento. +- A mecânica de alimentar uma lista mista de PNGs e PDFs em um reconhecedor em lote. +- Executar o trabalho OCR de forma assíncrona para que seu aplicativo permaneça responsivo. +- Recuperar os resultados, associá‑los aos arquivos de origem e imprimir uma saída limpa. + +**Pré‑requisitos**: Python 3.8+, compreensão básica de `asyncio` ou `concurrent.futures`, e uma biblioteca OCR que exponha uma classe `OcrEngine` semelhante à do exemplo (por exemplo, Aspose.OCR, wrapper do Tesseract ou um wrapper personalizado). Nenhuma configuração pesada necessária—basta instalar a biblioteca e você está pronto para usar. + +![extrair texto de PDFs de imagens](https://example.com/placeholder.png "Captura de tela da saída OCR – extrair texto de PDFs de imagens") + +## Extrair Texto de PDFs de Imagens – Configurando o Motor OCR + +A primeira coisa que você precisa é uma instância do motor OCR configurada para o idioma dos seus documentos. No nosso caso, usaremos francês, mas você pode trocá‑lo por qualquer idioma suportado. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Por que isso importa**: Definir o idioma antecipadamente melhora drasticamente a precisão. O motor usa dicionários e modelos de caracteres específicos do idioma; alimentá‑lo com o idioma errado é uma fonte comum de saída confusa. + +## Prepare a Lista de Arquivos – Imagens e PDFs Juntos + +Nosso reconhecedor em lote pode lidar tanto com imagens raster (`.png`, `.jpg`) quanto com contêineres PDF. Basta fornecer uma simples lista Python de caminhos de arquivos. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Dica**: Mantenha a lista plana; o motor desempacotará internamente cada página PDF em imagens antes do reconhecimento. Se você tem milhares de arquivos, considere dividir a lista em lotes menores para evitar picos de memória. + +## Inicie o Reconhecimento em Lote Assíncrono + +Em vez de bloquear a thread principal, iniciamos o trabalho OCR em segundo plano. O método retorna um `Future` que eventualmente conterá uma lista de objetos `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Como funciona**: Nos bastidores, o motor cria um pool de threads (ou uma tarefa assíncrona, dependendo da implementação). Isso permite que você continue fazendo outras tarefas—como atualizar uma UI, buscar mais arquivos ou registrar progresso—enquanto o processamento pesado ocorre em outro lugar. + +## Faça Algo Útil Enquanto o OCR Executa + +Um erro comum é ficar ocioso e sondar o futuro em um loop apertado. Em vez disso, você pode executar qualquer trabalho não relacionado. Para demonstração, vamos apenas imprimir uma linha de status. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Recolha os Resultados Quando o Future Completar + +Quando estiver pronto para coletar a saída OCR, use `as_completed` de `concurrent.futures`. Esse padrão funciona tanto com um futuro quanto com vários. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**O que você verá**: Cada caminho de arquivo seguido da representação de texto simples extraído. Para PDFs, `result.text` contém o texto concatenado de todas as páginas. + +### Saída Esperada (exemplo) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Se você notar caracteres ausentes, verifique se o idioma definido corresponde ao idioma do documento e considere pré‑processar as imagens (corrigir inclinação, aumentar contraste) antes de enviá‑las ao motor. + +## Lidando com Casos Limites e Armadilhas Comuns + +| Situação | O que Fazer | +|-----------|------------| +| **Idiomas mistos** | Execute uma passagem de detecção de idioma primeiro, então instancie motores separados por idioma. | +| **PDFs enormes (> 100 MB)** | Divida o PDF em páginas individuais no disco (por exemplo, usando `PyPDF2`) e alimente‑as como entradas separadas. | +| **Scripts não latinos** | Garanta que a biblioteca OCR inclua o pacote de idioma necessário; algumas bibliotecas exigem que você baixe arquivos de dados adicionais. | +| **Gargalo de desempenho** | Aumente o tamanho do pool de threads (`engine.set_thread_pool_size(8)`) ou troque para um backend acelerado por GPU, se disponível. | +| **Texto ausente em imagens de baixa resolução** | Pré‑procese com OpenCV: `cv2.resize`, `cv2.threshold` e `cv2.medianBlur` para melhorar a legibilidade. | + +## Exemplo Completo Funcionando (Pronto para Copiar‑Colar) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Salve isso como `extract_text_async.py`, substitua `YOUR_DIRECTORY` pelo caminho dos seus arquivos, instale o pacote OCR (`pip install your-ocr-lib`) e execute `python extract_text_async.py`. Você deverá ver a saída no console ilustrada anteriormente. + +## Próximos Passos – Indo Além da Extração Básica + +- **Pós‑processamento**: Remover espaços em branco extras, normalizar Unicode (`unicodedata.normalize`) ou executar um verificador ortográfico para limpar o ruído do OCR. +- **Saída estruturada**: Exportar resultados para CSV, JSON ou diretamente para um banco de dados para busca posterior. +- **Lotes paralelos**: Se você tem centenas de arquivos, inicie múltiplos futures e use uma fila para manter a CPU ocupada sem sobrecarregar a memória. +- **Integração com frameworks web**: Conectar este script a um endpoint Flask ou FastAPI para fornecer OCR sob demanda como serviço. + +--- + +### TL;DR + +Agora você sabe como **extrair texto de PDFs de imagens** com um script Python mínimo que executa OCR de forma assíncrona, permitindo **converter documentos escaneados em texto** enquanto seu programa permanece responsivo. Brinque com as configurações de idioma, tamanhos de lote e truques de pré‑processamento para extrair a máxima precisão de caracteres. + +Tem alguma variação que gostaria de compartilhar—talvez OCR em notas manuscritas ou um serviço baseado em nuvem? Deixe um comentário e feliz codificação! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir cobrem tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Extrair Texto de Imagem com Aspose OCR – Guia Passo a Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrair Texto de Imagens Usando Operação OCR em Pastas](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extrair Texto de Imagens Usando Aspose.OCR – Caracteres Permitidos](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..5595ddc96 --- /dev/null +++ b/ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Como fazer OCR de PDF usando Python, extrair texto de PDF, converter + texto de PDF escaneado e mudar o idioma do OCR em apenas algumas linhas de código. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: pt +og_description: 'Como fazer OCR de PDF com Python: um guia prático que mostra como + extrair texto de PDF, converter texto de PDF escaneado e mudar o idioma do OCR sem + esforço.' +og_title: Como fazer OCR de PDF em Python – Tutorial completo de programação +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Como fazer OCR de PDF em Python – Guia completo passo a passo +url: /pt/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como fazer OCR em PDF com Python – Guia Completo Passo a Passo + +Já se perguntou **como fazer OCR em PDF** sem pagar por ferramentas SaaS caras? Você não está sozinho. Seja digitalizando livros antigos, extraindo dados de notas fiscais ou simplesmente precisando de texto pesquisável a partir de um relatório escaneado, dominar OCR de PDF em Python pode economizar horas de cópia manual. + +Neste tutorial vamos percorrer um exemplo conciso e funcional que **extrai texto de PDF**, mostra como **converter texto de PDF escaneado** em strings editáveis e ainda demonstra como **alterar o idioma do OCR** caso seu documento não esteja em inglês. Ao final, você terá um snippet reutilizável que pode ser inserido em qualquer projeto. + +## Pré‑requisitos & Configuração + +Antes de começarmos, certifique‑se de que você tem: + +- Python 3.8+ instalado (o código funciona em 3.9, 3.10 e versões mais recentes) +- O pacote `ocr` que fornece a classe `OcrEngine` (instale via `pip install ocr-lib` – substitua pelo nome real do pacote que você usa) +- Um arquivo PDF que você deseja processar; para a demonstração usaremos `high_res_book.pdf` colocado em uma pasta chamada `YOUR_DIRECTORY` + +Se você estiver usando um ambiente virtual (altamente recomendado), ative‑o primeiro: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Dica profissional:** Mantenha seus arquivos PDF em um diretório dedicado `data/` para evitar dores de cabeça relacionadas a caminhos mais tarde. + +## Etapa 1: Criar uma Instância do Motor OCR (Como fazer OCR em PDF – Inicialização) + +A primeira coisa que você precisa fazer quando quer **executar OCR em PDF** é instanciar o motor. Pense no motor como o cérebro que lerá cada página, interpretará os glifos e devolverá texto puro. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Por que isso importa: sem um motor você não tem contexto para configurações de idioma, opções de renderização ou manipulação de PDF. O objeto `OcrEngine` contém todos esses padrões e permite ajustá‑los posteriormente. + +## Etapa 2: Definir o Idioma de Reconhecimento (Alterar Idioma do OCR) + +A maioria das bibliotecas de OCR tem o inglês como padrão, mas e se seu documento estiver em francês, alemão ou até japonês? Alterar o idioma é tão simples quanto chamar `set_recognition_language`. Isso satisfaz o requisito de **alterar idioma do OCR** e garante maior precisão. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Por que você pode precisar disso:** Um arquivo multilingue costuma conter páginas com idiomas mistos. Trocar de idioma em tempo real evita o reconhecimento incorreto de caracteres como “ß” ou “ñ”. + +## Etapa 3: Configurar Opções de Renderização de PDF (Converter Texto de PDF Escaneado de Forma Eficaz) + +Ao lidar com PDFs escaneados, a resolução e o modo de cor afetam drasticamente a qualidade do OCR. Renderizar a 300 DPI em escala de cinza é um ponto ideal para a maioria dos documentos—alto o suficiente para capturar detalhes, mas baixo o bastante para manter o uso de memória razoável. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +As chamadas encadeadas podem parecer sofisticadas, mas são apenas uma API fluente que retorna o mesmo objeto de opções a cada chamada. Se precisar de cor (por exemplo, para diagramas coloridos), substitua `"grayscale"` por `"color"`. + +## Etapa 4: Reconhecer o PDF e Capturar o Texto da Primeira Página (Extrair Texto de PDF) + +Agora vem o núcleo de **como fazer OCR em PDF**: fornecer ao motor o caminho do arquivo e extrair o texto reconhecido. O método devolve uma lista de resultados por página; cada resultado contém um atributo `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Se precisar do documento inteiro, itere sobre `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### E se o PDF estiver criptografado? + +Alguns PDFs são protegidos por senha. Nesse caso, você pode passar a senha para `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +O motor descriptografará em tempo real antes de executar o OCR—nenhum passo extra necessário. + +## Etapa 5: Pós‑Processamento do Texto Extraído (Ajuste Fino da Extração de Texto de PDF) + +A saída bruta do OCR costuma conter quebras de linha, espaços extras ou caracteres reconhecidos incorretamente. Uma rotina rápida de limpeza deixa a string extraída pronta para processamento posterior (indexação de busca, armazenamento em banco de dados, etc.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Agora você pode **extrair texto de PDF** com segurança e enviá‑lo para qualquer pipeline de NLP, motor de busca ou operação simples `open(...).write()`. + +## Bônus: Processamento em Lote de Vários PDFs (Escalar OCR em PDF) + +Se você tem uma pasta cheia de PDFs escaneados, envolva a lógica em um loop: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Este snippet demonstra como **executar OCR em PDF** em lote, uma necessidade comum em projetos de digitalização. + +## Saída Esperada + +Executar o exemplo de página única (Etapa 4) deve imprimir algo como: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Se você processar um livro com várias páginas, o console exibirá o texto limpo de cada página, e o script em lote deixará um arquivo `.txt` ao lado de cada PDF. + +## Armadilhas Comuns & Como Evitá‑las + +| Problema | Sintomas | Solução | +|----------|----------|---------| +| PDF de origem com baixa resolução | Caracteres embaralhados, palavras ausentes | Aumente o DPI (`set_dpi(400)` ou superior) | +| Idioma errado configurado | Muitos símbolos desconhecidos, especialmente caracteres acentuados | Use `engine.set_recognition_language(ocr.Language.FRENCH)` ou o enum apropriado | +| PDF grande causando erro de memória | `MemoryError` ou travamento após algumas páginas | Processar páginas em blocos (`engine.recognize_pdf(..., max_pages=10)`) | +| Fontes ausentes no PDF | Saída em branco para certas páginas | Verifique se o PDF realmente contém imagens raster; alguns PDFs são apenas vetoriais e precisam de tratamento diferente | + +## Ilustração da Imagem + +Abaixo está uma visualização rápida do fluxo de trabalho. O texto alternativo foi pensado para ser SEO‑friendly. + +![como fazer ocr pdf diagrama de fluxo mostrando inicialização do motor, definição de idioma, opções de renderização, reconhecimento e extração de texto](/images/ocr-workflow.png) + +*O diagrama não é necessário para o código funcionar, mas ajuda aprendizes visuais a entender onde cada etapa se encaixa.* + +## Conclusão + +Cobremos **como fazer OCR em PDF** com Python do início ao fim: criar um motor OCR, **alterar idioma do OCR**, configurar a renderização para **converter texto de PDF escaneado** e, finalmente, **extrair texto de PDF** para uso posterior. O exemplo completo e executável está pronto para ser inserido em qualquer projeto, e o script opcional em lote mostra como escalar a solução. + +Próximos passos sugeridos: + +- Adicionar **executar OCR em PDF** para arquivos multilingues percorrendo uma lista de idiomas. +- Integrar o texto extraído ao Elasticsearch para busca full‑text. +- Usar OCR para criar PDFs pesquisáveis incorporando a camada de texto de volta ao arquivo original (muitas bibliotecas expõem um método `save_as_searchable_pdf`). + +Sinta‑se à vontade para experimentar, ajustar configurações de DPI ou mudar para outro backend de OCR. Os fundamentos permanecem os mesmos, e agora você tem uma base sólida para construir. + +Feliz codificação, e que seus documentos escaneados finalmente se tornem pesquisáveis! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..b72aaebd0 --- /dev/null +++ b/ocr/portuguese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-06 +description: Como fazer OCR de PDF e criar arquivos PDF pesquisáveis a partir de imagens + usando Python. Aprenda a adicionar texto pesquisável e converter imagem para PDF/A + em minutos. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: pt +og_description: Como fazer OCR em PDF passo a passo. Aprenda a adicionar texto pesquisável + e converter imagem para PDF/A usando um script Python simples. +og_title: Como fazer OCR em PDF – Guia rápido para criar PDFs pesquisáveis +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Como fazer OCR de PDF em Python – Criar PDF pesquisável a partir de imagens +url: /pt/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como fazer OCR em PDF – Transforme Imagens Escaneadas em PDFs Pesquisáveis + +Já se perguntou **como fazer OCR em PDF** quando tudo o que você tem é uma imagem escaneada de uma nota fiscal ou recibo? Você não está sozinho. Em muitos escritórios a documentação recebida chega como PNGs ou JPEGs simples, e o próximo passo — tornar esse conteúdo pesquisável — parece uma caixa‑preta. + +A boa notícia? Com apenas algumas linhas de Python você pode **criar PDFs pesquisáveis**, **adicionar texto pesquisável**, e até **converter imagem para PDF/A** para arquivamento de longo prazo. Neste tutorial vamos percorrer cada etapa, explicar por que elas são importantes e fornecer um script pronto‑para‑executar que você pode inserir em qualquer projeto. + +> **Dica profissional:** A mesma abordagem funciona para digitalizações de várias páginas; basta percorrer os arquivos em um loop e o motor faz o trabalho pesado. + +--- + +## O que você precisará + +Antes de mergulharmos, certifique‑se de que você tem o seguinte em sua máquina: + +| Requisito | Por que é importante | +|-------------|-----------------| +| Python 3.9 ou mais recente | Sintaxe moderna e melhor suporte a bibliotecas | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Lida tanto com reconhecimento de imagem quanto com geração de PDF/A | +| Um arquivo de imagem (PNG, JPEG, TIFF) que você deseja transformar em um PDF pesquisável | A fonte do texto | +| Permissão de escrita na pasta de saída | Para que o script possa salvar o novo PDF | + +Se você ainda não instalou o SDK de OCR, execute: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +É isso — sem dependências de sistema complexas, apenas um pip install. + +--- + +## Visão geral de como fazer OCR em PDF + +Em alto nível, o processo consiste em três ações simples: + +1. **Reconhecer** o texto dentro da imagem enquanto preserva os gráficos originais. +2. **Exportar** o resultado do OCR junto com a imagem original como um **PDF/A pesquisável** (o formato de PDF amigável para arquivamento). +3. **Validar** que o arquivo resultante contém texto selecionável e pesquisável sobreposto à imagem original. + +A seguir, você verá cada etapa em código, com explicações do *porquê* por trás dos comandos. + +--- + +## Etapa 1: Reconhecer Texto da Imagem + +Primeiro, pedimos ao motor de OCR que leia os pixels e retorne um objeto de resultado que contém tanto a imagem bruta quanto o texto extraído. Pense nele como o motor “lendo” a nota fiscal para você. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Por que isso importa + +- **Preservar gráficos** significa que o layout visual (tabelas, logotipos, carimbos) permanece exatamente como o scanner capturou. +- O objeto `result` normalmente contém uma camada de texto oculto que inseriremos no PDF mais tarde. +- Usar `recognize_image` em vez de `recognize_pdf` evita uma etapa extra de conversão, o que acelera o processamento para imagens de página única. + +#### Variações comuns + +- Se você tem um **TIFF de várias páginas**, passe o caminho do arquivo diretamente; a maioria dos motores tratará cada página como uma imagem separada. +- Para PDFs que já contêm imagens, você pode chamar `engine.recognize_pdf("file.pdf")` e pular esta etapa completamente. + +--- + +## Etapa 2: Exportar Resultado do OCR como PDF/A pesquisável + +Agora pegamos o `result` da etapa 1 e instruímos o motor a gravar um novo arquivo. A bandeira chave aqui é *PDF/A* — a versão padrão ISO do PDF projetada para preservação de longo prazo. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Por que isso importa + +- **PDF pesquisável**: O arquivo de saída contém uma camada de texto oculta e selecionável. Você pode agora usar Ctrl + F no documento. +- **Conformidade PDF/A**: Algumas organizações (jurídicas, financeiras) exigem PDF/A para trilhas de auditoria; esta etapa satisfaz essa regra automaticamente. +- O método também **adiciona texto pesquisável** sem achatar a imagem, mantendo a fidelidade visual perfeita. + +#### Caso especial: Precisa de um PDF comum em vez disso? + +Se você não se importa com PDF/A, substitua `save_as_pdfa` por `save_as_pdf`. O restante do fluxo de trabalho permanece o mesmo. + +--- + +## Etapa 3: Verificar o PDF pesquisável + +Uma verificação rápida de sanidade salva você de bugs misteriosos mais tarde. Abra o arquivo gerado em qualquer visualizador de PDF, tente selecionar uma palavra e use a função de busca. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Saída esperada + +Ao executar o script, o console imprime: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Ao abrir o arquivo, você deverá ver a imagem original da nota fiscal com uma camada de texto tênue e invisível. Selecione qualquer palavra e perceberá que ela é selecionável — **esse é o texto pesquisável** que você acabou de adicionar. + +--- + +## Adicionando Texto pesquisável a PDFs Existentes (Bônus) + +Às vezes você já tem um PDF, mas precisa **adicionar texto pesquisável** a ele. O mesmo motor pode sobrepor resultados de OCR a um PDF existente: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Aqui `apply_to` mescla a camada oculta com as páginas originais, permitindo que você **crie PDFs pesquisáveis** sem re‑digitalizar. + +--- + +## Armadilhas Comuns e Dicas + +| Armadilha | Como evitar | +|---------|-----------------| +| **Imagens de origem de baixa resolução** (< 150 dpi) | Amplie ou solicite uma digitalização de resolução maior; a precisão do OCR cai drasticamente abaixo de 150 dpi. | +| **Dados de idioma ausentes** | Instale os pacotes de idioma apropriados para seu motor de OCR (`pip install pdfocr[eng,spa]`). | +| **Pasta de saída não gravável** | Execute o script com permissões suficientes ou escolha outro diretório. | +| **Falha na validação PDF/A** | Certifique‑se de que não está incorporando fontes não suportadas ou JavaScript; a maioria dos SDKs lida com isso automaticamente ao usar `save_as_pdfa`. | + +--- + +## Script Completo – Solução de Um Arquivo + +Abaixo está um script autônomo que une tudo. Copie‑e‑cole, substitua os caminhos de placeholder e você estará pronto para **converter imagem para PDF/A** em segundos. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**O que este script faz:** +1. Carrega o motor de OCR. +2. Lê a imagem escolhida e extrai o texto. +3. Grava um **PDF/A pesquisável** que você pode distribuir ou arquivar imediatamente. + +Sinta‑se à vontade para envolver a lógica `main` em uma função que processe uma pasta inteira — basta iterar sobre `os.listdir()` e repetir as três etapas para cada arquivo. + +--- + +## Próximos Passos e Tópicos Relacionados + +Agora que você dominou **como fazer OCR em PDF**, considere explorar estas ideias de continuação: + +- **Processamento em lote:** Use `concurrent.futures` para fazer OCR em dezenas de notas fiscais em paralelo. +- **Injeção de metadata:** Adicione datas de criação ou números de nota fiscal aos metadados do PDF para indexação mais fácil. +- **PDFs híbridos:** Combine texto pesquisável com imagens originais incorporadas para um “gêmeo digital” do documento em papel. +- **Saídas alternativas:** Exporte para **DOCX** ou **HTML** se sistemas posteriores precisarem de formatos editáveis. + +Cada um desses se baseia nos conceitos centrais que você acabou de aprender — reconhecer, exportar, validar. + +--- + +## Conclusão + +Em resumo, agora você sabe **como fazer OCR em PDF** ao transformar uma imagem simples em um **PDF/A pesquisável** com apenas três linhas de Python. O script cuida do trabalho pesado, preserva os gráficos originais e fornece um documento em conformidade com padrões que você pode pesquisar, arquivar ou compartilhar. + +Experimente com suas próprias notas fiscais, recibos ou contratos escaneados. Se encontrar algum problema, deixe um comentário abaixo ou consulte a documentação oficial do SDK — geralmente repleta de exemplos adicionais. Boa codificação e aproveite a nova capacidade de tornar qualquer imagem instantaneamente pesquisável! + +![Exemplo de como fazer OCR em PDF mostrando a imagem original e a sobreposição do PDF pesquisável](placeholder.png "Exemplo de como fazer OCR em PDF") + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como fazer OCR em PDF em .NET com Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Reconhecer Texto em PDF – Operações de OCR com Aspose.OCR para Java](/ocr/english/java/ocr-operations/) +- [Converter Imagens para PDF C# – Salvar Resultado OCR de Múltiplas Páginas](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/portuguese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..17f4989f3 --- /dev/null +++ b/ocr/portuguese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-06-06 +description: Como fazer OCR de PDF usando o Aspose OCR Cloud. Aprenda a extrair texto + de PDF, converter página de PDF em PNG e salvar imagens de páginas de PDF em Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: pt +og_description: Como fazer OCR de PDF com Aspose OCR Cloud. Este guia mostra como + extrair texto simples de PDF, converter página de PDF em PNG e salvar imagens das + páginas do PDF. +og_title: Como fazer OCR de PDF com Aspose OCR Cloud – Passo a passo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Como fazer OCR de PDF com Aspose OCR Cloud – Guia Completo +url: /pt/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como fazer OCR em PDF com Aspose OCR Cloud – Guia Completo + +Já se perguntou **como fazer OCR em PDF** sem precisar lidar com ferramentas pesadas de desktop? Você não está sozinho—muitos desenvolvedores encontram esse obstáculo quando precisam de uma maneira rápida e programática de extrair texto de documentos escaneados. A boa notícia? Com o Aspose OCR Cloud você pode **extrair texto de PDF**, transformar cada página em PNG e até **salvar imagens de páginas PDF** para uso posterior, tudo a partir de um script Python organizado. + +Neste tutorial vamos percorrer tudo o que você precisa saber: desde a instalação do SDK, licenciamento do motor, e reconhecimento de PDFs com várias páginas, até a extração de texto puro, conversão de páginas para PNG e persistência dessas imagens em disco. Ao final, você terá um trecho reutilizável que pode ser inserido em qualquer projeto que precise de **como fazer OCR em PDF**. + +## O que você vai precisar + +- **Python 3.8+** (o código funciona também em 3.10 e versões mais recentes) +- Uma conta no Aspose OCR Cloud – você receberá um arquivo de licença de teste gratuito (`Aspose.OCR.lic`) +- O pacote `asposeocrcloud` (`pip install asposeocrcloud`) +- Um PDF escaneado, com várias páginas, que você deseja processar + +É só isso. Sem binários extras, sem dependências nativas, apenas Python puro. + +## Como fazer OCR em PDF – Configuração e Licença + +Antes de chamar qualquer método de OCR, você precisa informar ao SDK quem você é. O Aspose usa um arquivo de licença leve que você coloca em um local acessível ao seu script. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Dica:* Se você pular a etapa de licença, o SDK ainda funcionará, mas inserirá uma pequena marca d'água nas imagens de saída. Não é ideal para produção. + +## Etapa 2: Instalar o SDK Python Aspose OCR Cloud + +Abra um terminal e execute: + +```bash +pip install asposeocrcloud +``` + +O pacote traz todas as dependências necessárias (requests, pillow, etc.) para que você não precise procurar nada mais. + +## Etapa 3: Criar um Motor OCR e Escolher um Idioma + +O motor é o coração da operação. Você pode especificar qualquer idioma suportado pelo Aspose; o inglês funciona na maioria dos casos. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Por que definir o idioma? Porque o motor OCR usa dicionários específicos de idioma para melhorar a precisão. Se você estiver processando PDFs em francês, basta trocar `ENGLISH` por `FRENCH`. + +## Etapa 4: Apontar para o seu PDF de Múltiplas Páginas + +Forneça ao motor o caminho completo do arquivo que você deseja processar. Caminhos relativos são aceitos, desde que resolvam a partir do diretório de trabalho do script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Certifique‑se de que o arquivo seja legível; caso contrário, você verá um `FileNotFoundError`. + +## Etapa 5: Executar OCR – Você Recebe uma Lista de Resultados + +Chamar `recognize_pdf` retorna uma lista onde cada elemento corresponde a uma página do PDF de origem. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Cada `OcrResult` contém duas propriedades úteis: + +* `text` – a representação em texto puro da página (ótimo para **extrair texto puro de pdf**) +* `image` – um objeto Pillow `Image` da página renderizada (perfeito para **converter página pdf png**) + +## Etapa 6: Extrair Texto do PDF e Converter Páginas para PNG + +Agora percorremos os resultados, imprimimos o texto extraído e salvamos uma versão PNG de cada página. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Saída Esperada no Console + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Você também encontrará `page_1.png`, `page_2.png`, … dentro de `YOUR_DIRECTORY`. Essas são as imagens rasterizadas das páginas que podem ser alimentadas em pipelines de processamento de imagem posteriores. + +## Etapa 7: Salvar Imagens de Páginas PDF (Processamento Opcional) + +Se você precisar apenas das imagens e não do texto, pode pular a linha `print(res.text)`. Por outro lado, se quiser armazenar o texto em arquivos `.txt` separados, basta acrescentar uma pequena gravação: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Esta pequena adição demonstra como é fácil **salvar imagens de páginas PDF** enquanto também persiste o conteúdo extraído. + +## Exemplo Completo Funcional + +Juntando tudo, aqui está o script completo que você pode copiar‑colar em `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Execute-o com: + +```bash +python ocr_pdf.py +``` + +Você deverá ver a impressão no console do texto de cada página e uma série de arquivos PNG. + + +## O que você deve aprender a seguir? + + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/portuguese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..e7b83a89a --- /dev/null +++ b/ocr/portuguese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-06-06 +description: Como pré-processar imagens para OCR usando Python. Aprenda a binarizar + imagens usando Otsu, como corrigir a inclinação de documentos escaneados e melhorar + a precisão do OCR para texto em alemão. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: pt +og_description: Como pré-processar imagens para OCR em Python. Este tutorial mostra + como binarizar a imagem usando Otsu, como corrigir a inclinação de documentos escaneados + e como melhorar a precisão do OCR para imagens em alemão. +og_title: Como pré-processar imagens para OCR – Guia completo em Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Como pré-processar imagens para OCR – Guia completo em Python +url: /pt/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Pré‑processar Imagens para OCR – Guia Completo em Python + +Já se perguntou **como pré‑processar imagens para OCR** para que o texto saia nítido como cristal? Você não está sozinho. Documentos escaneados — especialmente páginas alemãs ruidosas — podem ser um pesadelo para qualquer motor de OCR. A boa notícia? Alguns passos inteligentes de pré‑processamento podem transformar um escaneamento borrado e pontilhado em uma imagem limpa e legível por máquina. + +Neste tutorial vamos percorrer um exemplo prático que mostra **como pré‑processar imagens para OCR** usando Python. Você aprenderá a **binarizar imagem usando Otsu**, **como endireitar documentos escaneados**, e, de modo geral, **como melhorar a precisão do OCR** quando precisar **extrair texto de arquivos de imagem em alemão**. Sem enrolação, apenas um script funcional que você pode copiar‑colar hoje. + +## O Que Você Precisa + +- **Python 3.9+** (qualquer versão recente serve) +- Uma biblioteca de OCR que exponha a classe `OcrEngine` — para a demonstração vamos assumir um pacote genérico `ocr`. Instale‑a com `pip install ocr-lib`. +- Um escaneamento alemão ruidoso (`noisy_german_scan.tif`) que você queira testar. +- Um entendimento básico de funções Python (se você já escreveu um `def`, está pronto). + +> **Dica de especialista:** Se você estiver usando um SDK de OCR diferente (por exemplo, Tesseract via `pytesseract`), os conceitos permanecem os mesmos — basta adaptar os nomes dos métodos. + +## Visão Geral da Solução + +1. **Criar uma instância do motor de OCR.** +2. **Definir o idioma de reconhecimento para Alemão.** +3. **Construir um pipeline de pré‑processamento customizado** que inclui endireitamento, remoção de ruído, binarização (Otsu) e alongamento de contraste. +4. **Anexar o pipeline ao motor** para que cada imagem passe por ele automaticamente. +5. **Executar o OCR** em um escaneamento alemão ruidoso. +6. **Imprimir o texto extraído** para verificar o resultado. + +A seguir detalhamos cada passo, explicamos **por que** ele importa e mostramos o código exato que você precisa. + +![exemplo de como pré‑processar imagens para OCR](image.png "exemplo de como pré‑processar imagens para OCR") + +## Etapa 1: Criar uma Instância do Motor de OCR + +Primeiro de tudo — sem um motor, nada acontece. O objeto `OcrEngine` é o ponto de entrada que coordena todo o processamento posterior. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Por que isso importa:* Inicializar o motor configura recursos internos (como modelos de idioma) e fornece uma base limpa para anexar um pipeline customizado depois. + +## Etapa 2: Definir o Idioma de Reconhecimento para Alemão + +A precisão do OCR depende muito do idioma. Ao dizer ao motor que o texto está em Alemão, você ativa o conjunto de caracteres e o modelo de linguagem corretos. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Se você pular isso, o motor pode assumir o inglês por padrão, reconhecendo incorretamente os umlauts (ä, ö, ü) e o caractere ß — armadilhas comuns ao lidar com escaneamentos alemães. + +## Etapa 3: Construir um Pipeline de Pré‑processamento Customizado + +Este é o coração de **como pré‑processar imagens para OCR**. Vamos encadear quatro transformações: + +| Transformação | O que faz | Por que ajuda | +|----------------|-----------|---------------| +| **Deskew** | Rotaciona a imagem de volta ao horizontal (máx 5°) | Escaneamentos raramente ficam perfeitamente alinhados; endireitar remove a inclinação que confunde a segmentação de caracteres. | +| **Denoise** | Reduz manchas aleatórias (intensidade 0.7) | Ruído cria bordas falsas que o motor de OCR pode interpretar como caracteres. | +| **Binarize (Otsu)** | Converte para preto‑e‑branco usando o método de Otsu | Uma imagem binária limpa fornece ao motor um contraste nítido entre primeiro plano (texto) e fundo. | +| **Contrast Stretch** | Expande a faixa dinâmica | Melhora a legibilidade de traços fracos, especialmente em documentos antigos. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Como Endireitar Documentos Escaneados + +A chamada `deskew` acima é a resposta concreta para **como endireitar documentos escaneados**. Internamente, ela estima o ângulo dominante das linhas de texto via transformada de Hough e rotaciona a imagem de volta. Se seus documentos estiverem rotacionados mais de 5°, aumente `max_angle`, mas cuidado com artefatos de rotação excessiva. + +### Binarizar Imagem Usando Otsu + +A linha `binarize(method="otsu")` responde diretamente à consulta **binarize image using otsu**. O algoritmo de Otsu calcula um limiar que minimiza a variância intra‑classe, ideal para documentos com histogramas bimodais (texto escuro vs. fundo claro). + +## Etapa 4: Anexar o Pipeline ao Motor + +Agora informamos ao motor de OCR para executar cada imagem recebida através do pipeline que acabamos de montar. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Por que isso importa:* Sem registrar, o motor processaria o escaneamento bruto, ignorando toda a limpeza que configuramos. Esta etapa garante **como melhorar a precisão do OCR** aplicando o mesmo pré‑processamento de forma consistente. + +## Etapa 5: Reconhecer Texto de um Escaneamento Alemão Ruidoso + +Hora de juntar tudo. Alimentamos o motor com uma imagem alemã ruidosa e deixamos que ele faça o trabalho pesado. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Se quiser analisar o desempenho, pode cronometrar a chamada: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Etapa 6: Exibir o Texto Reconhecido + +Por fim, imprimimos a string extraída. Esta é a resposta direta a **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Saída Esperada + +Assumindo que o escaneamento de exemplo contenha a frase “Die schnelle braune Füchsin springt über den faulen Hund.” você deverá ver algo como: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Se a saída ainda contiver caracteres estranhos, considere ajustar a intensidade de `denoise` ou aumentar `max_angle` para o endireitamento. + +## Armadilhas Comuns & Como Superá‑las + +- **Modelo de idioma ausente:** Esquecer `set_recognition_language(Language.GERMAN)` costuma resultar em ausência de umlauts. Verifique a chamada. +- **Remoção de ruído excessiva:** Uma intensidade acima de 0.9 pode apagar traços finos, especialmente em fontes antigas. Mantenha entre 0.5‑0.7 na maioria dos casos. +- **Formato de arquivo incorreto:** Alguns motores de OCR falham com TIFFs de múltiplas páginas. Se você tem um documento multipágina, divida‑o em arquivos de página única primeiro. +- **Ordem do pipeline:** A ordem mostrada (deskew → denoise → binarize → contrast) é intencional. Binarizar antes de remover ruído pode fixar o ruído; sempre remova o ruído primeiro. + +## Expandindo o Pipeline (Próximos Passos) + +Agora que você tem uma base sólida, pode querer: + +- **Adicionar uma abertura morfológica** para limpar pequenos pontos (`.morph_open(kernel=3)`). +- **Integrar um modelo de linguagem** para correção pós‑processamento (`ocr_engine.apply_spellcheck()`). +- **Paralelizar o processamento em lote** para grandes volumes usando `concurrent.futures`. + +Todos esses são extensões naturais que mantêm a ideia central de **como pré‑processar imagens para OCR** enquanto aumentam ainda mais **como melhorar a precisão do OCR**. + +## Conclusão + +Acabamos de cobrir **como pré‑processar imagens para OCR** do início ao fim: criar um motor, definir o idioma alemão, montar um pipeline que **binarize image using Otsu**, **como endireitar documentos escaneados**, e finalmente **extrair texto de german image** com maior confiança. Seguindo as seis etapas acima, você verá um salto perceptível na qualidade do reconhecimento — nada de correções manuais intermináveis. + +Teste o script com seus próprios escaneamentos, experimente os parâmetros e deixe os resultados falarem por si. Tem dúvidas sobre algum ajuste específico de pré‑processamento? Deixe um comentário, e mergulharemos mais fundo juntos. + +Feliz codificação, e que seu OCR seja sempre preciso! + + +## O Que Você Deve Aprender a Seguir? + + +Os tutoriais a seguir abordam tópicos intimamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..243472a7b --- /dev/null +++ b/ocr/portuguese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-06 +description: OCR de imagem PNG com Python – aprenda como extrair texto de uma imagem, + execute um exemplo de OCR em Python e até leia texto em grego antigo facilmente. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: pt +og_description: OCR de imagem PNG em Python explicado. Este guia mostra como extrair + texto de uma imagem, executar um exemplo de OCR em Python e ler grego antigo com + facilidade. +og_title: OCR de Imagem PNG em Python – Tutorial Completo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR de Imagem PNG em Python – Guia Completo Passo a Passo +url: /pt/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR de Imagem PNG em Python – Guia Completo Passo a Passo + +Já se perguntou como **OCR PNG image** arquivos diretamente de um script Python? Talvez você tenha uma pasta cheia de manuscritos antigos digitalizados e precise **extract text from image** arquivos sem digitar tudo manualmente. A boa notícia é que você não precisa de um PhD em visão computacional—apenas algumas linhas de código e a biblioteca certa, e você estará lendo grego antigo em segundos. + +Neste tutorial vamos percorrer um **python OCR example** que reconhece texto de um PNG, define o idioma para grego politônico e imprime o resultado. Ao final você saberá exatamente como **recognize image text**, lidar com armadilhas comuns e adaptar o script para outros idiomas ou formatos de imagem. + +## O que você aprenderá + +- Instalar e configurar uma biblioteca Python OCR (pytesseract + Tesseract OCR) +- Criar uma instância do motor OCR e carregar um arquivo PNG +- Definir o idioma de reconhecimento para grego politônico para que você possa **read ancient greek** +- Exibir o texto reconhecido e solucionar problemas típicos +- Estender o script para processar em lote múltiplos PNGs ou mudar para outro idioma + +### Pré-requisitos + +| Requisito | Por que importa | +|-------------|----------------| +| Python 3.8+ | Sintaxe moderna e dicas de tipo | +| `pytesseract` package | Wrapper leve ao redor do motor Tesseract | +| Tesseract OCR binaries (≥ 5.0) | O motor real que faz o trabalho pesado | +| Greek language data (`grc.traineddata`) | Necessário para **read ancient greek** corretamente | +| Uma imagem PNG que você deseja analisar (ex., `ancient_greek.png`) | Nosso alvo para a demonstração **ocr png image** | + +Você pode instalar a parte Python com: + +```bash +pip install pytesseract Pillow +``` + +E no Ubuntu/macOS você adicionaria o próprio motor: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Não se esqueça de baixar os dados treinados do grego politônico: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(O caminho pode ser diferente; ajuste `TESSDATA_PREFIX` se necessário.)* + +## OCR PNG Image: Criar a Instância do Motor + +A primeira coisa que precisamos é um objeto que se comunica com o Tesseract. No `pytesseract` o motor é acessado através de funções ao nível do módulo, mas para clareza vamos encapsulá‑lo em uma classe pequena. Isso espelha o conceito de “engine” que você viu no snippet original. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Por que encapsular?** +- Mantém a API pública idêntica ao snippet que você começou, tornando a migração indolor. +- Permite adicionar logging ou tratamento de erros mais tarde sem tocar no fluxo principal. +- Demonstrar boa prática de OOP—algo que desenvolvedores seniores apreciam. + +## Extrair Texto da Imagem: Definir o Idioma para Grego Politônico + +Agora que temos um motor, precisamos dizer a ele qual idioma esperar. O grego politônico usa diacríticos que não são cobertos pelos dados padrão “greek”, então apontamos o Tesseract para o arquivo treinado `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Se você quiser **extract text from image** arquivos em outro idioma, basta substituir `"grc"` por `"eng"` para Inglês, `"fra"` para Francês, etc. A mesma linha funciona para qualquer idioma que você tenha instalado. + +## Reconhecer Texto da Imagem: Executar o OCR em um PNG + +Com o idioma definido, alimentamos o PNG no motor. O exemplo original usava um caminho codificado; vamos torná‑lo um pouco mais flexível usando objetos `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Dicas e Casos Limite** + +- **File not found** – envolva a chamada em um `try/except FileNotFoundError` para fornecer uma mensagem amigável. +- **Low‑resolution PNG** – considere pré‑processamento (ex., redimensionamento, binarização) com Pillow antes do OCR. +- **Non‑Greek text** – o Tesseract ainda tentará decodificar, mas a precisão cai drasticamente. Sempre combine o idioma. + +## Exibir o Texto Reconhecido + +Finalmente, imprimimos o resultado. Em um projeto real você pode gravar em um banco de dados, um CSV, ou até mesmo alimentá‑lo em um pipeline de tradução. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Quando você executar o script contra uma varredura clara de uma inscrição grega antiga, você deverá ver algo como: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Se a saída parecer confusa, verifique novamente se o arquivo **greek.traineddata** está na pasta correta e se o PNG não está muito ruidoso. + +## Exemplo Completo Funcional (Todas as Etapas em Um Script) + +Abaixo está o programa completo, pronto‑para‑executar. Salve como `ocr_greek.py` e execute `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Saída esperada** (truncada para brevidade): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Se você vir os caracteres gregos corretos, parabéns—você realizou com sucesso uma operação **ocr png image** em Python! + +## Perguntas Frequentes & Dicas Profissionais + +### Como melhorar a precisão em um PNG ruidoso? + +- Converter a imagem para escala de cinza: `img = img.convert('L')` +- Aplicar um limiar binário: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Aumentar a escala com `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Esses passos costumam transformar um pesadelo de **recognize image text** em um resultado limpo. + +### Posso processar uma pasta inteira de PNGs? + +Absolutamente. Envolva a chamada `recognize_image` em um loop `for` sobre `Path.glob("*.png")`. Armazene cada resultado em um dicionário ou grave em um CSV para análise posterior. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### E se eu precisar extrair apenas números? + +Passe uma string **config** personalizada para `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Dessa forma você pode **extract text from image** arquivos que contenham tabelas, números de série ou timestamps. + +### Existe uma maneira de obter pontuações de confiança? + +Sim—use `pytesseract.image_to_data` que retorna um TSV com confiança por palavra. Você pode filtrar tokens de baixa confiança antes de montar a string final. + +## Expandindo o Tutorial + +Agora que você dominou o básico, considere explorar estes tópicos relacionados: + +- **Batch OCR with multiprocessing** – acelere grandes corpora de PNGs. +- **Hybrid OCR + NLP pipelines** – traduza automaticamente o grego antigo extraído para o inglês moderno. +- **Alternative engines** – experimente `easyocr` ou métodos baseados em `opencv` para casos de uso específicos. +- **Cloud OCR services** – Google Vision, Azure Computer Vision ou AWS Textract para escalabilidade serverless. + +Cada um desses se baseia no núcleo **python ocr example** que acabamos de cobrir, então você se sentirá confortável em aprofundar. + +## Conclusão + +Transformamos um snippet simples em um fluxo robusto de **ocr png image** em Python. Ao criar um `OcrEngine`, definir o idioma para grego politônico, alimentar um PNG e imprimir o resultado, você agora sabe como **extract text from image** arquivos, **recognize image text**, e até **read ancient greek**. + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir cobrem tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Extrair Texto de Imagem com Aspose OCR – Guia Passo a Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Como Definir Valor de Limiar no Reconhecimento de Imagem OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [reconhecer texto de imagem com Aspose OCR para múltiplos idiomas](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/portuguese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..a3d5970a3 --- /dev/null +++ b/ocr/portuguese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-06 +description: Tutorial de OCR em Python mostrando como reconhecer texto em imagens, + realizar OCR de alta resolução e extrair texto em espanhol usando OCR acelerado + por GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: pt +og_description: Tutorial de OCR em Python que orienta você a reconhecer texto em imagens, + OCR de alta resolução e extrair texto em espanhol com aceleração por GPU. +og_title: Tutorial de OCR em Python – Reconhecimento de Texto Acelerado por GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Tutorial de OCR em Python – Reconheça Texto em Imagens com Aceleração por GPU +url: /pt/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial de OCR em Python – Reconhecer Texto em Imagem com Aceleração GPU + +Já se perguntou como **reconhecer texto em imagem** em um script Python sem passar horas ajustando configurações? Você não está sozinho. Neste **python ocr tutorial** vamos mostrar uma abordagem limpa e de ponta a ponta para extrair texto em espanhol de uma imagem de alta resolução, e ainda adicionaremos aceleração GPU para que o processo seja extremamente rápido. + +Pense nisso como uma demonstração rápida de pausa para o café que você pode expandir para um pipeline de nível de produção mais tarde. Ao final deste guia, você terá um programa executável que realiza **high resolution OCR**, utiliza uma GPU com suporte a CUDA e devolve os caracteres exatos em espanhol que você precisa. + +## O Que Você Vai Aprender + +- Como instalar e importar uma biblioteca OCR moderna que suporta aceleração GPU. +- Como criar uma instância do motor OCR e configurá‑la para **recognize image text** em espanhol. +- Como habilitar **gpu accelerated OCR** para ganhos de velocidade massivos em arquivos de alta resolução. +- Como lidar com casos extremos, como drivers CUDA ausentes ou fallback para CPU. +- Dicas para melhorar a precisão quando você precisar **extract spanish text** de digitalizações ruidosas. + +### Pré‑requisitos + +- Python 3.9+ (o código funciona também em 3.10 e versões mais recentes). +- Uma GPU compatível com CUDA (opcional, mas altamente recomendada). +- Familiaridade básica com pip e ambientes virtuais. + +Se você não possui algum desses itens, o tutorial ainda funciona — basta pular a etapa de GPU e a biblioteca fará fallback para CPU automaticamente. + +## Tutorial de OCR em Python: Instale os Pacotes Necessários + +Primeiro de tudo, precisamos de um motor OCR robusto. Para este tutorial, usaremos o pacote de código aberto **`easyocr`**, que já inclui suporte a GPU quando um dispositivo compatível é detectado. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Dica profissional:** Se você já tem o PyTorch instalado, certifique‑se de que ele corresponde à sua versão CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Versões incompatíveis são uma fonte comum de erros “GPU not found”. + +## Etapa 1: Crie uma Instância do Motor OCR + +Agora vamos iniciar o motor. EasyOCR chama sua classe principal `Reader`. O construtor aceita uma lista de códigos de idioma; passaremos `"es"` para espanhol. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Por que isso importa:* Ao declarar o idioma antecipadamente, o motor carrega apenas os pesos de rede neural necessários, o que economiza memória e acelera a inferência — especialmente útil quando você está lidando com **high resolution OCR** mais adiante. + +## Etapa 2: Prepare uma Imagem de Alta Resolução + +Imagens de alta resolução fornecem ao modelo mais pixels para trabalhar, o que geralmente se traduz em melhor reconhecimento de caracteres. Vamos supor que você tenha um arquivo chamado `high_res_spanish.png` dentro de uma pasta chamada `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Se você não tem uma amostra de alta resolução disponível, pode baixar uma gratuitamente do Unsplash ou gerar uma imagem sintética com Pillow. O importante é manter o DPI acima de 300 para obter os melhores resultados. + +## Etapa 3: Habilite a Aceleração GPU (Opcional, mas Recomendada) + +EasyOCR já tenta usar a GPU quando você define `gpu=True`. No entanto, é uma boa prática verificar se o dispositivo está realmente sendo usado, especialmente em configurações com múltiplas GPUs. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Por que verificar isso?* Se o script recair silenciosamente para CPU, você pode se perguntar por que uma operação de 5 segundos de repente leva 30 segundos. Essa pequena verificação torna o comportamento transparente e mantém seu pipeline de **gpu accelerated OCR** previsível. + +## Etapa 4: Execute OCR de Alta Resolução e Reconheça Texto em Imagem + +Agora a parte divertida — realmente ler o texto. O método `readtext` do EasyOCR retorna uma lista de tuplas contendo a caixa delimitadora, a string reconhecida e uma pontuação de confiança. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Se você precisar da string bruta sem coordenadas, defina `detail=0`. Para a maioria dos casos de uso de **recognize image text**, o padrão (`detail=1`) fornece contexto suficiente para pós‑processamento posterior. + +## Etapa 5: Extraia Texto em Espanhol e Limpe a Saída + +Como solicitamos ao EasyOCR o idioma espanhol, as strings retornadas já estão nesse idioma. Ainda assim, você pode querer concatená‑las, remover espaços em branco ou filtrar detecções de baixa confiança. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**E se a confiança estiver baixa?** Você pode reduzir o limiar (correndo o risco de ruído) ou pré‑processar a imagem (aumentar contraste, binarizar ou corrigir inclinação). Essas técnicas são comuns ao lidar com **high resolution OCR** em documentos digitalizados. + +## Etapa 6: Tratamento de Casos Extremos e Ajustes de Performance + +Mesmo os modelos mais bem treinados tropeçam em alguns cenários. Abaixo estão algumas correções rápidas que você pode colar no script. + +### 6.1 Fallback Quando Não Há GPU Presente + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Redução de Resolução de Imagens Muito Grandes + +Se sua imagem for maior que 4000 × 4000 px, você pode ficar sem memória GPU. Reduza proporcionalmente mantendo o DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Esses trechos mantêm o script robusto, seja em uma estação de trabalho ou em um laptop modesto. + +## Exemplo Completo Funcional + +Juntando tudo, aqui está o script completo que você pode copiar‑colar e executar imediatamente: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Saída esperada (exemplo):** + + + +## O Que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Extrair Texto de Imagem com Aspose OCR – Guia Passo a Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Como Fazer OCR de Texto em Imagem com Idioma Usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Como Reconhecer Retângulos de Página para Reconhecimento de Texto OCR no Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/portuguese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..ae6816224 --- /dev/null +++ b/ocr/portuguese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-06 +description: Reconheça texto a partir de imagem usando o mecanismo OCR em Python. + Aprenda como configurar o mecanismo OCR em Python e extrair texto de imagens com + processamento em nuvem em minutos. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: pt +og_description: Reconheça texto de imagem com o motor OCR Python. Este guia mostra + como configurar o motor OCR Python e extrair texto de imagem de forma eficiente. +og_title: Reconhecer texto de imagem em Python – Tutorial completo de configuração +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Reconhecer texto de imagem em Python – Guia completo de configuração do motor + OCR +url: /pt/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconhecer texto a partir de imagem em Python – Tutorial de Configuração Completa + +Já se perguntou como **reconhecer texto a partir de imagem** usando apenas algumas linhas de Python? Você não está sozinho. Seja construindo um scanner de recibos, um digitalizador de documentos ou um simples projeto de hobby, ser capaz de extrair texto de uma imagem é uma habilidade que traz resultados rapidamente. + +Neste tutorial vamos percorrer todo o processo — começando pela configuração do **configure OCR engine python**, passando pela autenticação na nuvem e, finalmente, mostrando como **extrair texto de imagem** com um resultado confiável. Sem mágica, apenas passos claros que você pode copiar‑colar e executar hoje. + +## O que você vai aprender + +- Como instalar e importar a biblioteca OCR necessária. +- Os comandos exatos para **configure OCR engine python** para processamento na nuvem. +- Um script completo e executável que **recognize text from image** e imprime a saída. +- Dicas para lidar com armadilhas comuns, como chaves de API ausentes ou formatos de imagem não suportados. +- Ideias avançadas, como processamento em lote e fallback local. + +### Pré‑requisitos + +- Python 3.8+ instalado na sua máquina. +- Uma conexão com a internet (o exemplo usa um serviço OCR baseado em nuvem). +- Uma chave de API válida do provedor OCR (você verá onde inseri‑la). + +Se você tem tudo isso, vamos mergulhar — sem enrolação, apenas um guia prático que funciona. + +--- + +## Passo 1: Instalar a Biblioteca OCR e importá‑la + +Antes de poder **configure OCR engine python**, você precisa da biblioteca que se comunica com o serviço na nuvem. No nosso exemplo usaremos um pacote fictício, porém representativo, chamado `ocrcloud`. Substitua‑o pelo pacote real que você está usando (ex.: `easyocr`, `google-cloud-vision`, etc.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Por que isso importa:** Importar a classe lhe dá acesso a métodos como `use_cloud()` e `set_api_key()`. Sem a importação, o restante do script geraria um `NameError`. + +*Dica de especialista:* Fixe a versão no seu `requirements.txt` (`ocrcloud==2.1.0`) para evitar mudanças inesperadas mais tarde. + +--- + +## Passo 2: Criar e **configure OCR engine python** para o Modo Cloud + +Agora realmente **configure OCR engine python**. O motor inicia em modo local por padrão; mudar para o modo cloud permite que você delegue a análise pesada de imagens a servidores poderosos. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explicação:** +- `OcrEngine()` cria um novo objeto de motor — pense nele como uma tela em branco. +- `use_cloud(True)` aciona um interruptor, dizendo ao motor para enviar imagens via HTTPS ao invés de processá‑las localmente. Isso é crucial para obter resultados de alta precisão em fontes complexas ou fotos de baixa resolução. + +--- + +## Passo 3: Autenticar com sua Chave de API da Nuvem + +A maioria dos serviços OCR na nuvem exige uma chave de API. Esta etapa mostra como injetar a credencial de forma segura. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Nota de segurança:** Nunca codifique a chave em um repositório público. Em produção, você a obteria de uma variável de ambiente: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Passo 4: **recognize text from image** – Enviar uma Imagem Remota para Processamento + +Com o motor configurado, finalmente podemos **recognize text from image**. O método `recognize_image()` aceita um caminho ou URL e devolve um objeto contendo o texto extraído. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**O que acontece nos bastidores?** +Os bytes da imagem são enviados para o endpoint do provedor, processados por um modelo de deep‑learning, e o texto puro é devolvido em streaming. Se a imagem for grande, o serviço pode redimensioná‑la automaticamente para acelerar a tarefa. + +--- + +## Passo 5: Exibir o Resultado da **extract text from image** + +Agora que o serviço OCR fez seu trabalho, basta imprimir o texto. Em aplicações reais você pode armazená‑lo em um banco de dados ou passá‑lo para outra função. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Saída esperada:** (exemplo) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Se a saída parecer confusa, verifique se a imagem está nítida e se você selecionou o modelo de idioma correto (muitos serviços permitem especificar `engine.set_language("en")`). + +--- + +## Tratamento de Casos Limite & Armadilhas Comuns + +### 1. Chave de API ausente ou inválida +Se aparecer um erro de autenticação, verifique: +- Se a chave está ativa e não expirou. +- Se está sendo lida corretamente da variável de ambiente. +- Se sua rede permite tráfego HTTPS de saída. + +### 2. Formatos de Imagem Não Suportados +A maioria das APIs OCR aceita JPEG, PNG e PDF. Tentar BMP ou TIFF pode gerar uma resposta “formato não suportado”. Converta com Pillow se necessário: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Limites de Taxa +Serviços na nuvem costumam limitar requisições por minuto. Se atingir o limite, implemente back‑off exponencial: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Fallback para OCR Local +Se a nuvem estiver indisponível, você pode mudar de volta: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Ter um fallback mantém seu aplicativo resiliente. + +--- + +## Exemplo Completo Funcional + +Juntando tudo, aqui está um script que você pode executar agora (basta substituir os valores de placeholder). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Execute:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Você deverá ver o texto extraído impresso no console, confirmando que você **recognize text from image** e **extract text from image** com sucesso usando um fluxo **configure OCR engine python** adequado. + +--- + +## Conclusão + +Acabamos de percorrer um processo completo, de ponta a ponta, que permite **recognize text from image** em Python, desde a instalação da biblioteca até a autenticação em um serviço de nuvem e, finalmente, a **extract text from image** com uma única chamada de função. Ao **configure OCR engine python** da maneira correta, você ganha flexibilidade (cloud vs. local) e confiabilidade (tratamento adequado de erros). + +O que vem a seguir? Experimente processar em lote uma pasta de recibos, adicionar detecção de idioma ou experimentar PDFs como entrada. O céu é o limite depois que você domina o básico. + +Feliz codificação, e sinta‑se à vontade para deixar dúvidas nos comentários — nada supera aprender juntos! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Extrair Texto de Imagem com Aspose OCR – Guia Passo a Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrair Texto de Imagem – Reconhecer Linha com Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Como Extrair Texto de Imagem Preparando Retângulos no OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..884e22eb4 --- /dev/null +++ b/ocr/portuguese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Execute OCR em imagem usando Python e veja as pontuações de confiança. + Aprenda como filtrar palavras de baixa confiança, definir limites e lidar com casos + extremos. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: pt +og_description: Execute OCR em imagem no Python, inspecione os níveis de confiança + e filtre palavras de baixa confiança. Este tutorial guia você por um exemplo completo + e executável. +og_title: Execute OCR em Imagem com Python – Guia Completo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Execute OCR em Imagem com Python – Guia Completo Passo a Passo +url: /pt/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Executar OCR em Imagem com Python – Guia Completo Passo a Passo + +Já precisou **executar OCR em arquivos de imagem** mas não sabia como obter texto confiável deles? Você não está sozinho—muitos desenvolvedores enfrentam o mesmo problema quando as palavras extraídas parecem instáveis e a pontuação de confiança é um mistério. + +Neste guia mergulharemos direto em uma solução funcional: você verá como executar OCR em imagem, ler a confiança geral e extrair quaisquer palavras de baixa confiança que possam precisar de revisão manual. Ao final você terá um script reutilizável, entenderá por que cada linha importa e saberá como ajustar o limite de confiança para seus próprios projetos. + +## O que este tutorial cobre + +Percorreremos todo o fluxo de trabalho—from carregar uma imagem até imprimir um relatório organizado das palavras que ficaram abaixo de 80 % de confiança. Ao longo do caminho discutiremos: + +* Escolher um motor de OCR sólido (usaremos **EasyOCR**, uma biblioteca Python de OCR popular) +* Interpretar o atributo `confidence` que todo resultado de OCR retorna +* Filtrar palavras com um **limite de confiança de OCR** personalizado +* Estender o script para processamento em lote ou motores alternativos como **pytesseract** + +Nenhuma experiência prévia com OCR é necessária, apenas familiaridade básica com Python e um ambiente de trabalho (Python 3.9+ recomendado). + +Pronto para transformar capturas de tela desfocadas em texto limpo e pesquisável? Vamos começar. + +--- + +## ## Como Executar OCR em Imagem com Python + +O coração do tutorial é um trecho de três etapas que espelha o código que você já viu. A seguir, vamos dividir cada linha, explicar o porquê e, depois, fornecer um script completo pronto para copiar‑e‑colar. + +### Etapa 1: Instalar e Importar o Motor de OCR + +Primeiro, certifique‑se de que a biblioteca de OCR está disponível. **EasyOCR** funciona pronto para uso em muitas línguas e fornece uma pontuação de confiança por palavra. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Por que EasyOCR?* Ele inclui um modelo de deep‑learning treinado em conjuntos de dados diversos, então você costuma obter valores de confiança mais altos que o motor Tesseract mais antigo, especialmente em imagens de qualidade mista. + +> **Dica profissional:** Se você estiver em um ambiente restrito (por exemplo, um contêiner Docker pequeno), `pytesseract` pode ser mais leve, mas você perderá parte da precisão moderna que o EasyOCR oferece. + +### Etapa 2: Executar OCR na Imagem + +Agora realmente **executamos OCR em imagem**. O método `recognize_image` do exemplo original é substituído pela chamada `readtext` do EasyOCR, que devolve uma lista de tuplas `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Cada entrada em `ocr_results` tem a forma: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +O terceiro elemento (`0.92` no exemplo) é a pontuação de confiança, variando de 0 a 1. + +### Etapa 3: Resumir a Confiança Geral + +Ao contrário do trecho anterior que imprimia um único atributo `confidence`, o EasyOCR fornece confiança por palavra. Para ter uma ideia geral, vamos calcular a média delas: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Por que a média?* Ela oferece uma verificação rápida de saúde—se a confiança geral estiver abaixo, digamos, 70 %, provavelmente será necessário melhorar a imagem (melhor iluminação, pré‑processamento, etc.). + +### Etapa 4: Listar Palavras de Baixa Confiança + +Agora vem a parte que responde diretamente ao requisito “listar palavras cuja confiança está abaixo do limite desejado”. Definiremos um **limite de confiança de OCR** de 0.80 (80 %) por padrão, mas você pode ajustá‑lo. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +O laço imprime cada palavra que não atingiu o corte, junto com sua confiança percentual. Este é o análogo exato do laço original `for recognized_word in recognition_result.words`, mas agora funciona com o formato de saída do EasyOCR. + +--- + +## ## Entendendo as Pontuações de Confiança do OCR + +Confiança não é um número mágico; é a estimativa do modelo sobre quão certo ele está de uma transcrição específica. Aqui estão alguns pontos a ter em mente: + +| Situação | Confiança Típica | O que Fazer | +|-----------|-------------------|------------| +| Digitalização clara e de alta resolução | 0.95 – 1.00 | Nenhum trabalho extra necessário | +| Leve desfoque ou iluminação desigual | 0.80 – 0.94 | Considerar pré‑processamento leve (aumento de contraste) | +| Muito ruído, texto rotacionado | < 0.70 | Aplicar pré‑processamento de imagem (deskew, denoise) ou mudar para outro motor de OCR | + +> **Atenção:** Algumas línguas (por exemplo, escrita cursiva) naturalmente produzem pontuações mais baixas. Ajuste o limite conforme necessário. + +### Casos Limite e Variações + +1. **Processamento em Lote** – Se precisar **executar OCR em imagem** em massa, envolva a lógica acima em um laço que itere sobre um diretório. +2. **Múltiplas Línguas** – Passe uma lista como `['en', 'fr']` para `easyocr.Reader` e o motor detectará ambas. +3. **Motores Alternativos** – Quer tentar **pytesseract**? Substitua o bloco do leitor por: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Você então precisará agregar as confidências por caractere em valores por palavra—um pouco mais de trabalho, mas viável. + +4. **Truques de Pré‑processamento** – Aplicar filtros OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) pode aumentar a confiança em digitalizações ruidosas. + +--- + +## ## Script Completo, Pronto para Executar + +Abaixo está o arquivo Python completo que você pode colocar no seu projeto. Salve como `ocr_report.py` e execute `python ocr_report.py`. Certifique‑se de que o caminho da imagem aponta para um arquivo real. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Saída esperada** (seus números variarão): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Se todas as palavras ultrapassarem a barra de 80 % você verá a mensagem amigável “All words meet the confidence threshold.” em vez disso. + +--- + +## ## Perguntas Frequentes (FAQ) + +**Q: Isso funciona com PDFs?** +A: Não diretamente. Converta cada página do PDF em uma imagem primeiro (por exemplo, com `pdf2image`) e então alimente o PNG/JPEG ao script. + +**Q: Meus números de confiança estão todos baixos—o que posso fazer?** +A: Experimente pré‑processamento de imagem: aumente o contraste, remova ruído de fundo ou rotacione a imagem para uma linha de base horizontal. EasyOCR também aceita um parâmetro `contrast_ths` que você pode ajustar. + +**Q: Posso exportar os resultados para CSV?** +A: Absolutamente. Após o laço de baixa confiança, escreva `ocr_results` em um `csv.DictWriter` onde cada linha contém `text`, `confidence` e as coordenadas da caixa delimitadora. + +**Q: Existe uma versão acelerada por GPU?** +A: EasyOCR usa CUDA automaticamente se uma GPU compatível e o PyTorch estiverem instalados. Verifique com `torch.cuda.is_available()` antes de executar o script. + +--- + +## Conclusão + +Acabamos de **executar OCR em imagem** usando Python, inspecionar a confiança geral e isolar quaisquer palavras de baixa confiança que precisam de revisão manual. + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como Definir Valor de Limiar em Reconhecimento de Imagem OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Como Usar Aspose OCR para Resultado JSON em Reconhecimento de Imagem](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extrair Texto de Imagem – Otimização OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/russian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..ebef41f34 --- /dev/null +++ b/ocr/russian/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Извлеките текст из изображения с помощью Python OCR за считанные минуты. + Откройте многоязычный OCR, автоматическое определение языка и способы точного извлечения + текста. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: ru +og_description: Быстро извлекайте текст из изображения с помощью Python OCR. Узнайте + о многоязычном OCR для изображений, автоматическом определении языка и о том, как + пошагово извлекать OCR‑текст. +og_title: Извлечение текста из изображения с помощью Python OCR – Полное руководство +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Извлечение текста из изображения с помощью Python OCR – Полное руководство +url: /ru/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Извлечение текста из изображения с помощью Python OCR – Полное руководство + +Когда‑то вам нужно было **извлечь текст из изображения**, но вы не знали, какая библиотека может автоматически обрабатывать несколько языков? Вы не одиноки — разработчики постоянно спрашивают, *как извлечь OCR‑текст* при работе с международными документами, чеками или отсканированными листовками. В этом руководстве мы пройдем практический пример на Python, который не только извлекает текст из изображения, но и **определяет язык** на лету, делая многоязычный OCR простым. + +Мы рассмотрим всё: от установки OCR‑пакета до включения **автоматического определения языка OCR**, запуск движка на примере изображения и вывод как обнаруженного языка, так и извлечённой строки. К концу вы получите переиспользуемый фрагмент кода, который можно вставить в любой проект, будь то конвейер перевода или сервис ingest‑данных. + +## Извлечение текста из изображения – подготовка окружения + +Прежде чем перейти к коду, убедитесь, что ваш компьютер удовлетворяет минимальным требованиям: + +- Python 3.8 или новее (библиотека использует type hints, которые игнорируются в более старых версиях) +- `pip` для управления пакетами +- Файл изображения, содержащий текст как минимум на двух разных языках (например, английский + испанский) + +Вам также понадобится OCR‑библиотека, которая питает эту демонстрацию. Для целей данного руководства мы будем использовать вымышленный пакет `ocr`, который имитирует популярные реальные инструменты, такие как Tesseract или EasyOCR, но предоставляет чистый Python API. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** Если возникнут ошибки доступа, добавьте перед командой `python -m` или используйте виртуальное окружение — так ваши глобальные site‑packages останутся чистыми. + +## Создание экземпляра OCR‑движка + +Теперь, когда библиотека готова, первый логичный шаг — **создать экземпляр OCR‑движка**. Думайте о движке как о умном сканере, который можно настроить перед тем, как подавать ему изображения. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Почему мы создаём объект движка отдельно, а не вызываем статический метод? Объект движка хранит состояние конфигурации (например, предпочтения языков), которое может быть переиспользовано для множества изображений, экономя время повторной инициализации каждый раз. + +## Включение автоматического определения языка OCR + +Большинство OCR‑инструментов требуют указать код языка — `eng` для английского, `spa` для испанского и т.д. Ручное угадывание языка противоречит смыслу **многоязычного OCR‑изображения**. К счастью, пакет `ocr` предлагает режим *auto detect language OCR*, который анализирует изображение и автоматически выбирает лучшую языковую модель. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Включив **detect language OCR** таким образом, вам не придётся поддерживать длинный список кодов языков. Движок попытается сопоставить увиденный скрипт — латиницу, кириллицу, ханзи и т.п. — и загрузит соответствующую модель автоматически. + +## Выполнение многоязычного OCR изображения + +С готовым движком пришло время действительно **извлечь текст из изображения**. Метод `recognize_image` принимает путь к файлу и возвращает объект результата, содержащий как необработанный текст, так и обнаруженный язык. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Если вам интересно, *как извлечь OCR‑текст* из PDF вместо PNG, тот же движок предлагает `recognize_pdf` — просто замените название метода. Логика определения остаётся той же, поэтому вы получаете ту же функцию **auto detect language OCR**. + +## Вывод обнаруженного языка и извлечённого текста + +Наконец, выводим то, что нашёл движок. Объект результата раскрывает `detected_language` (тег BCP‑47, например `en` или `es`) и `text`, содержащий сырые OCR‑данные. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Запуск скрипта на нашем примере изображения должен дать примерно следующее: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Обратите внимание, как движок правильно определил английский как основной язык, но всё равно захватил испанскую строку — именно то, что ожидается от надёжного **многоязычного OCR‑изображения**. + +### Что делать, если определение не удалось? + +Иногда OCR‑движок может вернуться к языку по умолчанию (обычно английскому), если изображение размыто или скрипт слишком экзотический. В таких случаях можно принудительно задать список языков: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Но помните, принудительное указание языков лишает вас удобства **auto detect language OCR**, поэтому используйте его только при известном подмножестве языков. + +## Частые подводные камни и надёжное извлечение OCR‑текста + +Даже при автоопределении могут возникнуть небольшие проблемы: + +1. **Низкое разрешение изображений** — точность OCR резко падает ниже 150 dpi. Увеличьте масштаб или запросите скан с более высоким разрешением. +2. **Шум и артефакты сжатия** — примените простой пороговый фильтр (`opencv` или `Pillow`) перед подачей изображения в движок. +3. **Смешанные скрипты на одной странице** — некоторые движки с трудом обрабатывают одновременно латинские и CJK‑символы. Разделите страницу на регионы и выполните отдельные распознавания при необходимости. + +Устранение этих проблем значительно повышает качество процесса **extract text from image**, особенно при работе с реальными многоязычными документами. + +## Полный рабочий пример + +Ниже представлен полностью готовый к запуску скрипт, объединяющий все обсуждённые шаги. Сохраните его как `multilingual_ocr.py` и выполните из командной строки. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Ожидаемый вывод** (при условии, что пример изображения содержит английский и испанский текст): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Не стесняйтесь заменять `multilang_page.png` любой картинкой, содержащей текст на других языках — благодаря **auto detect language OCR** скрипт всё равно выдаст разумный языковой тег и соответствующий текст. + +![Пример извлечения текста из изображения](https://example.com/ocr-sample.png "Extract text from image") + +## Заключение + +Теперь вы точно знаете, **как извлечь OCR‑текст** из изображения, как включить **auto detect language OCR** и как работать с **многоязычными OCR‑изображениями** с минимальным объёмом кода. Создав экземпляр OCR‑движка, включив автоматическое определение языка и вызвав `recognize_image`, вы надёжно получаете как идентификатор языка, так и сырый текст. + +Что дальше? Попробуйте передать извлечённые строки в API перевода, сохранить их в поисковой базе данных или собрать несколько страниц в один PDF‑отчёт. Вы также можете поэкспериментировать с различными OCR‑бэкендами (Tesseract, EasyOCR, Google Vision), сохраняя тот же высокий уровень абстракции благодаря единому интерфейсу **detect language OCR**. + +Если столкнётесь с неожиданностями, вернитесь к разделу «Частые подводные камни» или подкорректируйте шаги предобработки изображения. Приятного кодинга, и пусть ваш следующий проект будет полон правильно определённого и идеально извлечённого текста! + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/russian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..a2bb80990 --- /dev/null +++ b/ocr/russian/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-06-06 +description: Извлекайте текст из изображений PDF с помощью Python OCR. Узнайте, как + быстро преобразовать отсканированные документы в текст с помощью асинхронного пакетного + распознавания. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: ru +og_description: Извлекать текст из изображений PDF с помощью Python. Это пошаговое + руководство показывает, как преобразовать отсканированные документы в текст с использованием + асинхронного OCR. +og_title: Извлечение текста из PDF‑изображений – учебник по OCR на Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Извлечение текста из PDF‑изображений – руководство на Python по конвертации + отсканированных документов в текст +url: /ru/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Извлечение текста из PDF‑изображений – Руководство Python по конвертации отсканированных документов в текст + +Когда‑нибудь вам нужно было **извлечь текст из PDF‑изображений** без траты часов на переписывание? В этом руководстве мы покажем, как **конвертировать отсканированные документы в текст** с помощью простого асинхронного OCR‑рабочего процесса на Python. + +Если вы когда‑либо смотрели на стопку отсканированных PDF и думали: «Должен быть более быстрый способ», вы попали по адресу. Мы пройдемся по каждой строке кода, объясним, почему каждый элемент важен, и даже рассмотрим несколько крайних случаев, с которыми вы можете столкнуться. + +## Что вы узнаете + +- Как запустить OCR‑движок и задать язык распознавания. +- Как передать смешанный список PNG‑файлов и PDF‑документов в пакетный распознаватель. +- Как выполнять OCR‑задачу асинхронно, чтобы приложение оставалось отзывчивым. +- Как собрать результаты, сопоставить их с исходными файлами и вывести чистый текст. + +**Prerequisites**: Python 3.8+, базовое понимание `asyncio` или `concurrent.futures`, и OCR‑библиотека, предоставляющая класс `OcrEngine`, аналогичный примеру (например, Aspose.OCR, обёртка Tesseract или собственная обёртка). Никакой сложной настройки не требуется — просто установите библиотеку и вы готовы к работе. + +![извлечение текста из PDF‑изображений](https://example.com/placeholder.png "Скриншот вывода OCR – извлечение текста из PDF‑изображений") + +## Извлечение текста из PDF‑изображений – Настройка OCR‑движка + +Первое, что вам нужно, — это экземпляр OCR‑движка, сконфигурированный под язык ваших документов. В нашем случае мы используем французский, но вы можете заменить его любым поддерживаемым языком. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Почему это важно**: Установка языка заранее значительно повышает точность. Движок использует языко‑специфичные словари и модели символов; передача неверного языка — частая причина искажённого вывода. + +## Подготовка списка файлов – Изображения и PDF вместе + +Наш пакетный распознаватель умеет работать как с растровыми изображениями (`.png`, `.jpg`), так и с PDF‑контейнерами. Просто передайте обычный Python‑список путей к файлам. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: Держите список плоским; движок внутренне распакует каждую страницу PDF в изображения перед распознаванием. Если у вас тысячи файлов, разбейте список на более мелкие партии, чтобы избежать всплесков памяти. + +## Запуск асинхронного пакетного распознавания + +Вместо блокировки основного потока мы запускаем OCR‑задачу в фоне. Метод возвращает `Future`, который в итоге будет содержать список объектов `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Как это работает**: Под капотом движок создаёт пул потоков (или асинхронную задачу, в зависимости от реализации). Это позволяет вам продолжать выполнять другую работу — обновлять UI, загружать новые файлы или вести журнал прогресса — пока тяжёлая обработка происходит в другом месте. + +## Делайте что‑то полезное, пока работает OCR + +Распространённая ошибка — сидеть без дела и опрашивать `Future` в плотном цикле. Вместо этого можно выполнять любую несвязанную работу. Для демонстрации мы просто выведем строку статуса. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Сбор результатов после завершения `Future` + +Когда вы готовы собрать вывод OCR, используйте `as_completed` из `concurrent.futures`. Этот шаблон работает как с одним `Future`, так и с множеством. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Что вы увидите**: Каждый путь к файлу, за которым следует извлечённое представление в виде обычного текста. Для PDF `result.text` содержит конкатенированный текст всех страниц. + +### Ожидаемый вывод (пример) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Если вы заметили пропущенные символы, дважды проверьте, что выбранный язык совпадает с языком документа, и рассмотрите предварительную обработку изображений (выравнивание, увеличение контраста) перед передачей их в движок. + +## Обработка крайних случаев и распространённых подводных камней + +| Ситуация | Что делать | +|-----------|------------| +| **Смешанные языки** | Сначала выполните определение языка, затем создайте отдельные движки для каждого языка. | +| **Большие PDF (> 100 MB)** | Разбейте PDF на отдельные страницы на диске (например, с помощью `PyPDF2`) и передавайте их как отдельные записи. | +| **Нелатинские скрипты** | Убедитесь, что OCR‑библиотека содержит необходимый языковой пакет; некоторые библиотеки требуют загрузки дополнительных файлов данных. | +| **Узкое место в производительности** | Увеличьте размер пула потоков (`engine.set_thread_pool_size(8)`) или переключитесь на GPU‑ускоренный бекенд, если он доступен. | +| **Отсутствие текста в изображениях низкого разрешения** | Предобработайте с помощью OpenCV: `cv2.resize`, `cv2.threshold` и `cv2.medianBlur` для улучшения читаемости. | + +## Полный рабочий пример (готовый к копированию) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Сохраните этот файл как `extract_text_async.py`, замените `YOUR_DIRECTORY` на путь к вашим файлам, установите OCR‑пакет (`pip install your-ocr-lib`) и запустите `python extract_text_async.py`. Вы должны увидеть консольный вывод, показанный ранее. + +## Следующие шаги – Выход за рамки базового извлечения + +- **Post‑processing**: Удаляйте лишние пробелы, нормализуйте Unicode (`unicodedata.normalize`) или запускайте проверку орфографии, чтобы очистить шум OCR. +- **Структурированный вывод**: Экспортируйте результаты в CSV, JSON или напрямую в базу данных для последующего поиска. +- **Параллельные партии**: Если у вас сотни файлов, запустите несколько `Future` и используйте очередь, чтобы держать CPU занятым, не перегружая память. +- **Интеграция с веб‑фреймворками**: Подключите этот скрипт к эндпоинту Flask или FastAPI, чтобы предоставлять OCR‑услугу по запросу. + +--- + +### TL;DR + +Теперь вы знаете, как **извлекать текст из PDF‑изображений** с помощью минимального Python‑скрипта, который запускает OCR асинхронно, позволяя **конвертировать отсканированные документы в текст**, пока ваша программа остаётся отзывчивой. Поэкспериментируйте с настройками языка, размерами партий и приёмами предобработки, чтобы достичь максимальной точности. + +Есть свой подход, которым хотите поделиться — может, OCR рукописных заметок или облачный сервис? Оставьте комментарий, и счастливого кодинга! + +## Что стоит изучить дальше? + +Следующие учебники охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Извлечение текста из изображения с Aspose OCR – Пошаговое руководство](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Извлечение текста из изображений с помощью OCR‑операции по папкам](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Извлечение текста из изображений с Aspose.OCR – Разрешённые символы](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/russian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..6b843fcaf --- /dev/null +++ b/ocr/russian/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Как выполнить OCR PDF с помощью Python, извлечь текст из PDF, преобразовать + текст сканированного PDF и изменить язык OCR всего в несколько строк кода. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: ru +og_description: 'Как выполнять OCR PDF с помощью Python: практическое руководство, + показывающее, как извлекать текст из PDF, конвертировать текст сканированных PDF + и легко менять язык OCR.' +og_title: Как выполнить OCR PDF в Python – Полный программный учебник +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Как выполнить OCR PDF в Python – Полное пошаговое руководство +url: /ru/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как выполнять OCR PDF в Python – Полное пошаговое руководство + +Когда‑нибудь задавались вопросом, **как выполнять OCR PDF** файлов без оплаты дорогих SaaS‑инструментов? Вы не одиноки. Будь то оцифровка старых книг, извлечение данных из счетов‑фактур или просто необходимость в поисковом тексте из отсканированного отчёта, освоение PDF OCR в Python может сэкономить вам часы ручного копирования. + +В этом руководстве мы пройдём через лаконичный, работающий пример, который **извлекает текст из PDF**, показывает, как **преобразовать отсканированный PDF в редактируемые строки**, и даже демонстрирует, как **сменить язык OCR**, если ваш документ не на английском. К концу вы получите переиспользуемый фрагмент кода, который можно вставить в любой проект. + +## Требования и настройка + +Перед тем как начать, убедитесь, что у вас есть: + +- Установлен Python 3.8+ (код работает на 3.9, 3.10 и новее) +- Пакет `ocr`, предоставляющий класс `OcrEngine` (можно установить через `pip install ocr-lib` — замените на реальное название используемого пакета) +- PDF‑файл, который вы хотите обработать; для демонстрации мы будем использовать `high_res_book.pdf`, размещённый в папке `YOUR_DIRECTORY` + +Если вы используете виртуальное окружение (настоятельно рекомендуется), сначала активируйте его: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Совет:** Храните PDF‑файлы в отдельной директории `data/`, чтобы избежать проблем с путями в дальнейшем. + +## Шаг 1: Создание экземпляра OCR‑движка (Как выполнять OCR PDF – Инициализация) + +Самое первое, что нужно сделать, когда вы хотите **выполнять OCR на PDF** файлах, — это создать экземпляр движка. Думайте о движке как о мозге, который будет читать каждую страницу, интерпретировать глифы и возвращать вам чистый текст. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Почему это важно: без движка у вас нет контекста для настроек языка, параметров рендеринга или обработки PDF. Объект `OcrEngine` хранит все эти значения по умолчанию и позволяет менять их позже. + +## Шаг 2: Установка языка распознавания (Смена языка OCR) + +Большинство библиотек OCR по умолчанию используют английский, но что если ваш документ на французском, немецком или даже японском? Смена языка сводится к вызову `set_recognition_language`. Это удовлетворяет требованию **сменить язык OCR** и обеспечивает более высокую точность. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Почему это может понадобиться:** Многоязычный архив часто содержит страницы с разными языками. Переключение языка «на лету» предотвращает неверное распознавание символов вроде “ß” или “ñ”. + +## Шаг 3: Настройка параметров рендеринга PDF (Эффективное преобразование текста отсканированного PDF) + +При работе со сканированными PDF разрешение и режим цвета сильно влияют на качество OCR. Рендеринг с 300 DPI в градациях серого — оптимальный вариант для большинства документов: достаточно детализированный, но не слишком требовательный к памяти. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Сцеплённые вызовы могут выглядеть сложно, но это просто «fluent API», которое каждый раз возвращает один и тот же объект параметров. Если нужен цвет (например, для цветных схем), замените `"grayscale"` на `"color"`. + +## Шаг 4: Распознавание PDF и получение текста первой страницы (Извлечение текста из PDF) + +Теперь переходим к сути **как выполнять OCR PDF**: передаём движку путь к файлу и получаем распознанный текст. Метод возвращает список результатов по страницам; каждый результат содержит атрибут `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Если нужен весь документ, пройдитесь по `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Что если PDF зашифрован? + +Некоторые PDF защищены паролем. В этом случае можно передать пароль в `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Движок расшифрует файл «на лету» перед выполнением OCR — дополнительных шагов не требуется. + +## Шаг 5: Постобработка извлечённого текста (Точная настройка извлечения текста из PDF) + +Сырый вывод OCR часто содержит разрывы строк, лишние пробелы или иногда ошибочно распознанные символы. Быстрая процедура очистки делает строку готовой для дальнейшей обработки (индексация поиска, хранение в базе данных и т.д.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Теперь вы можете безопасно **извлекать текст из PDF** и передавать его в любой NLP‑конвейер, поисковый движок или простую операцию `open(...).write()`. + +## Бонус: Пакетная обработка нескольких PDF (Масштабирование OCR PDF) + +Если у вас есть папка, полная отсканированных PDF, оберните логику в цикл: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Этот фрагмент показывает, как **выполнять OCR на PDF** файлах массово, что часто требуется в проектах оцифровки. + +## Ожидаемый вывод + +Запуск одностраничного примера (Шаг 4) должен вывести что‑то вроде: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Если вы обработали многостраничную книгу, консоль отобразит очищенный текст каждой страницы, а пакетный скрипт создаст файл `.txt` рядом с каждым PDF. + +## Распространённые ошибки и как их избежать + +| Проблема | Симптомы | Решение | +|----------|----------|---------| +| PDF с низким разрешением | Искажённые символы, пропущенные слова | Увеличьте DPI (`set_dpi(400)` или выше) | +| Установлен неверный язык | Много неизвестных символов, особенно с диакритическими знаками | Используйте `engine.set_recognition_language(ocr.Language.FRENCH)` или соответствующий enum | +| Большой PDF вызывает ошибку памяти | `MemoryError` или сбой после нескольких страниц | Обрабатывайте страницы порциями (`engine.recognize_pdf(..., max_pages=10)`) | +| Отсутствуют шрифты в PDF | Пустой вывод для некоторых страниц | Убедитесь, что PDF действительно содержит растровые изображения; некоторые PDF только векторные и требуют иной обработки | + +## Иллюстрация + +Ниже представлена быстрая визуализация рабочего процесса. Альтернативный текст специально оптимизирован для SEO. + +![диаграмма рабочего процесса OCR PDF, показывающая инициализацию движка, настройку языка, параметры рендеринга, распознавание и извлечение текста](/images/ocr-workflow.png) + +*Диаграмма не требуется для работы кода, но помогает визуальным ученикам понять, где находится каждый шаг.* + +## Заключение + +Мы рассмотрели **как выполнять OCR PDF** файлов в Python от начала до конца: создание OCR‑движка, **смену языка OCR**, настройку рендеринга для **преобразования текста отсканированного PDF** и, наконец, **извлечение текста из PDF** для дальнейшего использования. Полный, готовый к запуску пример можно сразу вставить в любой проект, а дополнительный пакетный скрипт показывает, как масштабировать решение. + +Далее вы можете изучить: + +- Добавление **выполнения OCR на PDF** для многоязычных архивов с перебором списка языков. +- Интеграцию извлечённого текста с Elasticsearch для полнотекстового поиска. +- Использование OCR для создания поисковых PDF, встраивая слой текста обратно в оригинальный файл (многие библиотеки предоставляют метод `save_as_searchable_pdf`). + +Не стесняйтесь экспериментировать, менять настройки DPI или переключаться на другой OCR‑бэкенд. Основы остаются теми же, и теперь у вас есть надёжная база для дальнейшего развития. + +Счастливого кодинга, и пусть ваши отсканированные документы наконец‑то станут поисковыми! + +## Что стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Распознавание текста PDF – операции OCR с Aspose.OCR для Java](/ocr/english/java/ocr-operations/) +- [Как выполнять OCR текста изображения с выбором языка, используя Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Как выполнять OCR PDF в .NET с Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/russian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..4fe2af75c --- /dev/null +++ b/ocr/russian/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-06 +description: Как выполнять OCR PDF и создавать поисковые PDF‑файлы из изображений + с помощью Python. Научитесь добавлять поисковый текст и преобразовывать изображение + в PDF/A за считанные минуты. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: ru +og_description: Как выполнить OCR PDF пошагово. Узнайте, как добавить поисковый текст + и преобразовать изображение в PDF/A с помощью простого скрипта на Python. +og_title: Как выполнить OCR PDF – Краткое руководство по созданию поисковых PDF +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Как выполнить OCR PDF в Python — создать поисковый PDF из изображений +url: /ru/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как выполнить OCR PDF – Преобразовать отсканированные изображения в поисковые PDF + +Когда‑то задумывались **как выполнить OCR PDF**‑файлов, если у вас есть лишь отсканированное изображение счета или чека? Вы не одиноки. Во многих офисах входящая документация приходит в виде плоских PNG или JPEG, а следующий шаг — сделать содержимое доступным для поиска — кажется черным ящиком. + +Хорошие новости? Всего несколькими строками Python вы можете **создать поисковый PDF**, **добавить поисковый текст** и даже **преобразовать изображение в PDF/A** для долгосрочного архивирования. В этом руководстве мы пройдем каждый шаг, объясним, почему он важен, и предоставим готовый к запуску скрипт, который можно вставить в любой проект. + +> **Совет:** Тот же подход работает для многостраничных сканов; просто переберите файлы в цикле, и движок выполнит всю тяжелую работу. + +--- + +## Что понадобится + +Прежде чем приступить, убедитесь, что на вашем компьютере установлено следующее: + +| Требование | Почему это важно | +|------------|------------------| +| Python 3.9 или новее | Современный синтаксис и лучшая поддержка библиотек | +| OCR‑движок на основе `pdfium` (например, `pdfocr` или коммерческий SDK) | Обрабатывает как распознавание изображений, так и генерацию PDF/A | +| Файл изображения (PNG, JPEG, TIFF), который нужно превратить в поисковый PDF | Источник текста | +| Права записи в папку вывода | Чтобы скрипт мог сохранить новый PDF | + +Если OCR‑SDK ещё не установлен, выполните: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +И всё — никаких сложных системных зависимостей, только `pip install`. + +--- + +## Как выполнить OCR PDF – Обзор + +На высоком уровне процесс состоит из трёх простых действий: + +1. **Распознать** текст внутри изображения, сохранив оригинальную графику. +2. **Экспортировать** результат OCR вместе с оригинальным изображением как **поисковый PDF/A** (архивный вариант PDF). +3. **Проверить**, что полученный файл содержит выбираемый, поисковый текст, наложенный на оригинальную картинку. + +Ниже каждый шаг показан в коде с объяснением *почему* команд так написаны. + +--- + +## Шаг 1: Распознавание текста на изображении + +Сначала мы просим OCR‑движок прочитать пиксели и вернуть объект результата, содержащий как исходное изображение, так и извлечённый текст. По сути, движок «читает» ваш счёт за вас. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Почему это важно + +- **Сохранение графики** означает, что визуальное расположение (таблицы, логотипы, печати) остаётся точно таким, каким её захватил сканер. +- Объект `result` обычно содержит скрытый текстовый слой, который мы позже внедрим в PDF. +- Использование `recognize_image` вместо `recognize_pdf` избавляет от дополнительного шага конвертации, ускоряя обработку одиночных изображений. + +#### Распространённые варианты + +- Если у вас **многостраничный TIFF**, передайте путь к файлу напрямую; большинство движков обработают каждую страницу как отдельное изображение. +- Для PDF, уже содержащих изображения, можно вызвать `engine.recognize_pdf("file.pdf")` и полностью пропустить этот шаг. + +--- + +## Шаг 2: Экспорт результата OCR как поискового PDF/A + +Теперь берём `result` из шага 1 и просим движок записать новый файл. Ключевой флаг здесь — *PDF/A* — стандарт ISO для PDF, предназначенный для долгосрочного сохранения. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Почему это важно + +- **Поисковый PDF**: В выходном файле появляется скрытый, выбираемый текстовый слой. Теперь можно использовать Ctrl + F для поиска по документу. +- **Соответствие PDF/A**: Некоторые организации (юридические, финансовые) требуют PDF/A для аудиторских следов; этот шаг автоматически удовлетворяет требование. +- Метод также **добавляет поисковый текст** без сплющивания изображения, поэтому визуальная точность остаётся идеальной. + +#### Пограничный случай: нужен обычный PDF? + +Если PDF/A не требуется, замените `save_as_pdfa` на `save_as_pdf`. Остальная часть рабочего процесса остаётся без изменений. + +--- + +## Шаг 3: Проверка поискового PDF + +Быстрая проверка избавит от загадочных ошибок позже. Откройте сгенерированный файл в любом PDF‑просмотрщике, попробуйте выделить слово и используйте функцию поиска. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Ожидаемый вывод + +При запуске скрипта в консоль будет выведено: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Открыв файл, вы увидите оригинальное изображение счета с лёгким, невидимым текстовым слоем. Выделите любое слово — оно будет выбираемым; **это и есть добавленный поисковый текст**. + +--- + +## Добавление поискового текста в существующие PDF (Бонус) + +Иногда у вас уже есть PDF, но нужно **добавить поисковый текст**. Тот же движок может наложить результаты OCR на существующий PDF: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Здесь `apply_to` объединяет скрытый слой с оригинальными страницами, позволяя **создать поисковый PDF** без повторного сканирования. + +--- + +## Распространённые подводные камни и советы + +| Проблема | Как избежать | +|----------|--------------| +| **Низкое разрешение исходных изображений** (< 150 dpi) | Увеличьте масштаб или запросите скан более высокого разрешения; точность OCR резко падает ниже 150 dpi. | +| **Отсутствие языковых данных** | Установите соответствующие языковые пакеты для вашего OCR‑движка (`pip install pdfocr[eng,spa]`). | +| **Папка вывода недоступна для записи** | Запустите скрипт с достаточными правами или выберите другую директорию. | +| **Проверка PDF/A не проходит** | Убедитесь, что не встраиваете неподдерживаемые шрифты или JavaScript; большинство SDK автоматически справляются с этим при использовании `save_as_pdfa`. | + +--- + +## Полный скрипт — однофайловое решение + +Ниже представлен автономный скрипт, объединяющий всё вместе. Скопируйте‑вставьте, замените пути‑заполнители, и вы готовы **преобразовать изображение в PDF/A** за секунды. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Что делает этот скрипт:** +1. Загружает OCR‑движок. +2. Считывает выбранное изображение и извлекает текст. +3. Записывает **поисковый PDF/A**, готовый к распространению или архивированию. + +Не стесняйтесь вынести логику `main` в функцию, обрабатывающую целую папку — просто перебирайте `os.listdir()` и повторяйте три шага для каждого файла. + +--- + +## Следующие шаги и смежные темы + +Теперь, когда вы освоили **как выполнить OCR PDF**, рассмотрите следующие идеи: + +- **Пакетная обработка:** Используйте `concurrent.futures` для одновременного OCR десятков счетов. +- **Внедрение метаданных:** Добавляйте даты создания или номера счетов в метаданные PDF для упрощённого индексирования. +- **Гибридные PDF:** Комбинируйте поисковый текст с встраиваемыми оригинальными изображениями для «цифрового двойника» бумажного документа. +- **Альтернативные форматы вывода:** Экспортируйте в **DOCX** или **HTML**, если downstream‑системы требуют редактируемые форматы. + +Каждый из этих пунктов опирается на базовые концепции, которые вы только что изучили — распознавание, экспорт, проверка. + +--- + +## Итоги + +Короче говоря, теперь вы знаете **как выполнить OCR PDF**‑файлов, превратив простое изображение в **поисковый PDF/A** всего в три строки Python. Скрипт берёт на себя всю тяжёлую работу, сохраняет оригинальную графику и выдаёт документ, соответствующий стандартам, который можно искать, архивировать или делиться им. + +Попробуйте на своих счетах, чеках или сканированных контрактах. Если возникнут сложности, оставьте комментарий ниже или обратитесь к официальной документации SDK — обычно там полно дополнительных примеров. Приятного кодинга и наслаждайтесь новой возможностью мгновенно делать любые изображения поисковыми! + +![How to OCR PDF example showing original image and searchable PDF overlay](placeholder.png "How to OCR PDF example") + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/russian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..5af2931d2 --- /dev/null +++ b/ocr/russian/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Как выполнять OCR PDF с помощью Aspose OCR Cloud. Узнайте, как извлекать + текст из PDF, конвертировать страницу PDF в PNG и сохранять изображения страниц + PDF в Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: ru +og_description: Как выполнять OCR PDF с помощью Aspose OCR Cloud. Это руководство + показывает, как извлекать простой текст из PDF, конвертировать страницу PDF в PNG + и сохранять изображения страниц PDF. +og_title: Как выполнить OCR PDF с помощью Aspose OCR Cloud – пошагово +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Как распознать PDF с помощью Aspose OCR Cloud – Полное руководство +url: /ru/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как выполнять OCR PDF с помощью Aspose OCR Cloud – Полное руководство + +Ever wondered **how to OCR PDF** files without wrestling with heavyweight desktop tools? You’re not alone—many developers hit that wall when they need a quick, programmatic way to pull text out of scanned documents. The good news? With Aspose OCR Cloud you can **extract text from PDF**, turn each page into a PNG, and even **save PDF page images** for later use, all from a tidy Python script. + +In this tutorial we’ll walk through everything you need to know: from installing the SDK, licensing the engine, and recognizing multi‑page PDFs, to extracting plain text, converting pages to PNG, and persisting those images on disk. By the end you’ll have a reusable snippet you can drop into any project that needs **how to OCR PDF** capabilities. + +## Что вам понадобится + +- **Python 3.8+** (код работает также на 3.10 и новее) +- Учётная запись Aspose OCR Cloud – вы получите бесплатный пробный файл лицензии (`Aspose.OCR.lic`) +- Пакет `asposeocrcloud` (`pip install asposeocrcloud`) +- Отсканированный многостраничный PDF, который вы хотите обработать + +Это всё. Нет дополнительных бинарных файлов, нет нативных зависимостей, только чистый Python. + +## Как выполнить OCR PDF – Настройка и лицензия + +Before you can call any OCR methods, you have to tell the SDK who you are. Aspose uses a lightweight license file that you place somewhere accessible to your script. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* Если пропустить шаг с лицензией, SDK всё равно будет работать, но в полученных изображениях появится небольшой водяной знак. Не идеально для продакшна. + +## Шаг 2: Установите Python SDK Aspose OCR Cloud + +Open a terminal and run: + +```bash +pip install asposeocrcloud +``` + +The package pulls in all required dependencies (requests, pillow, etc.) so you don’t have to hunt down anything else. + +## Шаг 3: Создайте OCR‑движок и выберите язык + +The engine is the heart of the operation. You can specify any language supported by Aspose; English works for most cases. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Why set the language? Потому что OCR‑движок использует словари, специфичные для языка, чтобы повысить точность. Если вы обрабатываете французские PDF, просто замените `ENGLISH` на `FRENCH`. + +## Шаг 4: Укажите путь к вашему многостраничному PDF + +Give the engine the full path to the file you want to process. Relative paths are fine as long as they resolve from the script’s working directory. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Make sure the file is readable; otherwise you’ll see a `FileNotFoundError`. + +## Шаг 5: Запустите OCR – Вы получите список результатов + +Calling `recognize_pdf` returns a list where each element corresponds to one page of the source PDF. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Each `OcrResult` contains two handy properties: + +- `text` – текстовое представление страницы (отлично подходит для **extract plain text pdf**) +- `image` – объект Pillow `Image` отрисованной страницы (идеально для **convert pdf page png**) + +## Шаг 6: Извлеките текст из PDF и конвертируйте страницы в PNG + +Now we loop through the results, print the extracted text, and save a PNG version of every page. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Ожидаемый вывод в консоль + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +You’ll also find `page_1.png`, `page_2.png`, … floating in `YOUR_DIRECTORY`. Those are the rasterized page images you can feed into downstream image‑processing pipelines. + +## Шаг 7: Сохраните изображения страниц PDF (необязательно, пост‑обработка) + +If you only need the images and not the text, you can skip the `print(res.text)` line. Conversely, if you want to store the text in separate `.txt` files, just add a tiny write‑out: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +This small addition demonstrates how easy it is to **save PDF page images** while also persisting the extracted content. + +## Полный рабочий пример + +Putting everything together, here’s the complete script you can copy‑paste into `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Run it with: + +```bash +python ocr_pdf.py +``` + +You should see the console dump of each page’s text and a series of PNG files + +## Что изучать дальше? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/russian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..7380c2a82 --- /dev/null +++ b/ocr/russian/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Как предобрабатывать изображения для OCR с помощью Python. Узнайте, как + бинаризовать изображение методом Отсу, как исправлять наклон отсканированных документов + и повышать точность OCR для немецкого текста. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: ru +og_description: Как предобрабатывать изображения для OCR в Python. Этот учебник показывает, + как бинаризовать изображение с помощью метода Отсу, как исправлять наклон отсканированных + документов и как улучшить точность OCR для немецких изображений. +og_title: Как предобрабатывать изображения для OCR – Полное руководство по Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Как предобрабатывать изображения для OCR — Полное руководство по Python +url: /ru/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как предобрабатывать изображения для OCR – Полное руководство на Python + +Когда‑нибудь задумывались **как предобрабатывать изображения для OCR**, чтобы текст получался кристально‑чётким? Вы не одиноки. Сканированные документы — особенно шумные немецкие страницы — могут стать кошмаром для любого OCR‑движка. Хорошая новость? Несколько умных шагов предобработки могут превратить размытый, пятнистый скан в чистое, машинно‑читаемое изображение. + +В этом руководстве мы пройдём практический пример, показывающий **как предобрабатывать изображения для OCR** с помощью Python. Вы научитесь **бинаризировать изображение с помощью Otsu**, **как исправлять наклон сканированных документов**, и в целом **как улучшить точность OCR**, когда нужно **извлечь текст из немецкого изображения**. Без лишних слов, только рабочий скрипт, который можно скопировать‑вставить уже сегодня. + +## Что вам понадобится + +- **Python 3.9+** (подойдёт любая современная версия) +- Библиотека OCR, предоставляющая класс `OcrEngine` — для демонстрации будем считать, что существует пакет `ocr`. Установите его командой `pip install ocr-lib`. +- Шумный немецкий скан (`noisy_german_scan.tif`), который вы хотите протестировать. +- Базовое понимание функций Python (если вы уже писали `def`, вам достаточно). + +> **Pro tip:** Если вы используете другой OCR‑SDK (например, Tesseract через `pytesseract`), концепции остаются теми же — просто адаптируйте имена методов. + +## Обзор решения + +1. **Создать экземпляр OCR‑движка.** +2. **Установить язык распознавания — немецкий.** +3. **Собрать пользовательский конвейер предобработки**, включающий исправление наклона, подавление шума, бинаризацию (Otsu) и растяжение контраста. +4. **Привязать конвейер к движку**, чтобы каждое изображение проходило через него автоматически. +5. **Запустить OCR** на шумном немецком скане. +6. **Вывести извлечённый текст**, чтобы проверить результат. + +Ниже мы разберём каждый шаг, объясним **почему** он важен и покажем точный код, который вам нужен. + +![как предобрабатывать изображения для OCR пример](image.png "как предобрабатывать изображения для OCR пример") + +## Шаг 1: Создать экземпляр OCR‑движка + +Первое дело — без движка ничего не происходит. Объект `OcrEngine` — точка входа, координирующая всю последующую обработку. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Почему это важно:* Инициализация движка подготавливает внутренние ресурсы (например, языковые модели) и даёт вам чистый лист для последующего подключения пользовательского конвейера. + +## Шаг 2: Установить язык распознавания — немецкий + +Точность OCR сильно зависит от языка. Указав движку, что он будет работать с немецким, вы активируете нужный набор символов и языковую модель. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Если пропустить этот шаг, движок может по умолчанию использовать английский, неправильно распознавая умляуты (ä, ö, ü) и символ ß — типичные подводные камни при работе с немецкими сканами. + +## Шаг 3: Собрать пользовательский конвейер предобработки + +Это ядро **как предобрабатывать изображения для OCR**. Мы соединяем четыре преобразования: + +| Преобразование | Что делает | Почему помогает | +|----------------|------------|-----------------| +| **Deskew** | Поворачивает изображение обратно к горизонтали (макс 5°) | Скан почти никогда не выровнен идеально; исправление наклона убирает наклон, сбивающий сегментацию символов. | +| **Denoise** | Уменьшает случайные пятна (силa 0.7) | Шум создаёт ложные контуры, которые OCR может принять за символы. | +| **Binarize (Otsu)** | Преобразует в чёрно‑белое с помощью метода Оцу | Чистое бинарное изображение даёт движку резкий контраст между передним планом (текст) и фоном. | +| **Contrast Stretch** | Расширяет динамический диапазон | Улучшает читаемость слабых штрихов, особенно на старых документах. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Как исправлять наклон сканированных документов + +Вызов `deskew` выше — конкретный ответ на вопрос **как исправлять наклон сканированных документов**. Внутри он оценивает доминирующий угол строк текста через преобразование Хафа и вращает изображение обратно. Если ваши документы повернуты более чем на 5°, увеличьте `max_angle`, но будьте осторожны с артефактами пере‑поворота. + +### Бинаризировать изображение с помощью Otsu + +Строка `binarize(method="otsu")` напрямую отвечает на запрос **binarize image using otsu**. Алгоритм Оцу вычисляет порог, минимизирующий внутриклассовую дисперсию, что идеально подходит для документов с би‑модальными гистограммами (тёмный текст vs. светлый фон). + +## Шаг 4: Привязать конвейер к движку + +Теперь мы говорим OCR‑движку запускать каждое входящее изображение через только что построенный конвейер. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Почему это важно:* Без регистрации движок будет обрабатывать сырой скан, игнорируя всю очистку, которую мы только что настроили. Этот шаг гарантирует **как улучшить точность OCR**, применяя одинаковую предобработку последовательно. + +## Шаг 5: Распознать текст из шумного немецкого скана + +Пора собрать всё вместе. Мы передаём движку шумное немецкое изображение и позволяем ему выполнить тяжёлую работу. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Если хотите узнать о производительности, можете измерить время вызова: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Шаг 6: Вывести распознанный текст + +Наконец, выводим извлечённую строку. Это прямой ответ на **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Ожидаемый вывод + +Предположим, что в образце скана находится предложение «Die schnelle braune Füchsin springt über den faulen Hund.»; вы должны увидеть что‑то вроде: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Если вывод всё ещё содержит искажённые символы, попробуйте отрегулировать силу `denoise` или увеличить `max_angle` для исправления наклона. + +## Распространённые подводные камни и способы их решения + +- **Отсутствует языковая модель:** Пропуск `set_recognition_language(Language.GERMAN)` часто приводит к потере умляутов. Проверьте вызов ещё раз. +- **Чрезмерное подавление шума:** Сила выше 0.9 может стереть тонкие штрихи, особенно в старых шрифтах. Для большинства случаев держите значение в диапазоне 0.5‑0.7. +- **Неправильный формат файла:** Некоторые OCR‑движки «падают» на многостраничных TIFF. Если у вас многостраничный документ, разбейте его на отдельные файлы. +- **Порядок конвейера:** Показанный порядок (deskew → denoise → binarize → contrast) выбран намеренно. Бинаризация до подавления шума может «запечатлеть» шум; всегда сначала удаляйте шум. + +## Расширение конвейера (что дальше?) + +Теперь, когда у вас есть надёжная база, вы можете добавить: + +- **Морфологическое открытие** для очистки крошечных пятен (`.morph_open(kernel=3)`). +- **Интеграцию языковой модели** для пост‑обработки исправлений (`ocr_engine.apply_spellcheck()`). +- **Параллельную пакетную обработку** больших наборов данных с помощью `concurrent.futures`. + +Все эти шаги естественно расширяют идею **как предобрабатывать изображения для OCR**, одновременно повышая **как улучшить точность OCR** ещё больше. + +## Заключение + +Мы только что прошли весь процесс **как предобрабатывать изображения для OCR** от начала до конца: создали движок, задали немецкий язык, построили конвейер, который **бинаризирует изображение с помощью Otsu**, **исправляет наклон сканированных документов**, и, наконец, **извлекает текст из german image** с большей уверенностью. Следуя шести шагам выше, вы заметите значительный скачок в качестве распознавания — больше никаких бесконечных ручных исправлений. + +Попробуйте скрипт на своих сканах, поэкспериментируйте с параметрами и позвольте результатам говорить за себя. Есть вопросы о конкретных настройках предобработки? Оставляйте комментарий, и мы разберём их вместе. + +Счастливого кодинга, и пусть ваш OCR будет всегда точным! + +## Что стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом пособии. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, помогая вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/russian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..1b4fa5f61 --- /dev/null +++ b/ocr/russian/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,324 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG‑изображение с помощью Python – узнайте, как извлекать текст из + изображения, запустить пример OCR на Python и даже легко читать древнегреческий + текст. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: ru +og_description: OCR PNG‑изображение в Python объяснено. Это руководство показывает, + как извлечь текст из изображения, запустить пример OCR на Python и легко читать + древнегреческий. +og_title: OCR PNG‑изображения в Python – Полный учебник +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR PNG‑изображения в Python – Полное пошаговое руководство +url: /ru/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image в Python – Полное пошаговое руководство + +Когда‑нибудь задавались вопросом, как **OCR PNG image** файлы прямо из скрипта Python? Возможно, у вас есть папка, полная отсканированных древних манускриптов, и вам нужно **extract text from image** файлы без ручного ввода всего текста. Хорошая новость — вам не нужен PhD в области компьютерного зрения — достаточно нескольких строк кода и правильной библиотеки, и вы будете читать древнегреческий за секунды. + +В этом руководстве мы пройдем через **python OCR example**, который распознаёт текст из PNG, устанавливает язык на Greek polytonic и выводит результат. К концу вы точно будете знать, как **recognize image text**, справляться с типичными подводными камнями и адаптировать скрипт под другие языки или форматы изображений. + +## Что вы узнаете + +- Установить и настроить библиотеку OCR для Python (pytesseract + Tesseract OCR) +- Создать экземпляр OCR‑движка и загрузить PNG‑файл +- Установить язык распознавания на Greek polytonic, чтобы **read ancient greek** +- Вывести распознанный текст и решить типичные проблемы +- Расширить скрипт для пакетной обработки нескольких PNG или переключения на другой язык + +### Требования + +| Требование | Зачем это нужно | +|-------------|----------------| +| Python 3.8+ | Современный синтаксис и подсказки типов | +| `pytesseract` package | Тонкая обёртка вокруг движка Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Сам движок, который выполняет основную работу | +| Greek language data (`grc.traineddata`) | Необходимы для **read ancient greek** корректно | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Наша цель для демонстрации **ocr png image** | + +Вы можете установить Python‑часть с помощью: + +```bash +pip install pytesseract Pillow +``` + +А на Ubuntu/macOS добавить сам движок: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Не забудьте скачать обученные данные Greek polytonic: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Путь может отличаться; при необходимости скорректируйте `TESSDATA_PREFIX`.)* + +--- + +## OCR PNG Image: Создание экземпляра движка + +Первое, что нам нужно, — объект, который общается с Tesseract. В `pytesseract` движок вызывается через функции уровня модуля, но для ясности мы обернём его в небольшую класс‑обёртку. Это отражает концепцию «движка», которую вы видели в оригинальном фрагменте. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Почему оборачивать?** +- Сохраняет публичный API идентичным фрагменту, с которым вы начали, делая миграцию безболезненной. +- Позволяет позже добавить логирование или обработку ошибок, не меняя основной поток. +- Продемонстрирует хорошую практику ООП — то, что ценят старшие разработчики. + +--- + +## Извлечение текста из изображения: установка языка Greek Polytonic + +Теперь, когда у нас есть движок, нужно указать, какой язык ожидать. Greek polytonic использует диакритические знаки, которые не покрыты стандартными данными «greek», поэтому мы указываем Tesseract на файл `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Если когда‑нибудь понадобится **extract text from image** файлы на другом языке, просто замените `"grc"` на `"eng"` для английского, `"fra"` для французского и т.д. Та же строка работает для любого установленного языка. + +## Распознавание текста изображения: запуск OCR на PNG + +С установленным языком мы передаём PNG в движок. В оригинальном примере путь был зашит в код; мы сделаем его гибче, используя объекты `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Советы и крайние случаи** + +- **File not found** – оберните вызов в `try/except FileNotFoundError`, чтобы вывести дружелюбное сообщение. +- **Low‑resolution PNG** – рассмотрите предобработку (например, изменение размера, бинаризацию) с помощью Pillow перед OCR. +- **Non‑Greek text** – Tesseract всё равно попытается декодировать, но точность резко падает. Всегда подбирайте язык. + +## Вывод распознанного текста + +Наконец, мы печатаем результат. В реальном проекте вы можете записать его в базу данных, CSV‑файл или даже передать в конвейер перевода. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Когда вы запустите скрипт против чистого скана древнегреческой надписи, вы должны увидеть что‑то вроде: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Если вывод выглядит искажённым, дважды проверьте, что файл **greek.traineddata** находится в правильной папке и что PNG не слишком шумный. + +## Полный рабочий пример (Все шаги в одном скрипте) + +Ниже полностью готовая к запуску программа. Сохраните её как `ocr_greek.py` и выполните `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Ожидаемый вывод** (усечённый для краткости): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Если вы видите правильные греческие символы, поздравляем — вы успешно выполнили операцию **ocr png image** в Python! + +## Часто задаваемые вопросы и профессиональные советы + +### Как улучшить точность на шумном PNG? + +- Преобразуйте изображение в градации серого: `img = img.convert('L')` +- Примените бинарный порог: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Увеличьте масштаб с помощью `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Эти шаги часто превращают ночной кошмар **recognize image text** в чистый результат. + +### Можно ли обработать всю папку PNG? + +Абсолютно. Оберните вызов `recognize_image` в цикл `for` по `Path.glob("*.png")`. Сохраняйте каждый результат в словаре или записывайте в CSV для последующего анализа. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Что если нужно извлекать только числа? + +Передайте пользовательскую строку **config** в `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Таким образом вы сможете **extract text from image** файлы, содержащие таблицы, серийные номера или метки времени. + +### Как получить оценки уверенности? + +Да — используйте `pytesseract.image_to_data`, который возвращает TSV с уровнем уверенности для каждого слова. Вы можете отфильтровать токены с низкой уверенностью перед сборкой окончательной строки. + +## Расширение руководства + +Теперь, когда вы освоили основы, рассмотрите изучение следующих тем: + +- **Batch OCR with multiprocessing** – ускорьте обработку больших корпусов PNG. +- **Hybrid OCR + NLP pipelines** – автоматически переводите извлечённый древнегреческий в современный английский. +- **Alternative engines** – попробуйте `easyocr` или методы на основе `opencv` для специфических задач. +- **Cloud OCR services** – Google Vision, Azure Computer Vision или AWS Textract для масштабирования без серверов. + +Каждый из этих пунктов опирается на ядро **python ocr example**, которое мы только что рассмотрели, так что вы будете чувствовать себя уверенно, погружаясь глубже. + +## Заключение + +Мы взяли простой фрагмент кода и превратили его в надёжный рабочий процесс **ocr png image** в Python. Создав `OcrEngine`, установив язык на Greek polytonic, передав PNG и напечатав результат, вы теперь знаете, как **extract text from image** файлы, **recognize image text** и даже **read ancient greek**. + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом пособии. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Извлечение текста из изображения с Aspose OCR – пошаговое руководство](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Как установить значение порога в распознавании OCR изображения](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Распознавание текста изображения с Aspose OCR для нескольких языков](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/russian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..a498fe6c5 --- /dev/null +++ b/ocr/russian/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-06 +description: Учебник по OCR на Python, показывающий, как распознавать текст на изображениях, + выполнять OCR высокого разрешения и извлекать испанский текст с использованием ускоренного + GPU OCR. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: ru +og_description: Учебник по OCR на Python, который проведёт вас через распознавание + текста на изображениях, OCR высокого разрешения и извлечение испанского текста с + ускорением на GPU. +og_title: Учебник по OCR на Python — Распознавание текста с ускорением на GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Учебник по OCR в Python – распознавание текста на изображении с ускорением + на GPU +url: /ru/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Распознавание текста на изображении с ускорением GPU + +Когда‑нибудь задумывались, как **распознавать текст на изображении** в скрипте Python, не тратя часы на настройку? Вы не одиноки. В этом **python ocr tutorial** мы покажем чистый, сквозной способ извлечения испанского текста из изображения высокого разрешения и добавим ускорение GPU, чтобы процесс работал молниеносно. + +Считайте это быстрым демо‑примером во время кофейного перерыва, который позже можно расширить до производственного конвейера. К концу руководства у вас будет исполняемая программа, выполняющая **high resolution OCR**, использующая GPU с поддержкой CUDA и выводящая точные испанские символы, которые вам нужны. + +## Что вы узнаете + +- Как установить и импортировать современную OCR‑библиотеку, поддерживающую ускорение GPU. +- Как создать экземпляр OCR‑движка и настроить его на **распознавание текста на изображении** на испанском. +- Как включить **gpu accelerated OCR** для значительного ускорения работы с файлами высокого разрешения. +- Как обрабатывать крайние случаи, такие как отсутствие драйверов CUDA или переход на CPU. +- Советы по повышению точности, когда нужно **extract spanish text** из шумных сканов. + +### Требования + +- Python 3.9+ (код также работает на 3.10 и новее). +- GPU, совместимый с CUDA (опционально, но настоятельно рекомендуется). +- Базовые знания pip и виртуальных окружений. + +Если у вас нет чего‑то из этого, руководство всё равно будет работать — просто пропустите шаг с GPU, и библиотека автоматически перейдёт на CPU. + +--- + +## Python OCR Tutorial: Установка необходимых пакетов + +Сначала нам нужен надёжный OCR‑движок. Для этого руководства мы будем использовать открытый пакет **`easyocr`**, который поставляется с встроенной поддержкой GPU, если обнаружено совместимое устройство. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Если у вас уже установлен PyTorch, убедитесь, что он соответствует вашей версии CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Несоответствие версий — частая причина ошибок «GPU not found». + +--- + +## Шаг 1: Создание экземпляра OCR‑движка + +Теперь запускаем движок. EasyOCR называет свой основной класс `Reader`. Конструктор принимает список кодов языков; мы передадим `"es"` для испанского. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Почему это важно:* Указывая язык заранее, движок загружает только необходимые веса нейронной сети, что экономит память и ускоряет вывод — особенно полезно, когда вы работаете с **high resolution OCR** позже. + +## Шаг 2: Подготовка изображения высокого разрешения + +Изображения высокого разрешения предоставляют модели больше пикселей для обработки, что обычно приводит к лучшему распознаванию символов. Предположим, у вас есть файл `high_res_spanish.png`, находящийся в папке `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Если у вас нет готового образца высокого разрешения, вы можете скачать бесплатный с Unsplash или сгенерировать синтетическое изображение с помощью Pillow. Главное — держать DPI выше 300 для наилучшего результата. + +## Шаг 3: Включение ускорения GPU (опционально, но рекомендуется) + +EasyOCR уже пытается использовать GPU, когда вы задаёте `gpu=True`. Однако рекомендуется проверить, действительно ли устройство используется, особенно в системах с несколькими GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Зачем проверять это?* Если скрипт тихо переходит на CPU, вы можете задаться вопросом, почему операция, занимавшая 5 секунд, вдруг занимает 30 секунд. Эта небольшая проверка делает поведение прозрачным и сохраняет предсказуемость вашего конвейера **gpu accelerated OCR**. + +## Шаг 4: Выполнение OCR высокого разрешения и распознавание текста на изображении + +Теперь самая интересная часть — фактическое чтение текста. Метод `readtext` в EasyOCR возвращает список кортежей, содержащих ограничивающий прямоугольник, распознанную строку и оценку уверенности. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Если вам нужна только строка без координат, установите `detail=0`. Для большинства случаев использования **recognize image text** по умолчанию (`detail=1`) предоставляет достаточно контекста для последующей обработки. + +## Шаг 5: Извлечение испанского текста и очистка вывода + +Поскольку мы запросили у EasyOCR испанский язык, возвращаемые строки уже на этом языке. Тем не менее, вы можете захотеть объединить их, удалить пробелы или отфильтровать распознавания с низкой уверенностью. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Что делать, если уверенность низкая?** Вы можете либо снизить порог (риск шума), либо предварительно обработать изображение (увеличить контраст, бинаризовать или исправить наклон). Такие приёмы часто используют при работе с **high resolution OCR** на отсканированных документах. + +## Шаг 6: Обработка крайних случаев и оптимизация производительности + +Даже лучшие обученные модели сталкиваются с некоторыми сценариями. Ниже представлены несколько быстрых исправлений, которые вы можете вставить в скрипт. + +### 6.1 Запасной вариант при отсутствии GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Понижение разрешения очень больших изображений + +Если ваше изображение превышает 4000 × 4000 px, вы можете исчерпать память GPU. Понизьте разрешение пропорционально, сохраняя DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Эти фрагменты делают скрипт надёжным, независимо от того, работаете ли вы на рабочей станции или на скромном ноутбуке. + +--- + +## Полный рабочий пример + +Собрав всё вместе, представляем полный скрипт, который вы можете скопировать и сразу запустить: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Ожидаемый вывод (пример):** + + + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в своих проектах. + +- [Извлечение текста из изображения с Aspose OCR – пошаговое руководство](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Как выполнять OCR текста изображения с указанием языка с помощью Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Как распознавать прямоугольники страниц для OCR‑распознавания текста в Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/russian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..a5fca6570 --- /dev/null +++ b/ocr/russian/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-06-06 +description: Распознавайте текст на изображении с помощью OCR‑движка на Python. Узнайте, + как настроить OCR‑движок в Python и извлекать текст из изображения с облачной обработкой + за считанные минуты. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: ru +og_description: Распознавать текст с изображения с помощью OCR‑движка Python. Это + руководство показывает, как настроить OCR‑движок Python и эффективно извлекать текст + из изображения. +og_title: Распознавание текста с изображения в Python – Полный учебник по настройке +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Распознавание текста на изображении в Python – Полное руководство по настройке + OCR‑движка +url: /ru/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# распознать текст на изображении в Python – Полный учебник по настройке + +Задумывались ли вы когда‑нибудь, как **распознать текст на изображении** с помощью всего лишь нескольких строк кода на Python? Вы не одиноки. Независимо от того, создаёте ли вы сканер чеков, цифровизатор документов или простой хобби‑проект, возможность **извлечь текст из изображения** — навык, который быстро окупается. + +В этом руководстве мы пройдем весь процесс — начиная с настройки **configure OCR engine python**, переходя к аутентификации в облаке и, наконец, показывая, как **извлечь текст из изображения** с надёжным результатом. Никакой магии, только чёткие шаги, которые вы можете скопировать‑вставить и запустить уже сегодня. + +## Что вы узнаете + +- Как установить и импортировать необходимую OCR‑библиотеку. +- Точные команды для **configure OCR engine python** для облачной обработки. +- Полный, исполняемый скрипт, который **распознает текст на изображении** и выводит результат. +- Советы по работе с распространёнными проблемами, такими как отсутствие API‑ключей или неподдерживаемые форматы изображений. +- Идеи следующего уровня, такие как пакетная обработка и локальный резерв. + +### Prerequisites + +- Python 3.8+ установлен на вашем компьютере. +- Подключение к интернету (пример использует облачную OCR‑службу). +- Действительный API‑ключ от поставщика OCR (вы увидите, где его указать). + +Если всё готово, давайте погрузимся — без лишних слов, только практическое руководство, которое работает. + +--- + +## Шаг 1: Установить OCR‑библиотеку и импортировать её + +Прежде чем вы сможете **configure OCR engine python**, вам нужна библиотека, которая взаимодействует с облачной службой. В нашем примере мы используем вымышленный, но репрезентативный пакет под названием `ocrcloud`. Замените его реальным пакетом, который вы используете (например, `easyocr`, `google-cloud-vision` и т.д.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Почему это важно:** Импорт класса даёт вам доступ к методам вроде `use_cloud()` и `set_api_key()`. Без импорта остальная часть скрипта вызовет `NameError`. + +*Совет:* Зафиксируйте версию в вашем `requirements.txt` (`ocrcloud==2.1.0`), чтобы избежать неожиданных несовместимых изменений в дальнейшем. + +## Шаг 2: Создать и **configure OCR engine python** для облачного режима + +Теперь мы действительно **configure OCR engine python**. По умолчанию движок работает в локальном режиме; переключение в облачный режим позволяет вынести тяжёлый анализ изображений на мощные серверы. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explanation:** +- `OcrEngine()` создаёт новый объект движка — представьте его как чистый холст. +- `use_cloud(True)` переключает режим, заставляя движок отправлять изображения по HTTPS вместо локальной обработки. Это критически важно для получения высокоточных результатов на сложных шрифтах или фото низкого разрешения. + +## Шаг 3: Аутентификация с вашим облачным API‑ключом + +Большинство облачных OCR‑служб требуют API‑ключ. Этот шаг показывает, как безопасно передать учётные данные. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Примечание по безопасности:** Никогда не встраивайте ключ в открытый репозиторий. В продакшене вы бы получали его из переменной окружения: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## Шаг 4: **recognize text from image** – Отправка удалённого изображения для обработки + +С настроенным движком мы наконец можем **recognize text from image**. Метод `recognize_image()` принимает путь или URL и возвращает объект, содержащий извлечённый текст. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Что происходит под капотом?** +Байты изображения загружаются на конечную точку провайдера, обрабатываются моделью глубокого обучения, и результат в виде простого текста возвращается обратно. Если изображение большое, сервис может автоматически уменьшить его размер для ускорения обработки. + +## Шаг 5: Вывести результат **extract text from image** + +Теперь, когда OCR‑служба завершила работу, мы просто выводим текст. В реальных приложениях вы можете сохранить его в базе данных или передать другой функции. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Ожидаемый вывод:** (пример) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Если вывод выглядит искажённым, дважды проверьте, что изображение чёткое и что вы выбрали правильную языковую модель (многие сервисы позволяют указать `engine.set_language("en")`). + +## Обработка граничных случаев и распространённых проблем + +### 1. Отсутствующий или недействительный API‑ключ +Если вы видите ошибку аутентификации, убедитесь, что: +- Ключ активен и не истёк. +- Он корректно читается из переменной окружения. +- Ваша сеть позволяет исходящий HTTPS‑трафик. + +### 2. Неподдерживаемые форматы изображений +Большинство OCR‑API принимают JPEG, PNG и PDF. Попытка использовать BMP или TIFF может вызвать ответ «format not supported». При необходимости конвертируйте с помощью Pillow: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Ограничения по частоте запросов +Облачные сервисы часто ограничивают количество запросов в минуту. Если вы достигли лимита, реализуйте экспоненциальную задержку: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Резервный переход на локальный OCR +Если облако недоступно, вы можете переключиться обратно: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Наличие резервного варианта делает приложение устойчивым. + +## Полный рабочий пример + +Собрав всё вместе, представляем скрипт, который вы можете запустить прямо сейчас (просто замените значения‑заполнители). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Запустите:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Вы должны увидеть извлечённый текст, выведенный в консоль, что подтверждает успешное **recognize text from image** и **extract text from image** с использованием правильно **configure OCR engine python** рабочего процесса. + +## Заключение + +Мы только что прошли полный процесс от начала до конца, позволяющий **recognize text from image** в Python, от установки библиотеки до аутентификации облачной службы и, наконец, **extract text from image** одним вызовом функции. Правильно **configure OCR engine python** даёт вам и гибкость (облако vs. локально), и надёжность (корректная обработка ошибок). + +Что дальше? Попробуйте пакетную обработку папки с чеками, добавьте определение языка или экспериментируйте с PDF‑файлами в качестве входных данных. Возможности безграничны, как только вы освоите основы. + +Удачной разработки, и не стесняйтесь задавать вопросы в комментариях — ничто не сравнится с совместным обучением! + +## Что стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/russian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..cdfdded9e --- /dev/null +++ b/ocr/russian/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Запустите OCR на изображении с помощью Python и посмотрите оценки уверенности. + Узнайте, как фильтровать слова с низкой уверенностью, устанавливать пороги и обрабатывать + крайние случаи. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: ru +og_description: Выполните OCR изображения в Python, проверьте уровни уверенности и + отфильтруйте слова с низкой уверенностью. Этот учебник проведёт вас через полный, + готовый к запуску пример. +og_title: Запустите OCR на изображении с помощью Python – Полное руководство +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Запуск OCR на изображении с помощью Python — Полное пошаговое руководство +url: /ru/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Выполнить OCR на изображении с помощью Python – Полное пошаговое руководство + +Когда‑то вам нужно **выполнить OCR на изображении**, но вы не знали, как получить надёжный текст? Вы не одиноки — многие разработчики сталкиваются с тем же: извлечённые слова выглядят «дрожащими», а показатель уверенности остаётся загадкой. + +В этом руководстве мы сразу перейдём к работающему решению: вы увидите, как выполнить OCR на изображении, прочитать общую уверенность и вытащить любые слова с низкой уверенностью, которые могут потребовать ручной проверки. К концу вы получите переиспользуемый скрипт, поймёте, почему каждая строка важна, и узнаете, как настроить порог уверенности для своих проектов. + +## Что покрывает этот учебник + +Мы пройдём весь процесс — от загрузки изображения до печати аккуратного отчёта о словах, у которых уверенность ниже 80 %. По пути обсудим: + +* Выбор надёжного OCR‑движка (мы будем использовать **EasyOCR**, популярную библиотеку OCR для Python) +* Интерпретацию атрибута `confidence`, который возвращает каждый результат OCR +* Фильтрацию слов с помощью пользовательского **порога уверенности OCR** +* Расширение скрипта для пакетной обработки или альтернативных движков, таких как **pytesseract** + +Предыдущий опыт работы с OCR не требуется, достаточно базовых знаний Python и рабочей среды (рекомендовано Python 3.9+). + +Готовы превратить размытые скриншоты в чистый, индексируемый текст? Поехали. + +--- + +## ## Как выполнить OCR на изображении с помощью Python + +Сердце учебника — трёхшаговый фрагмент кода, который отражает уже показанный пример. Ниже мы разберём каждую строку, объясним, почему она нужна, и предоставим готовый скрипт, готовый к копированию. + +### Шаг 1: Установить и импортировать OCR‑движок + +Сначала убедитесь, что библиотека OCR доступна. **EasyOCR** работает «из коробки» для многих языков и выдаёт оценку уверенности для каждого слова. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Почему EasyOCR?* Он включает модель глубокого обучения, обученную на разнообразных наборах данных, поэтому обычно выдаёт более высокие значения уверенности, чем старый движок Tesseract, особенно на изображениях смешанного качества. + +> **Pro tip:** Если вы работаете в ограниченной среде (например, в небольшом Docker‑контейнере), `pytesseract` может быть легче, но вы потеряете часть современной точности, которую предоставляет EasyOCR. + +### Шаг 2: Выполнить OCR на изображении + +Теперь мы действительно **выполняем OCR на изображении**. Метод `recognize_image` из оригинального примера заменён вызовом `readtext` из EasyOCR, который возвращает список кортежей `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Каждый элемент в `ocr_results` выглядит так: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Третий элемент (`0.92` в примере) — это оценка уверенности в диапазоне от 0 до 1. + +### Шаг 3: Суммировать общую уверенность + +В отличие от предыдущего фрагмента, который выводил единственный атрибут `confidence`, EasyOCR даёт уверенность для каждого слова. Чтобы получить общее представление, мы вычислим их среднее: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Почему среднее?* Оно даёт быструю проверку состояния — если общая уверенность ниже, скажем, 70 %, вероятно, потребуется улучшить изображение (лучшее освещение, предобработка и т.д.). + +### Шаг 4: Список слов с низкой уверенностью + +Теперь переходим к части, которая напрямую отвечает на требование «вывести список слов, чья уверенность ниже заданного порога». По умолчанию мы задаём **порог уверенности OCR** = 0.80 (80 %), но вы можете изменить его. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Цикл выводит каждое слово, которое не прошло порог, вместе с процентом уверенности. Это точный аналог оригинального цикла `for recognized_word in recognition_result.words`, но теперь работает с форматом вывода EasyOCR. + +--- + +## ## Понимание оценок уверенности OCR + +Уверенность — это не магическое число; это оценка модели того, насколько она уверена в конкретной транскрипции. Учтите следующее: + +| Ситуация | Типичная уверенность | Что делать | +|-----------|-------------------|------------| +| Чёткое, высокоразрешающее сканирование | 0.95 – 1.00 | Дополнительные действия не требуются | +| Небольшое размытие или неравномерное освещение | 0.80 – 0.94 | Рассмотрите лёгкую предобработку (повышение контраста) | +| Сильный шум, повернутый текст | < 0.70 | Примените предобработку (выравнивание, удаление шума) или переключитесь на другой OCR‑движок | + +> **Watch out:** Некоторые языки (например, курсивное рукописное письмо) естественно дают более низкие оценки. Настройте порог соответственно. + +### Пограничные случаи и варианты + +1. **Пакетная обработка** – Если нужно **выполнить OCR на изображениях** массово, оберните вышеописанную логику в цикл, проходящий по каталогу. +2. **Несколько языков** – Передайте список вроде `['en', 'fr']` в `easyocr.Reader`, и движок будет распознавать оба. +3. **Альтернативные движки** – Хотите попробовать **pytesseract**? Замените блок чтения на: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Затем потребуется агрегировать уверенности по символам в уверенности по словам — немного больше работы, но выполнимо. + +4. **Трюки предобработки** – Применение фильтров OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) может повысить уверенность на шумных сканах. + +--- + +## ## Полный готовый к запуску скрипт + +Ниже представлен полностью готовый файл Python, который можно добавить в проект. Сохраните его как `ocr_report.py` и запустите `python ocr_report.py`. Убедитесь, что путь к изображению указывает на реальный файл. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Ожидаемый вывод** (ваши цифры будут отличаться): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Если каждое слово превышает порог в 80 %, вы увидите дружелюбное сообщение «All words meet the confidence threshold.». + +--- + +## ## Часто задаваемые вопросы (FAQ) + +**В: Работает ли это с PDF?** +О: Не напрямую. Сначала преобразуйте каждую страницу PDF в изображение (например, с помощью `pdf2image`), а затем передайте PNG/JPEG в скрипт. + +**В: Все мои оценки уверенности низкие — что делать?** +О: Попробуйте предобработку изображения: увеличьте контраст, удалите фоновой шум или поверните изображение в горизонтальное положение. EasyOCR также принимает параметр `contrast_ths`, который можно настроить. + +**В: Можно ли экспортировать результаты в CSV?** +О: Конечно. После цикла с низкой уверенностью запишите `ocr_results` в `csv.DictWriter`, где каждая строка будет содержать `text`, `confidence` и координаты ограничивающего прямоугольника. + +**В: Есть ли версия с ускорением на GPU?** +О: EasyOCR автоматически использует CUDA, если совместимый GPU и PyTorch установлены. Проверьте `torch.cuda.is_available()` перед запуском скрипта. + +--- + +## Заключение + +Мы только что **выполнили OCR на изображении** с помощью Python, проверили общую уверенность и выделили любые слова с низкой уверенностью, которые требуют ручного вмешательства. + +## Что изучать дальше? + +Следующие учебники охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/spanish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..111c15696 --- /dev/null +++ b/ocr/spanish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extrae texto de una imagen con OCR en Python en minutos. Descubre OCR + de imágenes multilingüe, detección automática del idioma en OCR y cómo extraer texto + OCR con precisión. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: es +og_description: Extrae texto de una imagen con Python OCR rápidamente. Aprende OCR + de imágenes multilingüe, detección automática de idioma OCR y cómo extraer texto + OCR paso a paso. +og_title: Extraer texto de una imagen usando OCR de Python – Guía completa +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Extraer texto de una imagen usando OCR de Python – Guía completa +url: /es/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraer Texto de una Imagen con Python OCR – Guía Completa + +¿Alguna vez necesitaste **extraer texto de una imagen** pero no estabas seguro de qué biblioteca podía manejar varios idiomas automáticamente? No estás solo—los desarrolladores preguntan constantemente *cómo extraer texto OCR* al trabajar con documentos internacionales, recibos o folletos escaneados. En este tutorial recorreremos un ejemplo práctico en Python que no solo extrae texto de una imagen sino que también **detecta el idioma** al vuelo, haciendo que el OCR de imágenes multilingüe sea muy sencillo. + +Cubriremos todo, desde la instalación del paquete OCR hasta habilitar **auto detect language OCR**, ejecutar el motor en una imagen de ejemplo y, finalmente, imprimir tanto el idioma detectado como la cadena extraída. Al final tendrás un fragmento reutilizable que puedes insertar en cualquier proyecto, ya sea que estés construyendo una canalización de traducción o un servicio de ingestión de datos. + +## Extraer Texto de una Imagen – Configuración del Entorno + +Antes de sumergirnos en el código, asegúrate de que tu estación de trabajo cumpla con estos requisitos mínimos: + +- Python 3.8 o superior (la biblioteca usa anotaciones de tipo que versiones anteriores ignoran) +- `pip` para la gestión de paquetes +- Un archivo de imagen que contenga texto en al menos dos idiomas diferentes (p. ej., inglés + español) + +También necesitarás la biblioteca OCR que impulsa esta demostración. Para el propósito de esta guía usaremos el paquete ficticio `ocr`, que refleja herramientas reales populares como Tesseract o EasyOCR pero ofrece una API Python limpia. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Consejo profesional:** Si encuentras errores de permisos, precede el comando con `python -m` o usa un entorno virtual—mantiene tus paquetes globales ordenados. + +## Crear una Instancia del Motor OCR + +Ahora que la biblioteca está lista, el primer paso lógico es **crear una instancia del motor OCR**. Piensa en el motor como un escáner inteligente que puedes configurar antes de alimentarle imágenes. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +¿Por qué instanciamos el motor por separado en lugar de llamar a un método estático? El objeto motor mantiene el estado de configuración (como preferencias de idioma) que podrías querer reutilizar en muchas imágenes, ahorrándote la sobrecarga de volver a inicializarlo cada vez. + +## Habilitar Auto Detect Language OCR + +La mayoría de las herramientas OCR requieren que especifiques un código de idioma—`eng` para inglés, `spa` para español, etc. Adivinar manualmente el idioma derrota el propósito de un flujo de trabajo **OCR de imagen multilingüe**. Afortunadamente, el paquete `ocr` ofrece un modo *auto detect language OCR* que inspecciona la imagen y selecciona el mejor modelo de idioma detrás de escena. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Habilitar **detect language OCR** de esta manera significa que no tendrás que mantener una larga lista de códigos de idioma. El motor intentará coincidir con el script que vea—latín, cirílico, han, etc.—y cargará el modelo apropiado automáticamente. + +## Realizar OCR de Imagen Multilingüe + +Con el motor preparado, es hora de **extraer texto de la imagen**. El método `recognize_image` acepta una ruta de archivo y devuelve un objeto de resultado que contiene tanto el texto bruto como el idioma que se detectó. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Si te preguntas *cómo extraer texto OCR* de un PDF en lugar de un PNG, el mismo motor ofrece `recognize_pdf`—solo cambia el nombre del método. La lógica de detección subyacente permanece idéntica, por lo que te beneficias de la misma funcionalidad **auto detect language OCR**. + +## Mostrar el Idioma Detectado y el Texto Extraído + +Finalmente, mostramos lo que el motor descubrió. El objeto de resultado expone `detected_language` (una etiqueta BCP‑47 como `en` o `es`) y `text`, que contiene la salida OCR cruda. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Ejecutar el script con nuestra imagen de ejemplo debería producir algo similar a: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Observa cómo el motor identificó correctamente el inglés como idioma principal, pero aun así capturó la línea en español—exactamente lo que esperas de una solución robusta de **OCR de imagen multilingüe**. + +### ¿Qué pasa si la detección falla? + +A veces el motor OCR puede recurrir a un idioma predeterminado (usualmente inglés) si la imagen está borrosa o el script es demasiado exótico. En esos casos puedes forzar una lista de idiomas: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Pero recuerda, forzar idiomas derrota la comodidad de **auto detect language OCR**, así que úsalo solo cuando conozcas un subconjunto de idiomas. + +## Problemas Comunes y Cómo Extraer Texto OCR de Forma Confiable + +Incluso con detección automática, algunos inconvenientes pueden interrumpirte: + +1. **Imágenes de baja resolución** – La precisión del OCR cae drásticamente por debajo de 150 dpi. Aumenta la escala o solicita un escaneo de mayor resolución. +2. **Ruido y artefactos de compresión** – Aplica un filtro de umbral simple (`opencv` o `Pillow`) antes de pasar la imagen al motor. +3. **Scripts mixtos en una sola página** – Algunos motores tienen dificultades con caracteres latinos y CJK simultáneos. Divide la página en regiones y ejecuta reconocimientos separados si es necesario. + +Abordar estos problemas mejora dramáticamente la calidad del proceso **extraer texto de imagen**, especialmente al trabajar con documentos reales y multilingües. + +## Ejemplo Completo Funcional + +A continuación tienes el script completo, listo para ejecutar, que combina todos los pasos que discutimos. Guárdalo como `multilingual_ocr.py` y ejecútalo desde la línea de comandos. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Salida esperada** (suponiendo que la imagen de ejemplo contiene texto en inglés y español): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Siéntete libre de reemplazar `multilang_page.png` por cualquier imagen que contenga texto en otros idiomas—gracias a **auto detect language OCR**, el script seguirá proporcionando una etiqueta de idioma razonable y el texto correspondiente. + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## Conclusión + +Ahora sabes exactamente **cómo extraer texto OCR** de una imagen, cómo habilitar **auto detect language OCR**, y cómo manejar escenarios de **OCR de imagen multilingüe** con un código mínimo. Al crear una instancia del motor OCR, activar la detección automática de idioma y llamar a `recognize_image`, puedes obtener de forma fiable tanto el identificador de idioma como el texto bruto. + +¿Qué sigue? Prueba a pasar las cadenas extraídas a una API de traducción, guárdalas en una base de datos searchable, o combina varias páginas en un único informe PDF. También puedes experimentar con diferentes back‑ends OCR (Tesseract, EasyOCR, Google Vision) manteniendo el mismo flujo de trabajo de alto nivel—gracias a la interfaz consistente de **detect language OCR**. + +Si encuentras alguna peculiaridad, revisita la sección “Problemas Comunes” o ajusta los pasos de preprocesamiento de la imagen. ¡Feliz codificación, y que tu próximo proyecto esté lleno de texto correctamente detectado y perfectamente extraído! + +## ¿Qué Deberías Aprender a Continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/spanish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..075cf11ca --- /dev/null +++ b/ocr/spanish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Extrae texto de imágenes PDF usando OCR en Python. Aprende cómo convertir + documentos escaneados a texto rápidamente con reconocimiento por lotes asíncrono. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: es +og_description: Extrae texto de imágenes PDF con Python. Esta guía paso a paso muestra + cómo convertir documentos escaneados a texto usando OCR asíncrono. +og_title: Extraer texto de imágenes PDF – Tutorial de OCR en Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Extraer texto de imágenes PDF – Guía de Python para convertir documentos escaneados + a texto +url: /es/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraer texto de PDFs de imágenes – Guía de Python para convertir documentos escaneados a texto + +¿Alguna vez necesitaste **extraer texto de PDFs de imágenes** sin pasar horas reescribiendo? En esta guía te mostraremos cómo **convertir documentos escaneados a texto** usando un flujo de trabajo OCR asíncrono simple en Python. + +Si alguna vez has mirado una pila de PDFs escaneados y pensado, “Tiene que haber una forma más rápida”, estás en el lugar correcto. Revisaremos cada línea de código, explicaremos por qué cada parte es importante, e incluso cubriremos algunos casos límite que podrías encontrar. + +## Lo que aprenderás + +- Cómo iniciar un motor OCR y establecer el idioma de reconocimiento. +- La mecánica de alimentar una lista mixta de PNG y PDFs a un reconocedor por lotes. +- Ejecutar el trabajo OCR de forma asíncrona para que tu aplicación permanezca receptiva. +- Recuperar los resultados, emparejarlos con sus archivos de origen y imprimir una salida limpia. + +**Prerequisitos**: Python 3.8+, un entendimiento básico de `asyncio` o `concurrent.futures`, y una biblioteca OCR que exponga una clase `OcrEngine` similar a la del ejemplo (p. ej., Aspose.OCR, wrapper de Tesseract, o un wrapper personalizado). No se requiere una configuración pesada—simplemente instala la biblioteca y estarás listo. + +![extraer texto de PDFs de imágenes](https://example.com/placeholder.png "Captura de pantalla del resultado OCR – extraer texto de PDFs de imágenes") + +## Extraer texto de PDFs de imágenes – Configuración del motor OCR + +Lo primero que necesitas es una instancia del motor OCR configurada para el idioma de tus documentos. En nuestro caso usaremos francés, pero puedes cambiarlo por cualquier idioma soportado. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Por qué es importante**: Configurar el idioma desde el principio mejora drásticamente la precisión. El motor utiliza diccionarios y modelos de caracteres específicos del idioma; alimentarlo con el idioma incorrecto es una causa frecuente de resultados distorsionados. + +## Preparar la lista de archivos – Imágenes y PDFs juntos + +Nuestro reconocedor por lotes puede manejar tanto imágenes raster (`.png`, `.jpg`) como contenedores PDF. Simplemente pasa una lista Python simple de rutas de archivo. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Consejo**: Mantén la lista plana; el motor desempaquetará internamente cada página PDF en imágenes antes del reconocimiento. Si tienes miles de archivos, considera dividir la lista en lotes más pequeños para evitar picos de memoria. + +## Iniciar reconocimiento por lotes asíncrono + +En lugar de bloquear el hilo principal, lanzamos el trabajo OCR en segundo plano. El método devuelve un `Future` que eventualmente contendrá una lista de objetos `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Cómo funciona**: Internamente el motor crea un pool de hilos (o una tarea async, según la implementación). Esto te permite seguir realizando otras tareas—como actualizar una UI, obtener más archivos o registrar el progreso—mientras el trabajo pesado se ejecuta en otro lugar. + +## Haz algo útil mientras OCR se ejecuta + +Un error común es quedarse inactivo y sondear el futuro en un bucle ajustado. En su lugar, puedes realizar cualquier trabajo no relacionado. Para la demostración, simplemente imprimiremos una línea de estado. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Recopilar resultados una vez que el Future se complete + +Cuando estés listo para recopilar la salida OCR, usa `as_completed` de `concurrent.futures`. Este patrón funciona tanto si tienes un futuro como varios. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Lo que verás**: Cada ruta de archivo seguida de la representación de texto plano extraído. Para PDFs, `result.text` contiene el texto concatenado de cada página. + +### Salida esperada (ejemplo) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Si notas caracteres faltantes, verifica que el idioma que configuraste coincida con el idioma del documento, y considera pre‑procesar las imágenes (corregir inclinación, aumentar contraste) antes de pasárselas al motor. + +## Manejo de casos límite y errores comunes + +| Situación | Qué hacer | +|-----------|------------| +| **Idiomas mixtos** | Ejecuta primero una detección de idioma, luego instancia motores separados por idioma. | +| **PDFs enormes (> 100 MB)** | Divide el PDF en páginas individuales en disco (p. ej., usando `PyPDF2`) y pásalas como entradas separadas. | +| **Escrituras no latinas** | Asegúrate de que la biblioteca OCR incluya el paquete de idioma necesario; algunas bibliotecas requieren que descargues archivos de datos adicionales. | +| **Cuello de botella de rendimiento** | Aumenta el tamaño del pool de hilos (`engine.set_thread_pool_size(8)`) o cambia a un backend acelerado por GPU si está disponible. | +| **Texto faltante en imágenes de baja resolución** | Pre‑procesa con OpenCV: `cv2.resize`, `cv2.threshold` y `cv2.medianBlur` para mejorar la legibilidad. | + +## Ejemplo completo funcional (listo para copiar y pegar) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Guarda esto como `extract_text_async.py`, reemplaza `YOUR_DIRECTORY` con la ruta a tus archivos, instala el paquete OCR (`pip install your-ocr-lib`), y ejecuta `python extract_text_async.py`. Deberías ver la salida de consola ilustrada anteriormente. + +## Próximos pasos – Más allá de la extracción básica + +- **Post‑procesamiento**: Elimina espacios en blanco extra, normaliza Unicode (`unicodedata.normalize`), o ejecuta un corrector ortográfico para limpiar el ruido del OCR. +- **Salida estructurada**: Exporta los resultados a CSV, JSON, o directamente a una base de datos para búsquedas posteriores. +- **Lotes paralelos**: Si tienes cientos de archivos, crea múltiples futures y usa una cola para mantener la CPU ocupada sin saturar la memoria. +- **Integrar con frameworks web**: Conecta este script a un endpoint de Flask o FastAPI para ofrecer OCR bajo demanda como servicio. + +--- + +### TL;DR + +Ahora sabes cómo **extraer texto de PDFs de imágenes** con un script Python mínimo que ejecuta OCR de forma asíncrona, permitiéndote **convertir documentos escaneados a texto** mientras tu programa permanece receptivo. Juega con la configuración de idioma, tamaños de lote y trucos de pre‑procesamiento para exprimir la máxima precisión de caracteres. + +¿Tienes alguna variante que quieras compartir—quizá OCR en notas manuscritas o un servicio en la nube? Deja un comentario, ¡y feliz codificación! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer texto de imagen con Aspose OCR – Guía paso a paso](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extraer texto de imágenes usando la operación OCR en carpetas](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extraer texto de imágenes usando Aspose.OCR – Caracteres permitidos](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..b6c57ea1f --- /dev/null +++ b/ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: Cómo hacer OCR de PDF usando Python, extraer texto de PDF, convertir + texto de PDF escaneado y cambiar el idioma del OCR en solo unas pocas líneas de + código. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: es +og_description: 'Cómo hacer OCR de PDF con Python: una guía práctica que te muestra + cómo extraer texto de PDF, convertir texto de PDF escaneado y cambiar el idioma + del OCR sin esfuerzo.' +og_title: Cómo hacer OCR a PDF en Python – Tutorial completo de programación +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Cómo hacer OCR a PDF en Python – Guía completa paso a paso +url: /es/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo hacer OCR de PDF en Python – Guía completa paso a paso + +¿Alguna vez te has preguntado **cómo hacer OCR de PDF** sin pagar por costosas herramientas SaaS? No eres el único. Ya sea que estés digitalizando libros antiguos, extrayendo datos de facturas, o simplemente necesites texto buscable de un informe escaneado, dominar el OCR de PDF en Python puede ahorrarte horas de copia manual. + +En este tutorial recorreremos un ejemplo conciso y funcional que **extrae texto de PDF**, te muestra cómo **convertir texto de PDF escaneado** en cadenas editables, y además demuestra cómo **cambiar el idioma del OCR** si tu documento no está en inglés. Al final tendrás un fragmento reutilizable que podrás insertar en cualquier proyecto. + +## Requisitos previos y configuración + +Antes de sumergirnos, asegúrate de tener: + +- Python 3.8+ instalado (el código funciona en 3.9, 3.10 y versiones más recientes) +- El paquete `ocr` que proporciona la clase `OcrEngine` (puedes instalarlo vía `pip install ocr-lib` – reemplaza con el nombre real del paquete que uses) +- Un archivo PDF que quieras procesar; para la demo usaremos `high_res_book.pdf` ubicado en una carpeta llamada `YOUR_DIRECTORY` + +Si estás usando un entorno virtual (altamente recomendado), actívalo primero: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Consejo profesional:** Mantén tus archivos PDF en un directorio dedicado `data/` para evitar dolores de cabeza relacionados con rutas más adelante. + +## Paso 1: Crear una instancia del motor OCR (Cómo hacer OCR de PDF – Inicialización) + +Lo primero que necesitas hacer cuando quieras **realizar OCR en PDF** es instanciar el motor. Piensa en el motor como el cerebro que leerá cada página, interpretará los glifos y te devolverá texto plano. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Por qué es importante: sin un motor no tienes contexto para la configuración del idioma, opciones de renderizado o manejo del PDF. El objeto `OcrEngine` contiene todos esos valores predeterminados y te permite ajustarlos más adelante. + +## Paso 2: Establecer el idioma de reconocimiento (Cambiar idioma del OCR) + +La mayoría de las bibliotecas OCR usan inglés por defecto, pero ¿qué pasa si tu documento está en francés, alemán o incluso japonés? Cambiar el idioma es tan simple como llamar a `set_recognition_language`. Esto satisface el requisito de **cambiar el idioma del OCR** y garantiza mayor precisión. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Por qué podrías necesitar esto:** Un archivo multilingüe a menudo contiene páginas con idiomas mezclados. Cambiar de idioma sobre la marcha evita el reconocimiento incorrecto de caracteres como “ß” o “ñ”. + +## Paso 3: Configurar opciones de renderizado de PDF (Convertir texto de PDF escaneado de manera eficaz) + +Al trabajar con PDFs escaneados, la resolución y el modo de color afectan dramáticamente la calidad del OCR. Renderizar a 300 DPI en escala de grises es un punto óptimo para la mayoría de los documentos: lo suficientemente alto para capturar detalle pero lo suficientemente bajo para mantener un uso razonable de memoria. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Las llamadas encadenadas pueden parecer elegantes, pero son simplemente una API fluida que devuelve el mismo objeto de opciones cada vez. Si necesitas color (p. ej., para diagramas coloreados), reemplaza `"grayscale"` por `"color"`. + +## Paso 4: Reconocer el PDF y obtener el texto de la primera página (Extraer texto de PDF) + +Ahora llega el núcleo de **cómo hacer OCR de PDF**: pasarle al motor la ruta del archivo y extraer el texto reconocido. El método devuelve una lista de resultados por página; cada resultado contiene un atributo `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Si necesitas todo el documento, itera sobre `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### ¿Qué pasa si el PDF está encriptado? + +Algunos PDFs están protegidos con contraseña. En ese caso puedes pasar la contraseña a `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +El motor descifrará sobre la marcha antes de realizar el OCR—no se requieren pasos adicionales. + +## Paso 5: Post‑procesamiento del texto extraído (Ajuste fino de la extracción de texto de PDF) + +La salida cruda del OCR suele contener saltos de línea, espacios extra o caracteres ocasionalmente mal reconocidos. Una rutina rápida de limpieza prepara la cadena extraída para su procesamiento posterior (indexación de búsqueda, almacenamiento en base de datos, etc.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Ahora puedes **extraer texto de PDF** de forma segura y alimentarlo a cualquier pipeline de NLP, motor de búsqueda o simple operación `open(...).write()`. + +## Bonus: Procesamiento por lotes de varios PDFs (Escalar OCR de PDF) + +Si tienes una carpeta llena de PDFs escaneados, envuelve la lógica en un bucle: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Este fragmento muestra cómo **realizar OCR en PDF** en bloque, una necesidad frecuente en proyectos de digitalización. + +## Salida esperada + +Ejecutar el ejemplo de una sola página (Paso 4) debería imprimir algo como: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Si procesas un libro de varias páginas, la consola mostrará el texto limpio de cada página, y el script por lotes dejará un archivo `.txt` junto a cada PDF. + +## Problemas comunes y cómo evitarlos + +| Problema | Síntomas | Solución | +|----------|----------|----------| +| PDF de origen de baja resolución | Caracteres distorsionados, palabras faltantes | Aumenta DPI (`set_dpi(400)` o superior) | +| Idioma incorrecto configurado | Muchos símbolos desconocidos, especialmente caracteres acentuados | Usa `engine.set_recognition_language(ocr.Language.FRENCH)` o el enum apropiado | +| PDF grande que causa error de memoria | `MemoryError` o bloqueo después de algunas páginas | Procesa páginas en bloques (`engine.recognize_pdf(..., max_pages=10)`) | +| Falta de fuentes en el PDF | Salida en blanco en ciertas páginas | Asegúrate de que el PDF contenga imágenes raster; algunos PDFs son solo vectoriales y requieren un manejo diferente | + +## Ilustración de imagen + +A continuación tienes una visual rápida del flujo de trabajo. El texto alternativo está deliberadamente optimizado para SEO. + +![diagrama del flujo de trabajo de cómo hacer OCR de PDF que muestra la inicialización del motor, configuración del idioma, opciones de renderizado, reconocimiento y extracción de texto](/images/ocr-workflow.png) + +*El diagrama no es necesario para que el código funcione, pero ayuda a los aprendices visuales a ver dónde encaja cada paso.* + +## Conclusión + +Hemos cubierto **cómo hacer OCR de PDF** en Python de principio a fin: crear un motor OCR, **cambiar el idioma del OCR**, configurar el renderizado para **convertir texto de PDF escaneado**, y finalmente **extraer texto de PDF** para su uso posterior. El ejemplo completo y ejecutable está listo para insertarse en cualquier proyecto, y el script opcional por lotes muestra cómo escalar la solución. + +A continuación, podrías explorar: + +- Añadir **realizar OCR en PDF** para archivos multilingües mediante un bucle sobre una lista de idiomas. +- Integrar el texto extraído con Elasticsearch para búsqueda de texto completo. +- Usar OCR para crear PDFs buscables incrustando la capa de texto de nuevo en el archivo original (muchas bibliotecas exponen un método `save_as_searchable_pdf`). + +Siéntete libre de experimentar, ajustar la configuración de DPI o cambiar a otro backend de OCR. Los fundamentos siguen siendo los mismos, y ahora tienes una base sólida sobre la que construir. + +¡Feliz codificación, y que tus documentos escaneados finalmente se vuelvan buscables! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Reconocer texto de PDF – Operaciones OCR con Aspose.OCR para Java](/ocr/english/java/ocr-operations/) +- [Cómo hacer OCR de texto en imágenes con idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Cómo hacer OCR de PDF en .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..f9f9a04df --- /dev/null +++ b/ocr/spanish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-06 +description: Cómo hacer OCR a PDF y crear archivos PDF buscables a partir de imágenes + usando Python. Aprende a añadir texto buscable y convertir imágenes a PDF/A en minutos. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: es +og_description: Cómo hacer OCR a un PDF paso a paso. Aprende a añadir texto buscable + y convertir una imagen a PDF/A usando un script sencillo de Python. +og_title: Cómo hacer OCR a PDF – Guía rápida para crear PDFs buscables +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Cómo hacer OCR a PDF en Python – Crear PDF buscable a partir de imágenes +url: /es/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo hacer OCR a PDF – Convertir imágenes escaneadas en PDFs buscables + +¿Alguna vez te has preguntado **cómo hacer OCR a PDF** cuando lo único que tienes es una imagen escaneada de una factura o un recibo? No eres el único. En muchas oficinas la documentación entrante llega como PNG o JPEG planos, y el siguiente paso—hacer que ese contenido sea buscable—parece una caja negra. + +¿La buena noticia? Con solo unas pocas líneas de Python puedes **crear PDFs buscables**, **añadir texto buscable**, e incluso **convertir la imagen a PDF/A** para archivado a largo plazo. En este tutorial repasaremos cada paso, explicaremos por qué es importante y te daremos un script listo para ejecutar que puedes incorporar a cualquier proyecto. + +> **Pro tip:** El mismo enfoque funciona para escaneos de varias páginas; solo recorre los archivos y el motor hace el trabajo pesado. + +--- + +## Lo que necesitarás + +Antes de profundizar, asegúrate de tener lo siguiente en tu máquina: + +| Requisito | Por qué es importante | +|-----------|-----------------------| +| Python 3.9 or newer | Sintaxis moderna y mejor soporte de bibliotecas | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | Maneja tanto el reconocimiento de imágenes como la generación de PDF/A | +| An image file (PNG, JPEG, TIFF) you want to turn into a searchable PDF | La fuente del texto | +| Write permission to the output folder | Para que el script pueda guardar el nuevo PDF | + +Si aún no has instalado el SDK de OCR, ejecuta: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +¡Eso es todo—sin dependencias de sistema complejas, solo un pip install. + +--- + +## Cómo hacer OCR a PDF – Visión general + +A alto nivel, el proceso consta de tres acciones simples: + +1. **Reconocer** el texto dentro de la imagen mientras se preserva la gráfica original. +2. **Exportar** el resultado OCR junto con la imagen original como un **PDF/A buscable** (el tipo de PDF amigable para archivado). +3. **Validar** que el archivo resultante contenga texto seleccionable y buscable superpuesto a la imagen original. + +A continuación verás cada paso en código, con explicaciones del *por qué* detrás de los comandos. + +--- + +## Paso 1: Reconocer texto de la imagen + +Primero le pedimos al motor OCR que lea los píxeles y devuelva un objeto de resultado que contiene tanto la imagen cruda como el texto extraído. Piensa en ello como el motor “leyendo” la factura por ti. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Por qué es importante + +- **Preservar gráficos** significa que el diseño visual (tablas, logotipos, sellos) permanece exactamente como lo capturó el escáner. +- El objeto `result` normalmente contiene una capa de texto oculta que más tarde incrustaremos en el PDF. +- Usar `recognize_image` en lugar de `recognize_pdf` evita un paso de conversión extra, lo que acelera el procesamiento para imágenes de una sola página. + +#### Variaciones comunes + +- Si tienes un **TIFF de varias páginas**, pasa la ruta del archivo directamente; la mayoría de los motores tratarán cada página como una imagen separada. +- Para PDFs que ya contienen imágenes, puedes llamar a `engine.recognize_pdf("file.pdf")` y omitir este paso por completo. + +--- + +## Paso 2: Exportar el resultado OCR como PDF/A buscable + +Ahora tomamos el `result` del paso 1 y le indicamos al motor que escriba un nuevo archivo. La bandera clave aquí es *PDF/A*—la versión estándar ISO del PDF diseñada para preservación a largo plazo. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Por qué es importante + +- **PDF buscable**: El archivo de salida contiene una capa de texto oculta y seleccionable. Ahora puedes usar Ctrl + F en el documento. +- **Cumplimiento PDF/A**: Algunas organizaciones (legal, finanzas) requieren PDF/A para auditorías; este paso satisface esa regla automáticamente. +- El método también **añade texto buscable** sin aplanar la imagen, por lo que la fidelidad visual se mantiene perfecta. + +#### Caso límite: ¿Necesitas un PDF normal en su lugar? + +Si no te importa PDF/A, reemplaza `save_as_pdfa` por `save_as_pdf`. El resto del flujo permanece igual. + +--- + +## Paso 3: Verificar el PDF buscable + +Una rápida comprobación de sanidad te ahorra errores misteriosos más adelante. Abre el archivo generado en cualquier visor de PDF, intenta seleccionar una palabra y usa la función de búsqueda. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Salida esperada + +Al ejecutar el script, la consola imprime: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Al abrir el archivo, deberías ver la imagen original de la factura con una capa de texto tenue e invisible. Resalta cualquier palabra y notarás que es seleccionable—**ese es el texto buscable** que acabas de añadir. + +--- + +## Añadir texto buscable a PDFs existentes (Bonus) + +A veces ya tienes un PDF pero necesitas **añadir texto buscable**. El mismo motor puede superponer los resultados OCR sobre un PDF existente: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Aquí `apply_to` combina la capa oculta con las páginas originales, permitiéndote **crear PDF buscable** sin volver a escanear. + +--- + +## Problemas comunes y consejos + +| Problema | Cómo evitarlo | +|----------|---------------| +| **Imágenes de origen de baja resolución** (< 150 dpi) | Escala o solicita un escaneo de mayor resolución; la precisión del OCR cae drásticamente por debajo de 150 dpi. | +| **Faltan datos de idioma** | Instala los paquetes de idioma apropiados para tu motor OCR (`pip install pdfocr[eng,spa]`). | +| **Carpeta de salida no escribible** | Ejecuta el script con permisos suficientes o elige otro directorio. | +| **Fallos en la validación PDF/A** | Asegúrate de no incrustar fuentes no compatibles o JavaScript; la mayoría de los SDK manejan esto automáticamente al usar `save_as_pdfa`. | + +--- + +## Script completo – Solución de un solo archivo + +A continuación tienes un script autocontenido que une todo. Copia‑pega, reemplaza las rutas de marcador de posición y estarás listo para **convertir imagen a PDF/A** en segundos. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Qué hace este script:** +1. Carga el motor OCR. +2. Lee la imagen elegida y extrae el texto. +3. Escribe un **PDF/A buscable** que puedes distribuir o archivar de inmediato. + +Si lo deseas, envuelve la lógica `main` en una función que procese una carpeta completa—simplemente itera sobre `os.listdir()` y repite los tres pasos para cada archivo. + +--- + +## Próximos pasos y temas relacionados + +Ahora que dominas **cómo hacer OCR a PDF**, considera explorar estas ideas complementarias: + +- **Procesamiento por lotes:** Usa `concurrent.futures` para hacer OCR a docenas de facturas en paralelo. +- **Inyección de metadatos:** Añade fechas de creación o números de factura a los metadatos del PDF para facilitar la indexación. +- **PDFs híbridos:** Combina texto buscable con imágenes originales incrustadas para un “gemelo digital” del documento en papel. +- **Salidas alternativas:** Exporta a **DOCX** o **HTML** si los sistemas posteriores necesitan formatos editables. + +Cada uno de estos se basa en los conceptos centrales que acabas de aprender—reconocer, exportar, verificar. + +--- + +## Conclusión + +En resumen, ahora sabes **cómo hacer OCR a PDF** convirtiendo una simple imagen en un **PDF/A buscable** con solo tres líneas de Python. El script se encarga del trabajo pesado, preserva los gráficos originales y te entrega un documento conforme a estándares que puedes buscar, archivar o compartir. + +Pruébalo con tus propias facturas, recibos o contratos escaneados. Si encuentras algún obstáculo, deja un comentario abajo o revisa la documentación oficial del SDK—generalmente está llena de ejemplos adicionales. ¡Feliz codificación y disfruta de la nueva capacidad de hacer cualquier imagen instantáneamente buscable! + +![How to OCR PDF example showing original image and searchable PDF overlay](placeholder.png "How to OCR PDF example") + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funcionalidades adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo hacer OCR a PDF en .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Reconocer texto PDF – Operaciones OCR con Aspose.OCR para Java](/ocr/english/java/ocr-operations/) +- [Convertir imágenes a PDF C# – Guardar resultado OCR multipágina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/spanish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..784f09fb3 --- /dev/null +++ b/ocr/spanish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-06-06 +description: Cómo hacer OCR de PDF usando Aspose OCR Cloud. Aprende a extraer texto + de PDF, convertir páginas de PDF a PNG y guardar imágenes de páginas de PDF en Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: es +og_description: Cómo hacer OCR de PDF con Aspose OCR Cloud. Esta guía muestra cómo + extraer texto plano de PDF, convertir una página de PDF a PNG y guardar imágenes + de páginas de PDF. +og_title: Cómo hacer OCR a PDF con Aspose OCR Cloud – Paso a paso +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Cómo hacer OCR a PDF con Aspose OCR Cloud – Guía completa +url: /es/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo hacer OCR a PDF con Aspose OCR Cloud – Guía Completa + +¿Alguna vez te has preguntado **how to OCR PDF** sin luchar con herramientas de escritorio pesadas? No estás solo—muchos desarrolladores se topan con ese obstáculo cuando necesitan una forma rápida y programática de extraer texto de documentos escaneados. ¿La buena noticia? Con Aspose OCR Cloud puedes **extract text from PDF**, convertir cada página en un PNG y incluso **save PDF page images** para uso posterior, todo desde un ordenado script de Python. + +En este tutorial recorreremos todo lo que necesitas saber: desde instalar el SDK, licenciar el motor y reconocer PDFs de varias páginas, hasta extraer texto plano, convertir páginas a PNG y guardar esas imágenes en disco. Al final tendrás un fragmento reutilizable que puedes insertar en cualquier proyecto que necesite capacidades de **how to OCR PDF**. + +## Lo que necesitarás + +- **Python 3.8+** (el código funciona también en 3.10 y versiones más recientes) +- Una cuenta de Aspose OCR Cloud – obtendrás un archivo de licencia de prueba gratuito (`Aspose.OCR.lic`) +- El paquete `asposeocrcloud` (`pip install asposeocrcloud`) +- Un PDF escaneado y multipágina que deseas procesar + +Eso es todo. Sin binarios extra, sin dependencias nativas, solo puro Python. + +## Cómo hacer OCR a PDF – Configuración y Licencia + +Antes de poder llamar a cualquier método de OCR, debes indicar al SDK quién eres. Aspose utiliza un archivo de licencia ligero que colocas en un lugar accesible para tu script. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro tip:* Si omites el paso de la licencia, el SDK seguirá funcionando pero incrustará una pequeña marca de agua en las imágenes de salida. No es ideal para producción. + +## Paso 2: Instalar el SDK de Python de Aspose OCR Cloud + +Abre una terminal y ejecuta: + +```bash +pip install asposeocrcloud +``` + +El paquete trae todas las dependencias necesarias (requests, pillow, etc.) para que no tengas que buscar nada más. + +## Paso 3: Crear un motor OCR y elegir un idioma + +El motor es el corazón de la operación. Puedes especificar cualquier idioma soportado por Aspose; English funciona para la mayoría de los casos. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +¿Por qué establecer el idioma? Porque el motor OCR utiliza diccionarios específicos del idioma para mejorar la precisión. Si estás procesando PDFs en francés, simplemente cambia `ENGLISH` por `FRENCH`. + +## Paso 4: Apuntar a tu PDF multipágina + +Proporciona al motor la ruta completa al archivo que deseas procesar. Las rutas relativas están bien siempre que se resuelvan desde el directorio de trabajo del script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Asegúrate de que el archivo sea legible; de lo contrario verás un `FileNotFoundError`. + +## Paso 5: Ejecutar OCR – Obtienes una lista de resultados + +Llamar a `recognize_pdf` devuelve una lista donde cada elemento corresponde a una página del PDF original. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Cada `OcrResult` contiene dos propiedades útiles: + +* `text` – la representación de texto plano de la página (ideal para **extract plain text pdf**) +* `image` – un objeto `Image` de Pillow de la página renderizada (perfecto para **convert pdf page png**) + +## Paso 6: Extraer texto del PDF y convertir páginas a PNG + +Ahora iteramos sobre los resultados, imprimimos el texto extraído y guardamos una versión PNG de cada página. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Salida esperada en consola + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +También encontrarás `page_1.png`, `page_2.png`, … en `YOUR_DIRECTORY`. Esas son las imágenes rasterizadas de las páginas que puedes alimentar a pipelines de procesamiento de imágenes posteriores. + +## Paso 7: Guardar imágenes de páginas PDF (Post‑procesamiento opcional) + +Si solo necesitas las imágenes y no el texto, puedes omitir la línea `print(res.text)`. Por el contrario, si deseas almacenar el texto en archivos `.txt` separados, simplemente agrega una pequeña escritura: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Esta pequeña adición demuestra lo fácil que es **save PDF page images** mientras también se persiste el contenido extraído. + +## Ejemplo completo en funcionamiento + +Juntando todo, aquí tienes el script completo que puedes copiar y pegar en `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Ejecuta con: + +```bash +python ocr_pdf.py +``` + +Deberías ver el volcado en consola del texto de cada página y una serie de archivos PNG + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo hacer OCR a PDF en .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Reconocer texto PDF – Operaciones OCR con Aspose.OCR para Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convertir imágenes a PDF C# – Guardar resultado OCR multipágina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/spanish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..c841021cd --- /dev/null +++ b/ocr/spanish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Cómo preprocesar imágenes para OCR usando Python. Aprende a binarizar + la imagen usando Otsu, cómo enderezar documentos escaneados y mejorar la precisión + del OCR para texto en alemán. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: es +og_description: Cómo preprocesar imágenes para OCR en Python. Este tutorial muestra + cómo binarizar una imagen usando Otsu, cómo enderezar documentos escaneados y cómo + mejorar la precisión del OCR para imágenes en alemán. +og_title: Cómo preprocesar imágenes para OCR – Guía completa de Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Cómo preprocesar imágenes para OCR – Guía completa de Python +url: /es/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo preprocesar imágenes para OCR – Guía completa en Python + +¿Alguna vez te has preguntado **cómo preprocesar imágenes para OCR** de modo que el texto salga nítido como el cristal? No eres el único. Los documentos escaneados —especialmente las páginas alemanas ruidosas— pueden ser una pesadilla para cualquier motor de OCR. ¿La buena noticia? Unos pocos pasos inteligentes de preprocesamiento pueden convertir un escaneo borroso y moteado en una imagen limpia y legible por máquina. + +En este tutorial recorreremos un ejemplo práctico que muestra **cómo preprocesar imágenes para OCR** usando Python. Aprenderás a **binarizar la imagen usando Otsu**, **cómo enderezar documentos escaneados**, y en general **cómo mejorar la precisión del OCR** cuando necesites **extraer texto de imágenes en alemán**. Sin rodeos, solo un script funcional que puedes copiar‑pegar hoy mismo. + +## Qué necesitarás + +- **Python 3.9+** (cualquier versión reciente sirve) +- Una biblioteca OCR que exponga una clase `OcrEngine` —para la demo asumiremos un paquete genérico `ocr`. Instálalo con `pip install ocr-lib`. +- Un escaneo ruidoso en alemán (`noisy_german_scan.tif`) que quieras probar. +- Un entendimiento básico de funciones en Python (si ya has escrito un `def`, estás listo). + +> **Consejo profesional:** Si utilizas otro SDK de OCR (p. ej., Tesseract vía `pytesseract`), los conceptos siguen siendo los mismos —solo adapta los nombres de los métodos. + +## Visión general de la solución + +1. **Crear una instancia del motor OCR.** +2. **Establecer el idioma de reconocimiento a alemán.** +3. **Construir una canalización de preprocesamiento personalizada** que incluya enderezado, eliminación de ruido, binarización (Otsu) y expansión de contraste. +4. **Adjuntar la canalización al motor** para que cada imagen la atraviese automáticamente. +5. **Ejecutar el OCR** sobre un escaneo ruidoso en alemán. +6. **Imprimir el texto extraído** para verificar el resultado. + +A continuación desglosamos cada paso, explicamos **por qué** es importante y mostramos el código exacto que necesitas. + +![cómo preprocesar imágenes para OCR ejemplo](image.png "cómo preprocesar imágenes para OCR ejemplo") + +## Paso 1: Crear una instancia del motor OCR + +Lo primero, sin una instancia nada ocurre. El objeto `OcrEngine` es el punto de entrada que coordina todo el procesamiento posterior. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Por qué es importante:* Inicializar el motor configura recursos internos (como modelos de idioma) y te brinda una base limpia para adjuntar una canalización personalizada más adelante. + +## Paso 2: Establecer el idioma de reconocimiento a alemán + +La precisión del OCR depende mucho del idioma. Al indicar al motor que espere alemán, activas el conjunto de caracteres y el modelo de lenguaje correctos. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Si omites esto, el motor podría usar inglés por defecto, reconociendo mal las diéresis (ä, ö, ü) y el carácter ß —errores comunes al trabajar con escaneos en alemán. + +## Paso 3: Construir una canalización de preprocesamiento personalizada + +Este es el corazón de **cómo preprocesar imágenes para OCR**. Encadenaremos cuatro transformaciones: + +| Transformación | Qué hace | Por qué ayuda | +|----------------|----------|---------------| +| **Deskew** | Rota la imagen de vuelta a horizontal (máx 5°) | Los escaneos rara vez están perfectamente alineados; enderezar elimina la inclinación que confunde la segmentación de caracteres. | +| **Denoise** | Reduce manchas aleatorias (intensidad 0.7) | El ruido crea bordes falsos que el motor OCR puede interpretar como caracteres. | +| **Binarize (Otsu)** | Convierte a blanco‑y‑negro usando el método de Otsu | Una imagen binaria limpia brinda al motor un contraste nítido entre primer plano (texto) y fondo. | +| **Contrast Stretch** | Expande el rango dinámico | Mejora la legibilidad de trazos débiles, especialmente en documentos antiguos. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Cómo enderezar documentos escaneados + +La llamada `deskew` anterior es la respuesta concreta a **cómo enderezar documentos escaneados**. Internamente estima el ángulo dominante de la línea de texto mediante la transformada de Hough y rota la imagen de vuelta. Si tus documentos están rotados más de 5°, aumenta `max_angle`, pero ten cuidado con artefactos de sobre‑rotación. + +### Binarizar la imagen usando Otsu + +La línea `binarize(method="otsu")` responde directamente a la consulta **binarizar imagen usando otsu**. El algoritmo de Otsu calcula un umbral que minimiza la varianza intra‑clase, perfecto para documentos con histogramas bimodales (texto oscuro vs. fondo claro). + +## Paso 4: Adjuntar la canalización al motor + +Ahora indicamos al motor OCR que ejecute cada imagen entrante a través de la canalización que acabamos de crear. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Por qué es importante:* Sin registrar la canalización, el motor procesaría el escaneo crudo, ignorando toda la limpieza que configuramos. Este paso asegura **cómo mejorar la precisión del OCR** aplicando el mismo preprocesamiento de forma consistente. + +## Paso 5: Reconocer texto de un escaneo ruidoso en alemán + +Es hora de juntar todo. Alimentamos al motor con una imagen ruidosa en alemán y dejamos que haga el trabajo pesado. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Si tienes curiosidad por el rendimiento, puedes medir el tiempo de la llamada: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Paso 6: Mostrar el texto reconocido + +Finalmente, imprimimos la cadena extraída. Esta es la respuesta directa a **extraer texto de imagen en alemán**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Salida esperada + +Suponiendo que el escaneo de ejemplo contiene la frase “Die schnelle braune Füchsin springt über den faulen Hund.” deberías ver algo como: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Si la salida aún contiene caracteres distorsionados, considera ajustar la intensidad de `denoise` o incrementar `max_angle` para el enderezado. + +## Problemas comunes y cómo abordarlos + +- **Modelo de idioma ausente:** Olvidar `set_recognition_language(Language.GERMAN)` suele producir la pérdida de diéresis. Verifica la llamada. +- **Sobre‑denoising:** Una intensidad superior a 0.9 puede borrar trazos finos, sobre todo en fuentes antiguas. Mantén 0.5‑0.7 para la mayoría de los casos. +- **Formato de archivo incorrecto:** Algunos motores OCR fallan con TIFF de varias páginas. Si tienes un documento multipágina, divídelo en archivos de una sola página primero. +- **Orden de la canalización:** El orden mostrado (deskew → denoise → binarize → contrast) es intencional. Binarizar antes de eliminar ruido puede fijar el ruido; siempre denoise primero. + +## Extender la canalización (¿Qué sigue?) + +Ahora que tienes una base sólida, podrías querer: + +- **Agregar una apertura morfológica** para limpiar pequeños puntos (`.morph_open(kernel=3)`). +- **Integrar un modelo de lenguaje** para corrección posterior (`ocr_engine.apply_spellcheck()`). +- **Paralelizar el procesamiento por lotes** para grandes volúmenes usando `concurrent.futures`. + +Todas estas son extensiones naturales que mantienen la idea central de **cómo preprocesar imágenes para OCR** mientras potencian **cómo mejorar la precisión del OCR** aún más. + +## Conclusión + +Acabamos de cubrir **cómo preprocesar imágenes para OCR** de principio a fin: crear un motor, establecer el idioma alemán, construir una canalización que **binarice la imagen usando Otsu**, **cómo enderezar documentos escaneados**, y finalmente **extraer texto de imagen en alemán** con mayor confianza. Siguiendo los seis pasos anteriores notarás un salto notable en la calidad del reconocimiento —adiós a las correcciones manuales interminables. + +Prueba el script con tus propios escaneos, experimenta con los parámetros y deja que los resultados hablen por sí mismos. ¿Tienes preguntas sobre algún ajuste de preprocesamiento en particular? Deja un comentario y profundizaremos juntos. + +¡Feliz codificación, y que tu OCR sea siempre preciso! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to OCR Image – Perform OCR on Image in OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..ca0c47a34 --- /dev/null +++ b/ocr/spanish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-06 +description: OCR de imagen PNG con Python – aprende cómo extraer texto de una imagen, + ejecutar un ejemplo de OCR en Python e incluso leer texto en griego antiguo fácilmente. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: es +og_description: OCR de imágenes PNG en Python explicado. Esta guía muestra cómo extraer + texto de una imagen, ejecutar un ejemplo de OCR en Python y leer griego antiguo + con facilidad. +og_title: OCR de imagen PNG en Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR de imagen PNG en Python – Guía completa paso a paso +url: /es/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image en Python – Guía Completa Paso a Paso + +¿Alguna vez te has preguntado cómo **OCR PNG image** archivos directamente desde un script de Python? Tal vez tengas una carpeta llena de manuscritos antiguos escaneados y necesites **extract text from image** archivos sin tener que escribir todo manualmente. La buena noticia es que no necesitas un doctorado en visión por computadora—solo unas pocas líneas de código y la biblioteca adecuada, y estarás leyendo griego antiguo en segundos. + +En este tutorial recorreremos un **python OCR example** que reconoce texto de un PNG, establece el idioma a Greek polytonic y muestra el resultado. Al final sabrás exactamente cómo **recognize image text**, manejar problemas comunes y adaptar el script a otros idiomas o formatos de imagen. + +## Lo Que Aprenderás + +- Instalar y configurar una biblioteca OCR para Python (pytesseract + Tesseract OCR) +- Crear una instancia del motor OCR y cargar un archivo PNG +- Establecer el idioma de reconocimiento a Greek polytonic para que puedas **read ancient greek** +- Mostrar el texto reconocido y solucionar problemas típicos +- Extender el script para procesar por lotes varios PNGs o cambiar a otro idioma + +### Requisitos Previos + +| Requisito | Por qué es importante | +|-------------|----------------| +| Python 3.8+ | Sintaxis moderna y anotaciones de tipo | +| `pytesseract` package | Pequeña capa alrededor del motor Tesseract | +| Tesseract OCR binaries (≥ 5.0) | El motor real que realiza el trabajo pesado | +| Greek language data (`grc.traineddata`) | Necesario para **read ancient greek** correctamente | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Nuestro objetivo para la demostración **ocr png image** | + +Puedes instalar la parte de Python con: + +```bash +pip install pytesseract Pillow +``` + +Y en Ubuntu/macOS agregarías el motor en sí: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +No olvides descargar los datos entrenados Greek polytonic: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(La ruta puede variar; ajusta `TESSDATA_PREFIX` si es necesario.)* + +## OCR PNG Image: Crear la Instancia del Motor + +Lo primero que necesitamos es un objeto que se comunique con Tesseract. En `pytesseract` el motor se accede mediante funciones a nivel de módulo, pero para mayor claridad lo envolveremos en una pequeña clase. Esto refleja el concepto de “engine” que viste en el fragmento original. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**¿Por qué envolverlo?** +- Mantiene la API pública idéntica al fragmento con el que comenzaste, facilitando la migración. +- Nos permite añadir registro o manejo de errores más tarde sin tocar el flujo principal. +- Demuestra una buena práctica de OOP—algo que los desarrolladores senior aprecian. + +## Extraer Texto de la Imagen: Establecer el Idioma a Greek Polytonic + +Ahora que tenemos un motor, necesitamos indicarle qué idioma esperar. Greek polytonic usa diacríticos que no están cubiertos por los datos estándar “greek”, así que apuntamos Tesseract al archivo entrenado `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Si alguna vez deseas **extract text from image** archivos en otro idioma, simplemente reemplaza `"grc"` por `"eng"` para inglés, `"fra"` para francés, etc. La misma línea funciona para cualquier idioma que tengas instalado. + +## Reconocer Texto de Imagen: Ejecutar el OCR en un PNG + +Con el idioma configurado, alimentamos el PNG al motor. El ejemplo original usaba una ruta codificada; lo haremos un poco más flexible usando objetos `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Consejos y Casos Límite** + +- **File not found** – envuelve la llamada en un `try/except FileNotFoundError` para dar un mensaje amigable. +- **Low‑resolution PNG** – considera pre‑procesar (p. ej., redimensionar, binarizar) con Pillow antes del OCR. +- **Non‑Greek text** – Tesseract seguirá intentando decodificar, pero la precisión disminuye drásticamente. Siempre coincide con el idioma. + +## Mostrar el Texto Reconocido + +Finalmente, imprimimos el resultado. En un proyecto real podrías escribir a una base de datos, un CSV, o incluso alimentarlo a una canalización de traducción. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Cuando ejecutes el script contra un escaneo claro de una inscripción griega antigua, deberías ver algo como: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Si la salida se ve desordenada, verifica que el archivo **greek.traineddata** esté en la carpeta correcta y que el PNG no sea demasiado ruidoso. + +## Ejemplo Completo Funcional (Todos los Pasos en un Solo Script) + +A continuación se muestra el programa completo, listo para ejecutar. Guárdalo como `ocr_greek.py` y ejecuta `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Salida esperada** (truncada por brevedad): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Si ves los caracteres griegos correctos, ¡felicitaciones—has realizado con éxito una operación **ocr png image** en Python! + +## Preguntas Comunes y Consejos Profesionales + +### ¿Cómo mejoro la precisión en un PNG ruidoso? + +- Convierte la imagen a escala de grises: `img = img.convert('L')` +- Aplica un umbral binario: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Aumenta la escala con `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Estos pasos a menudo convierten una pesadilla de **recognize image text** en un resultado limpio. + +### ¿Puedo procesar una carpeta completa de PNGs? + +Absolutamente. Envuelve la llamada `recognize_image` en un bucle `for` sobre `Path.glob("*.png")`. Guarda cada resultado en un diccionario o escríbelo a un CSV para análisis posterior. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### ¿Qué pasa si solo necesito extraer números? + +Pasa una cadena **config** personalizada a `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +De esa manera puedes **extract text from image** archivos que contengan tablas, números de serie o marcas de tiempo. + +### ¿Hay una forma de obtener puntuaciones de confianza? + +Sí—usa `pytesseract.image_to_data` que devuelve un TSV con la confianza por palabra. Puedes filtrar los tokens de baja confianza antes de ensamblar la cadena final. + +## Extender el Tutorial + +Ahora que dominas los conceptos básicos, considera explorar estos temas relacionados: + +- **Batch OCR with multiprocessing** – acelera grandes corpora de PNGs. +- **Hybrid OCR + NLP pipelines** – traduce automáticamente el griego antiguo extraído al inglés moderno. +- **Alternative engines** – prueba `easyocr` o métodos basados en `opencv` para casos de uso específicos. +- **Cloud OCR services** – Google Vision, Azure Computer Vision o AWS Textract para escalado sin servidor. + +Cada uno de estos se basa en el núcleo **python ocr example** que acabamos de cubrir, por lo que te sentirás cómodo profundizando más. + +## Conclusión + +Hemos tomado un fragmento simple y lo hemos convertido en un flujo de trabajo robusto **ocr png image** en Python. Al crear un `OcrEngine`, establecer el idioma a Greek polytonic, alimentar un PNG y imprimir el resultado, ahora sabes cómo **extract text from image** archivos, **recognize image text**, e incluso **read ancient greek**. + +## ¿Qué Deberías Aprender a Continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer Texto de Imagen con Aspose OCR – Guía Paso a Paso](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Cómo Establecer el Valor de Umbral en el Reconocimiento OCR de Imagen](/ocr/english/net/ocr-settings/set-threshold-value/) +- [reconocer texto de imagen con Aspose OCR para varios idiomas](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/spanish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..13b5acc2f --- /dev/null +++ b/ocr/spanish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-06 +description: Tutorial de OCR en Python que muestra cómo reconocer texto en imágenes, + realizar OCR de alta resolución y extraer texto en español usando OCR acelerado + por GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: es +og_description: Tutorial de OCR en Python que te guía a través del reconocimiento + de texto en imágenes, OCR de alta resolución y la extracción de texto en español + con aceleración GPU. +og_title: Tutorial de OCR en Python – Reconocimiento de Texto Acelerado por GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Tutorial de OCR en Python – Reconoce texto de imagen con aceleración GPU +url: /es/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial de OCR en Python – Reconocer Texto en Imágenes con Aceleración GPU + +¿Alguna vez te has preguntado cómo **reconocer texto en imágenes** en un script de Python sin pasar horas ajustando configuraciones? No eres el único. En este **tutorial de OCR en Python** te mostraremos una forma limpia y de extremo a extremo para extraer texto en español de una imagen de alta resolución, y añadiremos aceleración GPU para que el proceso sea ultrarrápido. + +Piénsalo como una demostración rápida de pausa para el café que puedes ampliar a una canalización de nivel producción más adelante. Al final de esta guía tendrás un programa ejecutable que realiza **high resolution OCR**, aprovecha una GPU con soporte CUDA y genera los caracteres en español exactos que necesitas. + +## Lo que aprenderás + +- Cómo instalar e importar una biblioteca OCR moderna que soporte aceleración GPU. +- Cómo crear una instancia del motor OCR y configurarla para **reconocer texto en imágenes** en español. +- Cómo habilitar **gpu accelerated OCR** para obtener ganancias de velocidad masivas en archivos de alta resolución. +- Cómo manejar casos límite como controladores CUDA faltantes o fallback a CPU. +- Consejos para mejorar la precisión cuando necesites **extraer texto en español** de escaneos ruidosos. + +### Requisitos previos + +- Python 3.9+ (el código funciona también en 3.10 y versiones posteriores). +- Una GPU compatible con CUDA (opcional pero muy recomendada). +- Familiaridad básica con pip y entornos virtuales. + +Si te falta alguno de estos, el tutorial sigue funcionando—simplemente omite el paso de GPU y la biblioteca hará fallback a CPU automáticamente. + +--- + +## Tutorial de OCR en Python: Instalar los paquetes requeridos + +Lo primero es contar con un motor OCR sólido. Para este tutorial usaremos el paquete de código abierto **`easyocr`**, que incluye soporte GPU integrado cuando se detecta un dispositivo compatible. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Si ya tienes PyTorch instalado, asegúrate de que coincida con tu versión de CUDA (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Las versiones incompatibles son una causa frecuente de errores “GPU not found”. + +--- + +## Paso 1: Crear una instancia del motor OCR + +Ahora iniciamos el motor. EasyOCR llama a su clase principal `Reader`. El constructor acepta una lista de códigos de idioma; pasaremos `"es"` para español. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Por qué es importante:* Al declarar el idioma de antemano, el motor carga solo los pesos de red neuronal necesarios, lo que ahorra memoria y acelera la inferencia—especialmente útil cuando trabajas con **high resolution OCR** más adelante. + +--- + +## Paso 2: Preparar una imagen de alta resolución + +Las imágenes de alta resolución le dan al modelo más píxeles con los que trabajar, lo que normalmente se traduce en un mejor reconocimiento de caracteres. Supongamos que tienes un archivo llamado `high_res_spanish.png` dentro de una carpeta llamada `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Si no tienes una muestra de alta resolución a mano, puedes descargar una gratis de Unsplash o generar una imagen sintética con Pillow. La clave es mantener el DPI por encima de 300 para obtener los mejores resultados. + +--- + +## Paso 3: Habilitar la aceleración GPU (Opcional pero recomendada) + +EasyOCR ya intenta usar la GPU cuando configuras `gpu=True`. Sin embargo, es buena práctica verificar que el dispositivo realmente se esté utilizando, sobre todo en equipos con múltiples GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*¿Por qué comprobar esto?* Si el script recurre silenciosamente a la CPU, podrías preguntarte por qué una operación de 5 segundos de repente tarda 30 segundos. Esta pequeña verificación hace que el comportamiento sea transparente y mantiene tu pipeline de **gpu accelerated OCR** predecible. + +--- + +## Paso 4: Realizar OCR de alta resolución y reconocer texto en la imagen + +Ahora la parte divertida—leer el texto. El método `readtext` de EasyOCR devuelve una lista de tuplas que contienen el cuadro delimitador, la cadena reconocida y una puntuación de confianza. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Si necesitas la cadena cruda sin coordenadas, establece `detail=0`. Para la mayoría de los casos de uso de **reconocer texto en imágenes**, el valor predeterminado (`detail=1`) te brinda suficiente contexto para post‑procesar más adelante. + +--- + +## Paso 5: Extraer texto en español y limpiar la salida + +Como le pedimos a EasyOCR que use español, las cadenas devueltas ya están en ese idioma. Aún así, puede que quieras concatenarlas, eliminar espacios en blanco o filtrar detecciones de baja confianza. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**¿Qué pasa si la confianza es baja?** Puedes bajar el umbral (arriesgándote a más ruido) o pre‑procesar la imagen (aumentar contraste, binarizar o corregir la inclinación). esos trucos son comunes al trabajar con **high resolution OCR** en documentos escaneados. + +--- + +## Paso 6: Manejo de casos límite y ajustes de rendimiento + +Incluso los modelos mejor entrenados tropiezan en algunos escenarios. A continuación tienes un par de correcciones rápidas que puedes pegar en el script. + +### 6.1 Fallback cuando no hay GPU presente + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Reducción de escala de imágenes muy grandes + +Si tu imagen es mayor de 4000 × 4000 px, podrías quedarte sin memoria GPU. Reduce la escala proporcionalmente manteniendo el DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Estos fragmentos mantienen el script robusto, ya sea que lo ejecutes en una estación de trabajo o en un portátil modesto. + +--- + +## Ejemplo completo y funcional + +Juntando todo, aquí tienes el script completo que puedes copiar‑pegar y ejecutar de inmediato: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Salida esperada (ejemplo):** + + + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer texto de una imagen con Aspose OCR – Guía paso a paso](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Cómo hacer OCR de texto en imágenes con idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Cómo reconocer rectángulos de página para el reconocimiento de texto OCR en Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/spanish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..0c3498523 --- /dev/null +++ b/ocr/spanish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-06-06 +description: Reconoce texto de una imagen usando el motor OCR de Python. Aprende cómo + configurar el motor OCR en Python y extraer texto de una imagen con procesamiento + en la nube en minutos. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: es +og_description: Reconocer texto de una imagen con el motor OCR de Python. Esta guía + muestra cómo configurar el motor OCR en Python y extraer texto de una imagen de + manera eficiente. +og_title: Reconocer texto de una imagen en Python – Tutorial completo de configuración +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Reconocer texto de una imagen en Python – Guía completa de configuración del + motor OCR +url: /es/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# recognize text from image in Python – Tutorial de configuración completa + +¿Alguna vez te has preguntado cómo **recognize text from image** usando solo unas pocas líneas de Python? No estás solo. Ya sea que estés construyendo un escáner de recibos, un digitalizador de documentos o un proyecto simple de hobby, poder extraer texto de imagen es una habilidad que paga rápidamente. + +En este tutorial recorreremos todo el proceso—comenzando con una configuración al estilo **configure OCR engine python**, pasando por la autenticación en la nube, y finalmente mostrándote cómo **extract text from image** con un resultado fiable. No hay magia, solo pasos claros que puedes copiar‑pegar y ejecutar hoy. + +## Lo que aprenderás + +- Cómo instalar e importar la biblioteca OCR requerida. +- Los comandos exactos para **configure OCR engine python** para procesamiento en la nube. +- Un script completo y ejecutable que **recognize text from image** e imprime la salida. +- Consejos para manejar problemas comunes como claves API faltantes o formatos de imagen no compatibles. +- Ideas de siguiente nivel como procesamiento por lotes y respaldo local. + +### Requisitos previos + +- Python 3.8+ instalado en tu máquina. +- Una conexión a internet (el ejemplo usa un servicio OCR basado en la nube). +- Una clave API válida del proveedor OCR (verás dónde insertarla). + +Si tienes eso, sumérgete—sin rodeos, solo una guía práctica que funciona. + +--- + +## Paso 1: Instalar la biblioteca OCR e importarla + +Antes de poder **configure OCR engine python**, necesitas la biblioteca que se comunica con el servicio en la nube. En nuestro ejemplo usaremos un paquete ficticio pero representativo llamado `ocrcloud`. Reemplázalo con el paquete real que estés usando (p.ej., `easyocr`, `google-cloud-vision`, etc.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Por qué es importante:** Importar la clase te da acceso a métodos como `use_cloud()` y `set_api_key()`. Sin la importación, el resto del script lanzaría un `NameError`. + +*Consejo profesional:* Fija la versión en tu `requirements.txt` (`ocrcloud==2.1.0`) para evitar cambios inesperados que rompan el código más adelante. + +## Paso 2: Crear y **configure OCR engine python** para modo Cloud + +Ahora realmente **configure OCR engine python**. El motor comienza en modo local por defecto; cambiar a modo cloud te permite delegar el análisis pesado de imágenes a servidores potentes. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Explicación:** +- `OcrEngine()` crea un nuevo objeto de motor—piénsalo como tu lienzo en blanco. +- `use_cloud(True)` activa un interruptor, indicando al motor que envíe imágenes vía HTTPS en lugar de procesarlas localmente. Esto es crucial para resultados de alta precisión en fuentes complejas o fotos de baja resolución. + +## Paso 3: Autenticar con tu clave API de la nube + +La mayoría de los servicios OCR en la nube requieren una clave API. Este paso muestra cómo inyectar la credencial de forma segura. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Nota de seguridad:** Nunca codifiques la clave directamente en un repositorio público. En producción la obtendrías de una variable de entorno: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## Paso 4: **recognize text from image** – Enviar una imagen remota para procesar + +Con el motor configurado, finalmente podemos **recognize text from image**. El método `recognize_image()` acepta una ruta o URL y devuelve un objeto que contiene el texto extraído. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**¿Qué ocurre tras bambalinas?** +Los bytes de la imagen se suben al endpoint del proveedor, son procesados por un modelo de deep‑learning, y el resultado en texto plano se devuelve en streaming. Si la imagen es grande, el servicio puede reducirla automáticamente para acelerar la tarea. + +## Paso 5: Mostrar el resultado del **extract text from image** + +Ahora que el servicio OCR ha hecho su trabajo, simplemente imprimimos el texto. En aplicaciones reales podrías almacenarlo en una base de datos o pasarlo a otra función. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Salida esperada:** (ejemplo) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Si la salida se ve distorsionada, verifica que la imagen sea clara y que hayas seleccionado el modelo de idioma correcto (muchos servicios permiten especificar `engine.set_language("en")`). + +## Manejo de casos límite y problemas comunes + +### 1. Clave API faltante o inválida +Si ves un error de autenticación, asegúrate de que: +- La clave está activa y no ha expirado. +- Se está leyendo correctamente desde la variable de entorno. +- Tu red permite tráfico HTTPS saliente. + +### 2. Formatos de imagen no compatibles +La mayoría de las APIs OCR aceptan JPEG, PNG y PDF. Intentar con BMP o TIFF puede generar una respuesta de “formato no soportado”. Convierte con Pillow si es necesario: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Límites de velocidad +Los servicios en la nube a menudo limitan la cantidad de solicitudes por minuto. Si alcanzas el límite, implementa un back‑off exponencial: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Recurso alternativo a OCR local +Si la nube está caída, puedes volver al local: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Tener un recurso alternativo mantiene tu aplicación resiliente. + +## Ejemplo completo funcional + +Juntándolo todo, aquí tienes un script que puedes ejecutar ahora mismo (solo reemplaza los valores de marcador). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Ejecuta:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Deberías ver el texto extraído impreso en la consola, confirmando que has **recognize text from image** y **extract text from image** exitosamente usando un flujo de trabajo **configure OCR engine python** correctamente configurado. + +## Conclusión + +Acabamos de recorrer un proceso completo de extremo a extremo que te permite **recognize text from image** en Python, desde instalar la biblioteca hasta autenticar un servicio en la nube y finalmente **extract text from image** con una única llamada a función. Al **configure OCR engine python** de la manera correcta, obtienes tanto flexibilidad (cloud vs. local) como fiabilidad (manejo adecuado de errores). + +¿Qué sigue? Prueba procesar por lotes una carpeta de recibos, añade detección de idioma, o experimenta con PDFs como entrada. El cielo es el límite una vez que domines lo básico. + +¡Feliz codificación, y siéntete libre de dejar cualquier pregunta en los comentarios—nada supera aprender juntos! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer texto de imagen con Aspose OCR – Guía paso a paso](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extraer texto de imagen – Reconocer línea con Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Cómo extraer texto de imagen preparando rectángulos en OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..d4811e788 --- /dev/null +++ b/ocr/spanish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,339 @@ +--- +category: general +date: 2026-06-06 +description: Ejecuta OCR en una imagen usando Python y observa los puntajes de confianza. + Aprende cómo filtrar palabras de baja confianza, establecer umbrales y manejar casos + límite. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: es +og_description: Ejecuta OCR en una imagen con Python, inspecciona los niveles de confianza + y filtra las palabras de baja confianza. Este tutorial te guía a través de un ejemplo + completo y ejecutable. +og_title: Ejecuta OCR en una imagen con Python – Guía completa +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Ejecutar OCR en una imagen con Python – Guía completa paso a paso +url: /es/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ejecutar OCR en Imagen con Python – Guía Completa Paso a Paso + +¿Alguna vez necesitaste **ejecutar OCR en imagen** pero no estabas seguro de cómo obtener texto fiable de ella? No estás solo: muchos desarrolladores se topan con el mismo problema cuando las palabras extraídas se ven temblorosas y la puntuación de confianza es un misterio. + +En esta guía nos sumergiremos directamente en una solución funcional: verás cómo ejecutar OCR en imagen, leer la confianza general y extraer cualquier palabra de baja confianza que pueda requerir revisión manual. Al final tendrás un script reutilizable, comprenderás por qué cada línea es importante y sabrás cómo ajustar el umbral de confianza para tus propios proyectos. + +## Qué Cubre este Tutorial + +Recorreremos todo el flujo de trabajo—desde cargar una imagen hasta imprimir un informe ordenado de palabras que quedaron por debajo del 80 % de confianza. En el camino hablaremos de: + +* Elegir un motor OCR sólido (usaremos **EasyOCR**, una popular biblioteca OCR para Python) +* Interpretar el atributo `confidence` que devuelve cada resultado OCR +* Filtrar palabras con un **umbral de confianza OCR** personalizado +* Extender el script para procesamiento por lotes o motores alternativos como **pytesseract** + +No se requiere experiencia previa en OCR, solo una familiaridad básica con Python y un entorno de trabajo (se recomienda Python 3.9+). + +¿Listo para convertir capturas de pantalla borrosas en texto limpio y buscable? Vamos a comenzar. + +--- + +## ## Cómo Ejecutar OCR en Imagen con Python + +El corazón del tutorial es un fragmento de tres pasos que refleja el código que ya viste. A continuación desglosaremos cada línea, explicaremos el porqué y luego te daremos un script completo listo para copiar y pegar. + +### Paso 1: Instalar e Importar el Motor OCR + +Primero, asegúrate de que la biblioteca OCR esté disponible. **EasyOCR** funciona listo para usar con muchos idiomas y te brinda una puntuación de confianza por palabra. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*¿Por qué EasyOCR?* Incluye un modelo de deep‑learning entrenado con conjuntos de datos diversos, por lo que típicamente obtienes valores de confianza más altos que con el motor más antiguo Tesseract, especialmente en imágenes de calidad mixta. + +> **Consejo profesional:** Si trabajas en un entorno con recursos limitados (p. ej., un contenedor Docker pequeño), `pytesseract` podría ser más liviano, pero perderás parte de la precisión moderna que ofrece EasyOCR. + +### Paso 2: Ejecutar OCR en la Imagen + +Ahora realmente **ejecutamos OCR en imagen**. El método `recognize_image` del ejemplo original se reemplaza con la llamada `readtext` de EasyOCR, que devuelve una lista de tuplas `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Cada entrada en `ocr_results` se ve así: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +El tercer elemento (`0.92` en el ejemplo) es la puntuación de confianza, que varía de 0 a 1. + +### Paso 3: Resumir la Confianza General + +A diferencia del fragmento anterior que imprimía un solo atributo `confidence`, EasyOCR brinda una confianza por palabra. Para obtener una visión general, promediaremos esas puntuaciones: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*¿Por qué promediar?* Te da una rápida comprobación de salud—si la confianza general está por debajo, digamos, del 70 %, probablemente necesites mejorar la imagen (mejor iluminación, pre‑procesamiento, etc.). + +### Paso 4: Listar Palabras de Baja Confianza + +Ahora llega la parte que responde directamente al requisito de “listar palabras cuya confianza esté por debajo del umbral deseado”. Estableceremos un **umbral de confianza OCR** de 0.80 (80 %) por defecto, pero puedes ajustarlo. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +El bucle imprime cada palabra que no alcanzó el umbral, junto con su porcentaje de confianza. Este es el análogo exacto del bucle original `for recognized_word in recognition_result.words`, pero ahora funciona con el formato de salida de EasyOCR. + +--- + +## ## Comprendiendo las Puntuaciones de Confianza de OCR + +La confianza no es un número mágico; es la estimación del modelo sobre cuán seguro está respecto a una transcripción particular. Ten en cuenta lo siguiente: + +| Situación | Confianza Típica | Qué Hacer | +|-----------|-------------------|------------| +| Escaneo claro y de alta resolución | 0.95 – 1.00 | No se necesita trabajo adicional | +| Ligeramente borroso o iluminación desigual | 0.80 – 0.94 | Considera un pre‑procesamiento leve (aumento de contraste) | +| Ruido intenso, texto rotado | < 0.70 | Aplica pre‑procesamiento (deskew, denoise) o cambia a otro motor OCR | + +> **Cuidado:** Algunos idiomas (p. ej., escritura cursiva) naturalmente producen puntuaciones más bajas. Ajusta el umbral en consecuencia. + +### Casos Límite y Variaciones + +1. **Procesamiento por Lotes** – Si necesitas **ejecutar OCR en imagen** en bloque, envuelve la lógica anterior en un bucle que itere sobre un directorio. +2. **Múltiples Idiomas** – Pasa una lista como `['en', 'fr']` a `easyocr.Reader` y el motor detectará ambos. +3. **Motores Alternativos** – ¿Quieres probar **pytesseract**? Sustituye el bloque del lector por: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Luego tendrás que agregar las confidencias por carácter en valores por palabra—un poco más de trabajo pero factible. + +4. **Trucos de Pre‑procesamiento** – Aplicar filtros de OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) puede aumentar la confianza en escaneos ruidosos. + +--- + +## ## Script Completo y Listo para Ejecutar + +A continuación tienes el archivo Python completo que puedes incorporar a tu proyecto. Guárdalo como `ocr_report.py` y ejecuta `python ocr_report.py`. Asegúrate de que la ruta de la imagen apunte a un archivo real. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Salida esperada** (tus números variarán): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Si cada palabra supera el 80 % verás el mensaje amistoso “All words meet the confidence threshold.” en su lugar. + +--- + +## ## Preguntas Frecuentes (FAQ) + +**P: ¿Esto funciona con PDFs?** +R: No directamente. Convierte cada página del PDF a una imagen primero (p. ej., con `pdf2image`) y luego alimenta el PNG/JPEG al script. + +**P: Mis números de confianza son todos bajos—¿qué puedo hacer?** +R: Prueba el pre‑procesamiento de la imagen: aumenta el contraste, elimina el ruido de fondo o rota la imagen a una línea base horizontal. EasyOCR también acepta un parámetro `contrast_ths` que puedes ajustar. + +**P: ¿Puedo exportar los resultados a CSV?** +R: Por supuesto. Después del bucle de baja confianza, escribe `ocr_results` a un `csv.DictWriter` donde cada fila contenga `text`, `confidence` y las coordenadas del cuadro delimitador. + +**P: ¿Existe una versión acelerada por GPU?** +R: EasyOCR usa CUDA automáticamente si hay una GPU compatible y PyTorch instalado. Verifica con `torch.cuda.is_available()` antes de ejecutar el script. + +--- + +## Conclusión + +Acabamos de **ejecutar OCR en imagen** usando Python, inspeccionamos la confianza general y aislamos cualquier palabra de baja confianza que necesite revisión manual. + +## ¿Qué Deberías Aprender a Continuar? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye código completo y ejemplos paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/swedish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..1fd1928a5 --- /dev/null +++ b/ocr/swedish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Extrahera text från en bild med Python OCR på några minuter. Upptäck + flerspråkig bild‑OCR, automatisk språkdetektering i OCR och hur du exakt extraherar + OCR‑text. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: sv +og_description: Extrahera text från bild med Python OCR snabbt. Lär dig flerspråkig + bild‑OCR, automatisk språkdetektering i OCR och hur du extraherar OCR‑text steg + för steg. +og_title: Extrahera text från bild med Python OCR – Komplett guide +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Extrahera text från bild med Python OCR – Komplett guide +url: /sv/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahera text från bild med Python OCR – Komplett guide + +Har du någonsin behövt **extrahera text från bild** men varit osäker på vilket bibliotek som kan hantera flera språk automatiskt? Du är inte ensam—utvecklare frågar ständigt *hur man extraherar OCR‑text* när de arbetar med internationella dokument, kvitton eller skannade flygblad. I den här handledningen går vi igenom ett praktiskt Python‑exempel som inte bara extraherar text från en bild utan också **detekterar språket** i farten, vilket gör flerspråkig bild‑OCR enkel. + +Vi kommer att gå igenom allt från att installera OCR‑paketet till att aktivera **auto detect language OCR**, köra motorn på ett exempelbild och slutligen skriva ut både detekterat språk och den extraherade strängen. I slutet har du ett återanvändbart kodsnutt som du kan lägga in i vilket projekt som helst, oavsett om du bygger en översättningspipeline eller en data‑ingest‑tjänst. + +## Extrahera text från bild – Ställ in miljön + +Innan vi dyker ner i koden, se till att din arbetsstation uppfyller dessa minimikrav: + +- Python 3.8 eller nyare (biblioteket använder typ‑hints som äldre versioner ignorerar) +- `pip` för paket‑hantering +- En bildfil som innehåller text på minst två olika språk (t.ex. engelska + spanska) + +Du kommer också att behöva OCR‑biblioteket som driver denna demo. För denna guide använder vi det fiktiva `ocr`‑paketet, som speglar populära verkliga verktyg som Tesseract eller EasyOCR men erbjuder ett rent Python‑API. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Proffstips:** Om du stöter på behörighetsfel, lägg till `python -m` före kommandot eller använd en virtuell miljö—det håller dina globala site‑packages prydliga. + +## Skapa OCR‑motorninstans + +Nu när biblioteket är klart är det första logiska steget att **skapa en OCR‑motorninstans**. Tänk på motorn som en smart skanner som du kan konfigurera innan du matar in bilder. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Varför skapar vi en motorinstans separat istället för att anropa en statisk metod? Motorobjektet håller konfigurationsstatus (som språkpreferenser) som du kanske vill återanvända över många bilder, vilket sparar dig kostnaden för att återinitiera det varje gång. + +## Aktivera Auto Detect Language OCR + +De flesta OCR‑verktyg kräver att du anger en språkkod—`eng` för English, `spa` för Spanish, och så vidare. Att manuellt gissa språket undergräver syftet med ett **multilingual image OCR**‑arbetsflöde. Lyckligtvis erbjuder `ocr`‑paketet ett *auto detect language OCR*-läge som granskar bilden och väljer den bästa språkmodellen i bakgrunden. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Genom att aktivera **detect language OCR** på detta sätt behöver du inte underhålla en lång lista med språkkoder. Motorn kommer att försöka matcha skriftsystemet den ser—Latin, Cyrillic, Han, etc.—och automatiskt ladda rätt modell. + +## Utför flerspråkig bild‑OCR + +Med motorn förberedd är det dags att faktiskt **extrahera text från bild**. Metoden `recognize_image` accepterar en filsökväg och returnerar ett resultatobjekt som innehåller både den råa texten och det språk som detekterades. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Om du undrar *hur man extraherar OCR‑text* från en PDF istället för en PNG, erbjuder samma motor `recognize_pdf`—byt bara metodnamnet. Den underliggande detekteringslogiken förblir identisk, så du drar nytta av samma **auto detect language OCR**‑funktion. + +## Visa detekterat språk och extraherad text + +Till sist skriver vi ut vad motorn har upptäckt. Resultatobjektet exponerar `detected_language` (en BCP‑47‑tagg som `en` eller `es`) och `text`, som innehåller den råa OCR‑utdata. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Att köra skriptet på vår exempelbild bör ge något liknande: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Observera hur motorn korrekt identifierade English som huvudspråk, men ändå fångade den spanska raden—precis vad du förväntar dig av en robust **multilingual image OCR**‑lösning. + +### Vad händer om detektering misslyckas? + +Ibland kan OCR‑motorn falla tillbaka till ett standardspråk (vanligtvis English) om bilden är suddig eller skriftsystemet är för exotiskt. I sådana fall kan du tvinga en språklista: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Men kom ihåg, att tvinga språk undergräver bekvämligheten med **auto detect language OCR**, så använd det bara när du har en känd delmängd av språk. + +## Vanliga fallgropar och hur du extraherar OCR‑text pålitligt + +Även med auto‑detektering kan några hinder göra dig besvärad: + +1. **Lågre lösning bilder** – OCR‑noggrannheten sjunker kraftigt under 150 dpi. Skala upp eller begär en högupplöst skanning. +2. **Brus och komprimeringsartefakter** – Applicera ett enkelt tröskelfilter (`opencv` eller `Pillow`) innan du matar bilden till motorn. +3. **Blandade skriftsystem på en sida** – Vissa motorer har problem med samtidiga Latin‑ och CJK‑tecken. Dela upp sidan i regioner och kör separata igenkänningar om det behövs. + +Att åtgärda dessa problem förbättrar avsevärt kvaliteten på **extract text from image**‑processen, särskilt när du hanterar verkliga, flerspråkiga dokument. + +## Fullt fungerande exempel + +Nedan är det kompletta, färdiga skriptet som kombinerar alla steg vi diskuterat. Spara det som `multilingual_ocr.py` och kör det från kommandoraden. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Förväntad output** (förutsatt att exempelbilden innehåller English och Spanish text): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Känn dig fri att ersätta `multilang_page.png` med vilken bild som helst som innehåller text på andra språk—tack vare **auto detect language OCR**, kommer skriptet fortfarande ge dig en rimlig språktagg och motsvarande text. + +![Exempel på extrahering av text från bild](https://example.com/ocr-sample.png "Extrahera text från bild") + +## Slutsats + +Du vet nu exakt **hur man extraherar OCR‑text** från en bild, hur man aktiverar **auto detect language OCR**, och hur man hanterar **multilingual image OCR**‑scenarier med minimal kod. Genom att skapa en OCR‑motorninstans, slå på automatisk språkdetection och anropa `recognize_image` kan du pålitligt hämta både språkidentifieraren och den råa texten. + +Vad blir nästa steg? Prova att skicka de extraherade strängarna till ett översättnings‑API, lagra dem i en sökbar databas, eller kombinera flera sidor till en enda PDF‑rapport. Du kan också experimentera med olika OCR‑back‑ends (Tesseract, EasyOCR, Google Vision) samtidigt som du behåller samma hög‑nivå‑arbetsflöde—tack vare det konsekventa **detect language OCR**‑gränssnittet. + +Om du stöter på några konstigheter, gå tillbaka till avsnittet “Common Pitfalls” eller justera bild‑förbehandlingsstegen. Lycka till med kodandet, och må ditt nästa projekt vara fullt av korrekt‑detekterad, perfekt‑extraherad text! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Konvertera bild till text – Utför OCR på bild från URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extrahera text från bild – OCR‑optimering med Aspose.OCR för .NET](/ocr/english/net/ocr-optimization/) +- [igenkänna textbild med Aspose OCR för flera språk](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/swedish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..f3d3d621e --- /dev/null +++ b/ocr/swedish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Extrahera text från bild‑PDF:er med Python OCR. Lär dig hur du snabbt + konverterar skannade dokument till text med asynkron batchigenkänning. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: sv +og_description: Extrahera text från bild‑pdf:er med Python. Denna steg‑för‑steg‑guide + visar hur du konverterar skannade dokument till text med async OCR. +og_title: Extrahera text från PDF med bilder – Python OCR-handledning +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Extrahera text från bild‑PDF – Python‑guide för att konvertera skannade dokument + till text +url: /sv/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahera text från bild‑PDF – Python‑guide för att konvertera skannade dokument till text + +Har du någonsin behövt **extrahera text från bild‑pdf** utan att spendera timmar på att skriva om? I den här guiden visar vi hur du **konverterar skannade dokument till text** med ett enkelt asynkront OCR‑arbetsflöde i Python. + +Om du någonsin har stirrat på en hög med skannade PDF‑filer och tänkt, “Det måste finnas ett snabbare sätt,” så är du på rätt plats. Vi går igenom varje kodrad, förklarar varför varje del är viktig, och täcker även några kantfall du kan stöta på. + +## Vad du kommer att lära dig + +- Hur du startar en OCR‑motor och ställer in igenkänningsspråket. +- Mekanismerna för att mata in en blandad lista med PNG‑ och PDF‑filer i en batch‑igenkännare. +- Kör OCR‑jobbet asynkront så att din app förblir responsiv. +- Hämtar resultaten, parar dem med sina källfiler och skriver ut ren output. + +**Förutsättningar**: Python 3.8+, en grundläggande förståelse för `asyncio` eller `concurrent.futures`, och ett OCR‑bibliotek som exponerar en `OcrEngine`‑klass liknande den i exemplet (t.ex. Aspose.OCR, Tesseract‑wrapper eller en egen wrapper). Ingen tung installation krävs – installera bara biblioteket så är du redo att köra. + +![extract text from images pdf](https://example.com/placeholder.png "Screenshot of OCR output – extract text from images pdf") + +## Extrahera text från bild‑PDF – Konfigurera OCR‑motorn + +Det första du behöver är en OCR‑motorinstans konfigurerad för språket i dina dokument. I vårt fall använder vi franska, men du kan byta till vilket stödjande språk som helst. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Varför detta är viktigt**: Att ställa in språket i förväg förbättrar noggrannheten avsevärt. Motorn använder språk‑specifika ordböcker och teckenmodeller; att mata in fel språk är en vanlig källa till förvrängd output. + +## Förbered fillistan – Bilder och PDF‑filer tillsammans + +Vår batch‑igenkännare kan hantera både rasterbilder (`.png`, `.jpg`) och PDF‑behållare. Mata bara in en vanlig Python‑lista med filsökvägar. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tips**: Håll listan platt; motorn kommer internt att packa upp varje PDF‑sida till bilder innan igenkänning. Om du har tusentals filer, överväg att dela upp listan i mindre batcher för att undvika minnesspikar. + +## Starta asynkron batch‑igenkänning + +Istället för att blockera huvudtråden startar vi OCR‑jobbet i bakgrunden. Metoden returnerar ett `Future` som så småningom kommer att innehålla en lista med `OcrResult`‑objekt. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Hur det fungerar**: Under huven skapar motorn en trådpool (eller en async‑uppgift, beroende på implementation). Detta låter dig fortsätta med annat arbete – som att uppdatera ett UI, hämta fler filer eller logga framsteg – medan den tunga lyftningen sker någon annanstans. + +## Gör något användbart medan OCR körs + +Ett vanligt misstag är att sitta stilla och pollera framtiden i en tight loop. Istället kan du utföra vilket orelaterat arbete som helst. För demonstration skriver vi bara ut en statusrad. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Samla resultat när Future är klar + +När du är redo att samla OCR‑outputen, använd `as_completed` från `concurrent.futures`. Detta mönster fungerar oavsett om du har ett eller flera futures. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Vad du kommer att se**: Varje filsökväg följt av den extraherade ren‑text‑representationen. För PDF‑filer innehåller `result.text` den sammanslagna texten från varje sida. + +### Förväntad output (exempel) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Om du märker saknade tecken, dubbelkolla att språket du angav matchar dokumentets språk, och överväg att förbehandla bilderna (räta upp, öka kontrast) innan du matar dem till motorn. + +## Hantera kantfall och vanliga fallgropar + +| Situation | Vad du ska göra | +|-----------|-----------------| +| **Blandade språk** | Kör en språkdetekteringspass först, skapa sedan separata motorer per språk. | +| **Stora PDF‑filer (> 100 MB)** | Dela upp PDF‑filen i enskilda sidor på disk (t.ex. med `PyPDF2`) och mata in dem som separata poster. | +| **Icke‑latinska skript** | Säkerställ att OCR‑biblioteket innehåller det nödvändiga språkpaketet; vissa bibliotek kräver att du laddar ner extra datafiler. | +| **Prestandaflaskhals** | Öka trådpoolsstorleken (`engine.set_thread_pool_size(8)`) eller byt till en GPU‑accelererad backend om den finns. | +| **Saknad text i lågupplösta bilder** | Förbehandla med OpenCV: `cv2.resize`, `cv2.threshold` och `cv2.medianBlur` för att förbättra läsbarheten. | + +## Fullt fungerande exempel (klar att kopiera och klistra in) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Spara detta som `extract_text_async.py`, ersätt `YOUR_DIRECTORY` med sökvägen till dina filer, installera OCR‑paketet (`pip install your-ocr-lib`), och kör `python extract_text_async.py`. Du bör se konsolutdata som illustrerades tidigare. + +## Nästa steg – Gå bortom grundläggande extraktion + +- **Efterbehandling**: Ta bort extra blanksteg, normalisera Unicode (`unicodedata.normalize`), eller kör en stavningskontroll för att rensa OCR‑brus. +- **Strukturerad output**: Exportera resultat till CSV, JSON eller direkt till en databas för efterföljande sökning. +- **Parallella batcher**: Om du har hundratals filer, starta flera futures och använd en kö för att hålla CPU:n upptagen utan att överbelasta minnet. +- **Integrera med webb‑ramverk**: Koppla detta skript till en Flask‑ eller FastAPI‑endpoint för att erbjuda OCR på begäran som en tjänst. + +--- + +### TL;DR + +Du vet nu hur du **extraherar text från bild‑pdf** med ett minimalt Python‑skript som kör OCR asynkront, vilket låter dig **konvertera skannade dokument till text** medan ditt program förblir responsivt. Experimentera med språkinställningarna, batch‑storlekar och förbehandlingsknep för att få ut varje sista tecken med högsta noggrannhet. + +Har du ett eget twist du vill dela – kanske OCR på handskrivna anteckningar eller en molnbaserad tjänst? Lämna en kommentar, och lycka till med kodningen! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extrahera text från bild med Aspose OCR – Steg‑för‑steg‑guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrahera text från bilder med OCR‑operation på mappar](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extrahera text från bilder med Aspose.OCR – Tillåtna tecken](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..aea747b29 --- /dev/null +++ b/ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Hur man OCR:ar PDF med Python, extraherar text från PDF, konverterar + skannad PDF‑text och ändrar OCR‑språk med bara några rader kod. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: sv +og_description: 'Hur man OCR:ar PDF med Python: en praktisk guide som visar hur du + extraherar text från PDF, konverterar skannad PDF‑text och ändrar OCR‑språk utan + ansträngning.' +og_title: Hur man OCR:ar PDF i Python – Fullständig programmeringshandledning +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Hur man OCR:ar PDF i Python – Komplett steg‑för‑steg‑guide +url: /sv/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man OCR:ar PDF i Python – Komplett steg‑för‑steg‑guide + +Har du någonsin funderat på **hur man OCR:ar PDF**‑filer utan att betala för dyra SaaS‑verktyg? Du är inte ensam. Oavsett om du digitaliserar gamla böcker, hämtar data från fakturor eller bara behöver sökbar text från en skannad rapport, så kan det att behärska PDF‑OCR i Python spara dig timmar av manuellt kopierande. + +I den här handledningen går vi igenom ett kortfattat, fungerande exempel som **extraherar text från PDF**, visar hur du **konverterar skannad PDF‑text** till redigerbara strängar och till och med demonstrerar hur du **byter OCR‑språk** om ditt dokument inte är på engelska. I slutet har du ett återanvändbart kodsnutt som du kan lägga in i vilket projekt som helst. + +## Förutsättningar och installation + +- Python 3.8+ installerat (koden fungerar på 3.9, 3.10 och senare) +- `ocr`‑paketet som tillhandahåller `OcrEngine`‑klassen (du kan installera det via `pip install ocr-lib` – ersätt med det faktiska paketnamnet du använder) +- En PDF‑fil du vill bearbeta; i demon använder vi `high_res_book.pdf` placerad i en mapp som heter `YOUR_DIRECTORY` + +Om du använder en virtuell miljö (starkt rekommenderat), aktivera den först: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Proffstips:** Förvara dina PDF‑filer i en dedikerad `data/`‑katalog för att undvika sökvägsrelaterade problem senare. + +## Steg 1: Skapa en OCR‑motorinstans (Hur man OCR:ar PDF – Initiering) + +Det allra första du måste göra när du vill **utföra OCR på PDF**‑filer är att skapa en instans av motorn. Tänk på motorn som hjärnan som läser varje sida, tolkar tecknen och ger dig tillbaka vanlig text. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Varför detta är viktigt: utan en motor har du ingen kontext för språkinställningar, renderingsalternativ eller PDF‑hantering. `OcrEngine`‑objektet innehåller alla dessa standardvärden och låter dig justera dem senare. + +## Steg 2: Ställ in igenkänningsspråket (Byt OCR‑språk) + +De flesta OCR‑bibliotek har engelska som standard, men vad händer om ditt dokument är på franska, tyska eller till och med japanska? Att byta språk är så enkelt som att anropa `set_recognition_language`. Detta uppfyller kravet **byta OCR‑språk** och ger högre noggrannhet. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Varför du kan behöva detta:** Ett flerspråkigt arkiv innehåller ofta sidor med blandade språk. Att byta språk i farten förhindrar felaktig igenkänning av tecken som “ß” eller “ñ”. + +## Steg 3: Konfigurera PDF‑renderingsalternativ (Konvertera skannad PDF‑text effektivt) + +När du arbetar med skannade PDF‑filer påverkar upplösning och färgläge OCR‑kvaliteten kraftigt. Rendering vid 300 DPI i gråskala är en bra kompromiss för de flesta dokument – tillräckligt hög för att fånga detaljer men låg nog för att hålla minnesanvändningen rimlig. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +De kedjade anropen kan se avancerade ut, men de är bara ett flytande API som returnerar samma options‑objekt varje gång. Om du behöver färg (t.ex. för färgdiagram), ersätt `"grayscale"` med `"color"`. + +## Steg 4: Känn igen PDF‑filen och hämta texten från första sidan (Extrahera text från PDF) + +Nu kommer kärnan i **hur man OCR:ar PDF**: att ge motorn en filsökväg och hämta den igenkända texten. Metoden returnerar en lista med sidresultat; varje resultat innehåller ett `text`‑attribut. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Om du behöver hela dokumentet, iterera över `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Vad händer om PDF‑filen är krypterad? + +Vissa PDF‑filer är lösenordsskyddade. I så fall kan du skicka lösenordet till `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Motorn kommer att dekryptera i farten innan OCR utförs – inga extra steg behövs. + +## Steg 5: Efterbehandling av den extraherade texten (Finjustera extraherad text från PDF) + +Rå OCR‑utdata innehåller ofta radbrytningar, extra mellanslag eller ibland felaktigt igenkända tecken. En snabb rensningsrutin gör den extraherade strängen klar för vidare bearbetning (sökindexering, databasinlagring osv.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Du kan nu säkert **extrahera text från PDF** och mata in den i någon NLP‑pipeline, sökmotor eller enkel `open(...).write()`‑operation. + +## Bonus: Batch‑bearbetning av flera PDF‑filer (Skala OCR på PDF) + +Om du har en mapp full av skannade PDF‑filer, omslut logiken i en loop: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Detta kodsnutt visar hur du **utför OCR på PDF**‑filer i bulk, ett vanligt behov i digitaliseringsprojekt. + +## Förväntad output + +Att köra enkelsidsexemplet (Steg 4) bör skriva ut något liknande: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Om du bearbetade en flersidig bok kommer konsolen att visa varje sidas rensade text, och batch‑skriptet kommer att lämna en `.txt`‑fil bredvid varje PDF. + +## Vanliga fallgropar och hur du undviker dem + +| Problem | Symptom | Lösning | +|-------|----------|-----| +| Låguppslöstad käll‑PDF | Slarviga tecken, saknade ord | Öka DPI (`set_dpi(400)` eller högre) | +| Fel språk inställt | Många okända symboler, särskilt bokstäver med diakritiska tecken | Använd `engine.set_recognition_language(ocr.Language.FRENCH)` eller motsvarande enum | +| Stor PDF som orsakar minnesfel | `MemoryError` eller krasch efter några sidor | Bearbeta sidor i delar (`engine.recognize_pdf(..., max_pages=10)`) | +| Saknade teckensnitt i PDF‑filen | Tomt resultat för vissa sidor | Säkerställ att PDF‑filen faktiskt innehåller rasterbilder; vissa PDF‑filer är enbart vektorgrafik och kräver annan hantering | + +## Bildillustration + +Nedan är en snabb visuell översikt av arbetsflödet. Alt‑texten är avsiktligt SEO‑vänlig. + +![arbetsflödesdiagram för hur man OCR:ar PDF som visar motorinitiering, språkval, renderingsalternativ, igenkänning och textutdrag](/images/ocr-workflow.png) + +*Diagrammet krävs inte för att koden ska köras, men det hjälper visuella inlärare att se var varje steg passar in.* + +## Slutsats + +Vi har gått igenom **hur man OCR:ar PDF**‑filer i Python från början till slut: skapa en OCR‑motor, **byta OCR‑språk**, konfigurera rendering för att **konvertera skannad PDF‑text**, och slutligen **extrahera text från PDF** för vidare användning. Det kompletta, körbara exemplet är redo att läggas in i vilket projekt som helst, och det valfria batch‑skriptet visar hur du skalar lösningen. + +Sedan kan du vilja utforska: + +- Lägga till **utför OCR på PDF** för flerspråkiga arkiv genom att loopa över en språklista. +- Integrera den extraherade texten med Elasticsearch för fulltextsökning. +- Använda OCR för att skapa sökbara PDF‑filer genom att bädda in textlagret tillbaka i originalfilen (många bibliotek erbjuder en `save_as_searchable_pdf`‑metod). + +Känn dig fri att experimentera, justera DPI‑inställningar eller byta till en annan OCR‑backend. Grunderna förblir desamma, och du har nu en solid grund att bygga vidare på. + +Lycka till med kodandet, och må dina skannade dokument äntligen bli sökbara! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Känn igen PDF‑text – OCR‑operationer med Aspose.OCR för Java](/ocr/english/java/ocr-operations/) +- [Hur man OCR:ar bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Hur man OCR:ar PDF i .NET med Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..ee88bc872 --- /dev/null +++ b/ocr/swedish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-06 +description: Hur man OCR:ar PDF och skapar sökbara PDF-filer från bilder med Python. + Lär dig att lägga till sökbar text och konvertera bild till PDF/A på några minuter. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: sv +og_description: Hur man OCR:ar PDF steg för steg. Lär dig att lägga till sökbar text + och konvertera bild till PDF/A med ett enkelt Python‑skript. +og_title: Hur man OCR:ar PDF – Snabbguide för att skapa sökbara PDF-filer +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Hur man OCR:ar PDF i Python – Skapa en sökbar PDF från bilder +url: /sv/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så OCR:ar du PDF – Gör skannade bilder till sökbara PDF-filer + +Har du någonsin undrat **hur man OCR:ar PDF**‑filer när allt du har är en skannad bild av en faktura eller ett kvitto? Du är inte ensam. På många kontor kommer den inkommande pappersarbetet som platta PNG‑ eller JPEG‑filer, och nästa steg—att göra innehållet sökbart—känns som en svart låda. + +Den goda nyheten? Med bara några rader Python kan du **skapa sökbara PDF**‑filer, **lägga till sökbar text**, och till och med **konvertera bild till PDF/A** för långtidsarkivering. I den här handledningen går vi igenom varje steg, förklarar varför det är viktigt, och ger dig ett färdigt skript som du kan slänga in i vilket projekt som helst. + +> **Proffstips:** Samma metod fungerar för flersidiga skanningar; loopa bara över filerna så sköter motorn det tunga arbetet. + +--- + +## Vad du behöver + +Innan vi dyker ner, se till att du har följande på din maskin: + +| Krav | Varför det är viktigt | +|------|-----------------------| +| Python 3.9 eller nyare | Modern syntax och bättre biblioteksstöd | +| `pdfium`‑baserad OCR‑motor (t.ex. `pdfocr` eller ett kommersiellt SDK) | Hantera både bildigenkänning och PDF/A‑generering | +| En bildfil (PNG, JPEG, TIFF) som du vill omvandla till en sökbar PDF | Källan till texten | +| Skrivbehörighet till mål‑mappen | Så skriptet kan spara den nya PDF‑filen | + +Om du ännu inte har installerat OCR‑SDK:t, kör: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Det är allt—inga komplexa systemberoenden, bara en pip‑installation. + +--- + +## Så OCR:ar du PDF – Översikt + +På en hög nivå består processen av tre enkla åtgärder: + +1. **Känn igen** texten i bilden samtidigt som den ursprungliga grafiken bevaras. +2. **Exportera** OCR‑resultatet tillsammans med originalbilden som en **sökbar PDF/A** (det arkivvänliga PDF‑formatet). +3. **Validera** att den resulterande filen innehåller ett markerbart, sökbart textlager ovanpå originalbilden. + +Nedan ser du varje steg i kod, med förklaringar till *varför* bakom kommandona. + +--- + +## Steg 1: Känn igen text från bilden + +Först ber vi OCR‑motorn att läsa pixlarna och returnera ett resultatobjekt som innehåller både den råa bilden och den extraherade texten. Tänk på det som att motorn “läser” fakturan åt dig. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Varför detta är viktigt + +- Att bevara grafik betyder att den visuella layouten (tabeller, logotyper, stämplar) förblir exakt som skannern fångade den. +- `result`‑objektet innehåller vanligtvis ett dolt textlager som vi senare kommer att bädda in i PDF‑filen. +- Att använda `recognize_image` istället för `recognize_pdf` undviker ett extra konverteringssteg, vilket snabbar upp bearbetningen för enkelsidiga bilder. + +#### Vanliga varianter + +- Om du har en **flersidig TIFF**, skicka filvägen direkt; de flesta motorer behandlar varje sida som en separat bild. +- För PDF‑filer som redan innehåller bilder kan du anropa `engine.recognize_pdf("file.pdf")` och hoppa över detta steg helt. + +--- + +## Steg 2: Exportera OCR‑resultat som sökbar PDF/A + +Nu tar vi `result` från steg 1 och instruerar motorn att skriva en ny fil. Den viktiga flaggan här är *PDF/A*—ISO‑standardversionen av PDF som är avsedd för långtidsbevarande. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Varför detta är viktigt + +- **Sökbar PDF**: Utdatafilen innehåller ett dolt, markerbart textlager. Du kan nu använda Ctrl + F i dokumentet. +- **PDF/A‑kompatibilitet**: Vissa organisationer (juridik, ekonomi) kräver PDF/A för revisionsspår; detta steg uppfyller den regeln automatiskt. +- Metoden **lägger också till sökbar text** utan att platta till bilden, så den visuella kvaliteten förblir perfekt. + +#### Specialfall: Behöver du en vanlig PDF istället? + +Om du inte bryr dig om PDF/A, ersätt `save_as_pdfa` med `save_as_pdf`. Resten av arbetsflödet förblir detsamma. + +--- + +## Steg 3: Verifiera den sökbara PDF‑filen + +En snabb kontroll sparar dig från mystiska buggar senare. Öppna den genererade filen i någon PDF‑visare, försök markera ett ord och använd sökfunktionen. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Förväntad utskrift + +När du kör skriptet skriver konsolen ut: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +När du öppnar filen bör du se den ursprungliga fakturabildern med ett svagt, osynligt textlager. Markera ett ord så ser du att det är markerbart—**det är den sökbara texten** du just lagt till. + +--- + +## Lägg till sökbar text i befintliga PDF‑filer (Bonus) + +Ibland har du redan en PDF men behöver **lägga till sökbar text** i den. Samma motor kan överlagra OCR‑resultat på en befintlig PDF: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Här sammanslår `apply_to` det dolda lagret med originalsidorna, så att du kan **skapa en sökbar PDF** utan att skanna om. + +--- + +## Vanliga fallgropar och tips + +| Fallgrop | Hur du undviker det | +|----------|---------------------| +| **Lågre upplösning på källbilder** (< 150 dpi) | Skala upp eller begär en skanning med högre upplösning; OCR‑noggrannheten sjunker dramatiskt under 150 dpi. | +| **Saknad språkdata** | Installera lämpliga språkpaket för din OCR‑motor (`pip install pdfocr[eng,spa]`). | +| **Målmappen är inte skrivbar** | Kör skriptet med tillräckliga rättigheter eller välj en annan katalog. | +| **PDF/A‑validering misslyckas** | Se till att du inte bäddar in osupporterade typsnitt eller JavaScript; de flesta SDK:er hanterar detta automatiskt när du använder `save_as_pdfa`. | + +--- + +## Fullt skript – En‑filslösning + +Nedan är ett fristående skript som binder ihop allt. Kopiera‑klistra in det, ersätt platshållar‑sökvägarna, och du är redo att **konvertera bild till PDF/A** på sekunder. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Vad detta skript gör:** +1. Laddar OCR‑motorn. +2. Läser den valda bilden och extraherar texten. +3. Skriver en **sökbar PDF/A** som du omedelbart kan distribuera eller arkivera. + +Känn dig fri att paketera `main`‑logiken i en funktion som bearbetar en hel mapp—iterera bara över `os.listdir()` och upprepa de tre stegen för varje fil. + +--- + +## Nästa steg & relaterade ämnen + +Nu när du har bemästrat **hur man OCR:ar PDF**, överväg att utforska dessa uppföljningsidéer: + +- **Batch‑bearbetning:** Använd `concurrent.futures` för att OCR:a dussintals fakturor parallellt. +- **Metadata‑injektion:** Lägg till skapandedatum eller fakturanummer i PDF‑metadata för enklare indexering. +- **Hybrid‑PDF‑filer:** Kombinera sökbar text med inbäddade originalbilder för en “digital tvilling” av pappersdokumentet. +- **Alternativa utdata:** Exportera till **DOCX** eller **HTML** om nedströms system behöver redigerbara format. + +--- + +## Sammanfattning + +Kort sagt, du vet nu **hur man OCR:ar PDF**‑filer genom att omvandla en enkel bild till en **sökbar PDF/A** med bara tre rader Python. Skriptet sköter det tunga arbetet, bevarar den ursprungliga grafiken och ger dig ett standard‑kompatibelt dokument som du kan söka i, arkivera eller dela. + +Prova det med dina egna fakturor, kvitton eller skannade kontrakt. Om du stöter på problem, lämna en kommentar nedan eller kolla SDK:ens officiella dokumentation—de är ofta fulla med extra exempel. Lycka till med kodandet, och njut av den nya förmågan att göra vilken bild som helst omedelbart sökbar! + +![Exempel på hur man OCR:ar PDF som visar originalbild och sökbar PDF‑överlappning](placeholder.png "Exempel på hur man OCR:ar PDF") + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/swedish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..1e50e1368 --- /dev/null +++ b/ocr/swedish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-06-06 +description: Hur man OCR:ar PDF med Aspose OCR Cloud. Lär dig att extrahera text från + PDF, konvertera PDF‑sidor till PNG och spara PDF‑sidbilder i Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: sv +og_description: Hur man OCR:ar PDF med Aspose OCR Cloud. Denna guide visar hur man + extraherar ren text från PDF, konverterar PDF-sidor till PNG och sparar PDF-sidbilder. +og_title: Hur man OCR:ar PDF med Aspose OCR Cloud – Steg för steg +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Hur man OCR:ar PDF med Aspose OCR Cloud – Komplett guide +url: /sv/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man OCR:ar PDF med Aspose OCR Cloud – Komplett guide + +Har du någonsin undrat **hur man OCR:ar PDF**-filer utan att kämpa med tunga skrivbordsverktyg? Du är inte ensam—många utvecklare stöter på den muren när de behöver ett snabbt, programatiskt sätt att hämta text från skannade dokument. Den goda nyheten? Med Aspose OCR Cloud kan du **extrahera text från PDF**, omvandla varje sida till en PNG och till och med **spara PDF‑sidbilder** för senare bruk, allt från ett snyggt Python‑skript. + +I den här handledningen går vi igenom allt du behöver veta: från att installera SDK:n, licensiera motorn och känna igen flersidiga PDF‑filer, till att extrahera ren text, konvertera sidor till PNG och spara dessa bilder på disk. I slutet har du ett återanvändbart kodsnutt som du kan lägga in i vilket projekt som helst som behöver **hur man OCR:ar PDF**‑funktionalitet. + +## Vad du behöver + +- **Python 3.8+** (koden fungerar även på 3.10 och nyare) +- Ett Aspose OCR Cloud‑konto – du får en gratis provlicensfil (`Aspose.OCR.lic`) +- `asposeocrcloud`‑paketet (`pip install asposeocrcloud`) +- En skannad, flersidig PDF som du vill bearbeta + +Det är allt. Inga extra binärer, inga inhemska beroenden, bara ren Python. + +## Så OCR:ar du PDF – Installation och licens + +Innan du kan anropa några OCR‑metoder måste du berätta för SDK:n vem du är. Aspose använder en lättviktig licensfil som du placerar någonstans där ditt skript kan nå den. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Proffstips:* Om du hoppar över licenssteget kommer SDK:n fortfarande att fungera men kommer att lägga in ett litet vattenstämpel i utdata‑bilderna. Inte idealiskt för produktion. + +## Steg 2: Installera Aspose OCR Cloud Python‑SDK + +Öppna en terminal och kör: + +```bash +pip install asposeocrcloud +``` + +Paketet hämtar alla nödvändiga beroenden (requests, pillow, osv.) så du behöver inte leta efter något annat. + +## Steg 3: Skapa en OCR‑motor och välj ett språk + +Motorn är hjärtat i operationen. Du kan ange vilket språk som helst som stöds av Aspose; engelska fungerar i de flesta fall. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Varför ange språk? För att OCR‑motorn använder språk‑specifika ordböcker för att förbättra noggrannheten. Om du bearbetar franska PDF‑filer, byt bara `ENGLISH` mot `FRENCH`. + +## Steg 4: Peka på din flersidiga PDF + +Ge motorn den fullständiga sökvägen till filen du vill bearbeta. Relativa sökvägar fungerar så länge de kan lösas från skriptets arbetskatalog. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Se till att filen är läsbar; annars får du ett `FileNotFoundError`. + +## Steg 5: Kör OCR – du får en lista med resultat + +Att anropa `recognize_pdf` returnerar en lista där varje element motsvarar en sida i käll‑PDF‑filen. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Varje `OcrResult` innehåller två praktiska egenskaper: + +* `text` – den rena textrepresentationen av sidan (perfekt för **extrahera ren text pdf**) +* `image` – ett Pillow `Image`‑objekt av den renderade sidan (perfekt för **konvertera pdf sida png**) + +## Steg 6: Extrahera text från PDF och konvertera sidor till PNG + +Nu loopar vi igenom resultaten, skriver ut den extraherade texten och sparar en PNG‑version av varje sida. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Förväntad konsolutdata + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Du kommer också att hitta `page_1.png`, `page_2.png`, … i `YOUR_DIRECTORY`. Det är de rasteriserade sidbilderna som du kan mata in i efterföljande bildbehandlings‑pipelines. + +## Steg 7: Spara PDF‑sidbilder (valfri efterbehandling) + +Om du bara behöver bilderna och inte texten kan du hoppa över raden `print(res.text)`. Omvänt, om du vill lagra texten i separata `.txt`‑filer, lägg bara till en liten utskrift: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Detta lilla tillägg visar hur enkelt det är att **spara PDF‑sidbilder** samtidigt som du bevarar det extraherade innehållet. + +## Fullt fungerande exempel + +När vi sätter ihop allt, här är det kompletta skriptet som du kan kopiera‑och‑klistra in i `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Kör det med: + +```bash +python ocr_pdf.py +``` + +Du bör se en konsolutskrift av varje sidas text och en serie PNG‑filer + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man OCR:ar PDF i .NET med Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Känn igen PDF‑text – OCR‑operationer med Aspose.OCR för Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Konvertera bilder till PDF C# – Spara flersidig OCR‑resultat](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/swedish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..99752e47f --- /dev/null +++ b/ocr/swedish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Hur man förbehandlar bilder för OCR med Python. Lär dig att binarisera + bild med Otsu, hur man räta upp skannade dokument och förbättra OCR‑noggrannheten + för tysk text. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: sv +og_description: Hur man förbehandlar bilder för OCR i Python. Denna handledning visar + hur man binariserar en bild med Otsu, hur man räta upp skannade dokument och hur + man förbättrar OCR‑noggrannheten för tyska bilder. +og_title: Hur man förbehandlar bilder för OCR – Komplett Python‑guide +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Hur man förbehandlar bilder för OCR – Komplett Python‑guide +url: /sv/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så förbehandlar du bilder för OCR – Komplett Python‑guide + +Har du någonsin undrat **hur man förbehandlar bilder för OCR** så att texten blir kristallklar? Du är inte ensam. Skannade dokument—särskilt brusiga tyska sidor—kan vara en mardröm för vilken OCR‑motor som helst. Den goda nyheten? Några smarta förbehandlingssteg kan förvandla en suddig, prickig skanning till en ren, maskinläsbar bild. + +I den här handledningen går vi igenom ett praktiskt exempel som visar **hur man förbehandlar bilder för OCR** med Python. Du lär dig att **binarisera bild med Otsu**, **hur man deskewar skannade dokument**, och övergripande **hur man förbättrar OCR‑noggrannhet** när du behöver **extrahera text från tyska bild**‑filer. Inga onödiga detaljer, bara ett fungerande skript du kan kopiera‑klistra idag. + +## Vad du behöver + +- **Python 3.9+** (vilken som helst nyare version fungerar) +- Ett OCR‑bibliotek som exponerar en `OcrEngine`‑klass – för demonstrationen antar vi ett generiskt `ocr`‑paket. Installera det med `pip install ocr-lib`. +- En brusig tysk skanning (`noisy_german_scan.tif`) som du vill testa mot. +- En grundläggande förståelse för Python‑funktioner (om du har skrivit ett `def` tidigare, är du klar). + +> **Proffstips:** Om du använder ett annat OCR‑SDK (t.ex. Tesseract via `pytesseract`), förblir koncepten desamma—anpassa bara metodnamnen. + +## Översikt av lösningen + +1. **Skapa en OCR‑motorinstans.** +2. **Ställ in igenkänningsspråket till tyska.** +3. **Bygg en anpassad förbehandlingspipeline** som inkluderar deskewing, denoising, binarisering (Otsu) och kontrastutsträckning. +4. **Anslut pipeline:n till motorn** så att varje bild automatiskt passerar igenom den. +5. **Kör OCR** på en brusig tysk skanning. +6. **Skriv ut den extraherade texten** för att verifiera resultatet. + +Nedan bryter vi ner varje steg, förklarar **varför** det är viktigt, och visar exakt den kod du behöver. + +![exempel på hur man förbehandlar bilder för OCR](image.png "exempel på hur man förbehandlar bilder för OCR") + +## Steg 1: Skapa en OCR‑motorinstans + +Först och främst—utan en motor händer ingenting. `OcrEngine`‑objektet är ingångspunkten som koordinerar all senare bearbetning. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Varför detta är viktigt:* Initiering av motorn sätter upp interna resurser (som språkmodeller) och ger dig en ren startpunkt för att senare fästa en anpassad pipeline. + +## Steg 2: Ställ in igenkänningsspråket till tyska + +OCR‑noggrannhet är starkt språkberoende. Genom att tala om för motorn att förvänta sig tyska aktiverar du rätt teckenuppsättning och språkmodell. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Om du hoppar över detta kan motorn defaulta till engelska och felaktigt känna igen umlauter (ä, ö, ü) samt ß‑tecknet—vanliga fallgropar när du arbetar med tyska skanningar. + +## Steg 3: Bygg en anpassad förbehandlingspipeline + +Detta är hjärtat i **hur man förbehandlar bilder för OCR**. Vi kedjar fyra transformationer: + +| Transformation | Vad den gör | Varför den hjälper | +|----------------|--------------|--------------------| +| **Deskew** | Roterar bilden tillbaka till horisontell (max 5°) | Skanningar är sällan perfekt inriktade; deskewing tar bort lutning som förvirrar teckensegmentering. | +| **Denoise** | Minskar slumpmässiga fläckar (styrka 0.7) | Brus skapar falska kanter som OCR‑motorn kan tolka som tecken. | +| **Binarize (Otsu)** | Konverterar till svart‑vitt med Otsus metod | En ren binär bild ger motorn en skarp kontrast mellan förgrund (text) och bakgrund. | +| **Contrast Stretch** | Utökar det dynamiska omfånget | Förbättrar läsbarheten av svaga streck, särskilt på gamla dokument. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Så deskewar du skannade dokument + +`deskew`‑anropet ovan är det konkreta svaret på **hur man deskewar skannade dokument**. Internt uppskattar det den dominerande textradens vinkel via Hough‑transform och roterar bilden tillbaka. Om dina dokument är roterade mer än 5°, öka `max_angle`, men var försiktig med över‑rotationsartefakter. + +### Binarisera bild med Otsu + +Raden `binarize(method="otsu")` svarar direkt på frågan **binarisera bild med otsu**. Otsus algoritm beräknar ett tröskelvärde som minimerar intra‑klassvarians, vilket är perfekt för dokument med bimodala histogram (mörk text vs. ljus bakgrund). + +## Steg 4: Anslut pipeline:n till motorn + +Nu säger vi åt OCR‑motorn att köra varje inkommande bild genom den pipeline vi just byggt. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Varför detta är viktigt:* Utan registrering skulle motorn bearbeta den råa skanningen och ignorera all den rengöring vi just konfigurerat. Detta steg säkerställer **hur man förbättrar OCR‑noggrannhet** genom att tillämpa samma förbehandling konsekvent. + +## Steg 5: Känn igen text från en brusig tysk skanning + +Dags att sätta ihop allt. Vi matar motorn med en brusig tysk bild och låter den göra det tunga arbetet. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Om du är nyfiken på prestanda kan du tidtaga anropet: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Steg 6: Skriv ut den igenkända texten + +Till sist skriver vi ut den extraherade strängen. Detta är det direkta svaret på **extrahera text från tysk bild**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Förväntad utdata + +Om exempel‑skanningen innehåller meningen “Die schnelle braune Füchsin springt über den faulen Hund.” bör du se något liknande: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Om utskriften fortfarande innehåller förvrängda tecken, överväg att justera `denoise`‑styrkan eller öka `max_angle` för deskewing. + +## Vanliga fallgropar & hur man hanterar dem + +- **Saknad språkmodell:** Att glömma `set_recognition_language(Language.GERMAN)` resulterar ofta i saknade umlauter. Dubbelkolla anropet. +- **Över‑brusreducering:** En styrka över 0.9 kan radera tunna streck, särskilt i äldre typsnitt. Håll dig till 0.5‑0.7 för de flesta fall. +- **Fel filformat:** Vissa OCR‑motorer hakar på fler‑sidiga TIFF‑filer. Om du har ett fler‑sidigt dokument, dela upp det i en‑sidiga filer först. +- **Pipeline‑ordning:** Den visade ordningen (deskew → denoise → binarize → contrast) är avsiktlig. Att binarisera före denoise kan låsa in brus; denoise alltid först. + +## Utöka pipeline:n (Vad kommer härnäst?) + +Nu när du har en solid bas kan du vilja: + +- **Lägg till en morfologisk öppning** för att rensa små fläckar (`.morph_open(kernel=3)`). +- **Integrera en språkmodell** för efterbearbetningskorrigering (`ocr_engine.apply_spellcheck()`). +- **Parallellisera batch‑bearbetning** för stora datamängder med `concurrent.futures`. + +Alla dessa är naturliga utökningar som behåller kärnidén **hur man förbehandlar bilder för OCR** samtidigt som de ytterligare ökar **hur man förbättrar OCR‑noggrannhet**. + +## Slutsats + +Vi har precis gått igenom **hur man förbehandlar bilder för OCR** från början till slut: skapa en motor, ställ in tyska som språk, bygg en pipeline som **binarisera bild med Otsu**, **hur man deskewar skannade dokument**, och slutligen **extrahera text från tysk bild** med högre förtroende. Genom att följa de sex stegen ovan kommer du märka en påtaglig förbättring i igenkänningskvaliteten—slut på oändliga manuella korrigeringar. + +Kör skriptet med dina egna skanningar, experimentera med parametrarna, och låt resultaten tala för sig själva. Har du frågor om en specifik förbehandlingsjustering? Lämna en kommentar så dyker vi djupare tillsammans. + +Lycka till med kodandet, och må din OCR alltid vara exakt! + +## Vad du bör lära dig härnäst? + +De följande handledningarna täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Hur man ställer in tröskelvärde i OCR‑bildigenkänning](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Hur man OCR:ar bild – Utför OCR på bild i OCR‑bildigenkänning](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..07ff30aa3 --- /dev/null +++ b/ocr/swedish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-06-06 +description: OCR PNG-bild med Python – lär dig hur du extraherar text från en bild, + kör ett Python OCR‑exempel och läs även antik grekisk text enkelt. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: sv +og_description: OCR PNG-bild i Python förklarad. Den här guiden visar hur man extraherar + text från en bild, kör ett Python‑OCR‑exempel och läser forngrekiska med lätthet. +og_title: OCR PNG-bild i Python – Komplett handledning +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR PNG‑bild i Python – Fullständig steg‑för‑steg‑guide +url: /sv/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG-bild i Python – Fullständig steg‑för‑steg‑guide + +Har du någonsin undrat hur man **OCR PNG image** filer direkt från ett Python‑script? Kanske har du en mapp full av skannade antika manuskript och du behöver **extract text from image** filer utan att manuellt skriva in allt. Den goda nyheten är att du inte behöver en doktorsexamen i datorseende—bara några rader kod och rätt bibliotek, så kommer du att läsa antik grekiska på sekunder. + +I den här handledningen går vi igenom ett **python OCR example** som känner igen text från en PNG, sätter språket till grekisk polytonisk, och skriver ut resultatet. I slutet vet du exakt hur man **recognize image text**, hanterar vanliga fallgropar, och anpassar skriptet för andra språk eller bildformat. + +## Vad du kommer att lära dig + +- Installera och konfigurera ett Python OCR‑bibliotek (pytesseract + Tesseract OCR) +- Skapa en OCR‑motorinstans och ladda en PNG‑fil +- Ställ in igenkänningsspråket till grekisk polytonisk så att du kan **read ancient greek** +- Skriv ut den igenkända texten och felsök vanliga problem +- Utöka skriptet för att batch‑processa flera PNG‑filer eller byta till ett annat språk + +### Förutsättningar + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | Modern syntax och typindikeringar | +| `pytesseract` package | Tunn omslag runt Tesseract‑motorn | +| Tesseract OCR binaries (≥ 5.0) | Den faktiska motorn som utför det tunga arbetet | +| Greek language data (`grc.traineddata`) | Behövs för att **read ancient greek** korrekt | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Vårt mål för **ocr png image**‑demo | + +Du kan installera Python‑delen med: + +```bash +pip install pytesseract Pillow +``` + +Och på Ubuntu/macOS skulle du lägga till själva motorn: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Glöm inte att ladda ner den grekiska polytoniska träningsdatan: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Sökvägen kan skilja sig; justera `TESSDATA_PREFIX` om det behövs.)* + +--- + +## OCR PNG-bild: Skapa motorinstansen + +Det första vi behöver är ett objekt som kommunicerar med Tesseract. I `pytesseract` nås motorn via modul‑nivåfunktioner, men för tydlighetens skull kommer vi att omsluta den i en liten klass. Detta speglar “engine”-konceptet du såg i det ursprungliga kodsnutten. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Varför omsluta den?** +- Behåller det offentliga API:et identiskt med kodsnutten du började med, vilket gör migration smärtfri. +- Gör det möjligt att lägga till loggning eller felhantering senare utan att röra huvudflödet. +- Visar god OOP‑praxis—något som erfarna utvecklare uppskattar. + +--- + +## Extrahera text från bild: Ställ in språket till grekisk polytonisk + +Nu när vi har en motor måste vi tala om för den vilket språk som förväntas. Grekisk polytonisk använder diakritiska tecken som inte täcks av den standard “greek”-datan, så vi pekar Tesseract på den tränade filen `grc`. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Om du någonsin vill **extract text from image** filer på ett annat språk, ersätt bara `"grc"` med `"eng"` för engelska, `"fra"` för franska osv. Samma rad fungerar för alla språk du har installerat. + +--- + +## Känn igen bildtext: Kör OCR på en PNG + +Med språket inställt matar vi PNG‑filen till motorn. Det ursprungliga exemplet använde en hårdkodad sökväg; vi gör det lite mer flexibelt genom att använda `Path`‑objekt. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Tips & kantfall** +- **File not found** – omslut anropet i ett `try/except FileNotFoundError` för att ge ett vänligt meddelande. +- **Low‑resolution PNG** – överväg förbehandling (t.ex. storleksändring, binarisering) med Pillow före OCR. +- **Non‑Greek text** – Tesseract kommer fortfarande att försöka avkoda, men noggrannheten sjunker kraftigt. Matcha alltid språket. + +--- + +## Skriv ut den igenkända texten + +Till sist skriver vi ut resultatet. I ett riktigt projekt kan du skriva till en databas, en CSV‑fil, eller till och med föra in det i en översättningspipeline. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +När du kör skriptet mot en klar skanning av en antik grekisk inskription bör du se något liknande: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Om utskriften ser förvrängd ut, dubbelkolla att filen **greek.traineddata** finns i rätt mapp och att PNG‑filen inte är för brusig. + +--- + +## Fullt fungerande exempel (alla steg i ett skript) + +Nedan är det kompletta, färdiga programmet. Spara det som `ocr_greek.py` och kör `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Förväntad utskrift** (avkortad för korthet): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Om du ser de korrekta grekiska tecknen, grattis—du har framgångsrikt utfört en **ocr png image**‑operation i Python! + +--- + +## Vanliga frågor & pro‑tips + +### Hur förbättrar jag noggrannheten på en brusig PNG? + +- Konvertera bilden till gråskala: `img = img.convert('L')` +- Applicera ett binärt tröskelvärde: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Skala upp med `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Dessa steg förvandlar ofta en **recognize image text**‑mardröm till ett rent resultat. + +### Kan jag bearbeta en hel mapp med PNG‑filer? + +Absolut. Omslut anropet `recognize_image` i en `for`‑loop över `Path.glob("*.png")`. Spara varje resultat i en dictionary eller skriv till en CSV för senare analys. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Vad händer om jag bara behöver extrahera siffror? + +Skicka en anpassad **config**‑sträng till `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +På så sätt kan du **extract text from image** filer som innehåller tabeller, serienummer eller tidsstämplar. + +### Finns det ett sätt att få förtroendesiffror? + +Ja—använd `pytesseract.image_to_data` som returnerar en TSV med förtroende per ord. Du kan filtrera bort lågt förtroende‑token innan du sätter ihop den slutgiltiga strängen. + +--- + +## Utöka handledningen + +Nu när du har bemästrat grunderna, överväg att utforska dessa relaterade ämnen: + +- **Batch OCR with multiprocessing** – snabba upp stora korpusar av PNG‑filer. +- **Hybrid OCR + NLP pipelines** – översätt automatiskt den extraherade antika grekiskan till modern engelska. +- **Alternative engines** – prova `easyocr` eller `opencv`‑baserade metoder för specifika användningsfall. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, eller AWS Textract för serverlös skalning. + +Var och en av dessa bygger på det grundläggande **python ocr example** vi just gick igenom, så du kommer känna dig bekväm att dyka djupare. + +## Slutsats + +Vi har tagit ett enkelt kodsnutt och gjort om det till ett robust **ocr png image**‑arbetsflöde i Python. Genom att skapa en `OcrEngine`, sätta språket till grekisk polytonisk, mata in en PNG och skriva ut resultatet, vet du nu hur man **extract text from image** filer, **recognize image text**, och till och med **read ancient greek**. + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extrahera text från bild med Aspose OCR – steg‑för‑steg‑guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Hur man ställer in tröskelvärde i OCR‑bildigenkänning](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Känna igen textbild med Aspose OCR för flera språk](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/swedish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..102fb2b34 --- /dev/null +++ b/ocr/swedish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR-handledning som visar hur man känner igen bildtext, utför + högupplöst OCR och extraherar spansk text med GPU-accelererad OCR. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: sv +og_description: Python OCR-handledning som guidar dig genom att känna igen bildtext, + högupplöst OCR och extrahera spansk text med GPU-acceleration. +og_title: Python OCR-handledning – GPU‑accelererad textigenkänning +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR-handledning – Känn igen bildtext med GPU-acceleration +url: /sv/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR‑handledning – Läs av bildtext med GPU‑acceleration + +Har du någonsin undrat hur man **läser av bildtext** i ett Python‑skript utan att spendera timmar på att justera inställningar? Du är inte ensam. I den här **python ocr‑handledningen** visar vi dig ett rent, end‑to‑end‑sätt att extrahera spansk text från en högupplöst bild, och vi lägger till GPU‑acceleration så att processen går blixtsnabbt. + +Tänk på det som en snabb kaffepaus‑demo som du senare kan expandera till en produktionsklar pipeline. I slutet av den här guiden har du ett körbart program som utför **high resolution OCR**, utnyttjar ett CUDA‑aktiverat GPU och levererar exakt de spanska tecken du behöver. + +## Vad du kommer att lära dig + +- Hur du installerar och importerar ett modernt OCR‑bibliotek som stödjer GPU‑acceleration. +- Hur du skapar en OCR‑motorinstans och ställer in den för att **läsa av bildtext** på spanska. +- Hur du aktiverar **gpu accelerated OCR** för enorma hastighetsökningar på högupplösta filer. +- Hur du hanterar kantfall som saknade CUDA‑drivrutiner eller fallback till CPU. +- Tips för att förbättra noggrannheten när du behöver **extrahera spansk text** från brusiga skanningar. + +### Förutsättningar + +- Python 3.9+ (koden fungerar även på 3.10 och nyare). +- Ett CUDA‑kompatibelt GPU (valfritt men starkt rekommenderat). +- Grundläggande kunskap om pip och virtuella miljöer. + +Om du saknar någon av dessa fungerar handledningen fortfarande – hoppa bara över GPU‑steget så faller biblioteket automatiskt tillbaka till CPU. + +--- + +## Python OCR‑handledning: Installera de nödvändiga paketen + +Först och främst behöver vi en robust OCR‑motor. I den här handledningen använder vi det öppna källkods‑paketet **`easyocr`**, som levereras med inbyggt GPU‑stöd när en kompatibel enhet upptäcks. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Proffstips:** Om du redan har PyTorch installerat, se till att det matchar din CUDA‑version (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Versioner som inte matchar är en vanlig källa till felmeddelandet “GPU not found”. + +--- + +## Steg 1: Skapa en OCR‑motorinstans + +Nu startar vi motorn. EasyOCR kallar sin huvudklass `Reader`. Konstruktorn accepterar en lista med språkkoder; vi skickar `"es"` för spanska. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Varför detta är viktigt:* Genom att deklarera språket i förväg laddar motorn bara de nödvändiga neurala nätverksvikterna, vilket sparar minne och snabbar upp inferensen – särskilt användbart när du senare arbetar med **high resolution OCR**. + +--- + +## Steg 2: Förbered en högupplöst bild + +Högupplösta bilder ger modellen fler pixlar att arbeta med, vilket vanligtvis ger bättre teckenigenkänning. Låt oss anta att du har en fil som heter `high_res_spanish.png` i en mapp som heter `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Om du inte har ett högupplöst exempel tillgängligt kan du ladda ner ett gratis från Unsplash eller generera en syntetisk bild med Pillow. Nyckeln är att hålla DPI över 300 för bästa resultat. + +--- + +## Steg 3: Aktivera GPU‑acceleration (valfritt men rekommenderat) + +EasyOCR försöker redan använda GPU:n när du sätter `gpu=True`. Det är dock god praxis att verifiera att enheten faktiskt används, särskilt på system med flera GPU:er. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Varför kontrollera detta?* Om skriptet tyst faller tillbaka till CPU kan du undra varför en 5‑sekunders operation plötsligt tar 30 sekunder. Denna lilla kontroll gör beteendet transparent och håller din **gpu accelerated OCR**‑pipeline förutsägbar. + +--- + +## Steg 4: Utför högupplöst OCR och läs av bildtext + +Nu det roliga — att faktiskt läsa texten. EasyOCR:s `readtext`‑metod returnerar en lista med tupler som innehåller avgränsningsrutan, den igenkända strängen och ett förtroendescore. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Om du behöver den råa strängen utan koordinater, sätt `detail=0`. För de flesta **recognize image text**‑användningsfall ger standardvärdet (`detail=1`) dig tillräckligt med kontext för efterbearbetning senare. + +--- + +## Steg 5: Extrahera spansk text och rensa utdata + +Eftersom vi bad EasyOCR om spanska är de returnerade strängarna redan på det språket. Du kan ändå vilja concatenatera dem, ta bort blanksteg eller filtrera bort lågt förtroende‑detektioner. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Vad händer om förtroendet är lågt?** Du kan antingen sänka tröskeln (med risk för brus) eller förbehandla bilden (öka kontrast, binarisera eller räta upp). Dessa knep är vanliga när du arbetar med **high resolution OCR** på skannade dokument. + +--- + +## Steg 6: Hantera kantfall och prestandajusteringar + +Även de bäst tränade modellerna snubblar på några scenarier. Nedan finns ett par snabba fixar som du kan klistra in i skriptet. + +### 6.1 Fallback när ingen GPU finns + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Nedskalning av mycket stora bilder + +Om din bild är större än 4000 × 4000 px kan du få slut på GPU‑minne. Nedskala proportionellt samtidigt som du bevarar DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Dessa kodsnuttar gör skriptet robust, oavsett om du kör på en arbetsstation eller en modest laptop. + +--- + +## Fullt fungerande exempel + +När vi sätter ihop allt, här är det kompletta skriptet som du kan kopiera‑klistra in och köra omedelbart: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Förväntad utskrift (exempel):** + + + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extrahera text från bild med Aspose OCR – steg‑för‑steg‑guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Hur man OCR‑läser bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Hur man känner igen sidrektanglar för OCR‑textigenkänning i Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/swedish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..9c4dd0777 --- /dev/null +++ b/ocr/swedish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-06-06 +description: igenkänna text från en bild med Python OCR-motor. Lär dig hur du konfigurerar + OCR-motorn i Python och extraherar text från en bild med molnbehandling på några + minuter. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: sv +og_description: Känn igen text från en bild med Python OCR-motor. Denna guide visar + hur du konfigurerar OCR-motorn i Python och extraherar text från en bild effektivt. +og_title: igenkänna text från bild i Python – Komplett installationshandledning +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: igenkänn text från bild i Python – Fullständig installationsguide för OCR-motor +url: /sv/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# känna igen text från bild i Python – Komplett installationshandledning + +Har du någonsin undrat hur man **recognize text from image** med bara några rader Python? Du är inte ensam. Oavsett om du bygger en kvittoscanner, en dokumentdigitaliserare eller ett enkelt hobbyprojekt, så är förmågan att extrahera text från bild en färdighet som snabbt lönar sig. + +I den här handledningen går vi igenom hela processen—från **configure OCR engine python**‑stiluppsättning, via molnautentisering, till att slutligen visa dig hur du **extract text from image** med ett pålitligt resultat. Ingen magi, bara tydliga steg som du kan kopiera‑klistra och köra idag. + +## Vad du kommer att lära dig + +- Hur du installerar och importerar det obligatoriska OCR‑biblioteket. +- De exakta kommandona för att **configure OCR engine python** för molnbehandling. +- Ett komplett, körbart skript som **recognize text from image** och skriver ut resultatet. +- Tips för att hantera vanliga fallgropar som saknade API‑nycklar eller ej stödda bildformat. +- Idéer på nästa nivå såsom batch‑bearbetning och lokalt reservläge. + +### Förutsättningar + +- Python 3.8+ installerat på din maskin. +- En internetanslutning (exemplet använder en molnbaserad OCR‑tjänst). +- En giltig API‑nyckel från OCR‑leverantören (du får se var du ska ange den). + +Om du har allt detta, låt oss dyka ner—utan onödig fluff, bara en praktisk guide som fungerar. + +--- + +## Steg 1: Installera OCR‑biblioteket och importera det + +Innan du kan **configure OCR engine python** behöver du biblioteket som kommunicerar med molntjänsten. I vårt exempel använder vi ett fiktivt men representativt paket som heter `ocrcloud`. Byt ut det mot det faktiska paket du använder (t.ex. `easyocr`, `google-cloud-vision`, osv.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Varför detta är viktigt:** Att importera klassen ger dig åtkomst till metoder som `use_cloud()` och `set_api_key()`. Utan importen skulle resten av skriptet kasta ett `NameError`. + +*Pro tip:* Lås versionen i din `requirements.txt` (`ocrcloud==2.1.0`) för att undvika oväntade brytande förändringar senare. + +## Steg 2: Skapa och **configure OCR engine python** för molnläge + +Nu **configure OCR engine python** på riktigt. Motorn startar i lokalt läge som standard; genom att växla till molnläge kan du avlasta tung bildanalys till kraftfulla servrar. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Förklaring:** +- `OcrEngine()` skapar ett nytt motorobjekt—tänk på det som en tom canvas. +- `use_cloud(True)` slår på en strömbrytare som talar om för motorn att skicka bilder över HTTPS istället för att bearbeta dem lokalt. Detta är avgörande för hög precision på komplexa typsnitt eller lågupplösta foton. + +## Steg 3: Autentisera med din moln‑API‑nyckel + +De flesta molnbaserade OCR‑tjänster kräver en API‑nyckel. Detta steg visar hur du säkert injicerar credentialen. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Säkerhetsnotering:** Kod aldrig in nyckeln i ett offentligt repo. I produktion hämtar du den från en miljövariabel: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## Steg 4: **recognize text from image** – Skicka en fjärrbild för bearbetning + +Med motorn konfigurerad kan vi äntligen **recognize text from image**. Metoden `recognize_image()` tar en sökväg eller URL och returnerar ett objekt som innehåller den extraherade texten. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Vad händer under huven?** +Bildens bytes laddas upp till leverantörens endpoint, bearbetas av en djupinlärningsmodell, och rentextresultatet strömmas tillbaka. Om bilden är stor kan tjänsten automatiskt nedskala den för att snabba upp jobbet. + +## Steg 5: Skriv ut resultatet från **extract text from image** + +Nu när OCR‑tjänsten har gjort sitt jobb skriver vi helt enkelt ut texten. I riktiga applikationer kan du lagra den i en databas eller skicka den till en annan funktion. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Förväntad utskrift:** (exempel) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Om utskriften ser förvrängd ut, dubbelkolla att bilden är tydlig och att du har valt rätt språkmodell (många tjänster låter dig ange `engine.set_language("en")`). + +## Hantera kantfall & vanliga fallgropar + +### 1. Saknad eller ogiltig API‑nyckel +Om du får ett autentiseringsfel, se till att: +- Nyckeln är aktiv och inte har gått ut. +- Den läses korrekt från miljövariabeln. +- Ditt nätverk tillåter utgående HTTPS‑trafik. + +### 2. Ej stödda bildformat +De flesta OCR‑API:er accepterar JPEG, PNG och PDF. Att försöka med BMP eller TIFF kan ge ett “format not supported”-svar. Konvertera med Pillow om det behövs: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Hastighetsgränser +Molntjänster begränsar ofta antalet förfrågningar per minut. Om du når en gräns, implementera exponentiell back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Reserv till lokal OCR +Om molnet är nere kan du växla tillbaka: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Att ha en reserv håller din app robust. + +## Fullt fungerande exempel + +Sätter vi ihop allt får du ett skript du kan köra direkt (byt bara ut platshållarvärdena). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Kör det:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Du bör se den extraherade texten skrivas ut i konsolen, vilket bekräftar att du framgångsrikt har **recognize text from image** och **extract text from image** med ett korrekt **configure OCR engine python**‑arbetsflöde. + +## Slutsats + +Vi har just gått igenom en komplett, end‑to‑end‑process som låter dig **recognize text from image** i Python, från att installera biblioteket till att autentisera en molntjänst och slutligen **extract text from image** med ett enda funktionsanrop. Genom att **configure OCR engine python** på rätt sätt får du både flexibilitet (moln vs. lokalt) och pålitlighet (korrekt felhantering). + +Vad blir nästa steg? Prova att batch‑processa en mapp med kvitton, lägg till språkdetection, eller experimentera med PDF‑filer som indata. Himlen är gränsen när du har bemästrat grunderna. + +Lycka till med kodandet, och tveka inte att ställa frågor i kommentarerna—inget slår att lära sig tillsammans! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extrahera text från bild med Aspose OCR – Steg‑för‑steg‑guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrahera text från bild – Känn igen rad med Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Hur man extraherar text från bild genom att förbereda rektanglar i OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..bfe5b15c0 --- /dev/null +++ b/ocr/swedish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,338 @@ +--- +category: general +date: 2026-06-06 +description: Kör OCR på en bild med Python och se förtroendesiffror. Lär dig hur du + filtrerar ord med låg förtroendegrad, sätter tröskelvärden och hanterar kantfall. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: sv +og_description: Kör OCR på en bild i Python, inspektera förtroendenivåer och filtrera + bort ord med låg förtroendegrad. Den här handledningen guidar dig genom ett komplett, + körbart exempel. +og_title: Kör OCR på bild med Python – Fullständig guide +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Kör OCR på bild med Python – Komplett steg‑för‑steg‑guide +url: /sv/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kör OCR på bild med Python – Komplett steg‑för‑steg‑guide + +Har du någonsin behövt **köra OCR på bild**‑filer men varit osäker på hur du får pålitlig text ur dem? Du är inte ensam – många utvecklare stöter på samma problem när de extraherade orden ser osäkra ut och förtroendesiffran är ett mysterium. + +I den här guiden dyker vi rakt in i en fungerande lösning: du får se hur du kör OCR på bild, läser av det totala förtroendet och plockar ut eventuella lågt‑förtroendeord som kan behöva manuell granskning. I slutet har du ett återanvändbart skript, förstår varför varje rad är viktig och vet hur du justerar förtroendetröskeln för dina egna projekt. + +## Vad den här handledningen täcker + +Vi går igenom hela arbetsflödet – från att ladda en bild till att skriva ut en snygg rapport över ord som hamnade under 80 % förtroende. På vägen diskuterar vi: + +* Att välja en solid OCR‑motor (vi använder **EasyOCR**, ett populärt Python‑OCR‑bibliotek) +* Att tolka `confidence`‑attributet som varje OCR‑resultat returnerar +* Att filtrera ord med ett anpassat **OCR‑förtroendetröskel** +* Att utöka skriptet för batch‑bearbetning eller alternativa motorer som **pytesseract** + +Ingen tidigare OCR‑erfarenhet krävs, bara en grundläggande kunskap om Python och en fungerande miljö (Python 3.9+ rekommenderas). + +Redo att förvandla suddiga skärmdumpar till ren, sökbar text? Låt oss börja. + +--- + +## ## Så kör du OCR på bild med Python + +Kärnan i handledningen är ett tresteg‑kodexempel som speglar koden du redan såg. Nedan bryter vi ner varje rad, förklarar varför, och ger dig sedan ett komplett, copy‑and‑paste‑klart skript. + +### Steg 1: Installera och importera OCR‑motorn + +Först, se till att OCR‑biblioteket är tillgängligt. **EasyOCR** fungerar direkt för många språk och ger ett förtroendevärde per ord. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Varför EasyOCR?* Det paketera en djupinlärningsmodell som tränats på varierande dataset, så du får vanligtvis högre förtroendevärden än den äldre Tesseract‑motorn, särskilt på bilder med blandad kvalitet. + +> **Proffstips:** Om du befinner dig i en begränsad miljö (t.ex. en liten Docker‑container) kan `pytesseract` vara lättare, men du förlorar en del av den moderna noggrannheten som EasyOCR erbjuder. + +### Steg 2: Kör OCR på bilden + +Nu kör vi faktiskt **OCR på bild**. Metoden `recognize_image` från originalexemplet ersätts med EasyOCR:s `readtext`‑anrop, som returnerar en lista med `(bbox, text, confidence)`‑tupler. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Varje post i `ocr_results` ser ut så här: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Det tredje elementet (`0.92` i exemplet) är förtroendesiffran som varierar från 0 till 1. + +### Steg 3: Sammanfatta totalt förtroende + +Till skillnad från det tidigare kodexemplet som skrev ut ett enda `confidence`‑attribut, ger EasyOCR ett förtroende per ord. För att få en övergripande bild räknar vi ut medelvärdet: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Varför medelvärde?* Det ger dig en snabb hälsokontroll – om det totala förtroendet är under, säg, 70 % behöver du troligen förbättra bilden (bättre belysning, förbehandling osv.). + +### Steg 4: Lista lågt‑förtroendeord + +Nu kommer delen som direkt svarar på kravet “lista ord vars förtroende är under den önskade tröskeln”. Vi sätter ett **OCR‑förtroendetröskel** på 0.80 (80 %) som standard, men du kan justera det. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Loopen skriver ut varje ord som inte klarade tröskeln, tillsammans med dess procentuella förtroende. Detta är den exakta motsvarigheten till det ursprungliga `for recognized_word in recognition_result.words`‑loopen, men nu anpassad för EasyOCR:s utskriftsformat. + +--- + +## ## Förstå OCR‑förtroendesiffror + +Förtroende är inte ett magiskt tal; det är modellens uppskattning av hur säker den är på en viss transkription. Här är några saker att ha i åtanke: + +| Situation | Typiskt förtroende | Vad du bör göra | +|-----------|-------------------|-----------------| +| Klar, högupplöst skanning | 0.95 – 1.00 | Ingen extra åtgärd behövs | +| Lätt oskärpa eller ojämn belysning | 0.80 – 0.94 | Överväg lätt förbehandling (kontrastökning) | +| Mycket brus, roterad text | < 0.70 | Använd bildförbehandling (deskew, denoise) eller byt till en annan OCR‑motor | + +> **Observera:** Vissa språk (t.ex. kursiv handstil) ger naturligt lägre siffror. Justera tröskeln därefter. + +### Edge Cases & Variationer + +1. **Batch‑bearbetning** – Om du behöver **köra OCR på bild**‑filer i bulk, paketera logiken i en loop som itererar över en katalog. +2. **Flera språk** – Skicka en lista som `['en', 'fr']` till `easyocr.Reader` så upptäcker motorn båda. +3. **Alternativa motorer** – Vill du prova **pytesseract**? Ersätt läsarblocket med: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Du måste då samla per‑tecken‑förtroenden till per‑ord‑värden – lite mer arbete men genomförbart. + +4. **Förbehandlingsknep** – Att använda OpenCV‑filter (`cv2.threshold`, `cv2.GaussianBlur`) kan öka förtroendet för brusiga skanningar. + +--- + +## ## Fullt, kör‑klart skript + +Nedan är den kompletta Python‑filen du kan släppa in i ditt projekt. Spara den som `ocr_report.py` och kör `python ocr_report.py`. Se till att bildsökvägen pekar på en riktig fil. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Förväntad utskrift** (dina siffror kommer att variera): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Om varje ord klarar 80 %-gränsen ser du meddelandet “All words meet the confidence threshold.” istället. + +--- + +## ## Vanliga frågor (FAQ) + +**Q: Fungerar detta med PDF‑filer?** +A: Inte direkt. Konvertera varje PDF‑sida till en bild först (t.ex. med `pdf2image`) och mata sedan in PNG/JPEG i skriptet. + +**Q: Mina förtroendesiffror är alla låga – vad kan jag göra?** +A: Prova bildförbehandling: öka kontrast, ta bort bakgrundsbrus eller rotera bilden till en horisontell baslinje. EasyOCR accepterar också en `contrast_ths`‑parameter som du kan justera. + +**Q: Kan jag exportera resultaten till CSV?** +A: Absolut. Efter loopen för lågt‑förtroende, skriv `ocr_results` till en `csv.DictWriter` där varje rad innehåller `text`, `confidence` och koordinater för bounding‑boxen. + +**Q: Finns det en GPU‑accelererad version?** +A: EasyOCR använder automatiskt CUDA om ett kompatibelt GPU och PyTorch är installerade. Verifiera med `torch.cuda.is_available()` innan du kör skriptet. + +--- + +## Slutsats + +Vi har precis **kört OCR på bild** med Python, granskat det totala förtroendet och isolerat eventuella lågt‑förtroendeord som behöver en manuell granskning. + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger vidare på teknikerna i den här guiden. Varje resurs innehåller kompletta kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementeringsmetoder i dina egna projekt. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/thai/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..6ed692abf --- /dev/null +++ b/ocr/thai/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-06-06 +description: ดึงข้อความจากภาพด้วย Python OCR ภายในไม่กี่นาที ค้นพบ OCR ภาพหลายภาษา + การตรวจจับภาษาอัตโนมัติด้วย OCR และวิธีดึงข้อความ OCR อย่างแม่นยำ. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: th +og_description: ดึงข้อความจากรูปภาพด้วย Python OCR อย่างรวดเร็ว เรียนรู้การทำ OCR + ภาพหลายภาษา การตรวจจับภาษาที่อัตโนมัติด้วย OCR และวิธีการดึงข้อความ OCR ทีละขั้นตอน +og_title: สกัดข้อความจากภาพโดยใช้ Python OCR – คู่มือฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: สกัดข้อความจากภาพด้วย Python OCR – คู่มือครบวงจร +url: /th/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดึงข้อความจากภาพด้วย Python OCR – คู่มือฉบับเต็ม + +เคยต้อง **ดึงข้อความจากภาพ** แต่ไม่แน่ใจว่าห้องสมุดใดสามารถจัดการหลายภาษาโดยอัตโนมัติได้หรือไม่? คุณไม่ได้อยู่คนเดียว—นักพัฒนามักถามว่า *วิธีดึงข้อความ OCR* อย่างไรเมื่อทำงานกับเอกสารระหว่างประเทศ, ใบเสร็จ, หรือโบรชัวร์ที่สแกนไว้ ในบทเรียนนี้เราจะเดินผ่านตัวอย่าง Python ที่ใช้งานได้จริง ซึ่งไม่เพียงดึงข้อความจากภาพเท่านั้น แต่ยัง **ตรวจจับภาษา** ไปพร้อมกัน ทำให้ OCR ภาพหลายภาษากลายเป็นเรื่องง่าย + +เราจะครอบคลุมตั้งแต่การติดตั้งแพคเกจ OCR ไปจนถึงการเปิดใช้งาน **auto detect language OCR**, การรันเอนจินบนภาพตัวอย่าง, และสุดท้ายการพิมพ์ทั้งภาษาที่ตรวจจับได้และสตริงที่ดึงออกมา เมื่อจบคุณจะมีสคริปต์ที่นำกลับไปใช้ได้ในทุกโปรเจกต์ ไม่ว่าจะเป็นการสร้าง pipeline แปลภาษา หรือบริการ ingest ข้อมูล + +## ดึงข้อความจากภาพ – การตั้งค่าสภาพแวดล้อม + +ก่อนที่เราจะลงลึกในโค้ด ให้ตรวจสอบว่าเครื่องของคุณตรงตามข้อกำหนดขั้นต่ำเหล่านี้: + +- Python 3.8 หรือใหม่กว่า (ไลบรารีใช้ type hints ที่เวอร์ชันเก่าจะไม่รองรับ) +- `pip` สำหรับจัดการแพคเกจ +- ไฟล์ภาพที่มีข้อความอย่างน้อยสองภาษา (เช่น English + Spanish) + +คุณยังต้องการไลบรารี OCR ที่เป็นหัวใจของเดโมนี้ สำหรับคู่มือนี้เราจะใช้แพคเกจสมมติ `ocr` ซึ่งทำหน้าที่คล้ายเครื่องมือจริงเช่น Tesseract หรือ EasyOCR แต่มี API ของ Python ที่เรียบง่าย + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro tip:** หากเจอข้อผิดพลาดเรื่องสิทธิ์ ให้ใส่ `python -m` ไว้หน้าคำสั่งหรือใช้ virtual environment—จะทำให้แพคเกจในระบบหลักของคุณสะอาดขึ้น + +## สร้างอินสแตนซ์ของ OCR Engine + +เมื่อไลบรารีพร้อมแล้ว ขั้นตอนแรกที่มีเหตุผลคือ **สร้างอินสแตนซ์ของ OCR engine** คิดว่าเอนจินเป็นสแกนเนอร์อัจฉริยะที่คุณสามารถตั้งค่าก่อนใส่ภาพเข้าไป + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +ทำไมต้องสร้างอินสแตนซ์แยกจากการเรียกเมธอดแบบสแตติก? อินสแตนซ์นี้เก็บสถานะการตั้งค่า (เช่น การตั้งค่าภาษา) ที่คุณอาจต้องการใช้ซ้ำหลายภาพ ลดภาระการสร้างใหม่ทุกครั้ง + +## เปิดใช้งาน Auto Detect Language OCR + +เครื่องมือ OCR ส่วนใหญ่ต้องระบุรหัสภาษา—`eng` สำหรับอังกฤษ, `spa` สำหรับสเปน, ฯลฯ การคาดเดาภาษาเองทำให้เสียจุดประสงค์ของ **multilingual image OCR** โชคดีที่แพคเกจ `ocr` มีโหมด *auto detect language OCR* ที่ตรวจสอบภาพและเลือกโมเดลภาษาที่เหมาะสมโดยอัตโนมัติ + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +การเปิด **detect language OCR** แบบนี้หมายความว่าคุณไม่ต้องดูแลรายการรหัสภาษายาว ๆ เอนจินจะพยายามจับสคริปต์ที่พบ—Latin, Cyrillic, Han ฯลฯ—และโหลดโมเดลที่ตรงกันโดยอัตโนมัติ + +## ทำ Multilingual Image OCR + +เมื่อเอนจินพร้อมแล้ว ถึงเวลาที่จะ **ดึงข้อความจากภาพ** จริง ๆ เมธอด `recognize_image` รับพาธไฟล์และคืนค่าอ็อบเจ็กต์ผลลัพธ์ที่มีทั้งข้อความดิบและภาษาที่ตรวจจับได้ + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +ถ้าคุณสงสัยว่า *วิธีดึงข้อความ OCR* จาก PDF แทน PNG คืออะไร เอนจินเดียวกันมี `recognize_pdf`—เพียงเปลี่ยนชื่อเมธอด การทำงานของการตรวจจับพื้นฐานยังคงเหมือนเดิม ดังนั้นคุณจะได้ประโยชน์จากฟีเจอร์ **auto detect language OCR** เหมือนกัน + +## แสดงภาษาที่ตรวจจับและข้อความที่ดึงออกมา + +สุดท้าย เราจะพิมพ์สิ่งที่เอนจินค้นพบ อ็อบเจ็กต์ผลลัพธ์เปิดเผย `detected_language` (แท็ก BCP‑47 เช่น `en` หรือ `es`) และ `text` ซึ่งเป็นผลลัพธ์ OCR ดิบ + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +การรันสคริปต์บนภาพตัวอย่างของเราควรให้ผลลัพธ์คล้ายกับ: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +สังเกตว่าเอนจินระบุอังกฤษเป็นภาษาหลักได้อย่างถูกต้อง แต่ก็ยังจับบรรทัดสเปนได้—พฤติกรรมที่คุณคาดหวังจากโซลูชัน **multilingual image OCR** ที่แข็งแกร่ง + +### ถ้าการตรวจจับล้มเหลวจะทำอย่างไร? + +บางครั้งเอนจิน OCR อาจย้อนกลับไปใช้ภาษาดีฟอลต์ (มักเป็นอังกฤษ) หากภาพเบลอหรือสคริปต์แปลกเกินไป ในกรณีนั้นคุณสามารถบังคับให้ใช้รายการภาษาได้: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +แต่จำไว้ว่า การบังคับภาษาอาจทำให้เสียความสะดวกของ **auto detect language OCR** ดังนั้นให้ใช้เฉพาะเมื่อคุณรู้ชุดภาษาที่ต้องการเท่านั้น + +## ปัญหาที่พบบ่อยและวิธีดึง OCR Text อย่างเชื่อถือได้ + +แม้จะเปิด auto‑detection แล้ว ยังมีอุปสรรคเล็กน้อยที่อาจทำให้คุณติดขัด: + +1. **ภาพความละเอียดต่ำ** – ความแม่นยำของ OCR ลดลงอย่างชัดเจนเมื่อต่ำกว่า 150 dpi ให้ทำการอัปสเกลหรือขอสแกนความละเอียดสูงขึ้น +2. **นอยส์และอาร์ติแฟคต์จากการบีบอัด** – ใช้ฟิลเตอร์ threshold ง่าย ๆ (`opencv` หรือ `Pillow`) ก่อนส่งภาพให้เอนจิน +3. **สคริปต์ผสมบนหน้าเดียว** – บางเอนจินทำงานได้ยากกับอักษร Latin และ CJK พร้อมกัน ให้แบ่งหน้าเป็นโซนและรันการจดจำแยกส่วนตามต้องการ + +การแก้ไขปัญหาเหล่านี้จะทำให้กระบวนการ **extract text from image** มีคุณภาพดีขึ้นอย่างมาก โดยเฉพาะเมื่อจัดการกับเอกสารหลายภาษาในโลกจริง + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์สมบูรณ์พร้อมรันที่รวมทุกขั้นตอนที่เราได้อธิบายไว้ บันทึกเป็น `multilingual_ocr.py` แล้วเรียกจาก command line + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**ผลลัพธ์ที่คาดหวัง** (สมมติว่าภาพตัวอย่างมีข้อความอังกฤษและสเปน): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +คุณสามารถเปลี่ยน `multilang_page.png` เป็นภาพใดก็ได้ที่มีข้อความในภาษาต่าง ๆ — ด้วย **auto detect language OCR** สคริปต์จะยังคงให้แท็กภาษาที่เหมาะสมและข้อความที่สอดคล้องกัน + +![Extract text from image example](https://example.com/ocr-sample.png "Extract text from image") + +## สรุป + +ตอนนี้คุณรู้แล้วว่า **วิธีดึง OCR text** จากภาพอย่างไร, วิธีเปิด **auto detect language OCR**, และวิธีจัดการกับสถานการณ์ **multilingual image OCR** ด้วยโค้ดเพียงไม่กี่บรรทัด โดยการสร้างอินสแตนซ์ OCR engine, เปิดการตรวจจับภาษาอัตโนมัติ, และเรียก `recognize_image` คุณสามารถดึงทั้งตัวระบุภาษาและข้อความดิบได้อย่างน่าเชื่อถือ + +ต่อไปคุณจะทำอะไร? ลองส่งสตริงที่ดึงมาไปยัง API แปลภาษา, เก็บไว้ในฐานข้อมูลที่ค้นหาได้, หรือรวมหลายหน้าเป็น PDF รายงานเดียว คุณยังสามารถทดลองใช้ backend OCR ต่าง ๆ (Tesseract, EasyOCR, Google Vision) โดยคง workflow ระดับสูงเดียวกัน—ขอบคุณอินเทอร์เฟซ **detect language OCR** ที่สอดคล้องกัน + +หากเจอข้อผิดพลาดใด ๆ ให้กลับไปอ่านส่วน “ปัญหาที่พบบ่อย” หรือปรับขั้นตอนการเตรียมภาพ Happy coding, และขอให้โปรเจกต์ต่อไปของคุณเต็มไปด้วยข้อความที่ตรวจจับได้ถูกต้องและดึงออกมาอย่างสมบูรณ์! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/thai/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..0aabcea42 --- /dev/null +++ b/ocr/thai/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-06-06 +description: ดึงข้อความจากไฟล์ PDF ที่เป็นรูปภาพโดยใช้ Python OCR. เรียนรู้วิธีแปลงเอกสารสแกนเป็นข้อความอย่างรวดเร็วด้วยการจดจำแบบแบตช์แบบอะซิงโครนัส. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: th +og_description: ดึงข้อความจากไฟล์ภาพ PDF ด้วย Python คู่มือขั้นตอนต่อขั้นตอนนี้แสดงวิธีแปลงเอกสารสแกนเป็นข้อความโดยใช้ + OCR แบบอะซิงค์ +og_title: สกัดข้อความจากไฟล์ PDF ที่เป็นรูปภาพ – บทเรียน OCR ด้วย Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: ดึงข้อความจากไฟล์ PDF ภาพ – คู่มือ Python เพื่อแปลงเอกสารสแกนเป็นข้อความ +url: /th/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดึงข้อความจากไฟล์ PDF รูปภาพ – คู่มือ Python เพื่อแปลงเอกสารสแกนเป็นข้อความ + +เคยต้องการ **ดึงข้อความจากไฟล์ PDF รูปภาพ** โดยไม่ต้องใช้เวลาหลายชั่วโมงในการพิมพ์ซ้ำหรือไม่? ในคู่มือนี้เราจะสาธิตวิธี **แปลงเอกสารสแกนเป็นข้อความ** ด้วยกระบวนการ OCR แบบอะซิงโครนัสที่ง่ายใน Python. + +หากคุณเคยมองดูกอง PDF สแกนแล้วคิดว่า “ต้องมีวิธีที่เร็วกว่า” คุณมาถูกที่แล้ว เราจะเดินผ่านทุกบรรทัดของโค้ด, อธิบายว่าทำไมแต่ละส่วนจึงสำคัญ, และแม้แต่ครอบคลุมกรณีขอบที่คุณอาจเจอ. + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีสร้างเครื่อง OCR และตั้งค่าภาษาในการจดจำ +- กลไกการป้อนรายการผสมของ PNG และ PDF ไปยังตัวจดจำแบบแบช +- การรันงาน OCR แบบอะซิงโครนัสเพื่อให้แอปของคุณตอบสนองได้ +- ดึงผลลัพธ์กลับมา, จับคู่กับไฟล์ต้นฉบับ, และพิมพ์ผลลัพธ์ที่สะอาด + +**Prerequisites**: Python 3.8+, ความเข้าใจพื้นฐานเกี่ยวกับ `asyncio` หรือ `concurrent.futures`, และไลบรารี OCR ที่เปิดเผยคลาส `OcrEngine` คล้ายกับตัวอย่าง (เช่น Aspose.OCR, ตัวห่อ Tesseract, หรือห่อแบบกำหนดเอง). ไม่ต้องตั้งค่าซับซ้อน—เพียงติดตั้งไลบรารีแล้วคุณก็พร้อมใช้งาน. + +![ดึงข้อความจากไฟล์ PDF รูปภาพ](https://example.com/placeholder.png "ภาพหน้าจอของผลลัพธ์ OCR – ดึงข้อความจากไฟล์ PDF รูปภาพ") + +## ดึงข้อความจากไฟล์ PDF รูปภาพ – การตั้งค่าเครื่อง OCR + +สิ่งแรกที่คุณต้องการคืออินสแตนซ์ของเครื่อง OCR ที่กำหนดค่าภาษาของเอกสารของคุณ ในกรณีของเราเราจะใช้ภาษาฝรั่งเศส, แต่คุณสามารถเปลี่ยนเป็นภาษาที่รองรับอื่นได้. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**ทำไมเรื่องนี้ถึงสำคัญ**: การตั้งค่าภาษาไว้ล่วงหน้าช่วยเพิ่มความแม่นยำอย่างมาก. เครื่องใช้พจนานุกรมและโมเดลอักขระเฉพาะภาษา; การป้อนภาษาไม่ตรงเป็นสาเหตุทั่วไปของผลลัพธ์ที่อ่านไม่ออก. + +## เตรียมรายการไฟล์ – รูปภาพและ PDF ร่วมกัน + +ตัวจดจำแบบแบชของเราสามารถจัดการทั้งภาพเรสเตอร์ (`.png`, `.jpg`) และคอนเทนเนอร์ PDF. เพียงแค่ป้อนรายการ Python ธรรมดาของเส้นทางไฟล์. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Tip**: รักษารายการให้เป็นแบน; เครื่องจะทำการแยกแต่ละหน้า PDF เป็นภาพภายในก่อนการจดจำ. หากคุณมีไฟล์หลายพันไฟล์, พิจารณาแบ่งรายการเป็นแบชเล็ก ๆ เพื่อหลีกเลี่ยงการกระตุ้นหน่วยความจำ. + +## เริ่มต้นการจดจำแบบแบชแบบอะซิงโครนัส + +แทนที่จะบล็อกเธรดหลัก, เราจะเปิดงาน OCR ในพื้นหลัง. เมธอดจะคืนค่า `Future` ที่ในที่สุดจะเก็บรายการของอ็อบเจ็กต์ `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**How it works**: ภายใต้ผิวเครื่องจะสร้าง thread pool (หรือ async task, ขึ้นกับการนำไปใช้). สิ่งนี้ทำให้คุณสามารถทำงานอื่นต่อได้—เช่นอัปเดต UI, ดึงไฟล์เพิ่ม, หรือบันทึกความคืบหน้า—ในขณะที่การประมวลผลหนักเกิดขึ้นที่อื่น. + +## ทำสิ่งที่เป็นประโยชน์ขณะ OCR ทำงาน + +ข้อผิดพลาดทั่วไปคือการนั่งรอและโพล `future` อย่างต่อเนื่อง. แทนที่จะทำเช่นนั้น, คุณสามารถทำงานที่ไม่เกี่ยวข้องอื่น ๆ ได้. เพื่อสาธิต, เราจะพิมพ์บรรทัดสถานะเท่านั้น. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## รวบรวมผลลัพธ์เมื่อ Future เสร็จสิ้น + +เมื่อคุณพร้อมที่จะเก็บผลลัพธ์ OCR, ใช้ `as_completed` จาก `concurrent.futures`. แพทเทิร์นนี้ทำงานได้ไม่ว่าจะมี future หนึ่งหรือหลายอัน. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**What you’ll see**: เส้นทางไฟล์แต่ละอันตามด้วยข้อความที่ดึงออกมาเป็น plain‑text. สำหรับ PDF, `result.text` จะมีข้อความที่ต่อเนื่องจากทุกหน้า. + +### ผลลัพธ์ที่คาดหวัง (ตัวอย่าง) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +หากคุณสังเกตเห็นอักขระหายไป, ตรวจสอบให้แน่ใจว่าภาษาที่ตั้งตรงกับภาษาของเอกสาร, และพิจารณาการพรี‑โปรเซสภาพ (deskew, เพิ่มความคอนทราสต์) ก่อนป้อนให้กับเครื่อง. + +## จัดการกรณีขอบและข้อผิดพลาดทั่วไป + +| สถานการณ์ | วิธีการทำ | +|-----------|------------| +| **ภาษาผสม** | ทำการตรวจจับภาษาก่อน, จากนั้นสร้างเครื่อง OCR แยกตามแต่ละภาษา. | +| **PDF ขนาดใหญ่ (> 100 MB)** | แยก PDF เป็นหน้าเดี่ยวบนดิสก์ (เช่น ใช้ `PyPDF2`) แล้วป้อนเป็นรายการแยก. | +| **สคริปต์ที่ไม่ใช่ละติน** | ตรวจสอบว่าไลบรารี OCR มีแพ็คเกจภาษาที่ต้องการ; บางไลบรารีต้องดาวน์โหลดไฟล์ข้อมูลเพิ่มเติม. | +| **คอขวดด้านประสิทธิภาพ** | เพิ่มขนาดของ thread pool (`engine.set_thread_pool_size(8)`) หรือเปลี่ยนไปใช้ backend ที่เร่งด้วย GPU หากมี. | +| **ข้อความหายในภาพความละเอียดต่ำ** | ทำการพรี‑โปรเซสด้วย OpenCV: `cv2.resize`, `cv2.threshold`, และ `cv2.medianBlur` เพื่อปรับปรุงความอ่านได้. | + +## ตัวอย่างทำงานเต็ม (พร้อมคัดลอก‑วาง) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +บันทึกไฟล์นี้เป็น `extract_text_async.py`, แทนที่ `YOUR_DIRECTORY` ด้วยเส้นทางไปยังไฟล์ของคุณ, ติดตั้งแพคเกจ OCR (`pip install your-ocr-lib`), แล้วรัน `python extract_text_async.py`. คุณควรเห็นผลลัพธ์บนคอนโซลตามที่แสดงไว้ก่อนหน้า. + +## ขั้นตอนต่อไป – ไปไกลกว่าการดึงข้อความพื้นฐาน + +- **การประมวลผลต่อ**: ลบช่องว่างเพิ่มเติม, ทำให้ Unicode ปกติ (`unicodedata.normalize`), หรือใช้ตัวตรวจสอบการสะกดเพื่อทำความสะอาดเสียงรบกวนจาก OCR. +- **ผลลัพธ์แบบโครงสร้าง**: ส่งออกผลลัพธ์เป็น CSV, JSON, หรือบันทึกโดยตรงลงฐานข้อมูลเพื่อการค้นหาในขั้นต่อไป. +- **แบชแบบขนาน**: หากคุณมีไฟล์หลายร้อยไฟล์, สร้างหลาย futures พร้อมใช้คิวเพื่อให้ CPU ทำงานต่อเนื่องโดยไม่ทำให้หน่วยความจำเต็ม. +- **รวมเข้ากับเว็บเฟรมเวิร์ก**: เชื่อมสคริปต์นี้กับ endpoint ของ Flask หรือ FastAPI เพื่อให้บริการ OCR ตามความต้องการ. + +--- + +### สรุปย่อ + +คุณตอนนี้รู้วิธี **ดึงข้อความจากไฟล์ PDF รูปภาพ** ด้วยสคริปต์ Python ขั้นต่ำที่รัน OCR แบบอะซิงโครนัส, ทำให้คุณ **แปลงเอกสารสแกนเป็นข้อความ** ขณะโปรแกรมของคุณยังคงตอบสนองได้. ทดลองปรับตั้งค่าภาษา, ขนาดแบช, และเทคนิคพรี‑โปรเซสเพื่อให้ได้ความแม่นยำสูงสุดของทุกอักขระ. + +มีไอเดียหรือวิธีการพิเศษที่อยากแชร์—เช่น OCR บนโน้ตมือเขียนหรือบริการคลาวด์? แสดงความคิดเห็นได้เลย, และขอให้สนุกกับการเขียนโค้ด! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แต่ละแหล่งรวมตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้ทางเลือกในโปรเจกต์ของคุณ. + +- [ดึงข้อความจากรูปภาพด้วย Aspose OCR – คู่มือขั้นตอนต่อขั้นตอน](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [ดึงข้อความจากรูปภาพโดยใช้การทำงาน OCR บนโฟลเดอร์](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [ดึงข้อความจากรูปภาพโดยใช้ Aspose.OCR – ตัวอักษรที่อนุญาต](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/thai/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3b3f4f61b --- /dev/null +++ b/ocr/thai/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-06-06 +description: วิธีทำ OCR PDF ด้วย Python, ดึงข้อความจาก PDF, แปลงข้อความจาก PDF ที่สแกน, + และเปลี่ยนภาษาของ OCR เพียงไม่กี่บรรทัดของโค้ด. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: th +og_description: 'วิธีทำ OCR PDF ด้วย Python: คู่มือปฏิบัติที่แสดงวิธีดึงข้อความจาก + PDF, แปลงข้อความจาก PDF สแกน, และเปลี่ยนภาษาของ OCR อย่างง่ายดาย.' +og_title: วิธีทำ OCR PDF ด้วย Python – บทเรียนการเขียนโปรแกรมเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: วิธีทำ OCR PDF ด้วย Python – คู่มือขั้นตอนเต็มครบถ้วน +url: /th/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีทำ OCR PDF ด้วย Python – คู่มือขั้นตอนเต็ม + +เคยสงสัย **วิธีทำ OCR PDF** โดยไม่ต้องจ่ายค่าใช้จ่ายสูงของเครื่องมือ SaaS หรือไม่? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะกำลังดิจิไทซ์หนังสือเก่า ดึงข้อมูลจากใบแจ้งหนี้ หรือแค่ต้องการข้อความที่ค้นหาได้จากรายงานสแกน การเชี่ยวชาญ OCR PDF ด้วย Python สามารถช่วยคุณประหยัดเวลาการคัดลอกด้วยมือหลายชั่วโมงได้ + +ในบทเรียนนี้เราจะพาคุณผ่านตัวอย่างสั้น ๆ ที่ทำงานได้จริง ซึ่ง **ดึงข้อความจาก PDF** แสดงวิธี **แปลงข้อความ PDF ที่สแกน** ให้เป็นสตริงที่แก้ไขได้ และแม้แต่สาธิตวิธี **เปลี่ยนภาษาของ OCR** หากเอกสารของคุณไม่ได้เป็นภาษาอังกฤษ เมื่อจบคุณจะได้โค้ดสแนปที่สามารถนำไปใช้ในโปรเจกต์ใดก็ได้ + +## ข้อกำหนดเบื้องต้น & การตั้งค่า + +ก่อนที่เราจะเริ่มลงมือทำ โปรดตรวจสอบว่าคุณมี: + +- Python 3.8+ ติดตั้งแล้ว (โค้ดทำงานบน 3.9, 3.10 และใหม่กว่า) +- แพคเกจ `ocr` ที่ให้คลาส `OcrEngine` (คุณสามารถติดตั้งได้ด้วย `pip install ocr-lib` – แทนที่ด้วยชื่อแพคเกจจริงที่คุณใช้) +- ไฟล์ PDF ที่ต้องการประมวลผล; สำหรับการสาธิตเราจะใช้ `high_res_book.pdf` ที่อยู่ในโฟลเดอร์ชื่อ `YOUR_DIRECTORY` + +หากคุณใช้ virtual environment (แนะนำอย่างยิ่ง) ให้เปิดใช้งานก่อน: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **เคล็ดลับ:** เก็บไฟล์ PDF ของคุณไว้ในไดเรกทอรี `data/` เฉพาะเพื่อหลีกเลี่ยงปัญหาเกี่ยวกับเส้นทางในภายหลัง + +## ขั้นตอนที่ 1: สร้างอินสแตนซ์ของ OCR Engine (How to OCR PDF – Initialization) + +สิ่งแรกที่คุณต้องทำเมื่อ **ต้องการทำ OCR บนไฟล์ PDF** คือสร้างอินสแตนซ์ของเอนจิน คิดว่าเอนจินเป็นสมองที่จะอ่านแต่ละหน้า แปลอักขระ และส่งข้อความธรรมดากลับมาให้คุณ + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +ทำไมจึงสำคัญ: หากไม่มีเอนจิน คุณจะไม่มีบริบทสำหรับการตั้งค่าภาษา ตัวเลือกการเรนเดอร์ หรือการจัดการ PDF `OcrEngine` จะเก็บค่าเริ่มต้นทั้งหมดเหล่านี้และให้คุณปรับแต่งได้ในภายหลัง + +## ขั้นตอนที่ 2: ตั้งค่าภาษาในการรับรู้ (Change OCR Language) + +ไลบรารี OCR ส่วนใหญ่ตั้งค่าเริ่มต้นเป็นภาษาอังกฤษ แต่ถ้าเอกสารของคุณเป็นภาษาฝรั่งเศส เยอรมัน หรือแม้แต่ญี่ปุ่น การเปลี่ยนภาษาก็ทำได้ง่ายโดยเรียก `set_recognition_language` ซึ่งตอบสนองต่อความต้องการ **เปลี่ยนภาษาของ OCR** และช่วยให้ความแม่นยำสูงขึ้น + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **เหตุผลที่คุณอาจต้องทำเช่นนี้:** คลังเอกสารหลายภาษามักมีหน้าที่ผสมภาษาต่าง ๆ การสลับภาษาแบบไดนามิกช่วยป้องกันการรับรู้อักขระผิดพลาด เช่น “ß” หรือ “ñ” + +## ขั้นตอนที่ 3: กำหนดตัวเลือกการเรนเดอร์ PDF (Convert Scanned PDF Text Effectively) + +เมื่อทำงานกับ PDF ที่สแกน ความละเอียดและโหมดสีมีผลอย่างมากต่อคุณภาพ OCR การเรนเดอร์ที่ 300 DPI ในโหมด grayscale เป็นจุดที่เหมาะสมสำหรับเอกสารส่วนใหญ่—ละเอียดพอที่จะจับรายละเอียด แต่ไม่สูงเกินไปจนใช้หน่วยความจำมาก + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +การเรียกต่อกันอาจดูหรูหรา แต่จริง ๆ แล้วเป็น Fluent API ที่คืนค่าอ็อบเจกต์ options เดียวกันทุกครั้ง หากคุณต้องการสี (เช่น สำหรับแผนภาพสี) ให้เปลี่ยน `"grayscale"` เป็น `"color"` + +## ขั้นตอนที่ 4: ทำการรับรู้ PDF และดึงข้อความหน้าที่ 1 (Extract Text from PDF) + +ตอนนี้มาถึงหัวใจของ **วิธีทำ OCR PDF**: ส่งเส้นทางไฟล์ให้เอนจินและดึงข้อความที่รับรู้ได้ วิธีนี้จะคืนรายการผลลัพธ์ของแต่ละหน้า; แต่ละผลลัพธ์มีแอตทริบิวต์ `text` + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +หากต้องการข้อความของทั้งเอกสาร ให้วนลูปผ่าน `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### ถ้า PDF ถูกเข้ารหัส? + +บาง PDF มีการป้องกันด้วยรหัสผ่าน ในกรณีนั้นคุณสามารถส่งรหัสผ่านไปยัง `recognize_pdf` ได้: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +เอนจินจะถอดรหัสแบบเรียลไทม์ก่อนทำ OCR—ไม่ต้องทำขั้นตอนเพิ่มเติม + +## ขั้นตอนที่ 5: การทำ Post‑Processing ข้อความที่ดึงมา (Fine‑Tuning Extract Text from PDF) + +ผลลัพธ์ OCR ดิบมักมีการขึ้นบรรทัดใหม่ ช่องว่างเกิน หรืออักขระที่รับรู้ผิดพลาดบ้าง การทำความสะอาดอย่างรวดเร็วจะทำให้สตริงที่ดึงมาพร้อมสำหรับการประมวลผลต่อ (เช่น การทำดัชนีการค้นหา การเก็บลงฐานข้อมูล ฯลฯ) + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +ตอนนี้คุณสามารถ **ดึงข้อความจาก PDF** อย่างปลอดภัยและส่งต่อไปยัง pipeline NLP, เครื่องมือค้นหา, หรือแม้กระทั่งการเขียนไฟล์ด้วย `open(...).write()` + +## โบนัส: การประมวลผลหลาย PDF พร้อมกัน (Scaling Perform OCR on PDF) + +หากคุณมีโฟลเดอร์เต็มไปด้วย PDF ที่สแกน ให้ห่อโค้ดไว้ในลูป: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +สแนปนี้แสดงวิธี **ทำ OCR บนไฟล์ PDF** เป็นชุดจำนวนมาก ซึ่งเป็นความต้องการทั่วไปสำหรับโครงการดิจิไทซ์ + +## ผลลัพธ์ที่คาดหวัง + +การรันตัวอย่างหน้าเดียว (ขั้นตอน 4) ควรพิมพ์ข้อความประมาณนี้: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +หากคุณประมวลผลหนังสือหลายหน้า คอนโซลจะแสดงข้อความที่ทำความสะอาดแล้วของแต่ละหน้า และสคริปต์แบชจะสร้างไฟล์ `.txt` ข้าง ๆ ทุกไฟล์ PDF + +## ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +| ปัญหา | อาการ | วิธีแก้ | +|-------|----------|-----| +| PDF ต้นฉบับความละเอียดต่ำ | ตัวอักษรแสดงเป็นอักขระผิด, คำหาย | เพิ่ม DPI (`set_dpi(400)` หรือสูงกว่า) | +| ตั้งค่าภาษาไม่ถูกต้อง | มีสัญลักษณ์ไม่รู้จักจำนวนมาก, โดยเฉพาะอักขระมีสำเนียง | ใช้ `engine.set_recognition_language(ocr.Language.FRENCH)` หรือ enum ที่เหมาะสม | +| PDF ขนาดใหญ่ทำให้เกิด MemoryError | `MemoryError` หรือแอปพังหลังจากหลายหน้า | ประมวลผลหน้าเป็นชิ้น (`engine.recognize_pdf(..., max_pages=10)`) | +| ฟอนต์หายใน PDF | ผลลัพธ์เป็นค่าว่างสำหรับบางหน้า | ตรวจสอบว่า PDF มีภาพ raster จริง; PDF บางไฟล์เป็น vector‑only และต้องการการจัดการแบบอื่น | + +## ภาพประกอบ + +ด้านล่างเป็นภาพแสดงขั้นตอนการทำงานอย่างรวดเร็ว ข้อความ alt ถูกออกแบบให้เป็น SEO‑friendly + +![วิธีทำ OCR PDF workflow diagram แสดงการเริ่มต้นเอนจิน, การตั้งค่าภาษา, ตัวเลือกการเรนเดอร์, การรับรู้, และการดึงข้อความ](/images/ocr-workflow.png) + +*แผนภาพนี้ไม่จำเป็นต่อการรันโค้ด แต่ช่วยให้ผู้เรียนที่ชอบภาพเห็นภาพรวมของแต่ละขั้นตอนได้ชัดเจนขึ้น* + +## สรุป + +เราได้ครอบคลุม **วิธีทำ OCR PDF** ด้วย Python ตั้งแต่การสร้าง OCR engine, **การเปลี่ยนภาษาของ OCR**, การตั้งค่าการเรนเดอร์เพื่อ **แปลงข้อความ PDF ที่สแกน**, และสุดท้าย **การดึงข้อความจาก PDF** เพื่อใช้งานต่อ ตัวอย่างเต็มที่พร้อมรันพร้อมใช้งานในโปรเจกต์ใดก็ได้ และสคริปต์แบชเสริมแสดงวิธีขยายโซลูชันให้รองรับหลายไฟล์ + +ต่อไปคุณอาจอยากสำรวจ: + +- เพิ่ม **ทำ OCR บน PDF** สำหรับคลังเอกสารหลายภาษาโดยวนลูปผ่านรายการภาษา +- ผสานข้อความที่ดึงมาเข้ากับ Elasticsearch เพื่อการค้นหาแบบเต็มข้อความ +- ใช้ OCR สร้าง PDF ที่ค้นหาได้โดยฝังชั้นข้อความกลับเข้าไฟล์ต้นฉบับ (หลายไลบรารีมีเมธอด `save_as_searchable_pdf`) + +ลองทดลอง ปรับค่า DPI หรือสลับไปใช้ backend OCR ตัวอื่นก็ได้ พื้นฐานยังคงเหมือนเดิมและคุณมีฐานที่มั่นคงสำหรับการต่อยอดต่อไป + +ขอให้เขียนโค้ดสนุกและเอกสารสแกนของคุณกลายเป็นข้อมูลที่ค้นหาได้! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/thai/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..97d438321 --- /dev/null +++ b/ocr/thai/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-06 +description: วิธีทำ OCR PDF และสร้างไฟล์ PDF ที่ค้นหาได้จากรูปภาพโดยใช้ Python เรียนรู้การเพิ่มข้อความที่ค้นหาได้และแปลงรูปภาพเป็น + PDF/A ภายในไม่กี่นาที +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: th +og_description: วิธีทำ OCR PDF ทีละขั้นตอน เรียนรู้การเพิ่มข้อความที่ค้นหาได้และแปลงภาพเป็น + PDF/A ด้วยสคริปต์ Python อย่างง่าย +og_title: วิธีทำ OCR PDF – คู่มือเร็วเพื่อสร้าง PDF ที่ค้นหาได้ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: วิธีทำ OCR PDF ด้วย Python – สร้าง PDF ที่ค้นหาได้จากรูปภาพ +url: /th/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีทำ OCR PDF – แปลงภาพสแกนเป็น PDF ที่ค้นหาได้ + +เคยสงสัยไหมว่า **วิธีทำ OCR PDF** เมื่อคุณมีเพียงภาพสแกนของใบแจ้งหนี้หรือใบเสร็จ? คุณไม่ได้เป็นคนเดียวที่เป็นเช่นนั้น ในหลายสำนักงาน เอกสารที่เข้ามามักเป็นไฟล์ PNG หรือ JPEG แบน และขั้นตอนต่อไป—การทำให้เนื้อหานั้นสามารถค้นหาได้—ดูเหมือนเป็นกล่องดำ + +ข่าวดีคือ? ด้วยเพียงไม่กี่บรรทัดของ Python คุณสามารถ **สร้าง PDF ที่ค้นหาได้** , **เพิ่มข้อความที่ค้นหาได้**, และแม้กระทั่ง **แปลงภาพเป็น PDF/A** เพื่อการเก็บรักษาระยะยาว ในบทแนะนำนี้เราจะเดินผ่านแต่ละขั้นตอน อธิบายเหตุผลที่สำคัญ และให้สคริปต์พร้อมใช้งานที่คุณสามารถใส่ลงในโครงการใดก็ได้ + +> **เคล็ดลับ:** วิธีเดียวกันนี้ใช้ได้กับการสแกนหลายหน้า; เพียงวนลูปไฟล์และเอนจินจะทำงานหนักให้เอง. + +--- + +## สิ่งที่คุณต้องเตรียม + +ก่อนที่เราจะดำเนินการต่อ โปรดตรวจสอบว่าคุณมีสิ่งต่อไปนี้บนเครื่องของคุณ: + +| ความต้องการ | เหตุผลที่สำคัญ | +|-------------|----------------| +| Python 3.9 หรือใหม่กว่า | ไวยากรณ์สมัยใหม่และการสนับสนุนไลบรารีที่ดีกว่า | +| `pdfium`‑based OCR engine (e.g., `pdfocr` or a commercial SDK) | จัดการการจดจำภาพและการสร้าง PDF/A | +| ไฟล์รูปภาพ (PNG, JPEG, TIFF) ที่คุณต้องการแปลงเป็น PDF ที่ค้นหาได้ | แหล่งที่มาของข้อความ | +| สิทธิ์การเขียนในโฟลเดอร์ผลลัพธ์ | เพื่อให้สคริปต์บันทึก PDF ใหม่ได้ | + +หากคุณยังไม่ได้ติดตั้ง OCR SDK ให้รัน: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +แค่นั้น—ไม่มีการพึ่งพาระบบที่ซับซ้อน เพียงแค่ `pip install`. + +--- + +## วิธีทำ OCR PDF – ภาพรวม + +ในระดับสูง กระบวนการประกอบด้วยสามการกระทำง่าย ๆ: + +1. **Recognize** ข้อความภายในภาพพร้อมคงกราฟิกเดิมไว้. +2. **Export** ผลลัพธ์ OCR พร้อมภาพต้นฉบับเป็น **searchable PDF/A** (รูปแบบ PDF ที่เหมาะกับการเก็บรักษาระยะยาว). +3. **Validate** ว่าไฟล์ที่ได้มีข้อความที่เลือกได้และค้นหาได้ซ้อนอยู่เหนือรูปภาพต้นฉบับ. + +ด้านล่างคุณจะเห็นแต่ละขั้นตอนในโค้ด พร้อมคำอธิบาย *ทำไม* ของคำสั่งต่าง ๆ + +--- + +## ขั้นตอนที่ 1: จดจำข้อความจากภาพ + +ก่อนอื่นเราขอให้เอนจิน OCR อ่านพิกเซลและคืนอ็อบเจกต์ผลลัพธ์ที่เก็บทั้งภาพดิบและข้อความที่สกัดออกมา คิดว่าเป็นการที่เอนจิน “อ่าน” ใบแจ้งหนี้ให้คุณ + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### ทำไมเรื่องนี้ถึงสำคัญ + +- **Preserving graphics** หมายถึงการคงเลย์เอาต์แบบภาพ (ตาราง, โลโก้, ตราประทับ) ให้เหมือนกับที่สแกนจับได้อย่างแม่นยำ. +- อ็อบเจกต์ `result` มักจะมีเลเยอร์ข้อความที่ซ่อนอยู่ซึ่งเราจะฝังลงใน PDF ในขั้นต่อไป. +- การใช้ `recognize_image` แทน `recognize_pdf` ช่วยหลีกเลี่ยงขั้นตอนแปลงเพิ่มเติม ทำให้การประมวลผลสำหรับภาพหน้าเดียวเร็วขึ้น. + +#### ความแปรผันทั่วไป + +- หากคุณมี **multi‑page TIFF** ให้ส่งพาธไฟล์โดยตรง; เอนจินส่วนใหญ่จะถือแต่ละหน้าเป็นภาพแยกกัน. +- สำหรับ PDF ที่มีภาพอยู่แล้ว คุณสามารถเรียก `engine.recognize_pdf("file.pdf")` และข้ามขั้นตอนนี้ได้เลย. + +--- + +## ขั้นตอนที่ 2: ส่งออกผลลัพธ์ OCR เป็น PDF/A ที่ค้นหาได้ + +ตอนนี้เรานำ `result` จากขั้นตอน 1 ไปบอกเอนจินให้เขียนไฟล์ใหม่ ธงสำคัญที่นี่คือ *PDF/A*—เวอร์ชันมาตรฐาน ISO ของ PDF ที่ออกแบบมาสำหรับการเก็บรักษาระยะยาว + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### ทำไมเรื่องนี้ถึงสำคัญ + +- **Searchable PDF**: ไฟล์ผลลัพธ์มีเลเยอร์ข้อความที่ซ่อนอยู่และสามารถเลือกได้ คุณจึงสามารถกด Ctrl + F ค้นหาในเอกสารได้ทันที. +- **PDF/A compliance**: องค์กรบางแห่ง (กฎหมาย, การเงิน) ต้องการ PDF/A เพื่อเป็นหลักฐานตรวจสอบ; ขั้นตอนนี้ทำให้เป็นไปตามกฎโดยอัตโนมัติ. +- วิธีนี้ยัง **adds searchable text** โดยไม่ทำให้ภาพแบนลง จึงรักษาความคมชัดของกราฟิกได้อย่างสมบูรณ์. + +#### Edge case: Need a regular PDF instead? + +หากคุณไม่ต้องการ PDF/A ให้เปลี่ยน `save_as_pdfa` เป็น `save_as_pdf` ส่วนที่เหลือของเวิร์กโฟลว์ยังคงเหมือนเดิม. + +--- + +## ขั้นตอนที่ 3: ตรวจสอบ PDF ที่ค้นหาได้ + +การตรวจสอบอย่างรวดเร็วจะช่วยป้องกันบั๊กที่ซ่อนอยู่ในภายหลัง เปิดไฟล์ที่สร้างขึ้นในโปรแกรมอ่าน PDF ใดก็ได้ ลองเลือกคำหนึ่งคำและใช้ฟังก์ชันค้นหา + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณรันสคริปต์ คอนโซลจะแสดง: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +เมื่อเปิดไฟล์ คุณควรเห็นภาพใบแจ้งหนี้ต้นฉบับพร้อมเลเยอร์ข้อความที่บางและมองไม่เห็น การไฮไลท์คำใดก็จะพบว่ามันเลือกได้—**นั่นคือข้อความที่ค้นหาได้** ที่คุณเพิ่งเพิ่มเข้าไป. + +--- + +## การเพิ่มข้อความที่ค้นหาได้ให้กับ PDF ที่มีอยู่ (โบนัส) + +บางครั้งคุณอาจมี PDF อยู่แล้วแต่ต้อง **add searchable text** ให้กับมัน เอนจินเดียวกันสามารถซ้อนผลลัพธ์ OCR ลงบน PDF ที่มีอยู่ได้: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +ที่นี่ `apply_to` จะผสานเลเยอร์ที่ซ่อนอยู่กับหน้าต้นฉบับ ทำให้คุณ **create searchable PDF** ได้โดยไม่ต้องสแกนใหม่. + +--- + +## ข้อผิดพลาดทั่วไปและเคล็ดลับ + +| ปัญหา | วิธีหลีกเลี่ยง | +|-------|----------------| +| **Low‑resolution source images** (< 150 dpi) | ขยายภาพหรือขอสแกนความละเอียดสูงกว่า; ความแม่นยำของ OCR ลดลงอย่างมากเมื่อต่ำกว่า 150 dpi. | +| **Missing language data** | ติดตั้งแพ็คเกจภาษาที่เหมาะกับ OCR engine ของคุณ (`pip install pdfocr[eng,spa]`). | +| **Output folder not writable** | รันสคริปต์ด้วยสิทธิ์ที่เพียงพอหรือเลือกไดเรกทอรีอื่น. | +| **PDF/A validation fails** | ตรวจสอบว่าไม่ได้ฝังฟอนต์หรือ JavaScript ที่ไม่รองรับ; ส่วนใหญ่ SDK จะจัดการให้โดยอัตโนมัติเมื่อใช้ `save_as_pdfa`. | + +--- + +## สคริปต์เต็ม – โซลูชันไฟล์เดียว + +ด้านล่างเป็นสคริปต์ที่ทำงานแบบอิสระซึ่งเชื่อมทุกอย่างเข้าด้วยกัน คัดลอก‑วาง แทนที่พาธตัวแปร แล้วคุณก็พร้อม **convert image to PDF/A** ภายในไม่กี่วินาที + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**สิ่งที่สคริปต์นี้ทำ:** +1. โหลด OCR engine. +2. อ่านภาพที่เลือกและสกัดข้อความ. +3. เขียน **searchable PDF/A** ที่คุณสามารถแจกจ่ายหรือเก็บรักษาได้ทันที. + +คุณสามารถห่อ `main` logic ไว้ในฟังก์ชันที่ประมวลผลโฟลเดอร์ทั้งหมด—เพียงวนลูป `os.listdir()` แล้วทำซ้ำสามขั้นตอนสำหรับแต่ละไฟล์. + +--- + +## ขั้นตอนต่อไปและหัวข้อที่เกี่ยวข้อง + +ตอนนี้คุณได้เชี่ยวชาญ **วิธีทำ OCR PDF** แล้ว ลองสำรวจแนวคิดต่อไปนี้: + +- **Batch processing:** ใช้ `concurrent.futures` เพื่อ OCR ใบแจ้งหนี้หลายสิบฉบับพร้อมกัน. +- **Metadata injection:** เพิ่มวันที่สร้างหรือหมายเลขใบแจ้งหนี้ลงในเมตาดาต้า PDF เพื่อการจัดทำดัชนีที่ง่ายขึ้น. +- **Hybrid PDFs:** ผสานข้อความที่ค้นหาได้กับภาพต้นฉบับที่ฝังไว้เพื่อสร้าง “digital twin” ของเอกสารกระดาษ. +- **Alternative outputs:** ส่งออกเป็น **DOCX** หรือ **HTML** หากระบบ downstream ต้องการรูปแบบที่แก้ไขได้. + +แต่ละหัวข้อนี้ต่อยอดจากแนวคิดหลักที่คุณเรียนรู้—recognize, export, verify. + +--- + +## สรุป + +โดยสรุป คุณตอนนี้รู้แล้วว่า **วิธีทำ OCR PDF** โดยการแปลงภาพง่าย ๆ ให้เป็น **searchable PDF/A** ด้วยเพียงสามบรรทัดของ Python สคริปต์จัดการงานหนัก คงกราฟิกต้นฉบับ และให้เอกสารที่เป็นมาตรฐานซึ่งคุณสามารถค้นหา, เก็บรักษา หรือแชร์ได้ + +ลองใช้กับใบแจ้งหนี้, ใบเสร็จ, หรือสัญญาที่สแกนของคุณ หากเจออุปสรรคใด ๆ คอมเมนต์ด้านล่างหรือดูเอกสารอย่างเป็นทางการของ SDK—มักจะมีตัวอย่างเพิ่มเติมมากมาย. Happy coding, และสนุกกับความสามารถใหม่ที่ทำให้ภาพใด ๆ กลายเป็นข้อมูลที่ค้นหาได้ทันที! + +![ตัวอย่างวิธีทำ OCR PDF แสดงภาพต้นฉบับและการซ้อนทับ PDF ที่ค้นหาได้](placeholder.png "ตัวอย่างวิธีทำ OCR PDF") + +## สิ่งที่คุณควรเรียนต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ต่อ‑ขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานทางเลือกในโครงการของคุณเอง + +- [วิธีทำ OCR PDF ด้วย .NET และ Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [จดจำข้อความ PDF – การทำ OCR ด้วย Aspose.OCR สำหรับ Java](/ocr/english/java/ocr-operations/) +- [แปลงภาพเป็น PDF C# – บันทึกผลลัพธ์ OCR หลายหน้า](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/thai/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..637a2c32d --- /dev/null +++ b/ocr/thai/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-06-06 +description: วิธีทำ OCR PDF ด้วย Aspose OCR Cloud. เรียนรู้การดึงข้อความจาก PDF, แปลงหน้าของ + PDF เป็น PNG, และบันทึกภาพหน้าของ PDF ด้วย Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: th +og_description: วิธีทำ OCR PDF ด้วย Aspose OCR Cloud คู่มือนี้แสดงวิธีสกัดข้อความธรรมดาจาก + PDF, แปลงหน้าของ PDF เป็น PNG, และบันทึกภาพหน้าของ PDF. +og_title: วิธี OCR PDF ด้วย Aspose OCR Cloud – ขั้นตอนโดยละเอียด +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: วิธีทำ OCR PDF ด้วย Aspose OCR Cloud – คู่มือเต็ม +url: /th/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีทำ OCR PDF ด้วย Aspose OCR Cloud – คู่มือเต็ม + +เคยสงสัย **how to OCR PDF** อย่างไรโดยไม่ต้องต่อสู้กับเครื่องมือเดสก์ท็อปที่หนักหน่วงไหม? คุณไม่ได้เป็นคนเดียว—นักพัฒนาหลายคนเจออุปสรรคนี้เมื่อต้องการวิธีที่รวดเร็วและโปรแกรมเมติกเพื่อดึงข้อความจากเอกสารสแกน ข่าวดีคือ? ด้วย Aspose OCR Cloud คุณสามารถ **extract text from PDF**, แปลงแต่ละหน้าเป็น PNG, และแม้กระทั่ง **save PDF page images** เพื่อใช้ในภายหลัง ทั้งหมดจากสคริปต์ Python ที่เรียบร้อย + +ในบทแนะนำนี้เราจะพาคุณผ่านทุกอย่างที่ต้องรู้: ตั้งแต่การติดตั้ง SDK, การให้ลิขสิทธิ์กับเอนจิน, การจดจำ PDF หลายหน้า, ไปจนถึงการดึงข้อความธรรมดา, การแปลงหน้าเป็น PNG, และการบันทึกรูปภาพเหล่านั้นลงดิสก์ เมื่อเสร็จคุณจะมีโค้ดสั้นที่นำกลับมาใช้ได้ซ้ำในโปรเจกต์ใด ๆ ที่ต้องการความสามารถ **how to OCR PDF**. + +## สิ่งที่คุณต้องเตรียม + +- **Python 3.8+** (โค้ดทำงานบน 3.10 และใหม่กว่าเช่นกัน) +- บัญชี Aspose OCR Cloud – คุณจะได้รับไฟล์ลิขสิทธิ์ทดลองฟรี (`Aspose.OCR.lic`) +- แพคเกจ `asposeocrcloud` (`pip install asposeocrcloud`) +- PDF สแกนหลายหน้าที่คุณต้องการประมวลผล + +เท่านี้เอง ไม่ต้องมีไบนารีเพิ่มเติม ไม่ต้องพึ่งพาไลบรารีเนทีฟ เพียงแค่ Python ธรรมดา + +## วิธีทำ OCR PDF – การตั้งค่าและลิขสิทธิ์ + +ก่อนที่คุณจะเรียกใช้เมธอด OCR ใด ๆ คุณต้องบอก SDK ว่าคุณเป็นใคร Aspose ใช้ไฟล์ลิขสิทธิ์ขนาดเล็กที่คุณวางไว้ในตำแหน่งที่สคริปต์ของคุณสามารถเข้าถึงได้ + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*เคล็ดลับ:* หากข้ามขั้นตอนลิขสิทธิ์ SDK จะยังทำงานได้แต่จะใส่ลายน้ำเล็ก ๆ ลงในภาพผลลัพธ์ ไม่เหมาะกับการใช้งานจริง + +## ขั้นตอนที่ 2: ติดตั้ง Aspose OCR Cloud Python SDK + +เปิดเทอร์มินัลและรัน: + +```bash +pip install asposeocrcloud +``` + +แพคเกจนี้จะดึง dependencies ที่จำเป็นทั้งหมด (requests, pillow, ฯลฯ) ทำให้คุณไม่ต้องหาอะไรเพิ่มเติม + +## ขั้นตอนที่ 3: สร้าง OCR Engine และเลือกภาษา + +เอนจินเป็นหัวใจของการทำงาน คุณสามารถระบุภาษาที่ Aspose รองรับได้; ภาษาอังกฤษทำงานได้ในกรณีส่วนใหญ่ + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +ทำไมต้องตั้งค่าภาษา? เพราะ OCR engine ใช้พจนานุกรมเฉพาะภาษาที่ช่วยเพิ่มความแม่นยำ หากคุณกำลังประมวลผล PDF ภาษาเฟรนช์ เพียงเปลี่ยน `ENGLISH` เป็น `FRENCH` + +## ขั้นตอนที่ 4: ระบุตำแหน่ง PDF หลายหน้า ของคุณ + +ให้เอนจินทราบพาธเต็มของไฟล์ที่คุณต้องการประมวลผล พาธแบบ relative ก็ใช้ได้ตราบใดที่อ้างอิงจากไดเรกทอรีทำงานของสคริปต์ + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +ตรวจสอบให้แน่ใจว่าไฟล์สามารถอ่านได้; หากไม่เช่นนั้นคุณจะเจอ `FileNotFoundError` + +## ขั้นตอนที่ 5: รัน OCR – คุณจะได้รายการผลลัพธ์ + +การเรียก `recognize_pdf` จะคืนค่าเป็นรายการที่แต่ละองค์ประกอบสอดคล้องกับหนึ่งหน้าของ PDF ต้นฉบับ + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +แต่ละ `OcrResult` มีสองคุณสมบัติที่สะดวก: + +* `text` – การแสดงผลเป็นข้อความธรรมดาของหน้า (เหมาะสำหรับ **extract plain text pdf**) +* `image` – วัตถุ Pillow `Image` ของหน้าที่เรนเดอร์ (เหมาะสำหรับ **convert pdf page png**) + +## ขั้นตอนที่ 6: ดึงข้อความจาก PDF และแปลงหน้าเป็น PNG + +ตอนนี้เราจะวนลูปผ่านผลลัพธ์, พิมพ์ข้อความที่ดึงออก, และบันทึกเวอร์ชัน PNG ของทุกหน้า + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### ผลลัพธ์ที่คาดว่าจะเห็นในคอนโซล + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +คุณจะพบไฟล์ `page_1.png`, `page_2.png`, … อยู่ใน `YOUR_DIRECTORY`. ไฟล์เหล่านี้คือภาพหน้าที่แปลงเป็น raster ที่คุณสามารถส่งต่อไปยัง pipeline การประมวลผลภาพต่อไปได้ + +## ขั้นตอนที่ 7: บันทึกภาพหน้า PDF (การประมวลผลหลังขั้นตอนเพิ่มเติม) + +หากคุณต้องการเพียงภาพและไม่ต้องการข้อความ คุณสามารถข้ามบรรทัด `print(res.text)` ได้ ในทางกลับกัน หากต้องการเก็บข้อความในไฟล์ `.txt` แยกต่างหาก เพียงเพิ่มการเขียนไฟล์เล็กน้อย: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +การเพิ่มเล็ก ๆ นี้แสดงให้เห็นว่าการ **save PDF page images** ทำได้ง่ายแค่ไหน พร้อมกับการบันทึกเนื้อหาที่ดึงออกมา + +## ตัวอย่างทำงานเต็มรูปแบบ + +เมื่อนำทุกอย่างมารวมกัน นี่คือสคริปต์เต็มที่คุณสามารถคัดลอก‑วางลงใน `ocr_pdf.py` : + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +รันด้วยคำสั่ง: + +```bash +python ocr_pdf.py +``` + +คุณควรเห็นข้อความที่แสดงในคอนโซลของแต่ละหน้าพร้อมกับไฟล์ PNG หลายไฟล์ + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานแบบอื่นในโปรเจกต์ของคุณ + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/thai/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..222f2a0f0 --- /dev/null +++ b/ocr/thai/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-06 +description: วิธีการเตรียมภาพล่วงหน้าสำหรับ OCR ด้วย Python เรียนรู้การทำไบนาไรซ์ภาพด้วย + Otsu วิธีการแก้เอียงเอกสารสแกน และเพิ่มความแม่นยำของ OCR สำหรับข้อความภาษาเยอรมัน +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: th +og_description: วิธีการเตรียมภาพล่วงหน้าสำหรับ OCR ด้วย Python บทเรียนนี้แสดงการทำให้ภาพเป็นสีขาว‑ดำด้วยวิธี + Otsu, วิธีการแก้ไขการเอียงของเอกสารสแกน, และวิธีการปรับปรุงความแม่นยำของ OCR สำหรับภาพภาษาเยอรมัน. +og_title: วิธีเตรียมภาพสำหรับ OCR – คู่มือ Python ฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: วิธีเตรียมภาพสำหรับ OCR – คู่มือ Python ฉบับเต็ม +url: /th/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีการเตรียมภาพสำหรับ OCR – คู่มือ Python ฉบับสมบูรณ์ + +เคยสงสัย **วิธีการเตรียมภาพสำหรับ OCR** ว่าจะทำให้ข้อความออกมาชัดเจนเหมือนคริสตัลหรือไม่? คุณไม่ได้เป็นคนเดียว เอกสารสแกน—โดยเฉพาะหน้าภาษาเยอรมันที่มีสัญญาณรบกวน—อาจเป็นฝันร้ายสำหรับเครื่อง OCR ใด ๆ ข่าวดีคือ? ขั้นตอนการเตรียมภาพอัจฉริยะไม่กี่ขั้นตอนสามารถเปลี่ยนสแกนที่เบลอและมีจุดรบกวนให้เป็นภาพที่สะอาดและอ่านได้โดยเครื่อง + +ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่างเชิงปฏิบัติที่แสดง **วิธีการเตรียมภาพสำหรับ OCR** ด้วย Python คุณจะได้เรียนรู้ **การทำให้ภาพเป็นสีขาวดำด้วย Otsu**, **วิธีการแก้ไขการเอียงของเอกสารสแกน**, และโดยรวม **วิธีการปรับปรุงความแม่นยำของ OCR** เมื่อคุณต้อง **ดึงข้อความจากไฟล์ภาพภาษาเยอรมัน** ไม่มีเนื้อหาเกินความจำเป็น เพียงสคริปต์ทำงานที่คุณสามารถคัดลอก‑วางได้ทันที + +## สิ่งที่คุณต้องเตรียม + +- **Python 3.9+** (any recent version works) +- ไลบรารี OCR ที่เปิดเผยคลาส `OcrEngine` – สำหรับการสาธิตเราจะสมมติว่าใช้แพคเกจ `ocr` ทั่วไป ติดตั้งด้วย `pip install ocr-lib`. +- สแกนภาษาเยอรมันที่มีสัญญาณรบกวน (`noisy_german_scan.tif`) ที่คุณต้องการทดสอบ +- ความเข้าใจพื้นฐานเกี่ยวกับฟังก์ชัน Python (ถ้าคุณเคยเขียน `def` มาก่อนก็พร้อม) + +> **Pro tip:** หากคุณใช้ SDK OCR ตัวอื่น (เช่น Tesseract ผ่าน `pytesseract`) แนวคิดยังคงเหมือนเดิม—เพียงปรับชื่อเมธอดให้ตรง + +## ภาพรวมของวิธีแก้ปัญหา + +1. **Create an OCR engine instance.** +2. **Set the recognition language to German.** +3. **Build a custom preprocessing pipeline** that includes deskewing, denoising, binarization (Otsu), and contrast stretching. +4. **Attach the pipeline to the engine** so every image passes through it automatically. +5. **Run the OCR** on a noisy German scan. +6. **Print the extracted text** to verify the result. + +ด้านล่างเราจะอธิบายแต่ละขั้นตอน แสดง **ทำไม** จึงสำคัญ และแสดงโค้ดที่คุณต้องใช้อย่างแม่นยำ + +![ตัวอย่างการเตรียมภาพสำหรับ OCR](image.png "ตัวอย่างการเตรียมภาพสำหรับ OCR") + +## ขั้นตอนที่ 1: สร้างอินสแตนซ์ของ OCR Engine + +First things first—without an engine, nothing happens. The `OcrEngine` object is the entry point that coordinates all later processing. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Why this matters:* การเริ่มต้น engine จะตั้งค่าทรัพยากรภายใน (เช่นโมเดลภาษา) และให้คุณมีพื้นฐานที่สะอาดเพื่อแนบ pipeline แบบกำหนดเองต่อไป + +## ขั้นตอนที่ 2: ตั้งค่าภาษาในการรับรู้เป็นภาษาเยอรมัน + +OCR accuracy is heavily language‑dependent. By telling the engine to expect German, you activate the right character set and language model. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +If you skip this, the engine might default to English, mis‑recognizing umlauts (ä, ö, ü) and the ß character—common pitfalls when dealing with German scans. + +## ขั้นตอนที่ 3: สร้าง Pipeline การเตรียมภาพแบบกำหนดเอง + +This is the heart of **how to preprocess images for OCR**. We’ll chain four transformations: + +| การแปลง | ทำอะไร | ทำไมถึงช่วย | +|----------|--------|--------------| +| **Deskew** | หมุนภาพกลับเป็นแนวนอน (สูงสุด 5°) | สแกนมักไม่ตรงแนวอย่างสมบูรณ์; การแก้เอียงจะลบความเอียงที่ทำให้การแยกอักขระสับสน | +| **Denoise** | ลดจุดรบกวนแบบสุ่ม (strength 0.7) | สัญญาณรบกวนสร้างขอบเท็จที่ OCR อาจตีความเป็นอักขระ | +| **Binarize (Otsu)** | แปลงเป็นสีขาว‑ดำโดยใช้วิธี Otsu | ภาพไบนารีที่สะอาดให้คอนทราสต์ชัดเจนระหว่างพื้นหน้า (ข้อความ) กับพื้นหลัง | +| **Contrast Stretch** | ขยายช่วงไดนามิก | ปรับปรุงการอ่านของเส้นที่อ่อนเฉา โดยเฉพาะในเอกสารเก่า | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### วิธีการแก้ไขการเอียงของเอกสารสแกน + +The `deskew` call above is the concrete answer to **how to deskew scanned documents**. Internally it estimates the dominant text line angle via Hough transform and rotates the image back. If your documents are rotated more than 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + +### ทำให้ภาพเป็นสีขาวดำโดยใช้ Otsu + +The `binarize(method="otsu")` line directly answers the query **binarize image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class variance, which is perfect for documents with bimodal histograms (dark text vs. light background). + +## ขั้นตอนที่ 4: แนบ Pipeline ไปยัง Engine + +Now we tell the OCR engine to run every incoming image through the pipeline we just built. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Why this matters:* Without registering, the engine would process the raw scan, ignoring all the cleaning we just configured. This step ensures **how to improve OCR accuracy** by applying the same preprocessing consistently. + +## ขั้นตอนที่ 5: รับรู้ข้อความจากสแกนภาษาเยอรมันที่มีสัญญาณรบกวน + +Time to put everything together. We feed the engine a noisy German image and let it do the heavy lifting. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +If you’re curious about performance, you can time the call: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## ขั้นตอนที่ 6: แสดงข้อความที่รับรู้ได้ + +Finally, we print the extracted string. This is the direct answer to **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### ผลลัพธ์ที่คาดหวัง + +Assuming the sample scan contains the sentence “Die schnelle braune Füchsin springt über den faulen Hund.” you should see something like: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +If the output still contains garbled characters, consider tweaking the `denoise` strength or increasing the `max_angle` for deskewing. + +## ข้อผิดพลาดทั่วไปและวิธีแก้ไข + +- **Missing language model:** ลืมเรียก `set_recognition_language(Language.GERMAN)` มักทำให้ไม่มีอูมลัตต์ ตรวจสอบการเรียกอีกครั้ง +- **Over‑denoising:** ความแรงมากกว่า 0.9 อาจลบเส้นบาง ๆ โดยเฉพาะในฟอนต์เก่า ควรใช้ 0.5‑0.7 สำหรับกรณีส่วนใหญ่ +- **Incorrect file format:** OCR บางตัวไม่รองรับ TIFF หลายหน้า หากมีเอกสารหลายหน้าให้แยกเป็นไฟล์หน้าเดียวก่อน +- **Pipeline order:** ลำดับที่แสดง (deskew → denoise → binarize → contrast) มีเหตุผล การทำ binarize ก่อน denoise จะตรึงสัญญาณรบกวนไว้ ควร denoise ก่อนเสมอ + +## การขยาย Pipeline (ต่อไปคืออะไร?) + +Now that you have a solid baseline, you might want to: + +- **Add a morphological opening** to clean tiny blobs (`.morph_open(kernel=3)`). +- **Integrate a language model** for post‑processing correction (`ocr_engine.apply_spellcheck()`). +- **Parallelize batch processing** for large datasets using `concurrent.futures`. + +All of these are natural extensions that keep the core idea of **how to preprocess images for OCR** intact while boosting **how to improve OCR accuracy** even further. + +## สรุป + +We’ve just covered **how to preprocess images for OCR** from start to finish: create an engine, set German language, build a pipeline that **binarize image using Otsu**, **how to deskew scanned documents**, and finally **extract text from german image** with higher confidence. By following the six steps above you’ll see a noticeable jump in recognition quality—no more endless manual corrections. + +Give the script a spin with your own scans, experiment with the parameters, and let the results speak for themselves. Got questions about a particular preprocessing tweak? Drop a comment, and we’ll dive deeper together. + +Happy coding, and may your OCR be ever accurate! + +## What Should You Learn Next? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [สกัดข้อความจากรูปภาพด้วย C# พร้อมเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [วิธีตั้งค่าค่าธรณีใน OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [วิธี OCR รูปภาพ – ทำ OCR บนรูปภาพใน OCR Image Recognition](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/thai/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..b4ff6d46a --- /dev/null +++ b/ocr/thai/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-06-06 +description: OCR รูป PNG ด้วย Python – เรียนรู้วิธีดึงข้อความจากภาพ, รันตัวอย่าง OCR + ด้วย Python และแม้กระทั่งอ่านข้อความภาษากรีกโบราณได้อย่างง่ายดาย. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: th +og_description: อธิบายการทำ OCR ภาพ PNG ด้วย Python คู่มือนี้แสดงวิธีดึงข้อความจากภาพ, + รันตัวอย่าง OCR ด้วย Python และอ่านภาษากรีกโบราณได้อย่างง่ายดาย +og_title: OCR รูปภาพ PNG ด้วย Python – คู่มือฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR ภาพ PNG ด้วย Python – คู่มือเต็มขั้นตอนโดยละเอียด +url: /th/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image ใน Python – คู่มือเต็มขั้นตอน + +เคยสงสัยไหมว่าจะแปลงข้อความจากไฟล์ **OCR PNG image** โดยตรงจากสคริปต์ Python ได้อย่างไร? บางทีคุณอาจมีโฟลเดอร์ที่เต็มไปด้วยต้นฉบับสแกนโบราณและต้องการ **extract text from image** โดยไม่ต้องพิมพ์ทุกอย่างด้วยตนเอง ข่าวดีคือคุณไม่จำเป็นต้องมีปริญญาเอกด้านคอมพิวเตอร์วิชัน—แค่ไม่กี่บรรทัดของโค้ดและไลบรารีที่เหมาะสม แล้วคุณก็จะอ่านภาษากรีกโบราณได้ในไม่กี่วินาที + +ในบทเรียนนี้เราจะเดินผ่าน **python OCR example** ที่จดจำข้อความจาก PNG ตั้งค่าภาษาเป็น Greek polytonic และพิมพ์ผลลัพธ์ออกมา เมื่อจบคุณจะรู้วิธี **recognize image text** อย่างแม่นยำ จัดการกับปัญหาที่พบบ่อย และปรับสคริปต์ให้ทำงานกับภาษาอื่นหรือรูปแบบภาพอื่นได้ + +## สิ่งที่คุณจะได้เรียนรู้ + +- ติดตั้งและกำหนดค่าไลบรารี OCR ของ Python (pytesseract + Tesseract OCR) +- สร้างอินสแตนซ์ของ OCR engine และโหลดไฟล์ PNG +- ตั้งค่าภาษาเป็น Greek polytonic เพื่อ **read ancient greek** +- แสดงข้อความที่จดจำได้และแก้ไขปัญหาที่พบบ่อย +- ขยายสคริปต์เพื่อประมวลผลหลาย PNG หรือสลับไปใช้ภาษาอื่น + +### ข้อกำหนดเบื้องต้น + +| ข้อกำหนด | เหตุผลที่สำคัญ | +|-------------|----------------| +| Python 3.8+ | ไวยากรณ์สมัยใหม่และ type hints | +| `pytesseract` package | ห่อหุ้มเบา ๆ รอบ engine ของ Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Engine จริงที่ทำงานหนัก | +| Greek language data (`grc.traineddata`) | จำเป็นสำหรับ **read ancient greek** อย่างถูกต้อง | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | เป้าหมายของการสาธิต **ocr png image** | + +คุณสามารถติดตั้งส่วนของ Python ด้วย: + +```bash +pip install pytesseract Pillow +``` + +และบน Ubuntu/macOS คุณจะต้องเพิ่ม engine เอง: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +อย่าลืมดาวน์โหลดข้อมูลฝึก Greek polytonic: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Path อาจแตกต่าง; ปรับ `TESSDATA_PREFIX` หากจำเป็น)* + +--- + +## OCR PNG Image: สร้างอินสแตนซ์ของ Engine + +สิ่งแรกที่เราต้องการคืออ็อบเจ็กต์ที่สื่อสารกับ Tesseract ใน `pytesseract` engine ถูกเข้าถึงผ่านฟังก์ชันระดับโมดูล แต่เพื่อความชัดเจนเราจะห่อหุ้มไว้ในคลาสเล็ก ๆ ซึ่งสะท้อนแนวคิด “engine” ที่คุณเห็นในโค้ดต้นฉบับ + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**ทำไมต้องห่อหุ้ม?** +- ทำให้ API สาธารณะเหมือนกับสแนปเพล็ตเดิม ทำให้การย้ายโค้ดเป็นเรื่องง่าย +- สามารถเพิ่ม logging หรือการจัดการข้อผิดพลาดในภายหลังโดยไม่ต้องแก้ไขโฟลว์หลัก +- แสดงแนวปฏิบัติ OOP ที่ดี — สิ่งที่นักพัฒนาระดับสูงชื่นชม + +--- + +## Extract Text from Image: ตั้งค่าภาษาเป็น Greek Polytonic + +ตอนนี้เรามี engine แล้ว เราต้องบอกให้มันรู้ว่าคาดหวังภาษาอะไร Greek polytonic ใช้เครื่องหมายวรรณยุกต์ที่ไม่ได้รวมอยู่ในข้อมูล “greek” ปกติ ดังนั้นเราจึงชี้ Tesseract ไปที่ไฟล์ฝึก `grc` + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +หากคุณต้องการ **extract text from image** ในภาษาอื่น เพียงเปลี่ยน `"grc"` เป็น `"eng"` สำหรับอังกฤษ, `"fra"` สำหรับฝรั่งเศส ฯลฯ บรรทัดเดียวนี้ทำงานกับทุกภาษาที่คุณติดตั้งไว้ + +--- + +## Recognize Image Text: รัน OCR บน PNG + +เมื่อกำหนดภาษาแล้ว เราจะส่ง PNG เข้า engine ตัวอย่างเดิมใช้พาธคงที่; เราจะทำให้ยืดหยุ่นขึ้นโดยใช้วัตถุ `Path` + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**เคล็ดลับและกรณีขอบ** + +- **ไฟล์ไม่พบ** – ห่อการเรียกใน `try/except FileNotFoundError` เพื่อแสดงข้อความที่เป็นมิตร +- **PNG ความละเอียดต่ำ** – พิจารณา pre‑processing (เช่น การปรับขนาด, การทำไบนารี) ด้วย Pillow ก่อน OCR +- **ข้อความไม่ใช่ภาษากรีก** – Tesseract จะพยายามถอดรหัสต่อไป แต่ความแม่นยำจะลดลงอย่างมาก ควรเลือกภาษาให้ตรงกันเสมอ + +--- + +## Output the Recognized Text + +สุดท้ายเราพิมพ์ผลลัพธ์ออกมา ในโครงการจริงคุณอาจบันทึกลงฐานข้อมูล, CSV, หรือส่งต่อไปยัง pipeline การแปล + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +เมื่อรันสคริปต์กับสแกนที่ชัดเจนของจารึกกรีกโบราณ คุณควรเห็นข้อความประมาณนี้: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +หากผลลัพธ์ดูเป็นอักขระแปลก ๆ ให้ตรวจสอบว่าไฟล์ **greek.traineddata** อยู่ในโฟลเดอร์ที่ถูกต้องและ PNG ไม่มีสัญญาณรบกวนมากเกินไป + +--- + +## Full Working Example (All Steps in One Script) + +ด้านล่างเป็นโปรแกรมเต็มที่พร้อมรัน บันทึกเป็น `ocr_greek.py` แล้วเรียก `python ocr_greek.py` + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**ผลลัพธ์ที่คาดหวัง** (ตัดทอนเพื่อความกระชับ): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +หากคุณเห็นอักขระกรีกที่ถูกต้อง ยินดีด้วย — คุณได้ทำการ **ocr png image** ด้วย Python สำเร็จแล้ว! + +--- + +## Common Questions & Pro Tips + +### ฉันจะปรับปรุงความแม่นยำบน PNG ที่มีสัญญาณรบกวนได้อย่างไร? + +- แปลงภาพเป็นระดับสีเทา: `img = img.convert('L')` +- ใช้ threshold แบบไบนารี: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- ขยายขนาดด้วย `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +ขั้นตอนเหล่านี้มักทำให้ **recognize image text** จากความยุ่งยากกลายเป็นผลลัพธ์ที่สะอาด + +### ฉันสามารถประมวลผลโฟลเดอร์เต็มของ PNG ได้หรือไม่? + +ได้เลย. ห่อการเรียก `recognize_image` ไว้ในลูป `for` ที่วนผ่าน `Path.glob("*.png")` แล้วเก็บผลลัพธ์ในดิกชันนารีหรือเขียนลง CSV เพื่อการวิเคราะห์ต่อไป + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### ถ้าฉันต้องการสกัดเฉพาะตัวเลขเท่านั้นจะทำอย่างไร? + +ส่งสตริง **config** ที่กำหนดเองไปยัง `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +วิธีนี้คุณสามารถ **extract text from image** ที่มีตาราง, หมายเลขซีเรียล, หรือ timestamps ได้อย่างแม่นยำ + +### มีวิธีรับคะแนนความเชื่อมั่นหรือไม่? + +มี — ใช้ `pytesseract.image_to_data` ซึ่งคืนค่า TSV พร้อมคะแนนความเชื่อมั่นต่อคำ คุณสามารถกรองโทเคนที่ความเชื่อมั่นต่ำก่อนประกอบสตริงสุดท้ายได้ + +--- + +## Extending the Tutorial + +เมื่อคุณเชี่ยวชาญพื้นฐานแล้ว ลองสำรวจหัวข้อที่เกี่ยวข้องต่อไปนี้: + +- **Batch OCR with multiprocessing** – เร่งความเร็วการประมวลผลคอร์ปัส PNG ขนาดใหญ่ +- **Hybrid OCR + NLP pipelines** – แปลกรีกโบราณที่สกัดออกมาเป็นอังกฤษสมัยใหม่โดยอัตโนมัติ +- **Alternative engines** – ทดลอง `easyocr` หรือวิธีการที่อิง `opencv` สำหรับกรณีใช้เฉพาะ +- **Cloud OCR services** – Google Vision, Azure Computer Vision, หรือ AWS Textract สำหรับการขยายแบบ serverless + +แต่ละหัวข้อนี้ต่อยอดจาก **python ocr example** ที่เราได้ครอบคลุมแล้ว ทำให้คุณพร้อมลุยต่อไปอย่างมั่นใจ + +--- + +## Conclusion + +เราได้เริ่มจากสแนปเพล็ตเล็ก ๆ แล้วพัฒนาเป็น workflow **ocr png image** ที่แข็งแรงใน Python โดยสร้าง `OcrEngine` ตั้งค่าภาษาเป็น Greek polytonic ส่ง PNG เข้า engine และพิมพ์ผลลัพธ์ ตอนนี้คุณรู้วิธี **extract text from image**, **recognize image text**, และแม้กระทั่ง **read ancient greek** + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานทางเลือกในโปรเจกต์ของคุณเอง + +- [สกัดข้อความจากรูปภาพด้วย Aspose OCR – คู่มือขั้นตอนต่อขั้นตอน](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [วิธีตั้งค่าค่าธรณีใน OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [จดจำข้อความจากภาพด้วย Aspose OCR สำหรับหลายภาษา](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/thai/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..4e458ecad --- /dev/null +++ b/ocr/thai/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-06 +description: บทเรียน OCR ด้วย Python แสดงวิธีการจดจำข้อความในภาพ, ทำ OCR ความละเอียดสูงและสกัดข้อความภาษาสเปนโดยใช้ + OCR ที่เร่งด้วย GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: th +og_description: บทเรียน OCR ด้วย Python ที่สอนคุณขั้นตอนการจดจำข้อความในรูปภาพ, OCR + ความละเอียดสูง, และการดึงข้อความภาษาสเปนด้วยการเร่งความเร็วด้วย GPU. +og_title: บทเรียน OCR ด้วย Python – การจดจำข้อความด้วย GPU เร่งความเร็ว +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: บทเรียน OCR ด้วย Python – การจดจำข้อความในภาพด้วยการเร่งความเร็วด้วย GPU +url: /th/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – การจดจำข้อความในรูปภาพด้วยการเร่งความเร็วด้วย GPU + +เคยสงสัยไหมว่า **recognize image text** ในสคริปต์ Python จะทำอย่างไรโดยไม่ต้องใช้เวลาหลายชั่วโมงปรับแต่งการตั้งค่า? คุณไม่ได้เป็นคนเดียว ใน **python ocr tutorial** นี้เราจะสาธิตวิธีที่สะอาดและครบวงจรในการสกัดข้อความสเปนจากภาพความละเอียดสูง พร้อมใส่การเร่งความเร็วด้วย GPU เพื่อให้กระบวนการทำงานเร็วเหมือนสายฟ้า + +คิดว่าเป็นการสาธิตสั้น ๆ ระหว่างพักกาแฟที่คุณสามารถขยายเป็นไพป์ไลน์ระดับการผลิตในภายหลังได้ เมื่ออ่านจบคุณจะได้โปรแกรมที่ทำงาน **high resolution OCR**, ใช้ GPU ที่เปิดใช้งาน CUDA, และแสดงอักขระสเปนที่ต้องการอย่างแม่นยำ + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีติดตั้งและนำเข้าไลบรารี OCR สมัยใหม่ที่รองรับการเร่งความเร็วด้วย GPU +- วิธีสร้างอินสแตนซ์ของ OCR engine และตั้งค่าให้ **recognize image text** เป็นภาษาสเปน +- วิธีเปิดใช้งาน **gpu accelerated OCR** เพื่อเพิ่มความเร็วอย่างมหาศาลกับไฟล์ความละเอียดสูง +- วิธีจัดการกับกรณีขอบเช่นขาดไดรเวอร์ CUDA หรือการ fallback ไปยัง CPU +- เคล็ดลับเพื่อปรับปรุงความแม่นยำเมื่อคุณต้อง **extract spanish text** จากสแกนที่มีเสียงรบกวน + +### ข้อกำหนดเบื้องต้น + +- Python 3.9+ (โค้ดทำงานได้บน 3.10 และใหม่กว่า) +- GPU ที่รองรับ CUDA (ไม่บังคับแต่แนะนำอย่างยิ่ง) +- ความคุ้นเคยพื้นฐานกับ pip และ virtual environments + +หากคุณขาดอย่างใดอย่างหนึ่งก็ไม่เป็นไร—บทเรียนยังทำงานได้—แค่ข้ามขั้นตอน GPU แล้วไลบรารีจะ fallback ไปยัง CPU โดยอัตโนมัติ + +--- + +## Python OCR Tutorial: Install the Required Packages + +ก่อนอื่นเราต้องมี OCR engine ที่แข็งแรง สำหรับบทเรียนนี้เราจะใช้แพคเกจโอเพ่นซอร์ส **`easyocr`** ซึ่งมีการสนับสนุน GPU ในตัวเมื่อพบอุปกรณ์ที่เข้ากันได้ + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** หากคุณมี PyTorch ติดตั้งอยู่แล้ว ให้ตรวจสอบให้ตรงกับเวอร์ชัน CUDA ของคุณ (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). เวอร์ชันที่ไม่ตรงกันเป็นสาเหตุทั่วไปของข้อผิดพลาด “GPU not found” + +--- + +## Step 1: Create an OCR Engine Instance + +ตอนนี้เราจะเปิดใช้งาน engine. EasyOCR มีคลาสหลักชื่อ `Reader`. ตัวสร้างรับรายการรหัสภาษา; เราจะส่ง `"es"` สำหรับสเปน + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*ทำไมเรื่องนี้สำคัญ:* การกำหนดภาษาล่วงหน้าช่วยให้ engine โหลดน้ำหนักของเครือข่ายประสาทเทียมที่จำเป็นเท่านั้น ซึ่งประหยัดหน่วยความจำและเร่งการ inference—โดยเฉพาะอย่างยิ่งเมื่อคุณทำ **high resolution OCR** ต่อไป + +--- + +## Step 2: Prepare a High‑Resolution Image + +ภาพความละเอียดสูงให้พิกเซลมากขึ้นสำหรับโมเดล ซึ่งมักทำให้การจดจำอักขระดีขึ้น สมมติว่าคุณมีไฟล์ชื่อ `high_res_spanish.png` อยู่ในโฟลเดอร์ `samples` + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +หากไม่มีตัวอย่างความละเอียดสูง คุณสามารถดาวน์โหลดฟรีจาก Unsplash หรือสร้างภาพสังเคราะห์ด้วย Pillow. สิ่งสำคัญคือรักษา DPI ไว้เหนือ 300 เพื่อผลลัพธ์ที่ดีที่สุด + +--- + +## Step 3: Enable GPU Acceleration (Optional but Recommended) + +EasyOCR จะพยายามใช้ GPU เมื่อคุณตั้งค่า `gpu=True`. อย่างไรก็ตาม ควรตรวจสอบว่าอุปกรณ์จริง ๆ ถูกใช้หรือไม่ โดยเฉพาะบนเครื่องที่มีหลาย GPU + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*ทำไมต้องตรวจสอบ?* หากสคริปต์ลับ ๆ fallback ไปยัง CPU คุณอาจสงสัยว่าทำไมงาน 5 วินาทีถึงใช้ 30 วินาที การตรวจสอบเล็ก ๆ นี้ทำให้พฤติกรรมโปร่งใสและทำให้ **gpu accelerated OCR** ของคุณคาดเดาได้ + +--- + +## Step 4: Perform High‑Resolution OCR and Recognize Image Text + +ตอนนี้มาถึงส่วนที่สนุก—การอ่านข้อความจริง ๆ วิธี `readtext` ของ EasyOCR จะคืนรายการของทูเพิลที่ประกอบด้วย bounding box, สตริงที่จดจำได้, และคะแนนความเชื่อมั่น + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +หากต้องการสตริงดิบโดยไม่มีพิกัด ให้ตั้งค่า `detail=0`. สำหรับกรณีการใช้ **recognize image text** ส่วนใหญ่ ค่าเริ่มต้น (`detail=1`) จะให้บริบทเพียงพอสำหรับการประมวลผลต่อไป + +--- + +## Step 5: Extract Spanish Text and Clean the Output + +เพราะเราเรียก EasyOCR ให้ใช้ภาษาสเปนแล้ว สตริงที่ได้จึงเป็นสเปนอยู่แล้ว อย่างไรก็ตาม คุณอาจต้องการต่อข้อความเข้าด้วยกัน, ลบช่องว่าง, หรือกรองการตรวจจับที่ความเชื่อมั่นต่ำ + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**ถ้าความเชื่อมั่นต่ำล่ะ?** คุณสามารถลดเกณฑ์ (เสี่ยงต่อเสียงรบกวน) หรือทำพรี‑โปรเซสภาพ (เพิ่มคอนทราสต์, ทำไบนารี, หรือแก้ไขการเอียง). เทคนิคเหล่านี้เป็นที่นิยมเมื่อทำ **high resolution OCR** กับเอกสารสแกน + +--- + +## Step 6: Handling Edge Cases and Performance Tweaks + +แม้โมเดลที่ฝึกอย่างดีที่สุดก็อาจเจอสถานการณ์บางอย่าง ด้านล่างเป็นวิธีแก้ไขด่วนที่คุณสามารถคัดลอกไปใส่ในสคริปต์ได้ + +### 6.1 Fallback When No GPU Is Present + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling Very Large Images + +หากภาพของคุณใหญ่กว่า 4000 × 4000 px คุณอาจหมดหน่วยความจำ GPU. ให้ลดขนาดโดยคงอัตราส่วนและรักษา DPI ไว้: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +โค้ดสั้น ๆ เหล่านี้ทำให้สคริปต์ของคุณแข็งแรง ไม่ว่าจะรันบนเวิร์กสเตชันหรือแล็ปท็อปที่มีทรัพยากรจำกัด + +--- + +## Full Working Example + +รวมทุกอย่างเข้าด้วยกัน นี่คือสคริปต์เต็มที่คุณสามารถคัดลอก‑วางและรันได้ทันที: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**ผลลัพธ์ที่คาดหวัง (ตัวอย่าง):** + + + +## What Should You Learn Next? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ต่อ‑ขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [สกัดข้อความจากรูปภาพด้วย Aspose OCR – คู่มือขั้นตอน](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [วิธี OCR ข้อความในรูปภาพพร้อมภาษาโดยใช้ Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [วิธีจดจำสี่เหลี่ยมหน้ากระดาษสำหรับ OCR Text Recognition ใน Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/thai/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..0cbc10214 --- /dev/null +++ b/ocr/thai/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-06 +description: จดจำข้อความจากภาพโดยใช้เครื่องมือ OCR ของ Python เรียนรู้วิธีกำหนดค่าเครื่องมือ + OCR ของ Python และดึงข้อความจากภาพด้วยการประมวลผลบนคลาวด์ในไม่กี่นาที. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: th +og_description: จดจำข้อความจากภาพด้วยเครื่องมือ OCR ของ Python. คู่มือนี้แสดงวิธีตั้งค่าเครื่องมือ + OCR ของ Python และสกัดข้อความจากภาพอย่างมีประสิทธิภาพ. +og_title: การจดจำข้อความจากภาพใน Python – คู่มือการตั้งค่าเต็ม +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: แยกข้อความจากภาพใน Python – คู่มือการตั้งค่า OCR Engine อย่างเต็ม +url: /th/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# recognize text from image in Python – Complete Setup Tutorial + +เคยสงสัยไหมว่า จะ **recognize text from image** ด้วยเพียงไม่กี่บรรทัดของ Python? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะสร้าง receipt‑scanner, document digitizer หรือโครงการงานอดิเรกง่าย ๆ การสามารถ **extract text from image** เป็นทักษะที่ให้ผลตอบแทนอย่างรวดเร็ว + +ในบทแนะนำนี้ เราจะพาคุณผ่านกระบวนการทั้งหมด—เริ่มจากการตั้งค่าแบบ **configure OCR engine python**, ผ่านการยืนยันตัวตนบนคลาวด์, และสุดท้ายแสดงวิธี **extract text from image** ด้วยผลลัพธ์ที่เชื่อถือได้ ไม่มีเวทมนตร์ เพียงขั้นตอนชัดเจนที่คุณสามารถคัดลอก‑วางและรันได้ทันที + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีการติดตั้งและนำเข้าไลบรารี OCR ที่จำเป็น +- คำสั่งที่แน่นอนเพื่อ **configure OCR engine python** สำหรับการประมวลผลบนคลาวด์ +- สคริปต์ที่สมบูรณ์และสามารถรันได้ที่ **recognize text from image** และพิมพ์ผลลัพธ์ +- เคล็ดลับในการจัดการกับปัญหาทั่วไป เช่น คีย์ API ที่หายไปหรือรูปแบบภาพที่ไม่รองรับ +- ไอเดียระดับต่อไป เช่น การประมวลผลเป็นชุดและการสำรองแบบโลคัล + +### ข้อกำหนดเบื้องต้น + +- ติดตั้ง Python 3.8+ บนเครื่องของคุณ +- การเชื่อมต่ออินเทอร์เน็ต (ตัวอย่างใช้บริการ OCR บนคลาวด์) +- คีย์ API ที่ใช้งานได้จากผู้ให้บริการ OCR (คุณจะเห็นว่าจะใส่ที่ไหน) + +ถ้าคุณมีทั้งหมดนี้แล้ว ไปต่อกันเลย—ไม่มีเนื้อหาเกินจำเป็น เพียงคู่มือที่ใช้งานได้จริง + +--- + +## ขั้นตอนที่ 1: ติดตั้งไลบรารี OCR และนำเข้า + +ก่อนที่คุณจะ **configure OCR engine python** คุณต้องมีไลบรารีที่สื่อสารกับบริการคลาวด์ ในตัวอย่างของเราจะใช้แพ็กเกจสมมติที่เป็นตัวอย่างชื่อ `ocrcloud`. แทนที่ด้วยแพ็กเกจจริงที่คุณใช้ (เช่น `easyocr`, `google-cloud-vision`, เป็นต้น). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**ทำไมเรื่องนี้สำคัญ:** การนำเข้าคลาสทำให้คุณเข้าถึงเมธอดเช่น `use_cloud()` และ `set_api_key()` หากไม่ได้นำเข้า สคริปต์ส่วนอื่นจะเกิด `NameError` + +*เคล็ดลับ:* ระบุเวอร์ชันในไฟล์ `requirements.txt` ของคุณ (`ocrcloud==2.1.0`) เพื่อหลีกเลี่ยงการเปลี่ยนแปลงที่ทำให้โค้ดเสียในภายหลัง + +--- + +## ขั้นตอนที่ 2: สร้างและ **configure OCR engine python** สำหรับโหมดคลาวด์ + +ตอนนี้เราจะ **configure OCR engine python** จริง ๆ เครื่องจะเริ่มในโหมดโลคัลโดยค่าเริ่มต้น; การสลับเป็นโหมดคลาวด์ทำให้คุณสามารถส่งงานวิเคราะห์ภาพหนักไปยังเซิร์ฟเวอร์ที่มีประสิทธิภาพ + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**คำอธิบาย:** +- `OcrEngine()` สร้างอ็อบเจกต์เอนจินใหม่—คิดว่าเป็นผืนผ้าเปล่าของคุณ +- `use_cloud(True)` สลับสวิตช์ บอกเอนจินให้ส่งภาพผ่าน HTTPS แทนการประมวลผลในเครื่อง นี่สำคัญสำหรับผลลัพธ์ที่แม่นยำสูงบนฟอนต์ซับซ้อนหรือภาพความละเอียดต่ำ + +--- + +## ขั้นตอนที่ 3: ยืนยันตัวตนด้วยคีย์ API ของคลาวด์ของคุณ + +บริการ OCR บนคลาวด์ส่วนใหญ่ต้องการคีย์ API ขั้นตอนนี้จะแสดงวิธีใส่ข้อมูลรับรองอย่างปลอดภัย + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**หมายเหตุด้านความปลอดภัย:** อย่าเขียนคีย์โดยตรงในรีโปสิตอรีสาธารณะ ในการผลิตคุณควรดึงจากตัวแปรสภาพแวดล้อม: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## ขั้นตอนที่ 4: **recognize text from image** – ส่งภาพจากระยะไกลเพื่อประมวลผล + +เมื่อเอนจินถูกตั้งค่าแล้ว เราจึงสามารถ **recognize text from image** ได้ในที่สุด เมธอด `recognize_image()` รับพาธหรือ URL และคืนอ็อบเจกต์ที่มีข้อความที่ดึงออกมา + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**อะไรเกิดขึ้นภายใน?** +ไบต์ของภาพจะถูกอัปโหลดไปยังเอ็นด์พอยต์ของผู้ให้บริการ ประมวลผลโดยโมเดล deep‑learning และผลลัพธ์เป็นข้อความธรรมชาติจะถูกส่งกลับ หากภาพใหญ่ บริการอาจลดขนาดอัตโนมัติเพื่อเร่งการทำงาน + +--- + +## ขั้นตอนที่ 5: แสดงผลลัพธ์ **extract text from image** + +เมื่อบริการ OCR ทำงานเสร็จแล้ว เราเพียงแค่พิมพ์ข้อความออกมา ในแอปพลิเคชันจริงคุณอาจเก็บไว้ในฐานข้อมูลหรือส่งต่อให้ฟังก์ชันอื่น + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**ผลลัพธ์ที่คาดหวัง:** (ตัวอย่าง) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +หากผลลัพธ์ดูเป็นอักขระแปลก ๆ ตรวจสอบว่าภาพชัดเจนและคุณได้เลือกโมเดลภาษาที่ถูกต้อง (หลายบริการให้คุณระบุ `engine.set_language("en")`). + +--- + +## การจัดการกรณีขอบและปัญหาทั่วไป + +### 1. คีย์ API หายหรือไม่ถูกต้อง +หากคุณเห็นข้อผิดพลาดการยืนยันตัวตน ตรวจสอบว่า: +- คีย์ยังใช้งานได้และไม่หมดอายุ +- ถูกอ่านจากสภาพแวดล้อมอย่างถูกต้อง +- เครือข่ายของคุณอนุญาตการส่งออก HTTPS + +### 2. รูปแบบภาพที่ไม่รองรับ +ส่วนใหญ่ OCR API รองรับ JPEG, PNG, และ PDF การลองใช้ BMP หรือ TIFF อาจทำให้ตอบกลับว่า “format not supported”. แปลงด้วย Pillow หากจำเป็น: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. ขีดจำกัดอัตราการเรียก +บริการคลาวด์มักจำกัดจำนวนคำขอต่อวินาที หากถึงขีดจำกัด ให้ใช้ exponential back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. สลับไปใช้ OCR โลคัลเป็นสำรอง +หากคลาวด์หยุดทำงาน คุณสามารถสลับกลับไปใช้: + +```python +engine.use_cloud(False) # revert to local mode +``` + +การมีสำรองทำให้แอปของคุณทนทาน + +--- + +## ตัวอย่างการทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือสคริปต์ที่คุณสามารถรันได้ทันที (เพียงแทนที่ค่าตัวแปรที่เป็น placeholder). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**รันมัน:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +คุณควรเห็นข้อความที่ดึงออกมาถูกพิมพ์ในคอนโซล ยืนยันว่าคุณได้ **recognize text from image** และ **extract text from image** อย่างสำเร็จโดยใช้กระบวนการ **configure OCR engine python** อย่างถูกต้อง + +--- + +## สรุป + +เราพึ่งผ่านกระบวนการครบวงจรที่ทำให้คุณ **recognize text from image** ด้วย Python ตั้งแต่การติดตั้งไลบรารีจนถึงการยืนยันตัวตนกับบริการคลาวด์และสุดท้าย **extract text from image** ด้วยการเรียกฟังก์ชันเดียว ด้วยการ **configure OCR engine python** อย่างถูกต้อง คุณจะได้ทั้งความยืดหยุ่น (คลาวด์ vs. โลคัล) และความน่าเชื่อถือ (การจัดการข้อผิดพลาดที่เหมาะสม). + +ต่อไปทำอะไรดี? ลองประมวลผลเป็นชุดของใบเสร็จ เพิ่มการตรวจจับภาษา หรือทดลองใช้ PDF เป็นอินพุต เมื่อคุณเชี่ยวชาญพื้นฐานแล้วไม่มีขีดจำกัด + +ขอให้สนุกกับการเขียนโค้ด และอย่าลังเลที่จะถามคำถามในคอมเมนต์—ไม่มีอะไรเทียบกับการเรียนรู้ร่วมกัน! + +--- + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้ทางเลือกในโปรเจกต์ของคุณ. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/thai/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..fc9cdad6a --- /dev/null +++ b/ocr/thai/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-06-06 +description: ใช้ Python ทำ OCR บนรูปภาพและดูคะแนนความเชื่อมั่น เรียนรู้วิธีกรองคำที่มีความเชื่อมั่นต่ำ + ตั้งค่าขีดจำกัด และจัดการกับกรณีขอบ. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: th +og_description: ทำ OCR บนรูปภาพด้วย Python, ตรวจสอบระดับความมั่นใจ, และกรองคำที่ความมั่นใจต่ำ + บทเรียนนี้จะพาคุณผ่านตัวอย่างที่สมบูรณ์และสามารถรันได้. +og_title: เรียกใช้ OCR บนภาพด้วย Python – คู่มือเต็ม +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: ทำ OCR บนภาพด้วย Python – คู่มือขั้นตอนเต็มแบบละเอียด +url: /th/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# รัน OCR บนภาพด้วย Python – คู่มือขั้นตอนเต็ม + +เคยต้องการ **run OCR on image** ไฟล์แต่ไม่แน่ใจว่าจะดึงข้อความที่เชื่อถือได้ออกมาอย่างไร? คุณไม่ได้เป็นคนเดียว—นักพัฒนาหลายคนเจอปัญหาเดียวกันเมื่อคำที่ดึงออกมาดูสั่นและคะแนนความเชื่อมั่นเป็นเรื่องลึกลับ + +ในคู่มือนี้เราจะลงลึกสู่โซลูชันที่ทำงานได้: คุณจะเห็นวิธี **run OCR on image**, อ่านคะแนนความเชื่อมั่นรวม, และดึงคำที่มีความเชื่อมั่นต่ำที่อาจต้องตรวจสอบด้วยมือออกมา เมื่อเสร็จคุณจะมีสคริปต์ที่ใช้ซ้ำได้, เข้าใจว่าทำไมแต่ละบรรทัดสำคัญ, และรู้วิธีปรับค่าเกณฑ์ความเชื่อมั่นสำหรับโปรเจคของคุณเอง + +## สิ่งที่บทแนะนำนี้ครอบคลุม + +* เลือกเครื่องมือ OCR ที่มั่นคง (เราจะใช้ **EasyOCR**, ไลบรารี OCR ของ Python ที่เป็นที่นิยม) +* การตีความแอตทริบิวต์ `confidence` ที่ผลลัพธ์ OCR ทุกอย่างส่งคืน +* กรองคำด้วย **OCR confidence threshold** ที่กำหนดเอง +* ขยายสคริปต์สำหรับการประมวลผลแบบแบตช์หรือเครื่องมือทางเลือกเช่น **pytesseract** + +ไม่จำเป็นต้องมีประสบการณ์ OCR มาก่อน, เพียงแค่คุ้นเคยพื้นฐานกับ Python และสภาพแวดล้อมการทำงาน (แนะนำ Python 3.9+). + +พร้อมที่จะเปลี่ยนภาพหน้าจอที่เบลอให้เป็นข้อความที่สะอาดและค้นหาได้หรือยัง? ไปกันเลย. + +--- + +## ## วิธีรัน OCR บนภาพด้วย Python + +หัวใจของบทแนะนำคือโค้ดสแนปสามขั้นตอนที่สะท้อนโค้ดที่คุณเคยเห็นแล้ว ด้านล่างเราจะแยกแต่ละบรรทัด, อธิบายเหตุผล, และให้สคริปต์เต็มพร้อมคัดลอกและวาง. + +### ขั้นตอน 1: ติดตั้งและนำเข้า OCR Engine + +แรกสุด, ตรวจสอบให้แน่ใจว่ามีไลบรารี OCR พร้อมใช้งาน **EasyOCR** ทำงานได้ทันทีสำหรับหลายภาษาและให้คะแนนความเชื่อมั่นต่อคำ. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*ทำไมต้อง EasyOCR?* มันรวมโมเดล deep‑learning ที่ฝึกด้วยชุดข้อมูลหลากหลาย, ดังนั้นคุณมักจะได้ค่าความเชื่อมั่นที่สูงกว่ากลไก Tesseract เก่า, โดยเฉพาะกับภาพคุณภาพผสม. + +> **เคล็ดลับ:** หากคุณอยู่ในสภาพแวดล้อมที่จำกัด (เช่น Docker container ขนาดเล็ก), `pytesseract` อาจเบากว่า, แต่คุณจะสูญเสียความแม่นยำสมัยใหม่ที่ EasyOCR มีให้. + +### ขั้นตอน 2: รัน OCR บนภาพ + +ตอนนี้เราจริง ๆ **run OCR on image**. เมธอด `recognize_image` จากตัวอย่างเดิมถูกแทนที่ด้วยการเรียก `readtext` ของ EasyOCR, ซึ่งคืนค่ารายการของ tuple `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +แต่ละรายการใน `ocr_results` มีลักษณะดังนี้: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +องค์ประกอบที่สาม (`0.92` ในตัวอย่าง) คือคะแนนความเชื่อมั่นที่อยู่ในช่วง 0 ถึง 1. + +### ขั้นตอน 3: สรุปคะแนนความเชื่อมั่นรวม + +ไม่เหมือนสแนปก่อนหน้าที่พิมพ์แอตทริบิวต์ `confidence` เดียว, EasyOCR ให้คะแนนความเชื่อมั่นต่อคำ. เพื่อให้ได้ความรู้โดยรวม, เราจะหาค่าเฉลี่ยของมัน: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*ทำไมต้องเฉลี่ย?* มันให้การตรวจสอบสุขภาพอย่างรวดเร็ว—หากความเชื่อมั่นรวมต่ำกว่า, เช่น 70 %, คุณอาจต้องปรับปรุงภาพ (แสงดีกว่า, การเตรียมข้อมูลล่วงหน้า, ฯลฯ). + +### ขั้นตอน 4: รายการคำที่ความเชื่อมั่นต่ำ + +ตอนนี้มาถึงส่วนที่ตอบโดยตรงต่อความต้องการ “รายการคำที่ความเชื่อมั่นต่ำกว่าขีดจำกัดที่ต้องการ”. เราจะตั้ง **OCR confidence threshold** ที่ 0.80 (80 %) เป็นค่าเริ่มต้น, แต่คุณสามารถปรับได้. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +ลูปนี้พิมพ์แต่ละคำที่ไม่ผ่านเกณฑ์, พร้อมกับเปอร์เซ็นต์ความเชื่อมั่นของมัน. นี่คือการทำงานที่เหมือนกับลูป `for recognized_word in recognition_result.words` ดั้งเดิม, แต่ตอนนี้ทำงานกับรูปแบบผลลัพธ์ของ EasyOCR. + +--- + +## ## ทำความเข้าใจคะแนนความเชื่อมั่นของ OCR + +ความเชื่อมั่นไม่ใช่ตัวเลขวิเศษ; มันเป็นการประมาณของโมเดลว่ามั่นใจแค่ไหนกับการถอดข้อความหนึ่ง. นี่คือบางสิ่งที่ควรจำ: + +| สถานการณ์ | ความเชื่อมั่นโดยทั่วไป | ควรทำ | +|-----------|-------------------|------------| +| สแกนที่ชัดเจนและความละเอียดสูง | 0.95 – 1.00 | ไม่ต้องทำงานเพิ่มเติม | +| เบลอเล็กน้อยหรือแสงไม่สม่ำเสมอ | 0.80 – 0.94 | พิจารณาการเตรียมข้อมูลล่วงหน้าเล็กน้อย (เพิ่มคอนทราสต์) | +| สัญญาณรบกวนมาก, ข้อความหมุน | < 0.70 | ใช้การเตรียมภาพล่วงหน้า (แก้ไขการเอียง, กำจัดสัญญาณรบกวน) หรือเปลี่ยนไปใช้เครื่องมือ OCR อื่น | + +> **ระวัง:** บางภาษา (เช่น การเขียนลายมือแบบต่อเนื่อง) จะให้คะแนนต่ำตามธรรมชาติ. ปรับเกณฑ์ตามนั้น. + +### กรณีขอบและความแปรผัน + +1. **Batch Processing** – หากคุณต้องการ **run OCR on image** ไฟล์เป็นจำนวนมาก, ให้ใส่ตรรกะข้างต้นในลูปที่วนผ่านไดเรกทอรี. +2. **Multiple Languages** – ส่งรายการเช่น `['en', 'fr']` ไปยัง `easyocr.Reader` แล้วเครื่องมือจะตรวจจับทั้งสองภาษา. +3. **Alternative Engines** – อยากลอง **pytesseract**? แทนที่บล็อกรีดเดอร์ด้วย: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + จากนั้นคุณต้องรวมคะแนนความเชื่อมั่นต่ออักขระเป็นคะแนนต่อคำ—อาจต้องทำงานเพิ่มเล็กน้อยแต่ทำได้. +4. **Pre‑processing Tricks** – การใช้ฟิลเตอร์ของ OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) สามารถเพิ่มความเชื่อมั่นสำหรับสแกนที่มีสัญญาณรบกวน. + +--- + +## ## สคริปต์เต็มพร้อมรัน + +ด้านล่างเป็นไฟล์ Python ฉบับเต็มที่คุณสามารถใส่ในโปรเจคของคุณได้ บันทึกเป็น `ocr_report.py` แล้วรัน `python ocr_report.py`. ตรวจสอบให้แน่ใจว่าเส้นทางภาพชี้ไปยังไฟล์จริง. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**ผลลัพธ์ที่คาดหวัง** (ตัวเลขของคุณอาจแตกต่าง): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +หากทุกคำผ่านเกณฑ์ 80 % คุณจะเห็นข้อความเป็นมิตร “All words meet the confidence threshold.” แทน. + +--- + +## ## คำถามที่พบบ่อย (FAQ) + +**Q: Does this work with PDFs?** +A: ไม่ได้โดยตรง. แปลงแต่ละหน้า PDF เป็นภาพก่อน (เช่น ด้วย `pdf2image`) แล้วจึงส่งไฟล์ PNG/JPEG เข้าไปในสคริปต์. + +**Q: My confidence numbers are all low—what can I do?** +A: ลองทำการเตรียมภาพล่วงหน้า: เพิ่มคอนทราสต์, กำจัดสัญญาณรบกวนพื้นหลัง, หรือหมุนภาพให้เป็นแนวนอน. EasyOCR ยังรับพารามิเตอร์ `contrast_ths` ที่คุณสามารถปรับได้. + +**Q: Can I export the results to CSV?** +A: แน่นอน. หลังจากลูปความเชื่อมั่นต่ำ, เขียน `ocr_results` ไปยัง `csv.DictWriter` โดยแต่ละแถวมี `text`, `confidence`, และพิกัด bounding‑box. + +**Q: Is there a GPU‑accelerated version?** +A: EasyOCR จะใช้ CUDA อัตโนมัติหากมี GPU ที่เข้ากันได้และติดตั้ง PyTorch. ตรวจสอบด้วย `torch.cuda.is_available()` ก่อนรันสคริปต์. + +--- + +## สรุป + +เราเพิ่ง **run OCR on image** ด้วย Python, ตรวจสอบคะแนนความเชื่อมั่นรวม, และแยกคำที่ความเชื่อมั่นต่ำที่ต้องการ + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคในคู่มือนี้. แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจคของคุณ. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/turkish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..8320bdb48 --- /dev/null +++ b/ocr/turkish/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-06-06 +description: Dakikalar içinde Python OCR ile görüntüden metin çıkarın. Çok dilli görüntü + OCR'ını keşfedin, otomatik dil tespiti OCR'ını ve OCR metnini doğru bir şekilde + nasıl çıkaracağınızı öğrenin. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: tr +og_description: Python OCR ile görüntüden hızlıca metin çıkarın. Çok dilli görüntü + OCR'ını, otomatik dil algılamalı OCR'ı ve OCR metnini adım adım nasıl çıkaracağınızı + öğrenin. +og_title: Python OCR Kullanarak Görüntüden Metin Çıkarma – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Python OCR Kullanarak Görüntüden Metin Çıkarma – Tam Rehber +url: /tr/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntüden Metin Çıkarma – Python OCR Tam Kılavuz + +Hiç **görüntüden metin çıkarma** ihtiyacı duydunuz mu, ama hangi kütüphanenin birden fazla dili otomatik olarak işleyebileceğinden emin olmadınız mı? Yalnız değilsiniz—geliştiriciler uluslararası belgeler, makbuzlar veya taranmış broşürlerle çalışırken *OCR metni nasıl çıkarılır* sorusunu sürekli soruyor. Bu öğreticide, yalnızca bir görüntüden metin çıkarmakla kalmayıp aynı zamanda **dili anlık olarak algılayan** pratik bir Python örneği üzerinden çok dilli görüntü OCR'ını nasıl kolayca yapabileceğinizi göstereceğiz. + +OCR paketinin kurulumundan **otomatik dil algılama OCR** özelliğini etkinleştirmeye, örnek bir resim üzerinde motoru çalıştırmaya ve sonunda hem algılanan dili hem de çıkarılan dizeyi yazdırmaya kadar her şeyi ele alacağız. Sonunda, ister bir çeviri hattı ister veri‑işleme servisi kuruyor olun, herhangi bir projeye ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına sahip olacaksınız. + +## Görüntüden Metin Çıkarma – Ortamı Hazırlama + +Koda geçmeden önce çalışma ortamınızın aşağıdaki minimum gereksinimleri karşıladığından emin olun: + +- Python 3.8 ve üzeri (kütüphane, eski sürümlerin göz ardı ettiği tip ipuçları kullanıyor) +- `pip` paket yönetimi için +- En az iki farklı dilde (ör. İngilizce + İspanyolca) metin içeren bir görüntü dosyası + +Bu demoyu çalıştırmak için OCR kütüphanesine de ihtiyacınız olacak. Bu rehberde, gerçek dünyada popüler olan Tesseract veya EasyOCR gibi araçları yansıtan, ancak temiz bir Python API'si sunan hayali `ocr` paketini kullanacağız. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Pro ipucu:** İzin hataları alırsanız komutu `python -m` ile ön ekleyin ya da bir sanal ortam kullanın—global site‑paketlerinizi düzenli tutar. + +## OCR Motoru Örneği Oluşturma + +Kütüphane hazır olduğuna göre, ilk mantıklı adım **bir OCR motoru örneği oluşturmak**tır. Motoru, görüntüleri beslemeden önce yapılandırabileceğiniz akıllı bir tarayıcı olarak düşünün. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Motoru ayrı bir nesne olarak örneklemek, statik bir metod çağırmaktan neden daha iyidir? Motor nesnesi, (dil tercihleri gibi) yapılandırma durumunu tutar ve bu sayede birden çok görüntüde aynı ayarları yeniden kullanabilir, her seferinde yeniden başlatma maliyetinden kaçınabilirsiniz. + +## Otomatik Dil Algılama OCR'ı Etkinleştirme + +Çoğu OCR aracı, `eng` İngilizce, `spa` İspanyolca gibi bir dil kodu belirtmenizi ister. Dili manuel tahmin etmek, **çok dilli görüntü OCR** akışının amacına aykırıdır. Neyse ki, `ocr` paketi, görüntüyü inceleyip sahne arkasında en uygun dil modelini seçen bir *otomatik dil algılama OCR* modu sunar. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Bu şekilde **dil algılama OCR**'ı etkinleştirmek, uzun bir dil kodu listesi tutmanız gerekmediği anlamına gelir. Motor, gördüğü alfabeyi—Latin, Kiril, Han vb.—eşleştirir ve uygun modeli otomatik olarak yükler. + +## Çok Dilli Görüntü OCR'ı Gerçekleştirme + +Motor hazır olduğuna göre, **görüntüden metin çıkarma** zamanıdır. `recognize_image` metodu bir dosya yolu alır ve hem ham metni hem de algılanan dili içeren bir sonuç nesnesi döndürür. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +*PDF'den OCR metni nasıl çıkarılır* diye merak ediyorsanız, aynı motor `recognize_pdf` sunar—sadece metod adını değiştirin. Altındaki algılama mantığı aynı kalır, böylece aynı **otomatik dil algılama OCR** özelliğinden yararlanırsınız. + +## Algılanan Dil ve Çıkarılan Metni Görüntüleme + +Son olarak, motorun bulduklarını ekrana bastırıyoruz. Sonuç nesnesi `detected_language` (ör. `en` veya `es` gibi bir BCP‑47 etiketi) ve `text` (ham OCR çıktısı) özelliklerini sunar. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Örnek görüntümüz üzerinde scripti çalıştırdığınızda aşağıdakine benzer bir çıktı almanız gerekir: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Motorun İngilizce'yi birincil dil olarak doğru bir şekilde tanımladığını, aynı zamanda İspanyolca satırı da yakaladığını göreceksiniz—bu, sağlam bir **çok dilli görüntü OCR** çözümünden beklediğiniz tam olarak budur. + +### Algılama Başarısız Olursa Ne Olur? + +Bazen görüntü bulanık ya da alfabe çok egzotik olduğunda OCR motoru varsayılan bir dile (genellikle İngilizce) geri dönebilir. Bu gibi durumlarda bir dil listesi zorlayabilirsiniz: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Ancak unutmayın, dilleri zorlamak **otomatik dil algılama OCR**'ın rahatlığını ortadan kaldırır; bu yüzden yalnızca bilinen bir dil alt kümesi olduğunda kullanın. + +## Yaygın Tuzaklar ve OCR Metnini Güvenilir Çıkarma + +Otomatik algılamaya rağmen, birkaç küçük sorun işinizi zorlaştırabilir: + +1. **Düşük çözünürlüklü görüntüler** – OCR doğruluğu 150 dpi altında hızla düşer. Görüntüyü büyütün ya da daha yüksek çözünürlüklü bir tarama isteyin. +2. **Gürültü ve sıkıştırma artefaktları** – Görüntüyü motora vermeden önce basit bir eşik filtresi (`opencv` veya `Pillow`) uygulayın. +3. **Tek sayfada karışık alfabeler** – Bazı motorlar aynı anda Latin ve CJK karakterlerini işlemek konusunda zorlanır. Gerekirse sayfayı bölüp ayrı bölgelere ayrı ayrı tanıma uygulayın. + +Bu sorunları ele almak, **görüntüden metin çıkarma** sürecinin kalitesini büyük ölçüde artırır, özellikle gerçek dünya çok dilli belgelerle çalışırken. + +## Tam Çalışan Örnek + +Aşağıda, tartıştığımız tüm adımları birleştiren, çalıştırmaya hazır tam script yer alıyor. `multilingual_ocr.py` olarak kaydedin ve komut satırından çalıştırın. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Beklenen çıktı** (örnek görüntünün İngilizce ve İspanyolca metin içerdiği varsayılırsa): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +`multilang_page.png` dosyasını, içinde başka dillerde metin bulunan herhangi bir resimle değiştirmekten çekinmeyin—**otomatik dil algılama OCR** sayesinde script hâlâ mantıklı bir dil etiketi ve ilgili metni sağlayacaktır. + +![Görüntüden metin çıkarma örneği](https://example.com/ocr-sample.png "Görüntüden metin çıkarma") + +## Sonuç + +Artık bir görüntüden **OCR metni nasıl çıkarılır**, **otomatik dil algılama OCR** nasıl etkinleştirilir ve **çok dilli görüntü OCR** senaryoları minimum kodla nasıl yönetilir, biliyorsunuz. Bir OCR motoru örneği oluşturup, otomatik dil algılamayı açıp `recognize_image` çağırarak hem dil tanımlayıcısını hem de ham metni güvenilir bir şekilde alabilirsiniz. + +Sırada ne var? Çıkarılan dizeleri bir çeviri API'sine gönderin, aranabilir bir veri tabanına kaydedin ya da birden fazla sayfayı tek bir PDF raporunda birleştirin. Aynı yüksek‑seviye iş akışını koruyarak farklı OCR arka uçları (Tesseract, EasyOCR, Google Vision) ile de deneyler yapabilirsiniz—**dil algılama OCR** arayüzünün tutarlılığı sayesinde. + +Herhangi bir tuhaflıkla karşılaşırsanız, “Yaygın Tuzaklar” bölümüne geri dönün ya da görüntü ön‑işleme adımlarını ayarlayın. Kodlamanın tadını çıkarın ve bir sonraki projenizin doğru‑algılanan, kusursuz‑çıkarılan metinlerle dolu olmasını dileriz! + + +## Sonra Ne Öğrenmelisiniz? + + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım‑adım açıklamalı tam çalışan kod örnekleri içerir. + +- [Resmi Metne Dönüştür – URL'den Görüntü Üzerinde OCR Yap](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Resimden Metin Çıkarma – Aspose.OCR ile .NET için OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) +- [Aspose OCR ile birden fazla dilde metin tanıma](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/turkish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..d7b3aeb25 --- /dev/null +++ b/ocr/turkish/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR kullanarak görüntü PDF'lerinden metin çıkarın. Tarama belgelerini, + asenkron toplu tanıma ile hızlıca metne dönüştürmeyi öğrenin. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: tr +og_description: Python ile görüntü PDF'lerinden metin çıkarın. Bu adım adım rehber, + taranmış belgeleri asenkron OCR kullanarak metne nasıl dönüştüreceğinizi gösterir. +og_title: Görüntülerden PDF Metni Çıkarma – Python OCR Eğitimi +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Görüntü PDF'lerinden Metin Çıkarma – Taralı Belgeleri Metne Dönüştürmek için + Python Rehberi +url: /tr/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntülerden PDF Metni Çıkarma – Tarama Belgelerini Metne Dönüştürmek için Python Rehberi + +Saatlerce yeniden yazmak zorunda kalmadan **extract text from images pdf**'yi çıkarmanız gerektiğinde? Bu rehberde, Python'da basit bir asenkron OCR iş akışı kullanarak **convert scanned documents to text** nasıl yapılacağını göstereceğiz. + +Eğer bir yığın taranmış PDF'ye bakıp “Daha hızlı bir yol olmalı” diye düşündüyseniz, doğru yerdesiniz. Her satır kodu adım adım inceleyecek, her parçanın neden önemli olduğunu açıklayacak ve karşılaşabileceğiniz bazı uç durumları ele alacağız. + +## Öğrenecekleriniz + +- Bir OCR motoru başlatma ve tanıma dilini ayarlama. +- PNG ve PDF'lerden oluşan karışık bir listeyi toplu tanıyıcıya beslemenin mekanikleri. +- OCR işini asenkron olarak çalıştırarak uygulamanızın yanıt vermeye devam etmesini sağlama. +- Sonuçları geri çekme, kaynak dosyalarla eşleştirme ve temiz bir çıktı üretme. + +**Önkoşullar**: Python 3.8+, `asyncio` veya `concurrent.futures` hakkında temel bir anlayış ve örnekteki `OcrEngine` sınıfına benzer bir OCR kütüphanesi (ör. Aspose.OCR, Tesseract sarmalayıcısı veya özel bir sarmalayıcı). Ağır bir kurulum gerekmez—kütüphaneyi kurun, hazırsınız. + +![görüntülerden pdf metni çıkarma](https://example.com/placeholder.png "OCR çıktısının ekran görüntüsü – extract text from images pdf") + +## Görüntülerden PDF Metni Çıkarma – OCR Motorunu Kurma + +İlk olarak, belgelerinizin diliyle yapılandırılmış bir OCR motoru örneğine ihtiyacınız var. Bizim örneğimizde Fransızca kullanacağız, ancak istediğiniz desteklenen herhangi bir dile değiştirebilirsiniz. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Neden bu önemli**: Dili önceden ayarlamak doğruluğu büyük ölçüde artırır. Motor, dile özgü sözlükler ve karakter modelleri kullanır; yanlış dil beslemek bozuk çıktının yaygın bir kaynağıdır. + +## Dosya Listesini Hazırlama – Görüntüler ve PDF'ler Birlikte + +Toplu tanıyıcımız hem raster görüntüleri (`.png`, `.jpg`) hem de PDF kapsayıcılarını işleyebilir. Sadece dosya yollarının bulunduğu sade bir Python listesi verin. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**İpucu**: Listeyi düz tutun; motor her PDF sayfasını tanımadan önce dahili olarak görüntülere ayıracaktır. Binlerce dosyanız varsa, bellek dalgalanmalarını önlemek için listeyi daha küçük partilere bölmeyi düşünün. + +## Asenkron Toplu Tanıma Başlatma + +Ana iş parçacığını engellemek yerine OCR görevini arka planda başlatıyoruz. Metot, sonunda bir `OcrResult` nesnesi listesi tutacak bir `Future` döndürür. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Nasıl çalışır**: Motor, uygulamanın uygulanışına bağlı olarak bir iş parçacığı havuzu (veya async görev) oluşturur. Bu sayede UI güncellemek, daha fazla dosya almak veya ilerlemeyi kaydetmek gibi diğer işleri yapmaya devam edebilirsiniz; ağır işlem başka bir yerde gerçekleşir. + +## OCR Çalışırken Faydalı Bir Şey Yapın + +Yaygın bir hata, boş oturup geleceği sıkı bir döngüde sorgulamaktır. Bunun yerine ilgisiz bir işi halledebilirsiniz. Demonstrasyon amaçlı sadece bir durum satırı yazdıracağız. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Future Tamamlandığında Sonuçları Toplama + +OCR çıktısını toplamak istediğinizde, `concurrent.futures`'dan `as_completed` kullanın. Bu desen, bir future ya da birden çok future olduğunda aynı şekilde çalışır. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Gördükleriniz**: Her dosya yolu, ardından çıkarılan düz metin temsiliyle birlikte. PDF'ler için `result.text` tüm sayfaların birleştirilmiş metnini içerir. + +### Beklenen Çıktı (örnek) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Eğer eksik karakterler fark ederseniz, ayarladığınız dilin belge diliyle eşleştiğinden emin olun ve motoru beslemeden önce görüntüleri ön‑işleme (eğikliği düzeltme, kontrast artırma) yapmayı düşünün. + +## Kenar Durumları ve Yaygın Tuzaklar + +| Durum | Ne Yapmalı | +|-----------|------------| +| **Karışık diller** | Önce bir dil algılama adımı çalıştırın, ardından dil başına ayrı motorlar oluşturun. | +| **Devasa PDF'ler (> 100 MB)** | PDF'yi disk üzerinde tek tek sayfalara bölün (ör. `PyPDF2` kullanarak) ve ayrı girişler olarak besleyin. | +| **Latin dışı yazı sistemleri** | OCR kütüphanesinin gerekli dil paketini içerdiğinden emin olun; bazı kütüphaneler ek veri dosyaları indirmenizi ister. | +| **Performans darboğazı** | İş parçacığı havuzu boyutunu artırın (`engine.set_thread_pool_size(8)`) veya mevcutsa GPU‑hızlandırmalı bir arka plan seçin. | +| **Düşük çözünürlüklü görüntülerde eksik metin** | OpenCV ile ön‑işleme yapın: `cv2.resize`, `cv2.threshold` ve `cv2.medianBlur` kullanarak okunabilirliği artırın. | + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Bu dosyayı `extract_text_async.py` olarak kaydedin, `YOUR_DIRECTORY` kısmını dosyalarınızın yolu ile değiştirin, OCR paketini kurun (`pip install your-ocr-lib`) ve `python extract_text_async.py` komutunu çalıştırın. Konsolda daha önce gösterilen çıktıyı görmelisiniz. + +## Sonraki Adımlar – Temel Çıkarma Ötesine Geçmek + +- **Post‑processing**: Fazla boşlukları temizleyin, Unicode'u normalleştirin (`unicodedata.normalize`) veya OCR gürültüsünü temizlemek için bir imla denetleyicisi çalıştırın. +- **Yapısal çıktı**: Sonuçları CSV, JSON olarak dışa aktarın veya doğrudan bir veritabanına kaydederek sonraki aramalara hazırlayın. +- **Paralel partiler**: Yüzlerce dosyanız varsa birden çok future oluşturun ve bir kuyruk kullanarak CPU'yu meşgul tutun, belleği aşırı yüklemeden. +- **Web çerçeveleriyle bütünleştirme**: Bu betiği bir Flask ya da FastAPI uç noktasına bağlayarak talep üzerine OCR hizmeti sunun. + +--- + +### TL;DR + +Artık **extract text from images pdf**'yi asenkron çalışan minimal bir Python betiğiyle nasıl yapacağınızı biliyorsunuz; bu sayede **convert scanned documents to text** işlemini programınız yanıt verirken gerçekleştirebilirsiniz. Dil ayarları, batch boyutları ve ön‑işleme püf noktalarıyla her karakteri yakalamak için deneyler yapın. + +Paylaşmak istediğiniz bir varyasyon var mı—belki el yazısı notlarda OCR ya da bulut tabanlı bir hizmet? Yorum bırakın, iyi kodlamalar! + +## Sonra Ne Öğrenmeli? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım adım açıklamalı tam çalışan kod örnekleri içerir. + +- [Aspose OCR ile Görüntüden Metin Çıkarma – Adım Adım Kılavuz](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Klasörlerde OCR İşlemi Kullanarak Görüntülerden Metin Çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Aspose.OCR Kullanarak Görüntülerden Metin Çıkarma – İzin Verilen Karakterler](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..fc2b90636 --- /dev/null +++ b/ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-06-06 +description: Python kullanarak PDF'yi OCR'lamak, PDF'den metin çıkarmak, taranmış + PDF metnini dönüştürmek ve sadece birkaç satır kodla OCR dilini değiştirmek. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: tr +og_description: 'Python ile PDF OCR: PDF''den metin çıkarmayı, taranmış PDF metnini + dönüştürmeyi ve OCR dilini zahmetsizce değiştirmeyi gösteren pratik bir rehber.' +og_title: Python'da PDF OCR Nasıl Yapılır – Tam Programlama Öğreticisi +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Python'da PDF'yi OCR ile İşlemek – Tam Adım Adım Rehber +url: /tr/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python'da PDF OCR Nasıl Yapılır – Tam Adım‑Adım Kılavuz + +Pahalı SaaS araçları ödemeden **PDF OCR nasıl yapılır** dosyalarını merak ettiniz mi? Tek başınıza değilsiniz. İster eski kitapları dijitalleştiriyor olun, faturalarından veri çekiyor olun, ya da sadece taranmış bir rapordan aranabilir metne ihtiyacınız olsun, Python'da PDF OCR'ı ustalaşmak saatlerce manuel kopyalamayı tasarruf ettirebilir. + +Bu öğreticide, **extracts text from PDF**, **convert scanned PDF text** ve **change OCR language** nasıl yapılır gösteren kısa ve çalışan bir örnek üzerinden ilerleyeceğiz. Sonunda, herhangi bir projeye ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına sahip olacaksınız. + +## Önkoşullar ve Kurulum + +- Python 3.8+ yüklü (kod 3.9, 3.10 ve daha yeni sürümlerde çalışır) +- `ocr` paketi, `OcrEngine` sınıfını sağlar (`pip install ocr-lib` ile kurabilirsiniz – kullandığınız gerçek paket adıyla değiştirin) +- İşlemek istediğiniz bir PDF dosyası; demo için `high_res_book.pdf` dosyasını `YOUR_DIRECTORY` adlı klasöre koyacağız + +Sanal bir ortam (şiddetle önerilir) kullanıyorsanız, önce onu etkinleştirin: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Pro tip:** PDF dosyalarınızı daha sonra yol‑ile ilgili sorunlardan kaçınmak için ayrı bir `data/` dizini altında tutun. + +## Adım 1: Bir OCR Motoru Örneği Oluşturun (PDF OCR Nasıl Yapılır – Başlatma) + +PDF dosyalarında **perform OCR on PDF** istediğinizde yapmanız gereken ilk şey motoru örneklemektir. Motoru, her sayfayı okuyacak, glifleri yorumlayacak ve size düz metin döndürecek bir beyin olarak düşünün. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Neden önemli: bir motor olmadan dil ayarları, render seçenekleri veya PDF işleme bağlamına sahip olmazsınız. `OcrEngine` nesnesi tüm bu varsayılanları tutar ve daha sonra ayarlamanıza izin verir. + +## Adım 2: Tanıma Dilini Ayarlayın (OCR Dilini Değiştirme) + +Çoğu OCR kütüphanesi varsayılan olarak İngilizce'dir, ancak belgeniz Fransızca, Almanca ya da hatta Japonca ise ne olur? Dili değiştirmek, `set_recognition_language` çağırmak kadar basittir. Bu, **change OCR language** gereksinimini karşılar ve daha yüksek doğruluk sağlar. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Neden buna ihtiyaç duyabilirsiniz:** Çok dilli bir arşiv genellikle karışık‑dil sayfaları içerir. Dilleri anında değiştirmek, “ß” veya “ñ” gibi karakterlerin hatalı tanınmasını önler. + +## Adım 3: PDF Render Seçeneklerini Yapılandırın (Taranmış PDF Metnini Etkili Bir Şekilde Dönüştürme) + +Taranmış PDF'lerle çalışırken, çözünürlük ve renk modu OCR kalitesini büyük ölçüde etkiler. Çoğu belge için 300 DPI'de gri tonlamada render etmek, detayları yakalamak için yeterli ama bellek kullanımını makul tutmak için düşük bir denge noktasıdır. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Zincirleme çağrılar şık görünebilir, ancak her seferinde aynı seçenekler nesnesini döndüren akıcı bir API'dir. Renk gerekiyorsa (ör. renkli diyagramlar için), `"grayscale"` yerine `"color"` kullanın. + +## Adım 4: PDF'yi Tanıyın ve İlk Sayfa Metnini Alın (PDF'ten Metin Çıkarma) + +Şimdi **how to OCR PDF**'in çekirdeği geliyor: motoru bir dosya yolu ile beslemek ve tanınan metni çıkarmak. Metot, sayfa sonuçlarının bir listesini döndürür; her sonuç bir `text` özelliği içerir. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Tüm belgeye ihtiyacınız varsa, `results` üzerinde döngü yapın: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### PDF Şifreli Olursa Ne Olur? + +Bazı PDF'ler şifre korumalı gelir. Bu durumda şifreyi `recognize_pdf` metoduna geçirebilirsiniz: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Motor, OCR gerçekleştirmeden önce anlık olarak şifreyi çözer—ek bir adım gerekmez. + +## Adım 5: Çıkarılan Metni Son İşleme (PDF'ten Metin Çıkarma İnce Ayarı) + +Ham OCR çıktısı genellikle satır sonları, fazladan boşluklar veya zaman zaman hatalı tanınan karakterler içerir. Hızlı bir temizlik rutini, çıkarılan dizeyi sonraki işlemler (arama indeksleme, veritabanı depolama vb.) için hazır hâle getirir. + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Artık güvenle **extract text from PDF** yapabilir ve herhangi bir NLP boru hattına, arama motoruna veya basit bir `open(...).write()` işlemine besleyebilirsiniz. + +## Bonus: Birden Çok PDF'i Toplu İşleme (PDF'te OCR Performansını Ölçeklendirme) + +Eğer içinde taranmış PDF'ler dolu bir klasörünüz varsa, mantığı bir döngü içinde sarın: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Bu kod parçacığı, toplu olarak **perform OCR on PDF** dosyalarını nasıl yapacağınızı gösterir; bu, dijitalleştirme projelerinde yaygın bir ihtiyaçtır. + +## Beklenen Çıktı + +Tek sayfalık örneği (Adım 4) çalıştırmak aşağıdakine benzer bir çıktı vermelidir: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Eğer çok sayfalı bir kitap işlediyseniz, konsol her sayfanın temizlenmiş metnini gösterecek ve toplu script her PDF'in yanına bir `.txt` dosyası bırakacaktır. + +## Yaygın Tuzaklar ve Nasıl Kaçınılır + +| Sorun | Belirtiler | Çözüm | +|-------|------------|-------| +| Düşük çözünürlüklü kaynak PDF | Bozuk karakterler, eksik kelimeler | DPI'yi artırın (`set_dpi(400)` veya daha yüksek) | +| Yanlış dil ayarı | Birçok bilinmeyen sembol, özellikle aksanlı karakterler | `engine.set_recognition_language(ocr.Language.FRENCH)` veya uygun enum'u kullanın | +| Büyük PDF bellek hatasına neden oluyor | `MemoryError` veya birkaç sayfadan sonra çökme | Sayfaları parçalar halinde işleyin (`engine.recognize_pdf(..., max_pages=10)`) | +| PDF'de eksik fontlar | Belirli sayfalar için boş çıktı | PDF'in gerçekten raster görüntüler içerdiğinden emin olun; bazı PDF'ler yalnızca vektör olup farklı bir işleme ihtiyaç duyar | + +## Görsel Açıklama + +Aşağıda iş akışının hızlı bir görseli bulunmaktadır. Alt metin kasıtlı olarak SEO‑dostudur. + +![pdf ocr nasıl yapılır iş akışı diyagramı, motor başlatma, dil ayarı, render seçenekleri, tanıma ve metin çıkarma](/images/ocr-workflow.png) + +*Diyagram kodun çalışması için gerekli değildir, ancak görsel öğrenenlerin her adımın nerede olduğunu görmesine yardımcı olur.* + +## Sonuç + +Python'da **how to OCR PDF** dosyalarını baştan sona ele aldık: bir OCR motoru oluşturma, **changing OCR language**, render'ı **convert scanned PDF text** için yapılandırma ve sonunda **extracting text from PDF** işlemiyle metni elde etme. Tam, çalıştırılabilir örnek herhangi bir projeye eklenmeye hazır ve isteğe bağlı toplu script çözümü nasıl ölçeklendireceğinizi gösteriyor. + +Next, you might want to explore: + +- Çok dilli arşivler için bir dil listesi üzerinden döngü yaparak **perform OCR on PDF** eklemek. +- Çıkarılan metni Elasticsearch ile tam metin arama için entegre etmek. +- OCR kullanarak metin katmanını orijinal dosyaya geri yerleştirerek aranabilir PDF'ler oluşturmak (birçok kütüphane `save_as_searchable_pdf` metodunu sunar). + +Dilediğiniz gibi denemeler yapın, DPI ayarlarını değiştirin veya farklı bir OCR arka ucuna geçin. Temeller aynı kalır ve artık üzerine inşa edebileceğiniz sağlam bir temele sahipsiniz. + +Kodlamaktan keyif alın, ve taranmış belgeleriniz nihayet aranabilir olsun! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..762c6e7ba --- /dev/null +++ b/ocr/turkish/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-06 +description: Python kullanarak PDF'yi OCR'leyin ve görüntülerden aranabilir PDF dosyaları + oluşturun. Dakikalar içinde aranabilir metin eklemeyi ve görüntüyü PDF/A'ya dönüştürmeyi + öğrenin. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: tr +og_description: PDF'yi adım adım OCR'lamak. Basit bir Python betiğiyle aranabilir + metin eklemeyi ve görüntüyü PDF/A'ya dönüştürmeyi öğrenin. +og_title: PDF'yi OCR'lamak – Aranabilir PDF'ler Oluşturmak için Hızlı Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Python'da PDF'yi OCR ile İşlemek – Görsellerden Aranabilir PDF Oluşturma +url: /tr/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF'yi OCR'lamak – Tarama Görüntülerini Aranabilir PDF'lere Dönüştürmek + +Hiç **PDF'yi OCR'lamak** istediğinizde elinizde sadece bir fatura ya da makbuzun taranmış görüntüsü olduğunu düşündünüz mü? Tek başınıza değilsiniz. Birçok ofiste gelen evraklar düz PNG ya da JPEG dosyaları olarak gelir ve bir sonraki adım—içeriği aranabilir hâle getirmek—bir kara kutu gibi görünür. + +İyi haber? Sadece birkaç satır Python ile **aranabilir PDF** dosyaları **oluşturabilir**, **aranabilir metin ekleyebilir** ve hatta **görüntüyü PDF/A'ya dönüştürebilirsiniz** uzun vadeli arşivleme için. Bu öğreticide her adımı adım adım inceleyecek, neden önemli olduğunu açıklayacak ve herhangi bir projeye ekleyebileceğiniz çalıştırmaya hazır bir betik sunacağız. + +> **Pro tip:** Aynı yaklaşım çok sayfalı taramalar için de çalışır; sadece dosyalar üzerinde döngü kurun ve motor ağır işi halleder. + +--- + +## Gereksinimler + +İşe başlamadan önce makinenizde aşağıdakilerin olduğundan emin olun: + +| Gereksinim | Neden Önemli | +|-------------|----------------| +| Python 3.9 ve üzeri | Modern sözdizimi ve daha iyi kütüphane desteği | +| `pdfium`‑tabanlı OCR motoru (ör. `pdfocr` veya ticari bir SDK) | Hem görüntü tanıma hem de PDF/A üretimini yönetir | +| Aranabilir PDF'ye dönüştürmek istediğiniz bir görüntü dosyası (PNG, JPEG, TIFF) | Metnin kaynağı | +| Çıktı klasörüne yazma izni | Betiğin yeni PDF'yi kaydedebilmesi için | + +OCR SDK'sını henüz kurmadıysanız, şu komutu çalıştırın: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Hepsi bu—karmaşık sistem bağımlılıkları yok, sadece bir pip kurulumu. + +--- + +## PDF'yi OCR'lamak – Genel Bakış + +Yüksek seviyede süreç üç basit adımdan oluşur: + +1. **Metni** görüntünün içinde tanı, orijinal grafikleri koruyarak. +2. OCR sonucunu **aranabilir PDF/A** (arşiv dostu PDF çeşidi) olarak orijinal görüntüyle birlikte dışa aktar. +3. Oluşan dosyanın, orijinal resmin üzerine seçilebilir, aranabilir bir metin katmanı içerdiğini **doğrula**. + +Aşağıda her adımı kod içinde görecek, komutların *neden* gerektiğini açıklayacağız. + +--- + +## Adım 1: Görüntüden Metni Tanıma + +İlk olarak OCR motoruna pikselleri okumasını ve hem ham görüntüyü hem de çıkarılan metni tutan bir sonuç nesnesi döndürmesini söylüyoruz. Motorun faturayı sizin için “okuduğunu” düşünün. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Neden Önemli + +- **Grafiklerin korunması**, görsel düzenin (tablolar, logolar, damgalar) tarayıcı tarafından yakalanan haliyle kalmasını sağlar. +- `result` nesnesi genellikle PDF'ye daha sonra gömeceğimiz gizli bir metin katmanı içerir. +- `recognize_image` kullanmak, `recognize_pdf` yerine ekstra bir dönüşüm adımını ortadan kaldırır; tek sayfalı görüntülerde işleme süresini hızlandırır. + +#### Yaygın varyasyonlar + +- **Çok sayfalı TIFF** dosyanız varsa, dosya yolunu doğrudan geçirin; çoğu motor her sayfayı ayrı bir görüntü olarak işler. +- Zaten içinde görüntü barındıran PDF'ler için `engine.recognize_pdf("file.pdf")` çağrısı yapabilir ve bu adımı tamamen atlayabilirsiniz. + +--- + +## Adım 2: OCR Sonucunu Aranabilir PDF/A Olarak Dışa Aktarma + +Şimdi adım 1'deki `result` nesnesini alıp motorun yeni bir dosya yazmasını sağlıyoruz. Buradaki kilit bayrak *PDF/A*—uzun vadeli koruma için tasarlanmış ISO‑standart PDF sürümüdür. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Neden Önemli + +- **Aranabilir PDF**: Çıktı dosyası gizli, seçilebilir bir metin katmanı içerir. Artık belge içinde Ctrl + F yapabilirsiniz. +- **PDF/A uyumu**: Bazı kuruluşlar (hukuk, finans) denetim izleri için PDF/A zorunluluğu getirir; bu adım kuralı otomatik olarak karşılar. +- Metod aynı zamanda **aranabilir metni** eklerken görüntüyü düzleştirmez, böylece görsel bütünlük mükemmel kalır. + +#### Kenar durumu: Normal PDF mi istiyorsunuz? + +PDF/A ile ilgilenmiyorsanız, `save_as_pdfa` yerine `save_as_pdf` kullanın. İş akışının geri kalanı aynı kalır. + +--- + +## Adım 3: Aranabilir PDF'yi Doğrulama + +Kısa bir tutarlılık kontrolü, ileride ortaya çıkabilecek gizemli hatalardan sizi korur. Oluşturulan dosyayı herhangi bir PDF görüntüleyicide açın, bir kelimeyi seçmeye çalışın ve arama fonksiyonunu kullanın. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Beklenen çıktı + +Betik çalıştırıldığında konsola şu bilgiler basılır: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Dosyayı açtığınızda, orijinal fatura görüntüsünün üzerine hafif, görünmez bir metin katmanı olduğunu görmelisiniz. Herhangi bir kelimeyi vurguladığınızda seçilebilir olduğunu fark edeceksiniz—**tam da eklediğiniz aranabilir metin**. + +--- + +## Mevcut PDF'lere Aranabilir Metin Ekleme (Bonus) + +Bazen zaten bir PDF'niz olur ve **aranabilir metin** eklemeniz gerekir. Aynı motor OCR sonuçlarını mevcut bir PDF üzerine bindirebilir: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Burada `apply_to`, gizli katmanı orijinal sayfalarla birleştirir ve **yeniden taramaya gerek kalmadan aranabilir PDF** oluşturmanızı sağlar. + +--- + +## Yaygın Tuzaklar ve İpuçları + +| Tuzak | Nasıl Önlenir | +|---------|-----------------| +| **Düşük çözünürlüklü kaynak görüntüler** (< 150 dpi) | Görüntüyü yükseltin veya daha yüksek çözünürlükte tarama talep edin; OCR doğruluğu 150 dpi altında ciddi şekilde düşer. | +| **Eksik dil verisi** | OCR motorunuz için uygun dil paketlerini kurun (`pip install pdfocr[eng,spa]`). | +| **Çıktı klasörü yazılabilir değil** | Betiği yeterli izinlerle çalıştırın veya farklı bir dizin seçin. | +| **PDF/A doğrulaması başarısız** | Desteklenmeyen fontları veya JavaScript'i gömmediğinizden emin olun; çoğu SDK `save_as_pdfa` kullandığınızda bunu otomatik halleder. | + +--- + +## Tam Betik – Tek‑Dosya Çözümü + +Aşağıda her şeyi bir araya getiren, bağımsız bir betik bulunuyor. Kopyalayıp yapıştırın, yer tutucu yolları değiştirin ve **görüntüyü PDF/A'ya** saniyeler içinde dönüştürmeye hazır olun. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Bu betik ne yapar:** +1. OCR motorunu yükler. +2. Seçilen görüntüyü okur ve metni çıkarır. +3. **Aranabilir PDF/A** yazar; hemen dağıtabilir veya arşivleyebilirsiniz. + +`main` mantığını bir fonksiyona sarıp bir klasörü işlemek isterseniz—sadece `os.listdir()` ile döngü kurun ve her dosya için üç adımı tekrarlayın. + +--- + +## Sonraki Adımlar & İlgili Konular + +Artık **PDF'yi OCR'lamak** konusunda uzmanlaştığınıza göre, aşağıdaki ileri fikirleri keşfetmeyi düşünün: + +- **Toplu işleme:** `concurrent.futures` kullanarak onlarca faturayı paralel olarak OCR'layın. +- **Metadata ekleme:** PDF metadata'sına oluşturma tarihleri veya fatura numaraları ekleyerek indekslemeyi kolaylaştırın. +- **Hibrit PDF'ler:** Aranabilir metni gömülü orijinal görüntülerle birleştirerek “dijital ikiz” oluşturun. +- **Alternatif çıktılar:** Alt sistemlerin düzenlenebilir formatlara ihtiyacı varsa **DOCX** ya da **HTML** olarak dışa aktarın. + +Bu konular, yeni öğrendiğiniz temel kavramlar—tanıma, dışa aktarma, doğrulama—üzerine inşa edilir. + +--- + +## Özet + +Kısaca, sadece üç satır Python ile basit bir görüntüyü **aranabilir PDF/A**'ya dönüştürerek **PDF'yi OCR'lamak** konusunda uzmanlaştınız. Betik ağır işi halleder, orijinal grafikleri korur ve arama, arşivleme veya paylaşım için standartlara uygun bir belge sunar. + +Kendi faturalarınız, makbuzlarınız veya taranmış sözleşmelerinizle deneyin. Sorun yaşarsanız, aşağıya yorum bırakın ya da SDK'nın resmi dokümantasyonuna göz atın—genellikle ekstra örneklerle doludur. İyi kodlamalar ve herhangi bir görüntüyü anında aranabilir hâle getirme yeteneğinin tadını çıkarın! + +![PDF'yi OCR'lamak örneği, orijinal görüntü ve aranabilir PDF katmanı gösteriyor](placeholder.png "PDF'yi OCR'lamak örneği") + + +## Sonraki Öğrenmeniz Gerekenler + + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, tam çalışan kod örnekleri ve adım adım açıklamalar içerir; böylece ek API özelliklerini ustalaşabilir ve projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/turkish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..5c5f68fea --- /dev/null +++ b/ocr/turkish/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-06-06 +description: Aspose OCR Cloud kullanarak PDF'yi OCR'lamak nasıl yapılır. PDF'den metin + çıkarmayı, PDF sayfasını PNG'ye dönüştürmeyi ve Python'da PDF sayfa görüntülerini + kaydetmeyi öğrenin. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: tr +og_description: Aspose OCR Cloud ile PDF'yi OCR'lamak nasıl yapılır. Bu kılavuz, düz + metin PDF'sini çıkarmayı, PDF sayfasını PNG'ye dönüştürmeyi ve PDF sayfa görüntülerini + kaydetmeyi gösterir. +og_title: Aspose OCR Cloud ile PDF'yi OCR'lamak – Adım Adım +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Aspose OCR Cloud ile PDF'yi OCR'lamak – Tam Rehber +url: /tr/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Cloud ile PDF OCR Nasıl Yapılır – Tam Kılavuz + +Ağır masaüstü araçlarıyla uğraşmadan **PDF OCR nasıl yapılır** dosyalarını merak ettiniz mi? Tek başınıza değilsiniz—birçok geliştirici, taranmış belgelerden metin çıkarmak için hızlı ve programatik bir yol gerektiğinde bu engelle karşılaşıyor. İyi haber? Aspose OCR Cloud ile **PDF'den metin çıkarabilir**, her sayfayı PNG'ye dönüştürebilir ve hatta **PDF sayfa görüntülerini** daha sonra kullanmak üzere kaydedebilirsiniz, hepsi düzenli bir Python betiğinden. + +Bu öğreticide, bilmeniz gereken her şeyi adım adım göstereceğiz: SDK'yı kurmaktan, motoru lisanslamaya ve çok sayfalı PDF'leri tanımaya, düz metin çıkarmaya, sayfaları PNG'ye dönüştürmeye ve bu görüntüleri diske kalıcı olarak kaydetmeye kadar. Sonunda, **PDF OCR nasıl yapılır** yeteneklerine ihtiyaç duyan herhangi bir projeye ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına sahip olacaksınız. + +## Gereksinimler + +- **Python 3.8+** (kod 3.10 ve üzeri sürümlerde de çalışır) +- Bir Aspose OCR Cloud hesabı – ücretsiz deneme lisans dosyasını (`Aspose.OCR.lic`) alacaksınız +- `asposeocrcloud` paketi (`pip install asposeocrcloud`) +- İşlemek istediğiniz taranmış, çok sayfalı bir PDF + +Hepsi bu. Ekstra ikili dosyalar, yerel bağımlılıklar yok, sadece saf Python. + +## PDF OCR Nasıl Yapılır – Kurulum ve Lisans + +Herhangi bir OCR metodunu çağırmadan önce SDK'ya kim olduğunuzu bildirmeniz gerekir. Aspose, betiğinizin erişebileceği bir yere koymanız gereken hafif bir lisans dosyası kullanır. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Pro ipucu:* Lisans adımını atlayarsanız, SDK yine çalışır ancak çıktı görüntülerine küçük bir filigran ekler. Üretim ortamı için ideal değildir. + +## Adım 2: Aspose OCR Cloud Python SDK'sını Kurun + +Bir terminal açın ve şu komutu çalıştırın: + +```bash +pip install asposeocrcloud +``` + +Paket, gerekli tüm bağımlılıkları (requests, pillow vb.) otomatik olarak çeker, böylece başka bir şey aramanıza gerek kalmaz. + +## Adım 3: Bir OCR Motoru Oluşturun ve Dil Seçin + +Motor, işlemin kalbidir. Aspose tarafından desteklenen herhangi bir dili belirtebilirsiniz; İngilizce çoğu durumda işe yarar. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Neden dili ayarlamalısınız? Çünkü OCR motoru, doğruluğu artırmak için dile özgü sözlükler kullanır. Fransızca PDF'ler işliyorsanız, sadece `ENGLISH` yerine `FRENCH` yazın. + +## Adım 4: Çok Sayfalı PDF'inize İşaret Edin + +Motora işlemek istediğiniz dosyanın tam yolunu verin. Göreceli yollar, betiğin çalışma dizininden çözüldükleri sürece uygundur. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Dosyanın okunabilir olduğundan emin olun; aksi takdirde `FileNotFoundError` alırsınız. + +## Adım 5: OCR'ı Çalıştırın – Sonuçların Listesini Alırsınız + +`recognize_pdf` çağrısı, her bir öğesi kaynak PDF'in bir sayfasına karşılık gelen bir liste döndürür. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Her `OcrResult` iki kullanışlı özelliğe sahiptir: + +* `text` – sayfanın düz metin temsili (**extract plain text pdf** için harika) +* `image` – işlenen sayfanın Pillow `Image` nesnesi (**convert pdf page png** için mükemmel) + +## Adım 6: PDF'den Metin Çıkarın ve Sayfaları PNG'ye Dönüştürün + +Şimdi sonuçlar üzerinde döngü kuruyor, çıkarılan metni yazdırıyor ve her sayfanın PNG sürümünü kaydediyoruz. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Beklenen Konsol Çıktısı + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +`page_1.png`, `page_2.png`, … dosyalarını `YOUR_DIRECTORY` içinde bulacaksınız. Bunlar, sonraki görüntü işleme boru hatlarına besleyebileceğiniz rasterleştirilmiş sayfa görüntüleridir. + +## Adım 7: PDF Sayfa Görüntülerini Kaydedin (İsteğe Bağlı Son İşlem) + +Sadece görüntülere ihtiyacınız varsa ve metne gerek yoksa, `print(res.text)` satırını atlayabilirsiniz. Aksine, metni ayrı `.txt` dosyalarına kaydetmek isterseniz, sadece küçük bir yazma işlemi ekleyin: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Bu küçük ekleme, **PDF sayfa görüntülerini kaydetmenin** ne kadar kolay olduğunu ve aynı zamanda çıkarılan içeriği kalıcı hale getirdiğini gösterir. + +## Tam Çalışan Örnek + +Her şeyi bir araya getirerek, `ocr_pdf.py` dosyasına kopyalayıp yapıştırabileceğiniz tam betiği aşağıda bulabilirsiniz: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Şu komutla çalıştırın: + +```bash +python ocr_pdf.py +``` + +Her sayfanın metninin konsola döküldüğünü ve bir dizi PNG dosyası oluşturulduğunu görmelisiniz + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanıza ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Aspose.OCR ile .NET'te PDF OCR Nasıl Yapılır](/ocr/english/net/text-recognition/recognize-pdf/) +- [PDF Metni Tanıma – Java için Aspose.OCR ile OCR İşlemleri](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Görüntüleri PDF'ye Dönüştür C# – Çok Sayfalı OCR Sonucunu Kaydet](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/turkish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..a064be670 --- /dev/null +++ b/ocr/turkish/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-06-06 +description: Python kullanarak OCR için görüntüleri nasıl ön işleme alacağınızı öğrenin. + Otsu yöntemiyle görüntüyü ikili hale getirmeyi, taranmış belgeleri nasıl düzleştireceğinizi + ve Almanca metin için OCR doğruluğunu nasıl artıracağınızı keşfedin. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: tr +og_description: Python’da OCR için görüntüleri nasıl ön işleme alacağınızı öğrenin. + Bu öğreticide Otsu yöntemiyle görüntüyü ikiliye çevirme, taranmış belgeleri eğriltme + ve Almanca görüntülerde OCR doğruluğunu artırma konuları gösterilmektedir. +og_title: OCR için Görüntüleri Nasıl Ön İşlemeye Alırsınız – Tam Python Rehberi +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: OCR için Görüntüleri Nasıl Ön İşlemeye Alırsınız – Tam Python Rehberi +url: /tr/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR için Görüntüleri Ön İşleme – Tam Python Rehberi + +OCR için görüntüleri nasıl ön işleme yapacağınızı hiç merak ettiniz mi, böylece metin kristal netliğinde çıkar? Tek başınıza değilsiniz. Tarama belgeleri—özellikle gürültülü Almanca sayfalar—herhangi bir OCR motoru için bir kabus olabilir. İyi haber? Birkaç akıllı ön işleme adımı, bulanık, lekeli bir taramayı temiz, makine tarafından okunabilir bir görüntüye dönüştürebilir. + +Bu öğreticide, Python kullanarak **OCR için görüntüleri nasıl ön işleme yapacağınızı** gösteren pratik bir örnek üzerinden ilerleyeceğiz. **Otsu ile görüntüyü ikiliye dönüştürmeyi**, **tarama belgelerini nasıl düzleştireceğinizi** ve genel olarak **OCR doğruluğunu nasıl artıracağınızı** öğreneceksiniz; özellikle **Almanca görüntü dosyalarından metin çıkarmak** gerektiğinde. Süslü bir giriş yok, bugün kopyalayıp yapıştırabileceğiniz çalışan bir betik. + +## What You’ll Need + +- **Python 3.9+** (herhangi bir yeni sürüm yeterlidir) +- `OcrEngine` sınıfını sunan bir OCR kütüphanesi – demo için genel bir `ocr` paketi varsayacağız. `pip install ocr-lib` ile kurun. +- Test etmek istediğiniz gürültülü bir Almanca tarama (`noisy_german_scan.tif`). +- Python fonksiyonları hakkında temel bir anlayış (daha önce bir `def` yazdıysanız, hazırsınız). + +> **Pro ipucu:** Farklı bir OCR SDK’sı (ör. `pytesseract` ile Tesseract) kullanıyorsanız, kavramlar aynı kalır—sadece metod isimlerini uyarlayın. + +## Overview of the Solution + +1. **Bir OCR motoru örneği oluşturun.** +2. **Tanıma dilini Almanca olarak ayarlayın.** +3. **Özel bir ön işleme hattı oluşturun**; bu hat, düzleştirme, gürültü giderme, ikiliye dönüştürme (Otsu) ve kontrast genişletmeyi içerir. +4. **Hattı motorla ilişkilendirin**; böylece her görüntü otomatik olarak bu hattı geçer. +5. **OCR’ı** gürültülü bir Almanca tarama üzerinde çalıştırın. +6. **Çıkarılan metni** yazdırarak sonucu doğrulayın. + +Aşağıda her adımı ayrıntılı olarak açıklıyor, **neden** önemli olduğunu gösteriyor ve ihtiyacınız olan tam kodu sunuyoruz. + +![how to preprocess images for OCR example](image.png "how to preprocess images for OCR example") + +## Step 1: Create an OCR Engine Instance + +İlk iş olarak—bir motor olmadan hiçbir şey olmaz. `OcrEngine` nesnesi, sonraki tüm işlemleri koordine eden giriş noktasıdır. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Why this matters:* Motoru başlatmak, iç kaynakları (dil modelleri gibi) kurar ve daha sonra özel bir hat eklemek için temiz bir ortam sağlar. + +## Step 2: Set the Recognition Language to German + +OCR doğruluğu büyük ölçüde dile bağlıdır. Motora Almanca bekleyeceğini söyleyerek doğru karakter kümesini ve dil modelini etkinleştirirsiniz. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Bunu atlamanız durumunda motor, varsayılan olarak İngilizceye geçebilir ve umlautları (ä, ö, ü) ve ß karakterini yanlış tanıyabilir—Almanca taramalarla çalışırken sık karşılaşılan tuzaklardır. + +## Step 3: Build a Custom Preprocessing Pipeline + +Bu, **OCR için görüntüleri nasıl ön işleme yapacağınız** konusunun kalbidir. Dört dönüşümü zincirleyeceğiz: + +| Dönüşüm | Ne yapar | Neden yardımcı olur | +|---------|----------|----------------------| +| **Deskew** | Görüntüyü yataya (maks 5°) döndürür | Taramalar nadiren mükemmel hizalanır; düzleştirme, karakter segmentasyonunu karıştıran eğimi ortadan kaldırır. | +| **Denoise** | Rastgele lekeleri azaltır (güç 0.7) | Gürültü, OCR motorunun karakter olarak yorumlayabileceği sahte kenarlar oluşturur. | +| **Binarize (Otsu)** | Otsu yöntemiyle siyah‑beyaz dönüştürür | Temiz bir ikili görüntü, motorun ön plan (metin) ve arka plan arasında keskin bir kontrast elde etmesini sağlar. | +| **Contrast Stretch** | Dinamik aralığı genişletir | Özellikle eski belgelerde soluk çizgilerin okunabilirliğini artırır. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### How to Deskew Scanned Documents + +Yukarıdaki `deskew` çağrısı, **tarama belgelerini nasıl düzleştireceğiniz** sorusunun somut cevabıdır. İçsel olarak, Hough dönüşümüyle baskın metin satırı açısını tahmin eder ve görüntüyü geri döndürür. Belgeleriniz 5°’den fazla döndürülmüşse `max_angle` değerini artırın, ancak aşırı döndürme artefaktlarına dikkat edin. + +### Binarize Image Using Otsu + +`binarize(method="otsu")` satırı, **otsu kullanarak görüntüyü ikiliye dönüştür** sorusuna doğrudan yanıt verir. Otsu algoritması, sınıf içi varyansı en aza indirecek bir eşik hesaplar; bu, koyu metin ve açık arka planın ikili histogramına sahip belgeler için mükemmeldir. + +## Step 4: Attach the Pipeline to the Engine + +Şimdi OCR motoruna, her gelen görüntünün az önce oluşturduğumuz hattı çalıştırmasını söylüyoruz. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Why this matters:* Kayıt yapılmazsa motor, ham taramayı işler ve yapılandırdığımız temizlik adımlarını görmez. Bu adım, **OCR doğruluğunu nasıl artıracağınız** konusunda aynı ön işleme adımlarını tutarlı bir şekilde uygulamayı sağlar. + +## Step 5: Recognize Text from a Noisy German Scan + +Her şeyi bir araya getirme zamanı. Motoru gürültülü bir Almanca görüntüye besliyoruz ve işi ona bırakıyoruz. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Performans merak ediyorsanız, çağrıyı zamanlayabilirsiniz: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Step 6: Output the Recognized Text + +Son olarak, çıkarılan dizeyi yazdırıyoruz. Bu, **Almanca görüntüden metin çıkar** sorusunun doğrudan yanıtıdır. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Expected Output + +Örnek tarama “Die schnelle braune Füchsin springt über den faulen Hund.” cümlesini içeriyorsa, aşağıdakine benzer bir çıktı görmelisiniz: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Çıktı hâlâ bozuk karakterler içeriyorsa, `denoise` gücünü ayarlamayı veya düzleştirme için `max_angle` değerini artırmayı düşünün. + +## Common Pitfalls & How to Tackle Them + +- **Dil modeli eksik:** `set_recognition_language(Language.GERMAN)` çağrısını unutmak, umlautların eksik olmasına yol açar. Bu satırı iki kez kontrol edin. +- **Aşırı gürültü giderme:** 0.9 üzerindeki bir güç, özellikle eski yazı tiplerinde ince çizgileri silebilir. Çoğu durum için 0.5‑0.7 arasında kalın. +- **Yanlış dosya formatı:** Bazı OCR motorları çok sayfalı TIFF’lerde takılır. Çok sayfalı bir belgeniz varsa, önce tek sayfalık dosyalara bölün. +- **Hattın sırası:** Gösterilen sıra (deskew → denoise → binarize → contrast) kasıtlıdır. İkiliye dönüştürme, gürültü giderme öncesinde yapılırsa gürültü kilitlenir; her zaman önce gürültü giderin. + +## Extending the Pipeline (What’s Next?) + +Şimdi sağlam bir temeliniz olduğuna göre, şunları eklemek isteyebilirsiniz: + +- Küçük lekeleri temizlemek için morfolojik bir açma ekleyin (`.morph_open(kernel=3)`). +- Son‑işleme düzeltmesi için bir dil modeli entegre edin (`ocr_engine.apply_spellcheck()`). +- Büyük veri kümeleri için `concurrent.futures` kullanarak toplu işleme paralelleştirin. + +Tüm bunlar, **OCR için görüntüleri nasıl ön işleme yapacağınız** temel fikrini korurken **OCR doğruluğunu nasıl artıracağınız** konusunda daha da ilerlemenizi sağlar. + +## Conclusion + +Başlangıçtan sona kadar **OCR için görüntüleri nasıl ön işleme yapacağınızı** kapsadık: bir motor oluşturun, Almanca dilini ayarlayın, **Otsu ile görüntüyü ikiliye dönüştürün**, **tarama belgelerini nasıl düzleştireceğinizi** yapın ve sonunda **Almanca görüntüden metin çıkar** ile daha yüksek güvenle sonuç alın. Yukarıdaki altı adımı izleyerek tanıma kalitesinde belirgin bir artış göreceksiniz—artık sonsuz manuel düzeltme yok. + +Kendi taramalarınızla betiği deneyin, parametrelerle oynayın ve sonuçların kendini kanıtlamasına izin verin. Belirli bir ön işleme ayarı hakkında sorularınız mı var? Yorum bırakın, birlikte daha derine inelim. + +İyi kodlamalar, OCR’unuz her zaman doğru olsun! + +## What Should You Learn Next? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan yakın konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım adım açıklamalar içerir. + +- [Aspose.OCR kullanarak dil seçimiyle C# görüntü metni çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [OCR Görüntü Tanıma’da Eşik Değerini Nasıl Ayarlarsınız](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Görüntüyü OCR Yapma – OCR Görüntü Tanıma’da Görüntü Üzerinde OCR Gerçekleştirme](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..02faec11b --- /dev/null +++ b/ocr/turkish/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-06-06 +description: Python ile PNG görüntü OCR – görüntüden metin çıkarmayı öğrenin, bir + Python OCR örneği çalıştırın ve hatta antik Yunan metinlerini kolayca okuyun. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: tr +og_description: Python'da OCR PNG görüntüsü açıklaması. Bu kılavuz, görüntüden metin + nasıl çıkarılır, bir Python OCR örneği nasıl çalıştırılır ve antik Yunanca nasıl + kolayca okunur gösterir. +og_title: Python'da PNG Görüntüsü OCR – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python'da PNG Görüntü OCR – Tam Adım Adım Rehber +url: /tr/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python’da OCR PNG Görüntüsü – Tam Adım‑Adım Kılavuz + +Ever wondered how to **OCR PNG image** files straight from a Python script? Maybe you have a folder full of scanned ancient manuscripts and you need to **extract text from image** files without manually typing everything. The good news is you don’t need a PhD in computer vision—just a few lines of code and the right library, and you’ll be reading ancient greek in seconds. + +Bu öğreticide **python OCR example**'ı adım adım inceleyeceğiz; PNG'den metni tanır, dili Yunan polytonik olarak ayarlar ve sonucu yazdırır. Sonuna geldiğinizde **recognize image text**'i tam olarak nasıl yapacağınızı, yaygın sorunları nasıl yöneteceğinizi ve betiği diğer diller veya görüntü formatları için nasıl uyarlayacağınızı öğreneceksiniz. + +## Öğrenecekleriniz + +- Python OCR kütüphanesini (pytesseract + Tesseract OCR) kurun ve yapılandırın +- Bir OCR motoru örneği oluşturun ve PNG dosyasını yükleyin +- Tanıma dilini Yunan polytonik olarak ayarlayın, böylece **read ancient greek** yapabilirsiniz +- Tanınan metni çıktıya alın ve tipik sorunları giderin +- Betik'i birden fazla PNG'yi toplu işleyebilecek veya başka bir dile geçebilecek şekilde genişletin + +### Önkoşullar + +| Gereksinim | Neden Önemli | +|-------------|----------------| +| Python 3.8+ | Modern syntax and type hints | +| `pytesseract` package | Thin wrapper around the Tesseract engine | +| Tesseract OCR binaries (≥ 5.0) | The actual engine that does the heavy lifting | +| Greek language data (`grc.traineddata`) | Needed for **read ancient greek** correctly | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Our target for the **ocr png image** demo | + +Python tarafını şu şekilde kurabilirsiniz: + +```bash +pip install pytesseract Pillow +``` + +Ubuntu/macOS üzerinde motoru şu şekilde ekleyebilirsiniz: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Yunan polytonik eğitim verisini indirmeyi unutmayın: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Yol farklı olabilir; gerekirse `TESSDATA_PREFIX`'i ayarlayın.)* + +--- + +## OCR PNG Görüntüsü: Motor Örneğini Oluşturma + +İlk olarak Tesseract ile iletişim kuran bir nesneye ihtiyacımız var. `pytesseract` içinde motor, modül‑seviyesindeki fonksiyonlarla erişilir, ancak açıklık için bunu küçük bir sınıfa sarmalayacağız. Bu, orijinal kod parçacığında gördüğünüz “engine” kavramını yansıtır. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Neden sarmalansın?** +- Kamu API'sını, başladığınız kod parçacığıyla aynı tutar, geçişi sorunsuz hâle getirir. +- Ana akışı etkilemeden daha sonra günlükleme veya hata yönetimi eklememizi sağlar. +- İyi OOP uygulamasını gösterir—kıdemli geliştiricilerin takdir ettiği bir şey. + +--- + +## Görüntüden Metin Çıkarma: Dili Yunan Polytonik Olarak Ayarlama + +Artık bir motorumuz olduğuna göre, hangi dili bekleyeceğini ona söylememiz gerekiyor. Yunan polytonik, standart “greek” verisiyle kapsanmayan diakritik işaretler kullanır, bu yüzden Tesseract'i `grc` eğitim dosyasına yönlendiririz. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Başka bir dilde **extract text from image** dosyaları çıkarmak isterseniz, sadece `"grc"` yerine İngilizce için `"eng"`, Fransızca için `"fra"` gibi bir değer koyun. Aynı satır, yüklü olan herhangi bir dil için çalışır. + +--- + +## Görüntü Metnini Tanıma: PNG Üzerinde OCR Çalıştırma + +Dil ayarlandıktan sonra PNG'yi motorun içine besliyoruz. Orijinal örnek sabit bir yol kullandı; biz `Path` nesneleriyle biraz daha esnek hâle getireceğiz. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**İpuçları & Kenar Durumları** + +- **File not found** – çağrıyı `try/except FileNotFoundError` içinde sarmalayarak dostça bir mesaj verin. +- **Low‑resolution PNG** – OCR'den önce Pillow ile ön işleme (ör. yeniden boyutlandırma, ikilileştirme) yapmayı düşünün. +- **Non‑Greek text** – Tesseract yine de çözümlemeye çalışır, ancak doğruluk büyük ölçüde düşer. Her zaman dili eşleştirin. + +--- + +## Tanınan Metni Çıktılamak + +Son olarak sonucu yazdırıyoruz. Gerçek bir projede bunu bir veritabanına, CSV'ye ya da hatta bir çeviri hattına aktarabilirsiniz. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Betik'i antik Yunan bir yazıtın net taraması üzerinde çalıştırdığınızda, aşağıdakine benzer bir çıktı görmelisiniz: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Çıktı bozuk görünüyorsa, **greek.traineddata** dosyasının doğru klasörde olduğundan ve PNG'nin çok gürültülü olmadığından emin olun. + +--- + +## Tam Çalışan Örnek (Tüm Adımlar Tek Betikte) + +Aşağıda eksiksiz, çalıştırmaya hazır program yer alıyor. `ocr_greek.py` olarak kaydedin ve `python ocr_greek.py` komutuyla çalıştırın. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Beklenen çıktı** (kısaltılmış olarak): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Doğru Yunan karakterlerini görürseniz, tebrikler—Python’da başarılı bir **ocr png image** işlemi gerçekleştirdiniz! + +--- + +## Yaygın Sorular & Profesyonel İpuçları + +### Gürültülü bir PNG'de doğruluğu nasıl artırırım? + +- Görüntüyü gri tonlamaya dönüştürün: `img = img.convert('L')` +- İkili eşik uygulayın: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Yeniden ölçeklendirin: `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Bu adımlar genellikle bir **recognize image text** kabusunu temiz bir sonuca dönüştürür. + +### Tüm bir PNG klasörünü işleyebilir miyim? + +Kesinlikle. `recognize_image` çağrısını `Path.glob("*.png")` üzerinden bir `for` döngüsüyle sarın. Her sonucu bir sözlükte saklayın veya daha sonra analiz için bir CSV'ye yazın. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Sadece sayıları çıkarmam gerekirse ne yapmalıyım? + +`image_to_string`'e özel bir **config** dizesi gönderin: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Bu şekilde tablolar, seri numaraları veya zaman damgaları içeren **extract text from image** dosyalarından metin çıkarabilirsiniz. + +### Güven skorlarını elde etmenin bir yolu var mı? + +Evet—her kelime için güven skorunu içeren bir TSV döndüren `pytesseract.image_to_data`'yı kullanın. Son dizeyi birleştirmeden önce düşük güvenilirlikli tokenları filtreleyebilirsiniz. + +--- + +## Öğreticiyi Genişletme + +Temelleri kavradığınıza göre, aşağıdaki ilgili konuları keşfetmeyi düşünün: + +- **Batch OCR with multiprocessing** – büyük PNG koleksiyonlarını hızlandırın. +- **Hybrid OCR + NLP pipelines** – çıkarılan antik Yunan'ı otomatik olarak modern İngilizceye çevirin. +- **Alternative engines** – belirli kullanım durumları için `easyocr` veya `opencv`‑tabanlı yöntemleri deneyin. +- **Cloud OCR services** – sunucusuz ölçeklendirme için Google Vision, Azure Computer Vision veya AWS Textract. + +Bunların her biri, az önce ele aldığımız temel **python ocr example** üzerine inşa edildiği için, daha derine dalarken rahat hissedeceksiniz. + +## Sonuç + +Basit bir kod parçacığını Python’da sağlam bir **ocr png image** iş akışına dönüştürdük. Bir `OcrEngine` oluşturarak, dili Yunan polytonik olarak ayarlayarak, bir PNG besleyerek ve sonucu yazdırarak, artık **extract text from image** dosyalarını, **recognize image text**'i ve hatta **read ancient greek** nasıl yapacağınızı biliyorsunuz. + +## Sonra Ne Öğrenmelisin? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/turkish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..e3328fb17 --- /dev/null +++ b/ocr/turkish/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR öğreticisi, görüntü metnini tanıma, yüksek çözünürlüklü OCR + gerçekleştirme ve GPU hızlandırmalı OCR kullanarak İspanyolca metin çıkarma yöntemlerini + gösterir. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: tr +og_description: Görüntü metnini tanıma, yüksek çözünürlüklü OCR ve GPU hızlandırmalı + İspanyolca metin çıkarma konularında size rehberlik eden Python OCR öğreticisi. +og_title: Python OCR Eğitimi – GPU Hızlandırmalı Metin Tanıma +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Python OCR Öğreticisi – GPU Hızlandırmasıyla Görüntü Metnini Tanıma +url: /tr/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python OCR Tutorial – Recognize Image Text with GPU Acceleration + +Hiç **görüntü metnini** bir Python betiğinde saatlerce ayar yapmadan tanımayı düşündünüz mü? Tek başınıza değilsiniz. Bu **python ocr tutorial**da yüksek çözünürlüklü bir resimden İspanyolca metni çıkarmanın temiz, uçtan uca bir yolunu göstereceğiz ve sürece GPU hızlandırmasını ekleyerek işlemi ışık hızında çalıştıracağız. + +Bunu, daha sonra üretim‑ağır bir pipeline’a genişletebileceğiniz hızlı bir kahve molası demosu gibi düşünün. Bu rehberin sonunda **yüksek çözünürlüklü OCR** yapan, CUDA‑destekli bir GPU kullanan ve ihtiyacınız olan tam İspanyolca karakterleri veren çalıştırılabilir bir programınız olacak. + +## What You’ll Learn + +- GPU hızlandırmasını destekleyen modern bir OCR kütüphanesinin nasıl kurulup içe aktarılacağını. +- OCR motoru örneği oluşturup **görüntü metnini** İspanyolca olarak tanımasını nasıl ayarlayacağınızı. +- Yüksek çözünürlüklü dosyalarda devasa hız artışı sağlayan **gpu accelerated OCR** nasıl etkinleştirileceğini. +- Eksik CUDA sürücüleri gibi kenar durumlarını nasıl ele alıp CPU’ya geri dönüleceğini. +- Gürültülü taramalardan **extract spanish text** alırken doğruluğu artırmak için ipuçları. + +### Prerequisites + +- Python 3.9+ (kod 3.10 ve üzeri sürümlerde de çalışır). +- CUDA‑uyumlu bir GPU (isteğe bağlı ama şiddetle tavsiye edilir). +- pip ve sanal ortamlarla temel aşinalık. + +Eğer bunlardan birine sahip değilseniz, öğretici yine çalışır—GPU adımını atlayın, kütüphane otomatik olarak CPU’ya geçer. + +--- + +## Python OCR Tutorial: Install the Required Packages + +İlk iş olarak sağlam bir OCR motoruna ihtiyacımız var. Bu öğreticide, uyumlu bir cihaz tespit edildiğinde yerleşik GPU desteği sunan açık kaynak **`easyocr`** paketini kullanacağız. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Eğer zaten PyTorch yüklüyse, CUDA sürümünüzle eşleştiğinden emin olun (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Uyumsuz sürümler “GPU not found” hatalarının yaygın bir kaynağıdır. + +--- + +## Step 1: Create an OCR Engine Instance + +Şimdi motoru başlatıyoruz. EasyOCR ana sınıfına `Reader` denir. Yapıcı, dil kodlarının bir listesini kabul eder; İspanyolca için `"es"` geçeceğiz. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Bu neden önemli:* Dili önceden belirterek motor yalnızca gerekli sinir ağı ağırlıklarını yükler, bu da belleği tasarruf ettirir ve çıkarım süresini hızlandırır—özellikle **high resolution OCR** ile çalışırken çok faydalıdır. + +--- + +## Step 2: Prepare a High‑Resolution Image + +Yüksek çözünürlüklü görüntüler modele daha fazla piksel sağlar ve genellikle daha iyi karakter tanıma anlamına gelir. `samples` adlı klasörde `high_res_spanish.png` adlı bir dosyanız olduğunu varsayalım. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Eğer elinizde yüksek çözünürlüklü bir örnek yoksa, Unsplash’tan ücretsiz bir tane indirebilir ya da Pillow ile sentetik bir görüntü oluşturabilirsiniz. En iyi sonuçlar için DPI’nın 300’ün üzerinde olmasına dikkat edin. + +--- + +## Step 3: Enable GPU Acceleration (Optional but Recommended) + +EasyOCR, `gpu=True` ayarlandığında GPU’yu kullanmaya çalışır. Ancak çoklu GPU sistemlerinde cihazın gerçekten kullanıldığını doğrulamak iyi bir uygulamadır. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Bunu neden kontrol etmelisiniz?* Eğer betik sessizce CPU’ya geri dönerse, 5 saniyelik bir işlemin aniden 30 saniyeye çıkmasını sorgulayabilirsiniz. Bu küçük kontrol, davranışı şeffaf hâle getirir ve **gpu accelerated OCR** pipeline’ınızın öngörülebilir olmasını sağlar. + +--- + +## Step 4: Perform High‑Resolution OCR and Recognize Image Text + +Şimdi eğlenceli kısım—metni gerçekten okumak. EasyOCR’un `readtext` metodu, sınırlayıcı kutu, tanınan dize ve bir güven puanı içeren tuple listesi döndürür. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Koordinatlar olmadan ham dizeye ihtiyacınız varsa `detail=0` ayarlayın. Çoğu **recognize image text** senaryosu için varsayılan (`detail=1`) daha sonra işleme koymak için yeterli bağlam sağlar. + +--- + +## Step 5: Extract Spanish Text and Clean the Output + +EasyOCR’dan İspanyolca istediğimiz için dönen dizeler zaten bu dilde. Yine de birleştirmek, boşlukları temizlemek ya da düşük güvenli tespitleri filtrelemek isteyebilirsiniz. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**Güven skoru düşük olursa ne yapmalı?** Eşiği düşürebilirsiniz (gürültü riski artar) ya da görüntüyü ön‑işleme tabi tutabilirsiniz (kontrastı artırma, ikilileştirme veya eğikliği düzeltme). Bu püf noktaları, taranmış belgelerde **high resolution OCR** ile uğraşırken yaygındır. + +--- + +## Step 6: Handling Edge Cases and Performance Tweaks + +En iyi eğitilmiş modeller bile bazı senaryolarda zorlanır. Aşağıda betiğe yapıştırabileceğiniz birkaç hızlı çözüm var. + +### 6.1 Fallback When No GPU Is Present + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Down‑sampling Very Large Images + +Görüntünüz 4000 × 4000 px’den büyükse GPU belleği tükenebilir. DPI’yı koruyarak orantılı bir şekilde aşağı örnekleyin: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Bu kod parçacıkları, ister bir iş istasyonunda ister mütevazı bir dizüstü bilgisayarda çalışıyor olun, betiğinizi dayanıklı tutar. + +--- + +## Full Working Example + +Hepsini bir araya getirdiğimizde, hemen kopyalayıp çalıştırabileceğiniz tam script aşağıdadır: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Beklenen çıktı (örnek):** + + + +## What Should You Learn Next? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım‑adım açıklamalarla tam çalışan kod örnekleri içerir. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [How to Recognize Page Rectangles for OCR Text Recognition in Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/turkish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..61ceff802 --- /dev/null +++ b/ocr/turkish/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-06 +description: Python OCR motoru kullanarak görüntüden metin tanıyın. OCR motorunu Python’da + nasıl yapılandıracağınızı ve bulut işleme ile dakikalar içinde görüntüden metin + nasıl çıkaracağınızı öğrenin. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: tr +og_description: Python OCR motoru ile görüntüden metin tanıma. Bu rehber, OCR motorunu + Python’da nasıl yapılandıracağınızı ve görüntüden metni verimli bir şekilde nasıl + çıkaracağınızı gösterir. +og_title: Python'da Görüntüden Metin Tanıma – Tam Kurulum Öğreticisi +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python'da Görüntüden Metin Tanıma – Tam OCR Motoru Kurulum Rehberi +url: /tr/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python’da görüntüden metin tanıma – Tam Kurulum Öğreticisi + +Sadece birkaç satır Python ile **recognize text from image** nasıl yapılır hiç merak ettiniz mi? Yalnız değilsiniz. İster bir fiş tarayıcı, bir belge dijitalleştirici ya da basit bir hobi projesi oluşturuyor olun, **extract text from image** yapabilmek hızlıca karşılığını veren bir beceridir. + +Bu öğreticide, **configure OCR engine python** tarzı kurulumdan başlayarak, bulut kimlik doğrulamasına geçecek ve sonunda **extract text from image** nasıl yapılır göstererek tüm süreci adım adım anlatacağız. Hiçbir sihir yok, sadece bugün kopyalayıp yapıştırıp çalıştırabileceğiniz net adımlar. + +## Öğrenecekleriniz + +- Gerekli OCR kütüphanesini nasıl kurup içe aktaracağınızı. +- Bulut işleme için **configure OCR engine python** komutlarını tam olarak. +- **recognize text from image** yapan tam, çalıştırılabilir bir betik ve çıktıyı yazdırır. +- Eksik API anahtarları veya desteklenmeyen görüntü formatları gibi yaygın sorunları ele almak için ipuçları. +- Toplu işleme ve yerel geri dönüş gibi ileri seviye fikirler. + +### Ön Koşullar + +- Makinenizde Python 3.8+ yüklü. +- İnternet bağlantısı (örnek bulut tabanlı bir OCR hizmeti kullanır). +- OCR sağlayıcısından geçerli bir API anahtarı (nerede ekleyeceğinizi göreceksiniz). + +Eğer bunlara sahipseniz, dalalım—gereksiz şeyler yok, sadece işe yarayan pratik bir rehber. + +--- + +## Adım 1: OCR Kütüphanesini Kurun ve İçe Aktarın + +**configure OCR engine python** yapmadan önce, bulut hizmetiyle iletişim kuran kütüphaneye ihtiyacınız var. Örneğimizde `ocrcloud` adlı hayali ama temsilî bir paket kullanacağız. Bunu kullandığınız gerçek paketle değiştirin (ör. `easyocr`, `google-cloud-vision`, vb.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Neden önemli:** Sınıfı içe aktarmak, `use_cloud()` ve `set_api_key()` gibi yöntemlere erişmenizi sağlar. İçe aktarma yapılmazsa, betiğin geri kalanı bir `NameError` hatası verir. + +*Pro ipucu:* Daha sonra beklenmedik kırılmalardan kaçınmak için `requirements.txt` dosyanızda sürümü sabitleyin (`ocrcloud==2.1.0`). + +--- + +## Adım 2: **configure OCR engine python** için Bulut Modu Oluşturun ve Ayarlayın + +Şimdi gerçekten **configure OCR engine python** yapıyoruz. Motor varsayılan olarak yerel modda başlar; bulut moduna geçmek, ağır görüntü analizini güçlü sunuculara yüklemenizi sağlar. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Açıklama:** +- `OcrEngine()` yeni bir motor nesnesi oluşturur—bunu boş bir tuval olarak düşünün. +- `use_cloud(True)` bir anahtarı çevirir, motorun görüntüleri yerel olarak işlemek yerine HTTPS üzerinden göndermesini söyler. Bu, karmaşık yazı tipleri veya düşük çözünürlüklü fotoğraflarda yüksek doğruluk sonuçları için kritiktir. + +--- + +## Adım 3: Bulut API Anahtarınızla Kimlik Doğrulama + +Çoğu bulut OCR hizmeti bir API anahtarı gerektirir. Bu adım, kimlik bilgilerini güvenli bir şekilde nasıl ekleyeceğinizi gösterir. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Güvenlik notu:** Anahtarı asla bir açık depoda sabit kodlamayın. Üretimde, onu bir ortam değişkeninden alırsınız: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +--- + +## Adım 4: **recognize text from image** – Uzaktan Görüntüyü İşleme Gönder + +Motor yapılandırıldıktan sonra, nihayet **recognize text from image** yapabiliriz. `recognize_image()` yöntemi bir yol ya da URL alır ve çıkarılan metni içeren bir nesne döndürür. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Arka planda ne oluyor?** +Görüntü baytları sağlayıcının uç noktasına yüklenir, bir derin öğrenme modeli tarafından işlenir ve düz metin sonucu geri akıtılır. Görüntü büyükse, hizmet işi hızlandırmak için otomatik olarak ölçek küçültebilir. + +--- + +## Adım 5: **extract text from image** Sonucunu Çıktıla + +OCR hizmeti işini tamamladığında, sadece metni yazdırıyoruz. Gerçek uygulamalarda bunu bir veritabanına kaydedebilir veya başka bir fonksiyona aktarabilirsiniz. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Beklenen çıktı:** (örnek) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Eğer çıktı bozuk görünüyorsa, görüntünün net olduğundan ve doğru dil modelini seçtiğinizden emin olun (birçok hizmet `engine.set_language("en")` ile dil belirlemenize izin verir). + +--- + +## Kenar Durumlarını ve Yaygın Tuzakları Ele Alma + +### 1. Eksik veya Geçersiz API Anahtarı +Eğer bir kimlik doğrulama hatası görüyorsanız, şunları kontrol edin: +- Anahtarın aktif ve süresi dolmamış olduğundan. +- Ortam değişkeninden doğru şekilde okunup okunmadığından. +- Ağınızın dışa doğru HTTPS trafiğine izin verip vermediğinden. + +### 2. Desteklenmeyen Görüntü Formatları +Çoğu OCR API'si JPEG, PNG ve PDF kabul eder. BMP veya TIFF denemek “format desteklenmiyor” yanıtı verebilir. Gerekirse Pillow ile dönüştürün: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Hız Sınırlamaları +Bulut hizmetleri genellikle dakikada istek sayısını sınırlar. Bir sınıra ulaşırsanız, üssel geri çekilme uygulayın: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Yerel OCR'a Geri Dönüş +Bulut hizmeti kapalıysa, geri geçiş yapabilirsiniz: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Bir geri dönüş mekanizması, uygulamanızın dayanıklı kalmasını sağlar. + +--- + +## Tam Çalışan Örnek + +Hepsini bir araya getirerek, şu anda çalıştırabileceğiniz bir betik (yer tutucu değerleri sadece değiştirin) burada: + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Çalıştır:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Konsola çıkarılan metnin yazdırıldığını görmelisiniz, bu da **recognize text from image** ve **extract text from image** işlemlerini doğru bir şekilde **configure OCR engine python** iş akışıyla başarıyla gerçekleştirdiğinizi doğrular. + +--- + +## Sonuç + +Python’da **recognize text from image** yapmanızı sağlayan, kütüphaneyi kurmaktan bulut hizmeti kimlik doğrulamaya ve sonunda tek bir fonksiyon çağrısıyla **extract text from image** yapmaya kadar tam, uçtan uca bir süreci adım adım gösterdik. **configure OCR engine python** doğru şekilde yaparak, hem esneklik (bulut vs. yerel) hem de güvenilirlik (doğru hata yönetimi) kazanırsınız. + +Sırada ne var? Bir klasör fatura dosyasını toplu işleyin, dil algılaması ekleyin veya PDF'leri girdi olarak deneyin. Temel konuları öğrendikten sonra sınır yok. + +Kodlamaktan keyif alın ve yorumlarda sorularınızı bırakmaktan çekinmeyin—birlikte öğrenmekten daha iyisi yok! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Aspose OCR ile Görüntüden Metin Çıkarma – Adım Adım Kılavuz](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Görüntüden Metin Çıkarma – Aspose.OCR ile Satır Tanıma](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [OCR’da Dikdörtgenler Hazırlayarak Görüntüden Metin Çıkarma](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1d29d3ba7 --- /dev/null +++ b/ocr/turkish/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-06-06 +description: Python kullanarak görüntüde OCR çalıştırın ve güven puanlarını görün. + Düşük güvenilirliğe sahip kelimeleri nasıl filtreleyeceğinizi, eşik değerlerini + nasıl ayarlayacağınızı ve uç durumları nasıl ele alacağınızı öğrenin. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: tr +og_description: Python'da görüntü üzerinde OCR çalıştırın, güven seviyelerini inceleyin + ve düşük güvenilirliğe sahip kelimeleri filtreleyin. Bu öğretici, size eksiksiz, + çalıştırılabilir bir örnek sunar. +og_title: Python ile Görüntüde OCR Çalıştırma – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Python ile Görüntüde OCR Çalıştırma – Tam Adım Adım Rehber +url: /tr/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntüde OCR Çalıştırma – Python ile Tam Adım‑Adım Kılavuz + +Hiç **run OCR on image** dosyalarıyla çalışmanız gerekti, ancak güvenilir metni nasıl çıkaracağınızdan emin olamadınız mı? Yalnız değilsiniz—birçok geliştirici, çıkarılan kelimeler titrek göründüğünde ve güven puanı bir muamma olduğunda aynı duvara çarpar. + +Bu kılavuzda doğrudan çalışan bir çözümle derinlemesine inceleyeceğiz: görüntüde OCR nasıl çalıştırılır, genel güven nasıl okunur ve manuel inceleme gerektirebilecek düşük güvenli kelimeler nasıl ayıklanır göreceksiniz. Sonunda yeniden kullanılabilir bir betiğe sahip olacak, her satırın neden önemli olduğunu anlayacak ve kendi projeleriniz için güven eşiğini nasıl ayarlayacağınızı bileceksiniz. + +## Bu Eğitimde Neler Ele Alınıyor + +Bir görüntüyü yüklemekten %80’in altındaki kelimelerin düzenli bir raporunu yazdırmaya kadar tüm iş akışını adım adım göstereceğiz. Yol boyunca şunları tartışacağız: + +* Sağlam bir OCR motoru seçimi (biz **EasyOCR**’u kullanacağız, popüler bir Python OCR kütüphanesi) +* Her OCR sonucunun döndürdüğü `confidence` özniteliğinin yorumlanması +* Özel bir **OCR confidence threshold** ile kelimelerin filtrelenmesi +* Betiğin toplu işleme veya **pytesseract** gibi alternatif motorlar için genişletilmesi + +Önceden OCR deneyimi gerekmez, sadece Python’a temel bir aşinalık ve çalışır bir ortam (Python 3.9+ önerilir) yeterlidir. + +Bulanık ekran görüntülerini temiz, aranabilir metne dönüştürmeye hazır mısınız? Hadi başlayalım. + +--- + +## ## Görüntüde OCR Çalıştırma – Python ile + +Eğitimin kalbi, zaten gördüğünüz kodu yansıtan üç adımlı bir snippet. Aşağıda her satırı ayıracağız, nedenini açıklayacağız ve ardından tam, kopyala‑yapıştır‑hazır bir betik sunacağız. + +### Adım 1: OCR Motorunu Kurun ve İçe Aktarın + +İlk olarak OCR kütüphanesinin mevcut olduğundan emin olun. **EasyOCR**, birçok dil için kutudan çıkar çıkmaz çalışır ve kelime başına bir güven puanı verir. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*EasyOCR neden?* Derin öğrenme modeli, çeşitli veri setleri üzerinde eğitildiği için genellikle eski Tesseract motorundan daha yüksek güven değerleri sunar, özellikle karışık kaliteye sahip görüntülerde. + +> **İpucu:** Sınırlı bir ortamda (ör. çok küçük bir Docker konteyneri) çalışıyorsanız `pytesseract` daha hafif olabilir, ancak EasyOCR’un sağladığı modern doğruluktan bir miktar feragat etmeniz gerekir. + +### Adım 2: Görüntüde OCR Çalıştırın + +Şimdi gerçekten **run OCR on image** yapıyoruz. Orijinal örnekteki `recognize_image` metodu, EasyOCR’un `readtext` çağrısı ile değiştirildi; bu, `(bbox, text, confidence)` üçlüsü içeren bir liste döndürür. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +`ocr_results` içindeki her giriş şu şekildedir: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Üçüncü öğe (`0.92` örnekte) 0 ile 1 arasında değişen güven puanını temsil eder. + +### Adım 3: Genel Güveni Özetleyin + +Önceki snippet tek bir `confidence` özniteliği yazdırıyorken, EasyOCR kelime başına bir güven verir. Genel bir izlenim elde etmek için bunların ortalamasını alacağız: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Neden ortalama?* Hızlı bir sağlık kontrolü sağlar—örneğin genel güven %70’in altındaysa, muhtemelen görüntüyü iyileştirmeniz gerekir (daha iyi aydınlatma, ön‑işleme vb.). + +### Adım 4: Düşük Güvenli Kelimeleri Listeleyin + +Şimdi “güven puanı istenen eşik değerinin altında olan kelimeleri listele” gereksinimini doğrudan karşılayan kısım geliyor. Varsayılan olarak **OCR confidence threshold** = 0.80 ( %80 ) olarak ayarlayacağız, ancak ihtiyacınıza göre değiştirebilirsiniz. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Döngü, kesme değerini karşılamayan her kelimeyi yüzde olarak güven puanı ile birlikte yazdırır. Bu, orijinal `for recognized_word in recognition_result.words` döngüsünün tam analoğudur, ancak EasyOCR’un çıktı formatıyla çalışır. + +--- + +## ## OCR Güven Puanlarını Anlamak + +Güven, sihirli bir sayı değildir; modelin belirli bir transkripsiyon hakkında ne kadar emin olduğunun tahminidir. Akılda tutmanız gereken birkaç nokta: + +| Durum | Tipik Güven | Ne Yapmalı | +|-----------|-------------------|------------| +| Temiz, yüksek çözünürlüklü tarama | 0.95 – 1.00 | Ek bir işleme gerek yok | +| Hafif bulanıklık veya dengesiz aydınlatma | 0.80 – 0.94 | Hafif ön‑işleme (kontrast artırma) düşünün | +| Yoğun gürültü, döndürülmüş metin | < 0.70 | Görüntü ön‑işleme (düzleştirme, gürültü azaltma) uygulayın veya farklı bir OCR motoruna geçin | + +> **Dikkat:** Bazı diller (ör. el yazısı) doğal olarak daha düşük puanlar üretir. Eşiği buna göre ayarlayın. + +### Kenar Durumları ve Varyasyonlar + +1. **Toplu İşleme** – **run OCR on image** dosyalarını toplu olarak çalıştırmanız gerekiyorsa, yukarıdaki mantığı bir dizin üzerinde dönen bir döngüye sarın. +2. **Birden Çok Dil** – `easyocr.Reader`’a `['en', 'fr']` gibi bir liste verin, motor her ikisini de algılar. +3. **Alternatif Motorlar** – **pytesseract** denemek ister misiniz? Okuyucu bloğunu şu şekilde değiştirin: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Ardından karakter bazlı güvenleri kelime bazına toplamanız gerekir—biraz daha iş ama mümkündür. + +4. **Ön‑İşleme Hileleri** – OpenCV filtreleri (`cv2.threshold`, `cv2.GaussianBlur`) gürültülü taramalarda güveni artırabilir. + +--- + +## ## Tam, Çalıştırmaya Hazır Betik + +Aşağıda projenize ekleyebileceğiniz tam Python dosyası bulunuyor. `ocr_report.py` olarak kaydedin ve `python ocr_report.py` komutuyla çalıştırın. Görüntü yolu gerçek bir dosyaya işaret ettiğinden emin olun. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Beklenen çıktı** (sayılar sizin için değişebilir): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Eğer her kelime %80 eşiğini geçerse, “All words meet the confidence threshold.” mesajını göreceksiniz. + +--- + +## ## Sıkça Sorulan Sorular (SSS) + +**S: Bu PDF’lerle çalışır mı?** +C: Doğrudan değil. Önce her PDF sayfasını bir görüntüye dönüştürün (ör. `pdf2image` ile) ve ardından PNG/JPEG’i betiğe besleyin. + +**S: Güven puanlarım çok düşük—ne yapabilirim?** +C: Görüntü ön‑işleme deneyin: kontrastı artırın, arka plan gürültüsünü kaldırın veya görüntüyü yatay bir temele döndürün. EasyOCR ayrıca ayarlayabileceğiniz bir `contrast_ths` parametresi sunar. + +**S: Sonuçları CSV’ye aktarabilir miyim?** +C: Kesinlikle. Düşük‑güven döngüsünden sonra `ocr_results`’ı `csv.DictWriter` ile yazın; her satır `text`, `confidence` ve sınırlayıcı kutu koordinatlarını içersin. + +**S: GPU‑hızlandırmalı bir sürüm var mı?** +C: EasyOCR, uyumlu bir GPU ve PyTorch kuruluysa otomatik olarak CUDA’yı kullanır. Betiği çalıştırmadan önce `torch.cuda.is_available()` ile kontrol edin. + +--- + +## Sonuç + +Python ile **run OCR on image** yaptık, genel güveni inceledik ve manuel gözden geçirme gerektirebilecek düşük‑güvenli kelimeleri izole ettik. + +## Sonraki Öğrenmeniz Gerekenler + + +Aşağıdaki eğitimler, bu kılavuzda gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım‑adım açıklamalı tam çalışan kod örnekleri içerir. + +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) +- [How to Use Aspose OCR for JSON Result in Image Recognition](/ocr/english/net/text-recognition/get-result-as-json/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md b/ocr/vietnamese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md new file mode 100644 index 000000000..0e9a8269e --- /dev/null +++ b/ocr/vietnamese/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Trích xuất văn bản từ hình ảnh bằng Python OCR trong vài phút. Khám phá + OCR hình ảnh đa ngôn ngữ, tự động phát hiện ngôn ngữ OCR và cách trích xuất văn + bản OCR một cách chính xác. +draft: false +keywords: +- extract text from image +- how to extract OCR text +- multilingual image OCR +- detect language OCR +- auto detect language OCR +language: vi +og_description: Trích xuất văn bản từ hình ảnh bằng Python OCR nhanh chóng. Tìm hiểu + OCR hình ảnh đa ngôn ngữ, tự động phát hiện ngôn ngữ OCR và cách trích xuất văn + bản OCR từng bước. +og_title: Trích xuất văn bản từ hình ảnh bằng Python OCR – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + headline: Extract Text from Image Using Python OCR – Complete Guide + type: TechArticle +- description: Extract text from image with Python OCR in minutes. Discover multilingual + image OCR, auto detect language OCR, and how to extract OCR text accurately. + name: Extract Text from Image Using Python OCR – Complete Guide + steps: + - name: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + text: '**Low‑resolution images** – OCR accuracy drops sharply below 150 dpi. Upscale + or request a higher‑resolution scan.' + - name: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + text: '**Noise and compression artifacts** – Apply a simple threshold filter (`opencv` + or `Pillow`) before feeding the image to the engine.' + - name: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + text: '**Mixed scripts on one page** – Some engines struggle with simultaneous + Latin and CJK characters. Split the page into regions and run separate recognitions + if needed.' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- Multilingual +title: Trích xuất văn bản từ hình ảnh bằng Python OCR – Hướng dẫn đầy đủ +url: /vi/python-java/general/extract-text-from-image-using-python-ocr-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Trích xuất văn bản từ hình ảnh bằng Python OCR – Hướng dẫn đầy đủ + +Bạn đã bao giờ cần **trích xuất văn bản từ hình ảnh** nhưng không chắc thư viện nào có thể tự động xử lý đa ngôn ngữ? Bạn không đơn độc—các nhà phát triển luôn hỏi *cách trích xuất văn bản OCR* khi làm việc với tài liệu quốc tế, biên lai, hoặc tờ rơi đã quét. Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ thực tế bằng Python không chỉ trích xuất văn bản từ hình ảnh mà còn **phát hiện ngôn ngữ** ngay lập tức, biến việc OCR đa ngôn ngữ thành việc nhẹ nhàng. + +Chúng ta sẽ bao phủ mọi thứ từ cài đặt gói OCR đến bật **tự động phát hiện ngôn ngữ OCR**, chạy engine trên một bức ảnh mẫu, và cuối cùng in ra cả ngôn ngữ đã phát hiện và chuỗi văn bản đã trích xuất. Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng trong bất kỳ dự án nào, dù bạn đang xây dựng một pipeline dịch thuật hay một dịch vụ thu thập dữ liệu. + +## Trích xuất văn bản từ hình ảnh – Cài đặt môi trường + +Trước khi chúng ta viết code, hãy chắc chắn máy của bạn đáp ứng các yêu cầu tối thiểu sau: + +- Python 3.8 hoặc mới hơn (thư viện sử dụng type hints mà các phiên bản cũ không hỗ trợ) +- `pip` để quản lý gói +- Một tệp hình ảnh chứa văn bản ít nhất hai ngôn ngữ khác nhau (ví dụ: Tiếng Anh + Tiếng Tây Ban Nha) + +Bạn cũng sẽ cần thư viện OCR cung cấp cho demo này. Đối với hướng dẫn này, chúng ta sẽ dùng gói giả tưởng `ocr`, mô phỏng các công cụ thực tế phổ biến như Tesseract hoặc EasyOCR nhưng có API Python sạch sẽ. + +```bash +# Install the OCR package and its optional image dependencies +pip install ocr[image] +``` + +> **Mẹo chuyên nghiệp:** Nếu gặp lỗi quyền, hãy thêm `python -m` vào trước lệnh hoặc sử dụng môi trường ảo—giúp giữ cho các site‑packages toàn cục của bạn gọn gàng. + +## Tạo đối tượng OCR Engine + +Bây giờ thư viện đã sẵn sàng, bước logic đầu tiên là **tạo một đối tượng OCR engine**. Hãy tưởng tượng engine như một máy quét thông minh mà bạn có thể cấu hình trước khi đưa ảnh vào. + +```python +import ocr + +# Step 1: Initialize the OCR engine +engine = ocr.OcrEngine() +``` + +Tại sao chúng ta khởi tạo engine riêng thay vì gọi một phương thức tĩnh? Đối tượng engine lưu trữ trạng thái cấu hình (như tùy chọn ngôn ngữ) mà bạn có thể tái sử dụng cho nhiều ảnh, giảm thiểu chi phí khởi tạo lại mỗi lần. + +## Bật chế độ Tự động Phát hiện Ngôn ngữ OCR + +Hầu hết các công cụ OCR yêu cầu bạn chỉ định mã ngôn ngữ—`eng` cho Tiếng Anh, `spa` cho Tiếng Tây Ban Nha, v.v. Việc đoán ngôn ngữ thủ công làm mất đi mục đích của quy trình **OCR hình ảnh đa ngôn ngữ**. May mắn là gói `ocr` cung cấp chế độ *auto detect language OCR* tự động kiểm tra ảnh và chọn mô hình ngôn ngữ phù hợp phía sau. + +```python +# Step 2: Turn on automatic language detection +engine.set_recognition_language(ocr.Language.AUTO_DETECT) +``` + +Kích hoạt **detect language OCR** theo cách này có nghĩa là bạn không cần duy trì danh sách dài các mã ngôn ngữ. Engine sẽ cố gắng khớp script mà nó thấy—Latin, Cyrillic, Han, v.v.—và tự động tải mô hình thích hợp. + +## Thực hiện OCR hình ảnh đa ngôn ngữ + +Với engine đã sẵn sàng, đã đến lúc **trích xuất văn bản từ hình ảnh** thực sự. Phương thức `recognize_image` nhận một đường dẫn tệp và trả về một đối tượng kết quả chứa cả văn bản thô và ngôn ngữ đã được phát hiện. + +```python +# Step 3: Run OCR on a multilingual image +image_path = "YOUR_DIRECTORY/multilang_page.png" +result = engine.recognize_image(image_path) +``` + +Nếu bạn thắc mắc *cách trích xuất văn bản OCR* từ PDF thay vì PNG, cùng một engine cung cấp `recognize_pdf`—chỉ cần đổi tên phương thức. Logic phát hiện nền tảng vẫn giống nhau, vì vậy bạn vẫn được hưởng lợi từ tính năng **auto detect language OCR**. + +## Hiển thị Ngôn ngữ Đã Phát hiện và Văn bản Đã Trích xuất + +Cuối cùng, chúng ta xuất ra những gì engine đã khám phá. Đối tượng kết quả cung cấp `detected_language` (một thẻ BCP‑47 như `en` hoặc `es`) và `text`, chứa đầu ra OCR thô. + +```python +# Step 4: Show the language and the extracted string +print(f"Detected language: {result.detected_language}") +print("Extracted text:") +print(result.text) +``` + +Chạy script trên ảnh mẫu của chúng ta sẽ cho ra kết quả tương tự: + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Lưu ý cách engine xác định đúng Tiếng Anh là ngôn ngữ chính, nhưng vẫn bắt được dòng Tiếng Tây Ban Nha—đúng như mong đợi từ một giải pháp **OCR hình ảnh đa ngôn ngữ** mạnh mẽ. + +### Nếu Phát hiện Thất bại thì sao? + +Đôi khi engine OCR có thể quay lại ngôn ngữ mặc định (thường là Tiếng Anh) nếu ảnh mờ hoặc script quá hiếm. Trong những trường hợp đó, bạn có thể buộc một danh sách ngôn ngữ: + +```python +engine.set_recognition_language([ocr.Language.ENGLISH, ocr.Language.SPANISH]) +``` + +Nhưng hãy nhớ, việc buộc ngôn ngữ sẽ làm mất tiện lợi của **auto detect language OCR**, vì vậy chỉ dùng khi bạn biết trước một tập hợp ngôn ngữ cụ thể. + +## Những Cạm Bẫy Thường Gặp và Cách Trích xuất Văn bản OCR Đáng Tin Cậy + +Ngay cả với tự động phát hiện, một vài trục trặc vẫn có thể làm bạn bối rối: + +1. **Ảnh độ phân giải thấp** – Độ chính xác OCR giảm mạnh dưới 150 dpi. Hãy nâng cấp hoặc yêu cầu bản scan độ phân giải cao hơn. +2. **Nhiễu và artefact nén** – Áp dụng bộ lọc ngưỡng đơn giản (`opencv` hoặc `Pillow`) trước khi đưa ảnh vào engine. +3. **Kết hợp script trên một trang** – Một số engine gặp khó khăn khi xử lý đồng thời ký tự Latin và CJK. Hãy chia trang thành các vùng và chạy nhận dạng riêng nếu cần. + +Giải quyết những vấn đề này sẽ cải thiện đáng kể chất lượng quy trình **trích xuất văn bản từ hình ảnh**, đặc biệt khi làm việc với tài liệu đa ngôn ngữ thực tế. + +## Ví dụ Hoàn chỉnh + +Dưới đây là script đầy đủ, sẵn sàng chạy, kết hợp tất cả các bước chúng ta đã thảo luận. Lưu lại với tên `multilingual_ocr.py` và thực thi từ dòng lệnh. + +```python +import ocr + +def main(): + # Initialize engine with auto language detection + engine = ocr.OcrEngine() + engine.set_recognition_language(ocr.Language.AUTO_DETECT) + + # Path to your multilingual image + image_path = "YOUR_DIRECTORY/multilang_page.png" + + # Perform OCR + result = engine.recognize_image(image_path) + + # Output results + print(f"Detected language: {result.detected_language}") + print("Extracted text:") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Kết quả mong đợi** (giả sử ảnh mẫu chứa văn bản Tiếng Anh và Tiếng Tây Ban Nha): + +``` +Detected language: en +Extracted text: +Welcome to our multilingual brochure. +¡Bienvenidos a nuestro folleto multilingüe! +``` + +Bạn có thể thay `multilang_page.png` bằng bất kỳ bức ảnh nào chứa văn bản ở các ngôn ngữ khác—nhờ **auto detect language OCR**, script vẫn sẽ cung cấp thẻ ngôn ngữ hợp lý và văn bản tương ứng. + +![Trích xuất văn bản từ hình ảnh ví dụ](https://example.com/ocr-sample.png "Trích xuất văn bản từ hình ảnh") + +## Kết luận + +Bây giờ bạn đã biết **cách trích xuất văn bản OCR** từ một hình ảnh, cách bật **auto detect language OCR**, và cách xử lý các tình huống **OCR hình ảnh đa ngôn ngữ** chỉ với một vài dòng code. Bằng cách tạo một OCR engine instance, bật tính năng phát hiện ngôn ngữ tự động, và gọi `recognize_image`, bạn có thể tin cậy để lấy cả định danh ngôn ngữ và văn bản thô. + +Tiếp theo bạn sẽ làm gì? Hãy đưa các chuỗi đã trích xuất vào một API dịch thuật, lưu chúng vào cơ sở dữ liệu có thể tìm kiếm, hoặc kết hợp nhiều trang thành một báo cáo PDF duy nhất. Bạn cũng có thể thử nghiệm với các back‑end OCR khác nhau (Tesseract, EasyOCR, Google Vision) trong khi giữ nguyên quy trình cấp cao—nhờ giao diện **detect language OCR** nhất quán. + +Nếu gặp bất kỳ vấn đề nào, hãy quay lại phần “Những Cạm Bẫy Thường Gặp” hoặc điều chỉnh các bước tiền xử lý ảnh. Chúc bạn lập trình vui vẻ, và hy vọng dự án tiếp theo của bạn sẽ đầy những văn bản được phát hiện chính xác và trích xuất hoàn hảo! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã được trình bày trong bài viết này. Mỗi tài nguyên bao gồm các ví dụ code hoàn chỉnh cùng giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md b/ocr/vietnamese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md new file mode 100644 index 000000000..2e35ee4aa --- /dev/null +++ b/ocr/vietnamese/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-06-06 +description: Trích xuất văn bản từ các tệp PDF hình ảnh bằng Python OCR. Tìm hiểu + cách chuyển đổi tài liệu quét sang văn bản một cách nhanh chóng với nhận dạng hàng + loạt bất đồng bộ. +draft: false +keywords: +- extract text from images pdf +- convert scanned documents to text +- python ocr batch processing +- asynchronous OCR python +- image to text conversion +language: vi +og_description: Trích xuất văn bản từ hình ảnh PDF bằng Python. Hướng dẫn chi tiết + này chỉ cách chuyển đổi tài liệu quét sang văn bản bằng OCR bất đồng bộ. +og_title: Trích xuất văn bản từ PDF hình ảnh – Hướng dẫn OCR Python +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Extract text from images pdf using Python OCR. Learn how to convert + scanned documents to text quickly with async batch recognition. + headline: Extract Text from Images PDF – Python Guide to Convert Scanned Documents + to Text + type: TechArticle +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Trích xuất văn bản từ PDF hình ảnh – Hướng dẫn Python để chuyển đổi tài liệu + quét thành văn bản +url: /vi/python-java/general/extract-text-from-images-pdf-python-guide-to-convert-scanned/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Trích xuất Văn bản từ PDF Hình ảnh – Hướng dẫn Python để Chuyển Đổi Tài liệu Quét thành Văn bản + +Bạn đã bao giờ cần **trích xuất văn bản từ pdf hình ảnh** mà không phải mất hàng giờ gõ lại? Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách **chuyển đổi tài liệu quét thành văn bản** bằng một quy trình OCR bất đồng bộ đơn giản trong Python. + +Nếu bạn từng nhìn chằm chằm vào một đống PDF đã quét và nghĩ, “Phải có cách nhanh hơn,” thì bạn đang ở đúng nơi. Chúng tôi sẽ đi qua từng dòng mã, giải thích lý do mỗi phần quan trọng, và thậm chí đề cập đến một vài trường hợp đặc biệt mà bạn có thể gặp phải. + +## Những gì Bạn sẽ Học + +- Cách khởi tạo một engine OCR và đặt ngôn ngữ nhận dạng. +- Cơ chế đưa một danh sách hỗn hợp các file PNG và PDF vào bộ nhận dạng hàng loạt. +- Chạy công việc OCR bất đồng bộ để ứng dụng của bạn vẫn phản hồi được. +- Lấy kết quả về, ghép chúng với các file nguồn, và in ra đầu ra sạch sẽ. + +**Yêu cầu trước**: Python 3.8+, hiểu biết cơ bản về `asyncio` hoặc `concurrent.futures`, và một thư viện OCR cung cấp lớp `OcrEngine` tương tự như trong ví dụ (ví dụ: Aspose.OCR, wrapper Tesseract, hoặc wrapper tùy chỉnh). Không cần cài đặt phức tạp—chỉ cần cài thư viện và bạn đã sẵn sàng. + +![trích xuất văn bản từ pdf hình ảnh](https://example.com/placeholder.png "Ảnh chụp màn hình kết quả OCR – trích xuất văn bản từ pdf hình ảnh") + +## Trích xuất Văn bản từ PDF Hình ảnh – Cài Đặt Engine OCR + +Điều đầu tiên bạn cần là một thể hiện engine OCR được cấu hình cho ngôn ngữ của tài liệu. Trong ví dụ của chúng tôi, chúng tôi sẽ dùng tiếng Pháp, nhưng bạn có thể thay đổi sang bất kỳ ngôn ngữ nào được hỗ trợ. + +```python +# Import the OCR library – replace with your actual import +from ocr import OcrEngine, Language + +# Step 1: Create and configure the OCR engine +engine = OcrEngine() +engine.set_recognition_language(Language.FRENCH) # Change to Language.ENGLISH, etc. +``` + +**Tại sao điều này quan trọng**: Đặt ngôn ngữ từ đầu sẽ cải thiện độ chính xác đáng kể. Engine sử dụng các từ điển và mô hình ký tự riêng cho từng ngôn ngữ; việc cung cấp ngôn ngữ sai là nguyên nhân phổ biến gây ra đầu ra rối rắm. + +## Chuẩn bị Danh sách File – Hình ảnh và PDF Cùng Nhau + +Bộ nhận dạng hàng loạt của chúng tôi có thể xử lý cả ảnh raster (`.png`, `.jpg`) và các file PDF. Chỉ cần đưa một danh sách Python đơn giản chứa các đường dẫn file. + +```python +# Step 2: Define the files to be processed (use your own directory) +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.pdf" +] +``` + +**Mẹo**: Giữ danh sách phẳng; engine sẽ tự động giải nén mỗi trang PDF thành ảnh trước khi nhận dạng. Nếu bạn có hàng ngàn file, hãy cân nhắc chia danh sách thành các batch nhỏ hơn để tránh tăng đột biến bộ nhớ. + +## Khởi động Nhận dạng Hàng loạt Bất đồng bộ + +Thay vì chặn luồng chính, chúng tôi sẽ khởi chạy công việc OCR ở nền. Phương thức trả về một `Future` sẽ cuối cùng chứa danh sách các đối tượng `OcrResult`. + +```python +# Step 3: Start asynchronous batch recognition +future = engine.recognize_batch_async(files) # returns a Future[List[OcrResult]] +``` + +**Cách hoạt động**: Bên trong, engine tạo một pool luồng (hoặc một tác vụ async, tùy vào triển khai). Điều này cho phép bạn tiếp tục thực hiện các công việc khác—như cập nhật UI, tải thêm file, hoặc ghi log tiến độ—trong khi phần xử lý nặng diễn ra ở nền. + +## Thực hiện Công việc Hữu ích Khi OCR Đang Chạy + +Một lỗi thường gặp là ngồi chờ và liên tục poll future trong vòng lặp chặt. Thay vào đó, bạn có thể thực hiện bất kỳ công việc không liên quan nào. Để minh họa, chúng tôi sẽ chỉ in một dòng trạng thái. + +```python +# Step 4: Perform other work while OCR runs +print("Batch started – doing other work...") +# Imagine you could be uploading files, sending heartbeats, etc. +``` + +## Thu thập Kết quả Khi Future Hoàn thành + +Khi bạn đã sẵn sàng thu thập đầu ra OCR, sử dụng `as_completed` từ `concurrent.futures`. Mẫu này hoạt động dù bạn có một hay nhiều future. + +```python +from concurrent.futures import as_completed + +# Step 5: Wait for the batch to finish and retrieve the results +for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] in the same order as `files` + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") +``` + +**Bạn sẽ thấy**: Mỗi đường dẫn file kèm theo biểu diễn văn bản thuần được trích xuất. Đối với PDF, `result.text` chứa văn bản đã được nối lại của mọi trang. + +### Đầu ra Dự kiến (ví dụ) + +``` +YOUR_DIRECTORY/doc1.png → +Bonjour, ceci est un test d’OCR. + +YOUR_DIRECTORY/doc2.png → +Le texte de la deuxième image apparaît ici. + +YOUR_DIRECTORY/doc3.pdf → +Page 1 du PDF : Lorem ipsum dolor sit amet… +Page 2 du PDF : Consectetur adipiscing elit… +``` + +Nếu bạn nhận thấy thiếu ký tự, hãy kiểm tra lại ngôn ngữ đã đặt có khớp với ngôn ngữ tài liệu không, và cân nhắc tiền xử lý ảnh (điều chỉnh góc, tăng độ tương phản) trước khi đưa vào engine. + +## Xử lý Các Trường hợp Đặc biệt và Những Cạm bẫy Thông thường + +| Tình huống | Cách giải quyết | +|-----------|-----------------| +| **Ngôn ngữ hỗn hợp** | Đầu tiên chạy bước phát hiện ngôn ngữ, sau đó khởi tạo các engine riêng cho từng ngôn ngữ. | +| **PDF lớn (> 100 MB)** | Tách PDF thành các trang riêng trên đĩa (ví dụ: dùng `PyPDF2`) và đưa chúng vào như các mục riêng biệt. | +| **Chữ viết không phải Latin** | Đảm bảo thư viện OCR có gói ngôn ngữ cần thiết; một số thư viện yêu cầu tải thêm file dữ liệu. | +| **Nút thắt hiệu năng** | Tăng kích thước pool luồng (`engine.set_thread_pool_size(8)`) hoặc chuyển sang backend hỗ trợ GPU nếu có. | +| **Thiếu văn bản trong ảnh độ phân giải thấp** | Tiền xử lý bằng OpenCV: `cv2.resize`, `cv2.threshold`, và `cv2.medianBlur` để cải thiện khả năng đọc. | + +## Ví dụ Hoàn chỉnh (Sẵn sàng Sao chép) + +```python +# ------------------------------------------------------------ +# Full script: extract text from images pdf – async OCR batch +# ------------------------------------------------------------ +import os +from concurrent.futures import as_completed +# Replace the import below with the actual OCR library you use +from ocr import OcrEngine, Language, OcrResult + +def main(): + # 1️⃣ Initialize OCR engine + engine = OcrEngine() + engine.set_recognition_language(Language.FRENCH) # Change as needed + + # 2️⃣ Build list of files (images + PDFs) + base_dir = "YOUR_DIRECTORY" + files = [ + os.path.join(base_dir, "doc1.png"), + os.path.join(base_dir, "doc2.png"), + os.path.join(base_dir, "doc3.pdf") + ] + + # 3️⃣ Launch async batch recognition + future = engine.recognize_batch_async(files) + + # 4️⃣ Do other work – here we just print a placeholder + print("Batch started – doing other work...") + + # 5️⃣ Retrieve results when ready + for completed in as_completed([future]): + ocr_results = completed.result() # List[OcrResult] + for path, result in zip(files, ocr_results): + print(f"{path} →\n{result.text}\n") + +if __name__ == "__main__": + main() +``` + +Lưu file này dưới tên `extract_text_async.py`, thay `YOUR_DIRECTORY` bằng đường dẫn tới các file của bạn, cài gói OCR (`pip install your-ocr-lib`), và chạy `python extract_text_async.py`. Bạn sẽ thấy đầu ra console như đã minh họa ở trên. + +## Các Bước Tiếp Theo – Vượt Qua Việc Trích xuất Cơ bản + +- **Hậu xử lý**: Loại bỏ khoảng trắng thừa, chuẩn hoá Unicode (`unicodedata.normalize`), hoặc chạy bộ kiểm tra chính tả để làm sạch nhiễu OCR. +- **Đầu ra có cấu trúc**: Xuất kết quả ra CSV, JSON, hoặc trực tiếp vào cơ sở dữ liệu để tìm kiếm downstream. +- **Batch song song**: Nếu bạn có hàng trăm file, khởi tạo nhiều future và dùng queue để giữ CPU bận mà không làm quá tải bộ nhớ. +- **Tích hợp với framework web**: Kết nối script này vào endpoint Flask hoặc FastAPI để cung cấp OCR theo yêu cầu như một dịch vụ. + +--- + +### TL;DR + +Bạn đã biết cách **trích xuất văn bản từ pdf hình ảnh** bằng một script Python tối thiểu chạy OCR bất đồng bộ, cho phép bạn **chuyển đổi tài liệu quét thành văn bản** trong khi chương trình vẫn phản hồi nhanh. Hãy thử nghiệm các cài đặt ngôn ngữ, kích thước batch, và các thủ thuật tiền xử lý để đạt độ chính xác tối đa. + +Có cách tiếp cận nào bạn muốn chia sẻ—có thể là OCR trên ghi chú viết tay hoặc dịch vụ dựa trên đám mây? Hãy để lại bình luận, và chúc bạn lập trình vui vẻ! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ code hoàn chỉnh với giải thích chi tiết từng bước, giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Images Using Aspose.OCR – Allowed Characters](/ocr/english/java/advanced-ocr-techniques/specify-allowed-characters/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8a135b12f --- /dev/null +++ b/ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-06-06 +description: Cách OCR PDF bằng Python, trích xuất văn bản từ PDF, chuyển đổi văn bản + PDF đã quét và thay đổi ngôn ngữ OCR chỉ trong vài dòng mã. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert scanned pdf text +- perform ocr on pdf +- change ocr language +language: vi +og_description: 'Cách OCR PDF bằng Python: hướng dẫn thực tế chỉ cho bạn cách trích + xuất văn bản từ PDF, chuyển đổi văn bản PDF đã quét và thay đổi ngôn ngữ OCR một + cách dễ dàng.' +og_title: Cách OCR PDF trong Python – Hướng dẫn lập trình đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Python, extract text from PDF, convert scanned + PDF text, and change OCR language in just a few lines of code. + headline: How to OCR PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Cách OCR PDF trong Python – Hướng dẫn chi tiết từng bước +url: /vi/python-java/general/how-to-ocr-pdf-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách OCR PDF trong Python – Hướng Dẫn Chi Tiết Từng Bước + +Bạn đã bao giờ tự hỏi **cách OCR PDF** mà không phải trả tiền cho các công cụ SaaS đắt đỏ chưa? Bạn không phải là người duy nhất. Dù bạn đang số hoá những cuốn sách cũ, trích xuất dữ liệu từ hoá đơn, hay chỉ cần văn bản có thể tìm kiếm từ một báo cáo đã quét, việc thành thạo OCR PDF trong Python có thể tiết kiệm cho bạn hàng giờ sao chép thủ công. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ ngắn gọn, hoạt động được, mà **trích xuất văn bản từ PDF**, cho bạn thấy cách **chuyển đổi văn bản PDF đã quét** thành các chuỗi có thể chỉnh sửa, và thậm chí minh họa cách **thay đổi ngôn ngữ OCR** nếu tài liệu của bạn không phải tiếng Anh. Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng và chèn vào bất kỳ dự án nào. + +## Yêu Cầu Trước & Cài Đặt + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +- Python 3.8+ đã được cài đặt (mã chạy được trên 3.9, 3.10 và các phiên bản mới hơn) +- Gói `ocr` cung cấp lớp `OcrEngine` (bạn có thể cài đặt bằng `pip install ocr-lib` – thay thế bằng tên gói thực tế bạn dùng) +- Một file PDF mà bạn muốn xử lý; trong demo chúng ta sẽ dùng `high_res_book.pdf` đặt trong thư mục `YOUR_DIRECTORY` + +Nếu bạn đang dùng môi trường ảo (được khuyến nghị mạnh mẽ), hãy kích hoạt nó trước: + +```bash +python -m venv .venv +source .venv/bin/activate # on Windows: .venv\Scripts\activate +pip install ocr-lib +``` + +> **Mẹo chuyên nghiệp:** Giữ các file PDF của bạn trong một thư mục `data/` riêng biệt để tránh các rắc rối liên quan đến đường dẫn sau này. + +## Bước 1: Tạo Một Instance của OCR Engine (Cách OCR PDF – Khởi Tạo) + +Điều đầu tiên bạn cần làm khi muốn **thực hiện OCR trên PDF** là khởi tạo engine. Hãy nghĩ engine như bộ não sẽ đọc từng trang, giải mã các glyph, và trả lại cho bạn văn bản thuần. + +```python +# Step 1: Create an OCR engine instance +engine = OcrEngine() +``` + +Tại sao điều này quan trọng: nếu không có engine, bạn sẽ không có ngữ cảnh cho các cài đặt ngôn ngữ, tùy chọn render, hay xử lý PDF. Đối tượng `OcrEngine` chứa tất cả các mặc định này và cho phép bạn điều chỉnh chúng sau này. + +## Bước 2: Đặt Ngôn Ngữ Nhận Diện (Thay Đổi Ngôn Ngữ OCR) + +Hầu hết các thư viện OCR mặc định là tiếng Anh, nhưng nếu tài liệu của bạn là tiếng Pháp, Đức, hoặc thậm chí tiếng Nhật thì sao? Thay đổi ngôn ngữ chỉ cần gọi `set_recognition_language`. Điều này đáp ứng yêu cầu **thay đổi ngôn ngữ OCR** và đảm bảo độ chính xác cao hơn. + +```python +# Step 2: Set the recognition language to English (or any supported language) +engine.set_recognition_language(ocr.Language.ENGLISH) # swap ENGLISH for FRANCAIS, etc. +``` + +> **Tại sao bạn có thể cần điều này:** Một kho lưu trữ đa ngôn ngữ thường chứa các trang hỗn hợp. Chuyển đổi ngôn ngữ ngay lập tức giúp tránh nhận dạng sai các ký tự như “ß” hay “ñ”. + +## Bước 3: Cấu Hình Các Tùy Chọn Render PDF (Chuyển Đổi Văn Bản PDF Đã Quét Hiệu Quả) + +Khi làm việc với PDF đã quét, độ phân giải và chế độ màu ảnh hưởng mạnh tới chất lượng OCR. Render ở 300 DPI với chế độ grayscale là điểm cân bằng cho hầu hết tài liệu—đủ chi tiết nhưng không gây tốn bộ nhớ quá mức. + +```python +# Step 3: Configure PDF rendering options (300 DPI, grayscale) +engine.pdf_render_options() \ + .set_dpi(300) \ + .set_color_mode("grayscale") +``` + +Các lệnh chuỗi có thể trông cầu kỳ, nhưng chúng chỉ là một Fluent API trả về cùng một đối tượng tùy chọn mỗi lần. Nếu bạn cần màu (ví dụ, cho các sơ đồ màu), hãy thay `"grayscale"` bằng `"color"`. + +## Bước 4: Nhận Diện PDF và Lấy Văn Bản Trang Đầu Tiên (Trích Xuất Văn Bản Từ PDF) + +Bây giờ là phần cốt lõi của **cách OCR PDF**: đưa engine một đường dẫn file và lấy ra văn bản đã nhận dạng. Phương thức trả về một danh sách các kết quả trang; mỗi kết quả chứa thuộc tính `text`. + +```python +# Step 4: Recognize the PDF and print the text of the first page +results = engine.recognize_pdf("YOUR_DIRECTORY/high_res_book.pdf") +print(results[0].text) # Text from the first page +``` + +Nếu bạn cần toàn bộ tài liệu, hãy lặp qua `results`: + +```python +for i, page in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(page.text) +``` + +### Nếu PDF Được Mã Hoá? + +Một số PDF được bảo vệ bằng mật khẩu. Trong trường hợp đó, bạn có thể truyền mật khẩu vào `recognize_pdf`: + +```python +results = engine.recognize_pdf( + "YOUR_DIRECTORY/secure_doc.pdf", + password="mySecret123" +) +``` + +Engine sẽ giải mã ngay trong quá trình thực hiện OCR—không cần bước bổ sung nào. + +## Bước 5: Xử Lý Sau Văn Bản Đã Trích Xuất (Tinh Chỉnh Văn Bản Được Trích Xuất Từ PDF) + +Kết quả OCR thô thường chứa các ngắt dòng, khoảng trắng thừa, hoặc một vài ký tự nhận dạng sai. Một routine làm sạch nhanh sẽ chuẩn bị chuỗi đã trích xuất cho các bước xử lý tiếp theo (đánh chỉ mục tìm kiếm, lưu trữ cơ sở dữ liệu, v.v.). + +```python +import re + +def clean_ocr_text(raw: str) -> str: + # Remove multiple spaces and line breaks + text = re.sub(r'\s+', ' ', raw) + # Strip leading/trailing whitespace + return text.strip() + +clean_text = clean_ocr_text(results[0].text) +print(clean_text) +``` + +Bây giờ bạn có thể an toàn **trích xuất văn bản từ PDF** và đưa nó vào bất kỳ pipeline NLP, công cụ tìm kiếm, hoặc thao tác `open(...).write()` đơn giản nào. + +## Bonus: Xử Lý Hàng Loạt Nhiều PDF (Mở Rộng OCR Trên PDF) + +Nếu bạn có một thư mục đầy các PDF đã quét, hãy bọc logic trong một vòng lặp: + +```python +import pathlib + +pdf_folder = pathlib.Path("YOUR_DIRECTORY") +for pdf_path in pdf_folder.glob("*.pdf"): + print(f"Processing {pdf_path.name} …") + pages = engine.recognize_pdf(str(pdf_path)) + full_text = "\n".join(page.text for page in pages) + cleaned = clean_ocr_text(full_text) + + # Save the extracted text alongside the PDF + txt_path = pdf_path.with_suffix(".txt") + txt_path.write_text(cleaned, encoding="utf-8") + print(f"Saved extracted text to {txt_path.name}") +``` + +Đoạn mã này cho thấy cách **thực hiện OCR trên PDF** hàng loạt, một nhu cầu phổ biến cho các dự án số hoá. + +## Kết Quả Dự Kiến + +Chạy ví dụ một trang (Bước 4) sẽ in ra một thứ gì đó như sau: + +``` +In the beginning God created the heavens and the earth. Now the earth was formless … +``` + +Nếu bạn xử lý một cuốn sách nhiều trang, console sẽ hiển thị văn bản đã làm sạch của mỗi trang, và script batch sẽ tạo một file `.txt` bên cạnh mỗi PDF. + +## Những Sai Lầm Thường Gặp & Cách Tránh + +| Vấn đề | Triệu chứng | Cách khắc phục | +|-------|------------|----------------| +| PDF nguồn độ phân giải thấp | Ký tự bị rối, từ bị thiếu | Tăng DPI (`set_dpi(400)` hoặc cao hơn) | +| Đặt ngôn ngữ sai | Nhiều ký tự không nhận dạng, đặc biệt là ký tự có dấu | Dùng `engine.set_recognition_language(ocr.Language.FRENCH)` hoặc enum phù hợp | +| PDF lớn gây lỗi bộ nhớ | `MemoryError` hoặc treo sau vài trang | Xử lý trang theo khối (`engine.recognize_pdf(..., max_pages=10)`) | +| Thiếu font trong PDF | Kết quả trống cho một số trang | Đảm bảo PDF thực sự chứa ảnh raster; một số PDF chỉ là vector và cần cách xử lý khác | + +## Minh Họa Hình Ảnh + +Dưới đây là một hình minh hoạ nhanh về quy trình làm việc. Văn bản alt được viết chuẩn SEO. + +![luồng công việc OCR PDF hiển thị khởi tạo engine, cài đặt ngôn ngữ, tùy chọn render, nhận dạng và trích xuất văn bản](/images/ocr-workflow.png) + +*Biểu đồ không bắt buộc để code chạy, nhưng nó giúp những người học bằng hình ảnh thấy được vị trí của mỗi bước trong quy trình.* + +## Kết Luận + +Chúng ta đã bao quát **cách OCR PDF** trong Python từ đầu đến cuối: tạo engine OCR, **thay đổi ngôn ngữ OCR**, cấu hình render để **chuyển đổi văn bản PDF đã quét**, và cuối cùng **trích xuất văn bản từ PDF** để sử dụng tiếp. Đoạn mã hoàn chỉnh, có thể chạy ngay đã sẵn sàng để chèn vào bất kỳ dự án nào, và script batch tùy chọn cho thấy cách mở rộng giải pháp. + +Tiếp theo, bạn có thể muốn khám phá: + +- Thêm **thực hiện OCR trên PDF** cho các kho lưu trữ đa ngôn ngữ bằng cách lặp qua danh sách ngôn ngữ. +- Tích hợp văn bản đã trích xuất với Elasticsearch để tìm kiếm toàn văn. +- Sử dụng OCR để tạo PDF có thể tìm kiếm bằng cách nhúng lớp văn bản trở lại file gốc (nhiều thư viện cung cấp phương thức `save_as_searchable_pdf`). + +Hãy thoải mái thử nghiệm, điều chỉnh cài đặt DPI, hoặc chuyển sang backend OCR khác. Các nguyên tắc cơ bản vẫn giữ nguyên, và giờ bạn đã có nền tảng vững chắc để xây dựng tiếp. + +Chúc lập trình vui vẻ, và hy vọng các tài liệu đã quét của bạn cuối cùng cũng trở nên có thể tìm kiếm được! + +## Bạn Nên Học Gì Tiếp Theo? + + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Nhận Diện Văn Bản PDF – Các Hoạt Động OCR với Aspose.OCR cho Java](/ocr/english/java/ocr-operations/) +- [Cách OCR Văn Bản Ảnh Với Ngôn Ngữ Sử Dụng Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Cách OCR PDF trong .NET với Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md b/ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md new file mode 100644 index 000000000..a85c79a6a --- /dev/null +++ b/ocr/vietnamese/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-06 +description: Cách OCR PDF và tạo các tệp PDF có thể tìm kiếm từ hình ảnh bằng Python. + Học cách thêm văn bản có thể tìm kiếm và chuyển đổi hình ảnh sang PDF/A trong vài + phút. +draft: false +keywords: +- how to ocr pdf +- create searchable pdf +- add searchable text +- ocr image to pdf +- convert image to pdf/a +language: vi +og_description: Cách OCR PDF từng bước. Học cách thêm văn bản có thể tìm kiếm và chuyển + đổi hình ảnh sang PDF/A bằng một script Python đơn giản. +og_title: Cách OCR PDF – Hướng dẫn nhanh tạo PDF có thể tìm kiếm +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + headline: How to OCR PDF in Python – Create Searchable PDF from Images + type: TechArticle +- description: How to OCR PDF and create searchable PDF files from images using Python. + Learn to add searchable text and convert image to PDF/A in minutes. + name: How to OCR PDF in Python – Create Searchable PDF from Images + steps: + - name: Why this matters + text: '- **Preserving graphics** means the visual layout (tables, logos, stamps) + stays exactly as the scanner captured it. - The `result` object typically contains + a hidden text layer that we’ll later embed into the PDF. - Using `recognize_image` + instead of `recognize_pdf` avoids an extra conversion step, ' + - name: Why this matters + text: '- **Searchable PDF**: The output file contains a hidden, selectable text + layer. You can now Ctrl + F through the document. - **PDF/A compliance**: Some + organizations (legal, finance) require PDF/A for audit trails; this step satisfies + that rule automatically. - The method also **adds searchable text' + - name: Expected output + text: 'When you run the script, the console prints:' + type: HowTo +tags: +- OCR +- PDF +- Python +- Automation +title: Cách OCR PDF trong Python – Tạo PDF có thể tìm kiếm từ hình ảnh +url: /vi/python-java/general/how-to-ocr-pdf-in-python-create-searchable-pdf-from-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách OCR PDF – Chuyển Hình Ảnh Quét Thành PDF Có Thể Tìm Kiếm + +Bạn đã bao giờ tự hỏi **cách OCR PDF** khi bạn chỉ có một hình ảnh quét của hoá đơn hoặc biên lai chưa? Bạn không phải là người duy nhất. Ở nhiều văn phòng, tài liệu đến dưới dạng PNG hoặc JPEG phẳng, và bước tiếp theo—làm cho nội dung có thể tìm kiếm—cảm giác như một hộp đen. + +Tin tốt? Chỉ với vài dòng Python, bạn có thể **tạo PDF có thể tìm kiếm**, **thêm văn bản có thể tìm kiếm**, và thậm chí **chuyển đổi hình ảnh sang PDF/A** để lưu trữ lâu dài. Trong hướng dẫn này, chúng tôi sẽ đi qua từng bước, giải thích tại sao chúng quan trọng, và cung cấp cho bạn một script sẵn sàng chạy mà bạn có thể đưa vào bất kỳ dự án nào. + +> **Mẹo chuyên nghiệp:** Cùng một cách tiếp cận cũng hoạt động cho các bản quét đa trang; chỉ cần lặp qua các tệp và engine sẽ thực hiện phần công việc nặng. + +--- + +## Những Gì Bạn Cần + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có những thứ sau trên máy của mình: + +| Yêu cầu | Tại sao quan trọng | +|-------------|----------------| +| Python 3.9 hoặc mới hơn | Cú pháp hiện đại và hỗ trợ thư viện tốt hơn | +| Engine OCR dựa trên `pdfium` (ví dụ, `pdfocr` hoặc SDK thương mại) | Xử lý cả nhận dạng hình ảnh và tạo PDF/A | +| Tệp hình ảnh (PNG, JPEG, TIFF) bạn muốn chuyển thành PDF có thể tìm kiếm | Nguồn của văn bản | +| Quyền ghi vào thư mục đầu ra | Để script có thể lưu PDF mới | + +Nếu bạn chưa cài đặt SDK OCR, chạy: + +```bash +pip install pdfocr # replace with your vendor's package name +``` + +Xong rồi—không có phụ thuộc hệ thống phức tạp, chỉ cần một lệnh pip install. + +--- + +## Cách OCR PDF – Tổng Quan + +Ở mức cao, quy trình bao gồm ba hành động đơn giản: + +1. **Nhận diện** văn bản trong hình ảnh đồng thời giữ nguyên đồ họa gốc. +2. **Xuất** kết quả OCR cùng với hình ảnh gốc thành một **PDF/A có thể tìm kiếm** (phiên bản PDF thân thiện lưu trữ lâu dài). +3. **Xác thực** rằng tệp kết quả chứa văn bản có thể chọn, có thể tìm kiếm được đặt lên trên ảnh gốc. + +Dưới đây bạn sẽ thấy từng bước trong mã, kèm giải thích *tại sao* phía sau các lệnh. + +--- + +## Bước 1: Nhận Diện Văn Bản Từ Hình Ảnh + +Đầu tiên chúng ta yêu cầu engine OCR đọc các pixel và trả về một đối tượng kết quả chứa cả hình ảnh thô và văn bản đã trích xuất. Hãy nghĩ nó như engine “đọc” hoá đơn cho bạn. + +```python +# Step 1: Recognize text from the image and keep the original graphics +result = engine.recognize_image("YOUR_DIRECTORY/invoice.png") +``` + +### Tại sao điều này quan trọng + +- **Giữ nguyên đồ họa** có nghĩa là bố cục trực quan (bảng, logo, con dấu) vẫn giữ nguyên như khi máy quét chụp. +- Đối tượng `result` thường chứa một lớp văn bản ẩn mà chúng ta sẽ nhúng vào PDF sau. +- Sử dụng `recognize_image` thay vì `recognize_pdf` tránh một bước chuyển đổi thêm, giúp tăng tốc xử lý cho ảnh một trang. + +#### Các biến thể phổ biến + +- Nếu bạn có **TIFF đa trang**, truyền đường dẫn tệp trực tiếp; hầu hết các engine sẽ coi mỗi trang là một hình ảnh riêng. +- Đối với các PDF đã chứa hình ảnh, bạn có thể gọi `engine.recognize_pdf("file.pdf")` và bỏ qua bước này hoàn toàn. + +--- + +## Bước 2: Xuất Kết Quả OCR Thành PDF/A Có Thể Tìm Kiếm + +Bây giờ chúng ta lấy `result` từ bước 1 và yêu cầu engine ghi một tệp mới. Cờ quan trọng ở đây là *PDF/A*—phiên bản PDF chuẩn ISO được thiết kế cho việc bảo quản lâu dài. + +```python +# Step 2: Export the OCR result together with the original image as a searchable PDF/A +result.save_as_pdfa("YOUR_DIRECTORY/invoice_searchable.pdf") +``` + +### Tại sao điều này quan trọng + +- **PDF có thể tìm kiếm**: Tệp đầu ra chứa một lớp văn bản ẩn, có thể chọn. Bạn có thể dùng Ctrl + F để tìm trong tài liệu. +- **Tuân thủ PDF/A**: Một số tổ chức (pháp lý, tài chính) yêu cầu PDF/A cho hồ sơ kiểm toán; bước này tự động đáp ứng yêu cầu. +- Phương pháp cũng **thêm văn bản có thể tìm kiếm** mà không làm phẳng hình ảnh, vì vậy độ trung thực hình ảnh vẫn hoàn hảo. + +#### Trường hợp đặc biệt: Cần PDF thường thay vì PDF/A? + +Nếu bạn không quan tâm đến PDF/A, thay `save_as_pdfa` bằng `save_as_pdf`. Phần còn lại của quy trình vẫn giữ nguyên. + +--- + +## Bước 3: Xác Thực PDF Có Thể Tìm Kiếm + +Kiểm tra nhanh giúp bạn tránh các lỗi bí ẩn sau này. Mở tệp đã tạo trong bất kỳ trình xem PDF nào, thử chọn một từ và sử dụng chức năng tìm kiếm. + +```python +# Step 3: The file "invoice_searchable.pdf" now contains selectable text layered over the original invoice image +import subprocess, os + +pdf_path = "YOUR_DIRECTORY/invoice_searchable.pdf" +if os.path.exists(pdf_path): + print(f"✅ PDF created successfully: {pdf_path}") + # Optionally open the file (works on macOS, Windows, Linux with appropriate commands) + subprocess.run(["open", pdf_path] if os.name == "posix" else ["start", pdf_path], shell=True) +else: + print("❌ Something went wrong – PDF not found.") +``` + +### Kết quả mong đợi + +Khi bạn chạy script, console sẽ in: + +``` +✅ PDF created successfully: YOUR_DIRECTORY/invoice_searchable.pdf +``` + +Mở tệp, bạn sẽ thấy hình ảnh hoá đơn gốc với một lớp văn bản mờ, vô hình. Khi bạn tô sáng bất kỳ từ nào, sẽ thấy nó có thể chọn—**đó là văn bản có thể tìm kiếm** mà bạn vừa thêm. + +--- + +## Thêm Văn Bản Có Thể Tìm Kiếm Vào PDF Đã Tồn Tại (Bonus) + +Đôi khi bạn đã có một PDF nhưng cần **thêm văn bản có thể tìm kiếm** vào đó. Cùng engine có thể phủ kết quả OCR lên một PDF hiện có: + +```python +# Bonus: Add searchable text to an existing PDF file +existing_pdf = engine.load_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result = engine.recognize_pdf("YOUR_DIRECTORY/old_scanned.pdf") +ocr_result.apply_to(existing_pdf).save_as_pdfa("YOUR_DIRECTORY/old_scanned_searchable.pdf") +``` + +Ở đây `apply_to` hợp nhất lớp ẩn với các trang gốc, cho phép bạn **tạo PDF có thể tìm kiếm** mà không cần quét lại. + +--- + +## Cạm Bẫy và Mẹo + +| Cạm bẫy | Cách tránh | +|---------|------------| +| **Hình ảnh nguồn độ phân giải thấp** (< 150 dpi) | Tăng độ phân giải hoặc yêu cầu bản quét độ phân giải cao hơn; độ chính xác OCR giảm đáng kể dưới 150 dpi. | +| **Thiếu dữ liệu ngôn ngữ** | Cài đặt các gói ngôn ngữ phù hợp cho engine OCR (`pip install pdfocr[eng,spa]`). | +| **Thư mục đầu ra không thể ghi** | Chạy script với quyền đủ hoặc chọn thư mục khác. | +| **Xác thực PDF/A thất bại** | Đảm bảo bạn không nhúng phông chữ không hỗ trợ hoặc JavaScript; hầu hết SDK sẽ tự động xử lý khi bạn dùng `save_as_pdfa`. | + +--- + +## Script Đầy Đủ – Giải Pháp Một Tệp + +Dưới đây là một script tự chứa, kết nối mọi thứ lại với nhau. Sao chép‑dán, thay đổi các đường dẫn placeholder, và bạn đã sẵn sàng **chuyển đổi hình ảnh sang PDF/A** trong vài giây. + +```python +#!/usr/bin/env python3 +""" +How to OCR PDF – Complete script to create a searchable PDF/A from an image. +Works with any OCR engine exposing `recognize_image` and `save_as_pdfa`. +""" + +import os +import subprocess + +# ---------------------------------------------------------------------- +# CONFIGURATION – change these paths to match your environment +# ---------------------------------------------------------------------- +INPUT_IMAGE = "YOUR_DIRECTORY/invoice.png" +OUTPUT_PDF = "YOUR_DIRECTORY/invoice_searchable.pdf" + +# ---------------------------------------------------------------------- +# INITIALIZE THE OCR ENGINE (replace with your SDK's init call) +# ---------------------------------------------------------------------- +# Example for a fictional `pdfocr` package: +# from pdfocr import Engine +# engine = Engine(api_key="YOUR_API_KEY") +# If you use a different library, adjust the import and init accordingly. +engine = Engine() # placeholder – insert real initialization here + +def main(): + # Step 1 – Recognize the image + print(f"🔎 Recognizing text from {INPUT_IMAGE} …") + result = engine.recognize_image(INPUT_IMAGE) + + # Step 2 – Save as searchable PDF/A + print(f"💾 Saving searchable PDF/A to {OUTPUT_PDF} …") + result.save_as_pdfa(OUTPUT_PDF) + + # Step 3 – Verify the file exists + if os.path.isfile(OUTPUT_PDF): + print("✅ Success! Searchable PDF/A created.") + # Open the file for a quick visual check (optional) + try: + if os.name == "posix": + subprocess.run(["open", OUTPUT_PDF]) + else: + subprocess.run(["start", OUTPUT_PDF], shell=True) + except Exception: + pass + else: + print("❌ Error: PDF not created.") + +if __name__ == "__main__": + main() +``` + +**Script này làm gì:** +1. Tải engine OCR. +2. Đọc hình ảnh đã chọn và trích xuất văn bản. +3. Ghi một **PDF/A có thể tìm kiếm** mà bạn có thể ngay lập tức phân phối hoặc lưu trữ. + +Bạn có thể gói logic `main` vào một hàm xử lý toàn bộ thư mục—chỉ cần lặp qua `os.listdir()` và lặp lại ba bước cho mỗi tệp. + +--- + +## Các Bước Tiếp Theo & Chủ Đề Liên Quan + +Bây giờ bạn đã nắm vững **cách OCR PDF**, hãy xem xét khám phá các ý tưởng sau: + +- **Xử lý hàng loạt:** Sử dụng `concurrent.futures` để OCR hàng chục hoá đơn đồng thời. +- **Chèn metadata:** Thêm ngày tạo hoặc số hoá đơn vào metadata của PDF để dễ lập chỉ mục hơn. +- **PDF hỗn hợp:** Kết hợp văn bản có thể tìm kiếm với hình ảnh gốc được nhúng để tạo “bản sao kỹ thuật số” của tài liệu giấy. +- **Đầu ra thay thế:** Xuất ra **DOCX** hoặc **HTML** nếu hệ thống downstream cần định dạng có thể chỉnh sửa. + +Mỗi mục trên đều dựa trên các khái niệm cốt lõi bạn vừa học—nhận diện, xuất, xác thực. + +--- + +## Wrap‑Up + +Tóm lại, bạn giờ đã biết **cách OCR PDF** bằng cách biến một hình ảnh đơn giản thành **PDF/A có thể tìm kiếm** chỉ với ba dòng Python. Script thực hiện phần công việc nặng, giữ nguyên đồ họa gốc, và cung cấp cho bạn một tài liệu tuân chuẩn mà bạn có thể tìm kiếm, lưu trữ hoặc chia sẻ. + +Hãy thử với hoá đơn, biên lai hoặc hợp đồng đã quét của bạn. Nếu gặp khó khăn, để lại bình luận bên dưới hoặc kiểm tra tài liệu chính thức của SDK—thường chứa nhiều ví dụ bổ sung. Chúc bạn lập trình vui vẻ, và tận hưởng khả năng mới giúp bất kỳ hình ảnh nào ngay lập tức có thể tìm kiếm! + +![Ví dụ cách OCR PDF hiển thị hình ảnh gốc và lớp PDF có thể tìm kiếm](placeholder.png "Ví dụ cách OCR PDF") + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách OCR PDF trong .NET với Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Nhận dạng Văn bản PDF – Các thao tác OCR với Aspose.OCR cho Java](/ocr/english/java/ocr-operations/) +- [Chuyển Đổi Hình Ảnh sang PDF C# – Lưu Kết Quả OCR Đa Trang](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md b/ocr/vietnamese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md new file mode 100644 index 000000000..05c414f26 --- /dev/null +++ b/ocr/vietnamese/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-06-06 +description: Cách OCR PDF bằng Aspose OCR Cloud. Học cách trích xuất văn bản từ PDF, + chuyển đổi trang PDF sang PNG và lưu hình ảnh các trang PDF bằng Python. +draft: false +keywords: +- how to ocr pdf +- extract text from pdf +- convert pdf page png +- extract plain text pdf +- save pdf page images +language: vi +og_description: Cách OCR PDF với Aspose OCR Cloud. Hướng dẫn này cho thấy cách trích + xuất văn bản thuần từ PDF, chuyển đổi trang PDF sang PNG và lưu hình ảnh các trang + PDF. +og_title: Cách OCR PDF với Aspose OCR Cloud – Từng bước +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to OCR PDF using Aspose OCR Cloud. Learn to extract text from PDF, + convert PDF page PNG, and save PDF page images in Python. + headline: How to OCR PDF with Aspose OCR Cloud – Complete Guide + type: TechArticle +tags: +- OCR +- Python +- PDF processing +title: Cách OCR PDF với Aspose OCR Cloud – Hướng Dẫn Toàn Diện +url: /vi/python-java/general/how-to-ocr-pdf-with-aspose-ocr-cloud-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách OCR PDF với Aspose OCR Cloud – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi **cách OCR PDF** mà không phải vật lộn với các công cụ desktop nặng? Bạn không phải là người duy nhất—nhiều nhà phát triển gặp khó khăn khi cần một cách nhanh chóng, lập trình để lấy văn bản từ tài liệu đã quét. Tin tốt là gì? Với Aspose OCR Cloud bạn có thể **trích xuất văn bản từ PDF**, chuyển mỗi trang thành PNG, và thậm chí **lưu hình ảnh trang PDF** để sử dụng sau, tất cả từ một script Python gọn gàng. + +Trong hướng dẫn này, chúng ta sẽ đi qua mọi thứ bạn cần biết: từ cài đặt SDK, cấp phép cho engine, và nhận dạng các PDF đa trang, đến việc trích xuất văn bản thuần, chuyển các trang sang PNG, và lưu các hình ảnh đó trên đĩa. Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng để chèn vào bất kỳ dự án nào cần khả năng **cách OCR PDF**. + +## Những gì bạn cần + +- **Python 3.8+** (mã hoạt động trên 3.10 và các phiên bản mới hơn) +- Một tài khoản Aspose OCR Cloud – bạn sẽ nhận được file giấy phép dùng thử miễn phí (`Aspose.OCR.lic`) +- Gói `asposeocrcloud` (`pip install asposeocrcloud`) +- Một file PDF đã quét, đa trang mà bạn muốn xử lý + +Chỉ vậy thôi. Không cần binary bổ sung, không phụ thuộc gốc, chỉ Python thuần. + +## Cách OCR PDF – Cài đặt và Cấp phép + +Trước khi bạn có thể gọi bất kỳ phương thức OCR nào, bạn phải cho SDK biết bạn là ai. Aspose sử dụng một file giấy phép nhẹ mà bạn đặt ở vị trí mà script của bạn có thể truy cập. + +```python +# Step 1: Import the OCR package and apply your license (optional but recommended) +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply the license – replace the path with your actual .lic file location +License().set_license("Aspose.OCR.lic") +``` + +*Mẹo chuyên nghiệp:* Nếu bạn bỏ qua bước cấp phép, SDK vẫn hoạt động nhưng sẽ chèn một watermark nhỏ vào các hình ảnh đầu ra. Không lý tưởng cho môi trường production. + +## Bước 2: Cài đặt Aspose OCR Cloud Python SDK + +Mở terminal và chạy: + +```bash +pip install asposeocrcloud +``` + +Gói này sẽ tự động tải về tất cả các phụ thuộc cần thiết (requests, pillow, v.v.) nên bạn không cần tìm kiếm gì thêm. + +## Bước 3: Tạo một OCR Engine và Chọn Ngôn ngữ + +Engine là trái tim của quá trình. Bạn có thể chỉ định bất kỳ ngôn ngữ nào được Aspose hỗ trợ; tiếng Anh hoạt động cho hầu hết các trường hợp. + +```python +# Step 3: Create an OCR engine and set the recognition language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) +``` + +Tại sao phải đặt ngôn ngữ? Bởi vì OCR engine sử dụng các từ điển riêng cho từng ngôn ngữ để cải thiện độ chính xác. Nếu bạn đang xử lý các PDF tiếng Pháp, chỉ cần thay `ENGLISH` bằng `FRENCH`. + +## Bước 4: Chỉ định PDF Đa Trang của Bạn + +Đưa engine đường dẫn đầy đủ tới file bạn muốn xử lý. Các đường dẫn tương đối cũng được chấp nhận miễn là chúng giải quyết được từ thư mục làm việc của script. + +```python +# Step 4: Specify the path to the multi‑page PDF you want to process +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" +``` + +Đảm bảo file có thể đọc được; nếu không bạn sẽ gặp lỗi `FileNotFoundError`. + +## Bước 5: Chạy OCR – Bạn Nhận Được Danh Sách Kết Quả + +Gọi `recognize_pdf` trả về một danh sách, trong đó mỗi phần tử tương ứng với một trang của PDF nguồn. + +```python +# Step 5: Run OCR on the PDF – a list of OcrResult objects is returned (one per page) +results = engine.recognize_pdf(pdf_path) +``` + +Mỗi `OcrResult` chứa hai thuộc tính hữu ích: + +* `text` – biểu diễn văn bản thuần của trang (tuyệt vời cho **extract plain text pdf**) +* `image` – một đối tượng Pillow `Image` của trang đã render (hoàn hảo cho **convert pdf page png**) + +## Bước 6: Trích xuất Văn bản từ PDF và Chuyển Trang sang PNG + +Bây giờ chúng ta lặp qua các kết quả, in ra văn bản đã trích xuất và lưu phiên bản PNG của mỗi trang. + +```python +# Step 6: Iterate through each page, output the extracted text and optionally save the page image +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + # Extract plain text for this page + print(res.text) # <-- this is the "extract plain text pdf" part + # Convert the page to PNG and save it + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # <-- this does the "convert pdf page png" +``` + +### Expected Console Output + +``` +--- Page 1 --- +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +--- Page 2 --- +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +``` + +Bạn cũng sẽ thấy các file `page_1.png`, `page_2.png`, … xuất hiện trong `YOUR_DIRECTORY`. Đó là các hình ảnh raster của các trang mà bạn có thể đưa vào các pipeline xử lý ảnh tiếp theo. + +## Bước 7: Lưu Hình ảnh Trang PDF (Xử lý Sau Tùy chọn) + +Nếu bạn chỉ cần hình ảnh mà không cần văn bản, bạn có thể bỏ qua dòng `print(res.text)`. Ngược lại, nếu bạn muốn lưu văn bản vào các file `.txt` riêng, chỉ cần thêm một đoạn ghi nhỏ: + +```python +# Optional: Save each page's text to a .txt file +for i, res in enumerate(results, start=1): + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) +``` + +Thêm nhỏ này cho thấy việc **lưu hình ảnh trang PDF** và đồng thời lưu nội dung đã trích xuất là bao nhiêu dễ dàng. + +## Ví dụ Hoạt Động Đầy Đủ + +Kết hợp mọi thứ lại, đây là script hoàn chỉnh bạn có thể sao chép‑dán vào `ocr_pdf.py`: + +```python +import asposeocrcloud as ocr +from asposeocrcloud import OcrEngine, License + +# Apply your license – optional but removes watermarks +License().set_license("Aspose.OCR.lic") + +# Initialize the OCR engine and set language +engine = OcrEngine() +engine.set_recognition_language(ocr.Language.ENGLISH) + +# Path to the source PDF +pdf_path = "YOUR_DIRECTORY/sample_multi_page.pdf" + +# Run OCR – get a list of results (one per page) +results = engine.recognize_pdf(pdf_path) + +# Process each page +for i, res in enumerate(results, start=1): + print(f"--- Page {i} ---") + print(res.text) # extract plain text PDF + # Save the rendered page as PNG + res.image.save(f"YOUR_DIRECTORY/page_{i}.png") # convert PDF page PNG + # Optional: also save the text to a .txt file + with open(f"YOUR_DIRECTORY/page_{i}.txt", "w", encoding="utf-8") as f: + f.write(res.text) # save PDF page images + text +``` + +Chạy nó với: + +```bash +python ocr_pdf.py +``` + +Bạn sẽ thấy đầu ra console của văn bản mỗi trang và một loạt các file PNG. + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, dựa trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md b/ocr/vietnamese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..30bf31193 --- /dev/null +++ b/ocr/vietnamese/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-06-06 +description: Cách tiền xử lý hình ảnh cho OCR bằng Python. Học cách nhị phân hoá hình + ảnh bằng Otsu, cách chỉnh nghiêng tài liệu đã quét và cải thiện độ chính xác OCR + cho văn bản tiếng Đức. +draft: false +keywords: +- how to preprocess images for OCR +- binarize image using otsu +- how to deskew scanned documents +- how to improve OCR accuracy +- extract text from german image +language: vi +og_description: Cách tiền xử lý hình ảnh cho OCR trong Python. Hướng dẫn này cho thấy + cách nhị phân hoá hình ảnh bằng Otsu, cách chỉnh nghiêng tài liệu đã quét, và cách + cải thiện độ chính xác OCR cho hình ảnh tiếng Đức. +og_title: Cách Tiền Xử Lý Hình Ảnh cho OCR – Hướng Dẫn Python Toàn Diện +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + headline: How to Preprocess Images for OCR – Complete Python Guide + type: TechArticle +- description: How to preprocess images for OCR using Python. Learn to binarize image + using Otsu, how to deskew scanned documents, and improve OCR accuracy for German + text. + name: How to Preprocess Images for OCR – Complete Python Guide + steps: + - name: How to Deskew Scanned Documents + text: The `deskew` call above is the concrete answer to **how to deskew scanned + documents**. Internally it estimates the dominant text line angle via Hough + transform and rotates the image back. If your documents are rotated more than + 5°, bump `max_angle` up, but beware of over‑rotation artifacts. + - name: Binarize Image Using Otsu + text: The `binarize(method="otsu")` line directly answers the query **binarize + image using otsu**. Otsu’s algorithm computes a threshold that minimizes intra‑class + variance, which is perfect for documents with bimodal histograms (dark text + vs. light background). + - name: Expected Output + text: 'Assuming the sample scan contains the sentence “Die schnelle braune Füchsin + springt über den faulen Hund.” you should see something like:' + type: HowTo +tags: +- OCR +- image preprocessing +- Python +- German language +title: Cách Tiền Xử Lý Hình Ảnh cho OCR – Hướng Dẫn Python Toàn Diện +url: /vi/python-java/general/how-to-preprocess-images-for-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Tiền Xử Lý Ảnh Cho OCR – Hướng Dẫn Python Đầy Đủ + +Bạn đã bao giờ tự hỏi **cách tiền xử lý ảnh cho OCR** để văn bản trở nên trong suốt? Bạn không phải là người duy nhất. Các tài liệu được quét—đặc biệt là những trang tiếng Đức nhiễu—có thể là cơn ác mộng đối với bất kỳ công cụ OCR nào. Tin tốt? Một vài bước tiền xử lý thông minh có thể biến một bản quét mờ, bị vệt thành một hình ảnh sạch, có thể đọc được bởi máy. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ thực tế cho thấy **cách tiền xử lý ảnh cho OCR** bằng Python. Bạn sẽ học cách **binarize image using Otsu**, **how to deskew scanned documents**, và tổng thể **how to improve OCR accuracy** khi cần **extract text from German image**. Không có phần thừa, chỉ có một script hoạt động mà bạn có thể sao chép‑dán ngay hôm nay. + +## Những Gì Bạn Cần Chuẩn Bị + +- **Python 3.9+** (bất kỳ phiên bản mới nào cũng được) +- Thư viện OCR cung cấp lớp `OcrEngine` – trong ví dụ chúng ta sẽ giả định một gói `ocr` chung. Cài đặt bằng `pip install ocr-lib`. +- Một bản quét tiếng Đức nhiễu (`noisy_german_scan.tif`) mà bạn muốn thử. +- Kiến thức cơ bản về hàm Python (nếu bạn đã viết một `def` trước đây, bạn đã sẵn sàng). + +> **Mẹo chuyên nghiệp:** Nếu bạn đang dùng một SDK OCR khác (ví dụ, Tesseract qua `pytesseract`), các khái niệm vẫn giữ nguyên—chỉ cần điều chỉnh tên phương thức. + +## Tổng Quan Về Giải Pháp + +1. **Tạo một thể hiện OCR engine.** +2. **Đặt ngôn ngữ nhận dạng thành tiếng Đức.** +3. **Xây dựng một pipeline tiền xử lý tùy chỉnh** bao gồm deskew, denoise, binarization (Otsu) và contrast stretching. +4. **Gắn pipeline vào engine** để mọi ảnh đều tự động đi qua. +5. **Chạy OCR** trên bản quét tiếng Đức nhiễu. +6. **In ra văn bản đã trích xuất** để kiểm chứng kết quả. + +Dưới đây chúng ta sẽ phân tích từng bước, giải thích **tại sao** chúng quan trọng, và hiển thị đoạn code chính xác mà bạn cần. + +![how to preprocess images for OCR example](image.png "how to preprocess images for OCR example") + +## Bước 1: Tạo Một Thể Hiện OCR Engine + +Đầu tiên—không có engine, không có gì xảy ra. Đối tượng `OcrEngine` là điểm vào điều phối tất cả các xử lý sau này. + +```python +# Step 1: Initialize the OCR engine +from ocr import OcrEngine, Language + +ocr_engine = OcrEngine() +``` + +*Lý do quan trọng:* Khởi tạo engine thiết lập các tài nguyên nội bộ (như mô hình ngôn ngữ) và cung cấp cho bạn một nền tảng sạch để gắn pipeline tùy chỉnh sau này. + +## Bước 2: Đặt Ngôn Ngữ Nhận Dạng Thành Tiếng Đức + +Độ chính xác OCR phụ thuộc mạnh vào ngôn ngữ. Khi bạn thông báo cho engine rằng sẽ xử lý tiếng Đức, bạn kích hoạt bộ ký tự và mô hình ngôn ngữ phù hợp. + +```python +# Step 2: Tell the engine we’re working with German text +ocr_engine.set_recognition_language(Language.GERMAN) +``` + +Nếu bỏ qua bước này, engine có thể mặc định tiếng Anh, gây lỗi nhận dạng các ký tự umlaut (ä, ö, ü) và ký tự ß—điểm yếu thường gặp khi làm việc với tài liệu tiếng Đức. + +## Bước 3: Xây Dựng Pipeline Tiền Xử Lý Tùy Chỉnh + +Đây là phần cốt lõi của **cách tiền xử lý ảnh cho OCR**. Chúng ta sẽ nối bốn biến đổi: + +| Transformation | What it does | Why it helps | +|----------------|--------------|--------------| +| **Deskew** | Rotates the image back to horizontal (max 5°) | Scans are rarely perfectly aligned; deskewing removes slant that confuses character segmentation. | +| **Denoise** | Reduces random speckles (strength 0.7) | Noise creates false edges that the OCR engine may interpret as characters. | +| **Binarize (Otsu)** | Converts to black‑and‑white using Otsu’s method | A clean binary image gives the engine a sharp contrast between foreground (text) and background. | +| **Contrast Stretch** | Expands the dynamic range | Improves readability of faint strokes, especially on old documents. | + +```python +# Step 3: Assemble the preprocessing pipeline +preprocessing_pipeline = ( + ocr_engine.preprocessing() + .deskew(max_angle=5) # auto‑deskew up to 5° + .denoise(strength=0.7) # medium denoise + .binarize(method="otsu") # **binarize image using Otsu** + .contrast(stretch=True) # auto contrast stretch +) + +# Explanation: +# - `deskew` corrects rotation; 5° is a safe ceiling for most scans. +# - `denoise` with 0.7 balances smoothing without erasing thin characters. +# - `binarize` with method "otsu" automatically selects the optimal threshold. +# - `contrast` stretch brightens faint ink while keeping dark ink dark. +``` + +### Cách Deskew Các Tài Liệu Được Quét + +Lệnh `deskew` ở trên là câu trả lời cụ thể cho **how to deskew scanned documents**. Nội bộ, nó ước tính góc dòng văn bản chủ đạo bằng biến đổi Hough và xoay ảnh trở lại. Nếu tài liệu của bạn bị quay hơn 5°, tăng `max_angle` lên, nhưng hãy cẩn thận với các hiện tượng artefact do xoay quá mức. + +### Binarize Image Using Otsu + +Dòng `binarize(method="otsu")` trả lời trực tiếp truy vấn **binarize image using otsu**. Thuật toán Otsu tính ngưỡng tối thiểu phương sai trong‑lớp, rất phù hợp cho các tài liệu có biểu đồ histogram nhị phân (văn bản đậm vs. nền sáng). + +## Bước 4: Gắn Pipeline Vào Engine + +Bây giờ chúng ta chỉ định cho OCR engine chạy mọi ảnh đầu vào qua pipeline vừa xây dựng. + +```python +# Step 4: Register the custom pipeline +ocr_engine.set_preprocessing(preprocessing_pipeline) +``` + +*Lý do quan trọng:* Nếu không đăng ký, engine sẽ xử lý bản quét thô, bỏ qua toàn bộ việc làm sạch mà chúng ta đã cấu hình. Bước này đảm bảo **cách cải thiện độ chính xác OCR** bằng cách áp dụng cùng một tiền xử lý một cách nhất quán. + +## Bước 5: Nhận Dạng Văn Bản Từ Bản Quét Tiếng Đức Nhiễu + +Đến lúc lắp ráp mọi thứ. Chúng ta đưa engine một ảnh tiếng Đức nhiễu và để nó thực hiện công việc nặng nhọc. + +```python +# Step 5: Run OCR on the target file +image_path = "YOUR_DIRECTORY/noisy_german_scan.tif" +recognition_result = ocr_engine.recognize_image(image_path) +``` + +Nếu bạn muốn biết thời gian thực hiện, có thể đo thời gian gọi hàm: + +```python +import time +start = time.time() +result = ocr_engine.recognize_image(image_path) +print(f"OCR took {time.time() - start:.2f}s") +``` + +## Bước 6: Xuất Văn Bản Đã Nhận Dạng + +Cuối cùng, chúng ta in ra chuỗi đã trích xuất. Đây là câu trả lời trực tiếp cho **extract text from german image**. + +```python +# Step 6: Display the OCR output +print("=== Recognized German Text ===") +print(recognition_result.text) +``` + +### Kết Quả Dự Kiến + +Giả sử bản quét mẫu chứa câu “Die schnelle braune Füchsin springt über den faulen Hund.” bạn sẽ thấy kết quả tương tự: + +``` +=== Recognized German Text === +Die schnelle braune Füchsin springt über den faulen Hund. +``` + +Nếu đầu ra vẫn còn ký tự lộn xộn, hãy cân nhắc điều chỉnh độ mạnh `denoise` hoặc tăng `max_angle` cho deskew. + +## Những Sai Lầm Thường Gặp & Cách Khắc Phục + +- **Thiếu mô hình ngôn ngữ:** Quên `set_recognition_language(Language.GERMAN)` thường dẫn đến mất các ký tự umlaut. Kiểm tra lại lời gọi này. +- **Denoise quá mức:** Giá trị mạnh hơn 0.9 có thể xóa bỏ các nét mảnh, đặc biệt trong phông chữ cũ. Giữ trong khoảng 0.5‑0.7 cho hầu hết trường hợp. +- **Định dạng tệp không đúng:** Một số engine OCR không hỗ trợ TIFF đa trang. Nếu bạn có tài liệu đa trang, hãy chia thành các tệp một trang trước. +- **Thứ tự pipeline:** Thứ tự được hiển thị (deskew → denoise → binarize → contrast) là có chủ đích. Binarize trước khi denoise có thể “khóa” nhiễu; luôn denoise trước. + +## Mở Rộng Pipeline (Tiếp Theo?) + +Giờ bạn đã có một nền tảng vững chắc, có thể muốn: + +- **Thêm một phép mở hình thái** để làm sạch các đốm nhỏ (`.morph_open(kernel=3)`). +- **Tích hợp mô hình ngôn ngữ** để sửa lỗi sau khi nhận dạng (`ocr_engine.apply_spellcheck()`). +- **Song song hoá xử lý batch** cho tập dữ liệu lớn bằng `concurrent.futures`. + +Tất cả những mở rộng này vẫn giữ nguyên ý tưởng **cách tiền xử lý ảnh cho OCR** trong khi tăng cường **cách cải thiện độ chính xác OCR** hơn nữa. + +## Kết Luận + +Chúng ta vừa hoàn thành **cách tiền xử lý ảnh cho OCR** từ đầu đến cuối: tạo engine, đặt ngôn ngữ tiếng Đức, xây dựng pipeline **binarize image using Otsu**, **how to deskew scanned documents**, và cuối cùng **extract text from german image** với độ tin cậy cao hơn. Thực hiện sáu bước trên, bạn sẽ thấy chất lượng nhận dạng tăng đáng kể—không còn phải sửa tay vô tận. + +Hãy thử script với các bản quét của bạn, điều chỉnh các tham số, và để kết quả tự nói lên câu chuyện. Có câu hỏi về một tweak tiền xử lý cụ thể? Để lại bình luận, chúng tôi sẽ cùng bạn khám phá sâu hơn. + +Chúc lập trình vui vẻ, và chúc OCR của bạn luôn chính xác! + +## Bạn Nên Học Gì Tiếp Theo? + + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm mã mẫu đầy đủ cùng giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Trích xuất văn bản ảnh C# với lựa chọn ngôn ngữ bằng Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Cách Đặt Giá Trị Ngưỡng Trong Nhận Diện Ảnh OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Cách OCR Ảnh – Thực Hiện OCR Trên Ảnh Trong Nhận Diện Ảnh OCR](/ocr/english/net/image-and-drawing-recognition/perform-ocr-on-image/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..2b4fb14ae --- /dev/null +++ b/ocr/vietnamese/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-06 +description: OCR ảnh PNG bằng Python – học cách trích xuất văn bản từ hình ảnh, chạy + ví dụ OCR bằng Python và thậm chí dễ dàng đọc văn bản tiếng Hy Lạp cổ. +draft: false +keywords: +- ocr png image +- extract text from image +- python ocr example +- read ancient greek +- recognize image text +language: vi +og_description: Giải thích OCR ảnh PNG trong Python. Hướng dẫn này chỉ cách trích + xuất văn bản từ hình ảnh, chạy một ví dụ OCR bằng Python và đọc tiếng Hy Lạp cổ + một cách dễ dàng. +og_title: OCR ảnh PNG trong Python – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + headline: OCR PNG Image in Python – Full Step‑by‑Step Guide + type: TechArticle +- description: OCR PNG image with Python – learn how to extract text from image, run + a python OCR example and even read ancient greek text easily. + name: OCR PNG Image in Python – Full Step‑by‑Step Guide + steps: + - name: Prerequisites + text: '| Requirement | Why it matters | |-------------|----------------| | Python + 3.8+ | Modern syntax and type hints | | `pytesseract` package | Thin wrapper + around the Tesseract engine | | Tesseract OCR binaries (≥ 5.0) | The actual + engine that does the heavy lifting | | Greek language data (`grc.trained' + - name: How do I improve accuracy on a noisy PNG? + text: '- Convert the image to grayscale: `img = img.convert(''L'')` - Apply a + binary threshold: `img = img.point(lambda x: 0 if x < 128 else 255, ''1'')` + - Upscale with `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)`' + - name: Can I process a whole folder of PNGs? + text: Absolutely. Wrap the `recognize_image` call in a `for` loop over `Path.glob("*.png")`. + Store each result in a dictionary or write to a CSV for later analysis. + - name: What if I need to extract numbers only? + text: 'Pass a custom **config** string to `image_to_string`:' + - name: Is there a way to get confidence scores? + text: Yes—use `pytesseract.image_to_data` which returns a TSV with confidence + per word. You can filter out low‑confidence tokens before assembling the final + string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR ảnh PNG trong Python – Hướng dẫn chi tiết từng bước +url: /vi/python-java/general/ocr-png-image-in-python-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR PNG Image trong Python – Hướng Dẫn Chi Tiết Từng Bước + +Bạn đã bao giờ tự hỏi làm thế nào để **OCR PNG image** các tệp trực tiếp từ một script Python? Có thể bạn có một thư mục đầy các bản sao quét của các bản thảo cổ và bạn cần **extract text from image** các tệp mà không phải gõ tay mọi thứ. Tin tốt là bạn không cần bằng tiến sĩ về thị giác máy tính—chỉ cần vài dòng code và thư viện phù hợp, và bạn sẽ đọc tiếng Hy Lạp cổ trong vài giây. + +Trong hướng dẫn này, chúng ta sẽ đi qua một **python OCR example** nhận dạng văn bản từ một PNG, đặt ngôn ngữ thành Greek polytonic, và in kết quả. Khi kết thúc, bạn sẽ biết chính xác cách **recognize image text**, xử lý các vấn đề thường gặp, và điều chỉnh script cho các ngôn ngữ hoặc định dạng ảnh khác. + +## Những Điều Bạn Sẽ Học + +- Cài đặt và cấu hình một thư viện OCR cho Python (pytesseract + Tesseract OCR) +- Tạo một thể hiện OCR engine và tải một tệp PNG +- Đặt ngôn ngữ nhận dạng thành Greek polytonic để bạn có thể **read ancient greek** +- Xuất văn bản đã nhận dạng và khắc phục các vấn đề thường gặp +- Mở rộng script để xử lý hàng loạt nhiều PNG hoặc chuyển sang ngôn ngữ khác + +### Yêu Cầu Trước + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.8+ | Cú pháp hiện đại và gợi ý kiểu | +| `pytesseract` package | Lớp bao bọc nhẹ cho engine Tesseract | +| Tesseract OCR binaries (≥ 5.0) | Engine thực tế thực hiện các tác vụ nặng | +| Greek language data (`grc.traineddata`) | Cần thiết để **read ancient greek** chính xác | +| A PNG image you want to analyse (e.g., `ancient_greek.png`) | Đối tượng cho bản demo **ocr png image** | + +Bạn có thể cài đặt phần Python bằng: + +```bash +pip install pytesseract Pillow +``` + +Và trên Ubuntu/macOS bạn sẽ cài đặt engine: + +```bash +# Ubuntu +sudo apt-get install tesseract-ocr libtesseract-dev + +# macOS (Homebrew) +brew install tesseract +``` + +Đừng quên tải dữ liệu đã được đào tạo cho Greek polytonic: + +```bash +wget https://github.com/tesseract-ocr/tessdata/blob/main/greek.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ +``` + +*(Đường dẫn có thể khác; điều chỉnh `TESSDATA_PREFIX` nếu cần.)* + +## OCR PNG Image: Tạo Thể Hiện Engine + +Điều đầu tiên chúng ta cần là một đối tượng giao tiếp với Tesseract. Trong `pytesseract` engine được truy cập thông qua các hàm ở mức module, nhưng để rõ ràng chúng ta sẽ bọc nó trong một lớp nhỏ. Điều này phản ánh khái niệm “engine” mà bạn đã thấy trong đoạn mã gốc. + +```python +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + """ + Simple wrapper around pytesseract to keep the API similar to the original example. + """ + def __init__(self, tess_cmd: str = "tesseract"): + # You can point pytesseract to a custom binary if you installed it somewhere unusual. + pytesseract.pytesseract.tesseract_cmd = tess_cmd + + def set_recognition_language(self, language: str): + """ + Store the language code for later calls. + Example: 'grc' for Greek polytonic. + """ + self.lang = language + + def recognize_image(self, image_path: str): + """ + Open the PNG, run OCR, and return the raw result object. + """ + img = Image.open(image_path) + # pytesseract returns a string; we wrap it for consistency with the original code. + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text=text) + +class OcrResult: + """Container for OCR output – mimics the .text attribute used in the example.""" + def __init__(self, text: str): + self.text = text +``` + +**Tại sao lại bọc nó?** +- Giữ API công cộng giống hệt đoạn mã mẫu, giúp việc di chuyển dễ dàng. +- Cho phép chúng ta thêm logging hoặc xử lý lỗi sau này mà không ảnh hưởng tới luồng chính. +- Thể hiện thực hành OOP tốt—điều mà các nhà phát triển cấp cao đánh giá cao. + +## Extract Text from Image: Đặt Ngôn Ngữ Thành Greek Polytonic + +Bây giờ chúng ta đã có engine, chúng ta cần chỉ định ngôn ngữ mà nó sẽ nhận dạng. Greek polytonic sử dụng dấu phụ mà dữ liệu “greek” tiêu chuẩn không bao gồm, vì vậy chúng ta chỉ định Tesseract tới tệp `grc` đã được đào tạo. + +```python +# Step 2: Set the recognition language to Greek polytonic +engine = OcrEngine() +engine.set_recognition_language("grc") # 'grc' is the ISO‑639‑2 code for ancient Greek +``` + +Nếu bạn muốn **extract text from image** các tệp bằng ngôn ngữ khác, chỉ cần thay `"grc"` bằng `"eng"` cho tiếng Anh, `"fra"` cho tiếng Pháp, v.v. Dòng lệnh này hoạt động cho bất kỳ ngôn ngữ nào bạn đã cài đặt. + +## Recognize Image Text: Chạy OCR trên PNG + +Với ngôn ngữ đã được đặt, chúng ta đưa PNG vào engine. Ví dụ gốc sử dụng đường dẫn cứng; chúng ta sẽ làm cho linh hoạt hơn bằng cách sử dụng các đối tượng `Path`. + +```python +# Step 3: Recognize text from the image file +image_path = Path("YOUR_DIRECTORY/ancient_greek.png") +ocr_result = engine.recognize_image(str(image_path)) +``` + +**Mẹo & Trường Hợp Đặc Biệt** + +- **File not found** – bọc lời gọi trong `try/except FileNotFoundError` để đưa ra thông báo thân thiện. +- **Low‑resolution PNG** – cân nhắc tiền xử lý (ví dụ: thay đổi kích thước, nhị phân hoá) bằng Pillow trước khi OCR. +- **Non‑Greek text** – Tesseract vẫn sẽ cố gắng giải mã, nhưng độ chính xác giảm đáng kể. Luôn luôn khớp ngôn ngữ. + +## Xuất Văn Bản Đã Nhận Dạng + +Cuối cùng, chúng ta in kết quả. Trong một dự án thực tế, bạn có thể ghi vào cơ sở dữ liệu, file CSV, hoặc thậm chí đưa vào quy trình dịch thuật. + +```python +# Step 4: Output the recognized text +print("=== OCR Result ===") +print(ocr_result.text) +``` + +Khi bạn chạy script trên một bản quét rõ ràng của một khắc văn Hy Lạp cổ, bạn sẽ thấy kết quả giống như: + +``` +=== OCR Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος... +``` + +Nếu đầu ra bị rối, hãy kiểm tra lại rằng tệp **greek.traineddata** nằm trong thư mục đúng và PNG không quá nhiễu. + +## Ví Dụ Hoàn Chỉnh (Tất Cả Các Bước Trong Một Script) + +Dưới đây là chương trình hoàn chỉnh, sẵn sàng chạy. Lưu lại với tên `ocr_greek.py` và thực thi `python ocr_greek.py`. + +```python +# ocr_greek.py +from pathlib import Path +from PIL import Image +import pytesseract + +class OcrEngine: + def __init__(self, tess_cmd: str = "tesseract"): + pytesseract.pytesseract.tesseract_cmd = tess_cmd + self.lang = "eng" # default fallback + + def set_recognition_language(self, language: str): + self.lang = language + + def recognize_image(self, image_path: str): + img = Image.open(image_path) + text = pytesseract.image_to_string(img, lang=self.lang) + return OcrResult(text) + +class OcrResult: + def __init__(self, text: str): + self.text = text + +def main(): + # 1️⃣ Create an OCR engine instance + engine = OcrEngine() + + # 2️⃣ Set the language to Greek polytonic (read ancient greek) + engine.set_recognition_language("grc") + + # 3️⃣ Path to the PNG you want to analyse + png_path = Path("YOUR_DIRECTORY/ancient_greek.png") + if not png_path.is_file(): + raise FileNotFoundError(f"Cannot find image at {png_path}") + + # 4️⃣ Recognize and retrieve the text + result = engine.recognize_image(str(png_path)) + + # 5️⃣ Print the extracted text + print("=== OCR PNG Image Result ===") + print(result.text) + +if __name__ == "__main__": + main() +``` + +**Expected output** (rút gọn để ngắn gọn): + +``` +=== OCR PNG Image Result === +Ἀνδρὸς ἐστὶν ὁ ἥλιος· +Καὶ ὁ ἥλιος ἀνατέλλει· +``` + +Nếu bạn thấy các ký tự Hy Lạp đúng, chúc mừng—bạn đã thực hiện thành công một thao tác **ocr png image** trong Python! + +## Câu Hỏi Thường Gặp & Mẹo Chuyên Nghiệp + +### Làm sao để cải thiện độ chính xác trên PNG nhiễu? + +- Chuyển ảnh sang thang xám: `img = img.convert('L')` +- Áp dụng ngưỡng nhị phân: `img = img.point(lambda x: 0 if x < 128 else 255, '1')` +- Mở rộng kích thước với `img = img.resize((img.width*2, img.height*2), Image.LANCZOS)` + +Các bước này thường biến một cơn ác mộng **recognize image text** thành kết quả sạch sẽ. + +### Tôi có thể xử lý toàn bộ thư mục PNG không? + +Chắc chắn. Bọc lời gọi `recognize_image` trong một vòng lặp `for` qua `Path.glob("*.png")`. Lưu mỗi kết quả vào một dictionary hoặc ghi vào CSV để phân tích sau. + +```python +for png in Path("my_folder").glob("*.png"): + res = engine.recognize_image(str(png)) + print(f"{png.name}: {res.text[:50]}...") +``` + +### Nếu tôi chỉ cần trích xuất số? + +Gửi một chuỗi **config** tùy chỉnh tới `image_to_string`: + +```python +digits = pytesseract.image_to_string(img, lang=self.lang, config='outputbase digits') +``` + +Bằng cách đó bạn có thể **extract text from image** các tệp chứa bảng, số sê-ri, hoặc dấu thời gian. + +### Có cách nào để lấy điểm tin cậy không? + +Có—sử dụng `pytesseract.image_to_data` trả về một TSV với độ tin cậy cho mỗi từ. Bạn có thể lọc bỏ các token có độ tin cậy thấp trước khi ghép chuỗi cuối cùng. + +## Mở Rộng Hướng Dẫn + +Bây giờ bạn đã nắm vững các kiến thức cơ bản, hãy xem xét khám phá các chủ đề liên quan sau: + +- **Batch OCR with multiprocessing** – tăng tốc xử lý khối lượng lớn PNG. +- **Hybrid OCR + NLP pipelines** – tự động dịch tiếng Hy Lạp cổ đã trích xuất sang tiếng Anh hiện đại. +- **Alternative engines** – thử `easyocr` hoặc các phương pháp dựa trên `opencv` cho các trường hợp sử dụng cụ thể. +- **Cloud OCR services** – Google Vision, Azure Computer Vision, hoặc AWS Textract cho việc mở rộng không máy chủ. + +Mỗi mục này dựa trên **python ocr example** cốt lõi mà chúng ta vừa đề cập, vì vậy bạn sẽ cảm thấy tự tin khi khám phá sâu hơn. + +## Kết Luận + +Chúng ta đã lấy một đoạn mã đơn giản và biến nó thành một quy trình **ocr png image** mạnh mẽ trong Python. Bằng cách tạo một `OcrEngine`, đặt ngôn ngữ thành Greek polytonic, đưa PNG vào và in kết quả, bạn giờ đã biết cách **extract text from image** các tệp, **recognize image text**, và thậm chí **read ancient greek**. + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ code hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Trích xuất Văn bản từ Hình ảnh bằng Aspose OCR – Hướng Dẫn Từng Bước](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Cách Đặt Giá Trị Ngưỡng trong Nhận Diện Hình ảnh OCR](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Nhận dạng Văn bản ảnh với Aspose OCR cho Nhiều Ngôn ngữ](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md b/ocr/vietnamese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md new file mode 100644 index 000000000..9b265d09b --- /dev/null +++ b/ocr/vietnamese/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-06 +description: Hướng dẫn OCR bằng Python cho thấy cách nhận dạng văn bản trong hình + ảnh, thực hiện OCR độ phân giải cao và trích xuất văn bản tiếng Tây Ban Nha bằng + OCR tăng tốc GPU. +draft: false +keywords: +- python ocr tutorial +- recognize image text +- high resolution ocr +- gpu accelerated ocr +- extract spanish text +language: vi +og_description: Hướng dẫn OCR Python giúp bạn nhận dạng văn bản trong hình ảnh, OCR + độ phân giải cao và trích xuất văn bản tiếng Tây Ban Nha với tốc độ tăng nhờ GPU. +og_title: Hướng dẫn OCR Python – Nhận dạng văn bản tăng tốc bằng GPU +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + headline: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + type: TechArticle +- description: Python OCR tutorial showing how to recognize image text, perform high + resolution OCR and extract Spanish text using GPU accelerated OCR. + name: Python OCR Tutorial – Recognize Image Text with GPU Acceleration + steps: + - name: Prerequisites + text: '- Python 3.9+ (the code works on 3.10 and newer as well). - A CUDA‑compatible + GPU (optional but highly recommended). - Basic familiarity with pip and virtual + environments.' + - name: 6.1 Fallback When No GPU Is Present + text: "```python if not torch.cuda.is_available(): # Re‑initialize the reader + without GPU to avoid hidden errors reader = Reader(lang_list=[\"es\"], gpu=False) + print(\"\U0001F504 Re‑initialized reader for CPU execution.\") ```" + - name: 6.2 Down‑sampling Very Large Images + text: 'If your image is larger than 4000 × 4000 px, you might run out of GPU memory. + Down‑sample proportionally while preserving DPI:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +- GPU +- Spanish +title: Hướng dẫn OCR Python – Nhận dạng văn bản trong hình ảnh với tăng tốc GPU +url: /vi/python-java/general/python-ocr-tutorial-recognize-image-text-with-gpu-accelerati/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hướng Dẫn Python OCR – Nhận Dạng Văn Bản Ảnh Với Tăng Tốc GPU + +Bạn đã bao giờ tự hỏi làm thế nào để **recognize image text** trong một script Python mà không phải tốn hàng giờ điều chỉnh cài đặt? Bạn không phải là người duy nhất. Trong **python ocr tutorial** này, chúng tôi sẽ cho bạn thấy một cách sạch sẽ, end‑to‑end để trích xuất văn bản tiếng Tây Ban Nha từ một bức ảnh độ phân giải cao, và chúng tôi sẽ thêm tăng tốc GPU vào để quá trình chạy cực nhanh. + +Hãy nghĩ đây như một bản demo nhanh trong lúc uống cà phê mà bạn có thể mở rộng thành một pipeline cấp sản xuất sau này. Khi kết thúc hướng dẫn này, bạn sẽ có một chương trình có thể chạy được thực hiện **high resolution OCR**, tận dụng GPU hỗ trợ CUDA, và xuất ra các ký tự tiếng Tây Ban Nha chính xác mà bạn cần. + +## Những Điều Bạn Sẽ Học + +- Cách cài đặt và import một thư viện OCR hiện đại hỗ trợ tăng tốc GPU. +- Cách tạo một thể hiện OCR engine và thiết lập để **recognize image text** bằng tiếng Tây Ban Nha. +- Cách bật **gpu accelerated OCR** để đạt tốc độ tăng vọt trên các tệp độ phân giải cao. +- Cách xử lý các trường hợp đặc biệt như thiếu driver CUDA hoặc chuyển sang CPU. +- Các mẹo để cải thiện độ chính xác khi bạn cần **extract spanish text** từ các bản quét nhiễu. + +### Yêu Cầu Trước + +- Python 3.9+ (mã cũng chạy trên 3.10 và các phiên bản mới hơn). +- GPU tương thích CUDA (tùy chọn nhưng rất được khuyến nghị). +- Kiến thức cơ bản về pip và môi trường ảo. + +Nếu bạn thiếu bất kỳ mục nào, hướng dẫn vẫn hoạt động — chỉ cần bỏ qua bước GPU và thư viện sẽ tự động chuyển sang CPU. + +--- + +## Python OCR Tutorial: Install the Required Packages + +Đầu tiên, chúng ta cần một engine OCR vững chắc. Trong tutorial này, chúng tôi sẽ sử dụng gói mã nguồn mở **`easyocr`**, nó đi kèm hỗ trợ GPU tích hợp khi phát hiện thiết bị tương thích. + +```bash +# Create a fresh virtual environment (optional but tidy) +python -m venv ocr-env +source ocr-env/bin/activate # On Windows use `ocr-env\Scripts\activate` + +# Install EasyOCR and its optional torch dependencies +pip install easyocr[torch] # Installs both CPU and GPU builds of PyTorch +``` + +> **Pro tip:** Nếu bạn đã cài đặt PyTorch, hãy chắc chắn rằng nó phù hợp với phiên bản CUDA của bạn (`pip install torch==2.2.0+cu121 -f https://download.pytorch.org/whl/torch_stable.html`). Các phiên bản không khớp là nguyên nhân phổ biến gây lỗi “GPU not found”. + +--- + +## Bước 1: Tạo Một Thể Hiện OCR Engine + +Bây giờ chúng ta khởi động engine. EasyOCR gọi lớp chính của nó là `Reader`. Constructor nhận một danh sách các mã ngôn ngữ; chúng ta sẽ truyền `"es"` cho tiếng Tây Ban Nha. + +```python +# Step 1: Initialize the OCR reader for Spanish +from easyocr import Reader + +# The `gpu` flag tells EasyOCR to try using CUDA if it’s available. +reader = Reader(lang_list=["es"], gpu=True) +``` + +*Why this matters:* Bằng cách khai báo ngôn ngữ ngay từ đầu, engine chỉ tải các trọng số mạng nơ-ron cần thiết, giúp tiết kiệm bộ nhớ và tăng tốc suy luận — đặc biệt hữu ích khi bạn làm việc với **high resolution OCR** sau này. + +--- + +## Bước 2: Chuẩn Bị Ảnh Độ Phân Giải Cao + +Ảnh độ phân giải cao cung cấp cho mô hình nhiều pixel hơn để làm việc, thường dẫn đến nhận dạng ký tự tốt hơn. Giả sử bạn có một tệp tên `high_res_spanish.png` nằm trong thư mục `samples`. + +```python +import os + +# Construct an absolute path – keeps the script portable +image_path = os.path.join("samples", "high_res_spanish.png") + +# Quick sanity check – raise a clear error if the file is missing +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") +``` + +Nếu bạn chưa có mẫu ảnh độ phân giải cao, có thể tải một ảnh miễn phí từ Unsplash hoặc tạo ảnh tổng hợp bằng Pillow. Điều quan trọng là giữ DPI trên 300 để đạt kết quả tốt nhất. + +--- + +## Bước 3: Bật Tăng Tốc GPU (Tùy Chọn nhưng Được Khuyến Nghị) + +EasyOCR đã cố gắng sử dụng GPU khi bạn đặt `gpu=True`. Tuy nhiên, nên kiểm tra thiết bị thực sự đang được dùng, đặc biệt trên các máy có nhiều GPU. + +```python +import torch + +# Verify CUDA availability – helpful for debugging +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device found – falling back to CPU. Performance will be slower.") +``` + +*Why check this?* Nếu script âm thầm chuyển sang CPU, bạn có thể thắc mắc tại sao một thao tác 5 giây đột nhiên kéo dài 30 giây. Kiểm tra nhỏ này làm cho hành vi trở nên trong suốt và giữ cho pipeline **gpu accelerated OCR** của bạn dự đoán được. + +--- + +## Bước 4: Thực Hiện High‑Resolution OCR và Nhận Dạng Văn Bản Ảnh + +Bây giờ là phần thú vị — thực sự đọc văn bản. Phương thức `readtext` của EasyOCR trả về một danh sách các tuple chứa bounding box, chuỗi đã nhận dạng, và điểm tin cậy. + +```python +# Step 4: Run OCR on the high‑resolution image +results = reader.readtext(image_path, detail=1, paragraph=False) + +# `results` looks like: +# [ +# ([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], 'Texto reconocido', 0.98), +# ... +# ] +``` + +Nếu bạn chỉ cần chuỗi thô mà không có tọa độ, đặt `detail=0`. Đối với hầu hết các trường hợp **recognize image text**, mặc định (`detail=1`) cung cấp đủ ngữ cảnh để xử lý sau. + +--- + +## Bước 5: Trích Xuất Văn Bản Tiếng Tây Ban Nha và Làm Sạch Kết Quả + +Vì chúng ta đã yêu cầu EasyOCR cho tiếng Tây Ban Nha, các chuỗi trả về đã ở ngôn ngữ đó. Tuy nhiên, bạn có thể muốn nối chúng lại, loại bỏ khoảng trắng, hoặc lọc các phát hiện có độ tin cậy thấp. + +```python +# Step 5: Consolidate high‑confidence Spanish strings +extracted_text = [] +for bbox, text, conf in results: + if conf > 0.85: # Drop anything below 85 % confidence + extracted_text.append(text) + +# Join everything into a single block – perfect for further NLP tasks +final_text = "\n".join(extracted_text) + +print("📝 Extracted Spanish text:") +print(final_text) +``` + +**What if the confidence is low?** Bạn có thể hạ ngưỡng (đối mặt với nhiễu) hoặc tiền xử lý ảnh (tăng độ tương phản, nhị phân hoá, hoặc chỉnh nghiêng). Những thủ thuật này thường được dùng khi làm **high resolution OCR** trên tài liệu quét. + +--- + +## Bước 6: Xử Lý Các Trường Hợp Đặc Biệt và Tinh Chỉnh Hiệu Suất + +Ngay cả các mô hình được huấn luyện tốt nhất cũng gặp khó khăn trong một vài kịch bản. Dưới đây là một vài giải pháp nhanh bạn có thể dán vào script. + +### 6.1 Fallback Khi Không Có GPU + +```python +if not torch.cuda.is_available(): + # Re‑initialize the reader without GPU to avoid hidden errors + reader = Reader(lang_list=["es"], gpu=False) + print("🔄 Re‑initialized reader for CPU execution.") +``` + +### 6.2 Giảm Kích Thước Ảnh Rất Lớn + +Nếu ảnh của bạn lớn hơn 4000 × 4000 px, bạn có thể hết bộ nhớ GPU. Hạ độ phân giải tỷ lệ trong khi giữ DPI: + +```python +from PIL import Image + +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path + +image_path = resize_if_needed(image_path) +``` + +Các đoạn mã này giúp script ổn định, dù bạn chạy trên workstation mạnh mẽ hay laptop khiêm tốn. + +--- + +## Ví Dụ Hoàn Chỉnh + +Kết hợp tất cả lại, đây là script đầy đủ bạn có thể sao chép‑dán và chạy ngay: + +```python +# python_ocr_tutorial.py +import os +import torch +from PIL import Image +from easyocr import Reader + +# ---------------------------------------------------------------------- +# Helper: Resize very large images to avoid GPU OOM errors +def resize_if_needed(path, max_dim=3000): + img = Image.open(path) + if max(img.size) > max_dim: + scale = max_dim / max(img.size) + new_size = (int(img.width * scale), int(img.height * scale)) + img = img.resize(new_size, Image.LANCZOS) + resized_path = path.replace(".png", "_resized.png") + img.save(resized_path) + return resized_path + return path +# ---------------------------------------------------------------------- + +# 1️⃣ Verify CUDA availability (optional) +if torch.cuda.is_available(): + print(f"✅ CUDA device detected: {torch.cuda.get_device_name(0)}") +else: + print("⚠️ No CUDA device – using CPU (expect slower performance).") + +# 2️⃣ Initialize the OCR engine for Spanish (GPU if possible) +reader = Reader(lang_list=["es"], gpu=torch.cuda.is_available()) + +# 3️⃣ Path to the high‑resolution image +image_path = os.path.join("samples", "high_res_spanish.png") +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + +# 4️⃣ Resize if the image is gigantic +image_path = resize_if_needed(image_path) + +# 5️⃣ Run OCR – this is the core **recognize image text** step +results = reader.readtext(image_path, detail=1, paragraph=False) + +# 6️⃣ Filter and concatenate high‑confidence Spanish strings +extracted = [] +for bbox, txt, conf in results: + if conf > 0.85: + extracted.append(txt) + +final_text = "\n".join(extracted) + +# 7️⃣ Output the result – **extract spanish text** ready for downstream processing +print("\n📝 Extracted Spanish text:") +print(final_text) +``` + +**Expected output (example):** + + + +## Bạn Nên Học Gì Tiếp Theo? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Trích Xuất Văn Bản Từ Ảnh Với Aspose OCR – Hướng Dẫn Từng Bước](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Cách OCR Văn Bản Ảnh Với Ngôn Ngữ Sử Dụng Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Cách Nhận Dạng Các Hình Chữ Nhật Trang Để Nhận Diện Văn Bản OCR Trong Aspose.OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md b/ocr/vietnamese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md new file mode 100644 index 000000000..5fecde6b9 --- /dev/null +++ b/ocr/vietnamese/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-06-06 +description: Nhận dạng văn bản từ hình ảnh bằng công cụ OCR Python. Tìm hiểu cách + cấu hình công cụ OCR Python và trích xuất văn bản từ hình ảnh với xử lý đám mây + trong vài phút. +draft: false +keywords: +- recognize text from image +- extract text from image +- configure OCR engine python +language: vi +og_description: Nhận dạng văn bản từ hình ảnh bằng công cụ OCR Python. Hướng dẫn này + cho thấy cách cấu hình công cụ OCR Python và trích xuất văn bản từ hình ảnh một + cách hiệu quả. +og_title: Nhận dạng văn bản từ hình ảnh trong Python – Hướng dẫn cài đặt đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + headline: recognize text from image in Python – Full OCR Engine Setup Guide + type: TechArticle +- description: recognize text from image using Python OCR engine. Learn how to configure + OCR engine python and extract text from image with cloud processing in minutes. + name: recognize text from image in Python – Full OCR Engine Setup Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed on your machine. - An internet connection (the + example uses a cloud‑based OCR service). - A valid API key from the OCR provider + (you’ll see where to plug it in).' + - name: 1. Missing or Invalid API Key + text: 'If you see an authentication error, make sure: - The key is active and + not expired. - It’s being read from the environment correctly. - Your network + allows outbound HTTPS traffic.' + - name: 2. Unsupported Image Formats + text: 'Most OCR APIs accept JPEG, PNG, and PDF. Trying a BMP or TIFF may trigger + a “format not supported” response. Convert with Pillow if needed:' + - name: 3. Rate Limits + text: 'Cloud services often cap requests per minute. If you hit a limit, implement + exponential back‑off:' + - name: 4. Fallback to Local OCR + text: 'If the cloud is down, you can switch back:' + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: recognize text from image in Python – Full OCR Engine Setup Guide +url: /vi/python-java/general/recognize-text-from-image-in-python-full-ocr-engine-setup-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Nhận dạng văn bản từ hình ảnh trong Python – Hướng dẫn thiết lập đầy đủ + +Bạn đã bao giờ tự hỏi làm thế nào để **recognize text from image** chỉ với vài dòng Python? Bạn không phải là người duy nhất. Dù bạn đang xây dựng một công cụ quét biên lai, một phần mềm số hoá tài liệu, hay một dự án sở thích đơn giản, khả năng trích xuất văn bản từ hình ảnh là một kỹ năng mang lại lợi ích nhanh chóng. + +Trong hướng dẫn này, chúng ta sẽ đi qua toàn bộ quy trình—bắt đầu từ việc thiết lập kiểu **configure OCR engine python**, tiến tới xác thực đám mây, và cuối cùng cho bạn thấy cách **extract text from image** với kết quả đáng tin cậy. Không có phép thuật, chỉ là các bước rõ ràng mà bạn có thể sao chép‑dán và chạy ngay hôm nay. + +## Những gì bạn sẽ học + +- Cách cài đặt và import thư viện OCR cần thiết. +- Các lệnh chính xác để **configure OCR engine python** cho xử lý đám mây. +- Một script hoàn chỉnh, có thể chạy được mà **recognize text from image** và in ra kết quả. +- Mẹo xử lý các vấn đề thường gặp như thiếu khóa API hoặc định dạng hình ảnh không được hỗ trợ. +- Các ý tưởng nâng cao như xử lý hàng loạt và dự phòng cục bộ. + +### Yêu cầu trước + +- Python 3.8+ đã được cài đặt trên máy của bạn. +- Kết nối internet (ví dụ sử dụng dịch vụ OCR dựa trên đám mây). +- Một khóa API hợp lệ từ nhà cung cấp OCR (bạn sẽ thấy nơi chèn nó). + +Nếu bạn đã có những thứ này, hãy bắt đầu—không có phần thừa, chỉ có hướng dẫn thực tế hoạt động. + +--- + +## Bước 1: Cài đặt Thư viện OCR và Import Nó + +Trước khi bạn có thể **configure OCR engine python**, bạn cần thư viện giao tiếp với dịch vụ đám mây. Trong ví dụ của chúng tôi, chúng tôi sẽ sử dụng một gói giả tưởng nhưng đại diện có tên `ocrcloud`. Thay thế nó bằng gói thực tế bạn đang dùng (ví dụ: `easyocr`, `google-cloud-vision`, v.v.). + +```bash +pip install ocrcloud +``` + +```python +# Step 1: Import the OCR client +from ocrcloud import OcrEngine +``` + +**Tại sao điều này quan trọng:** Việc import lớp cho phép bạn truy cập các phương thức như `use_cloud()` và `set_api_key()`. Nếu không import, phần còn lại của script sẽ gây ra lỗi `NameError`. + +*Mẹo chuyên nghiệp:* Ghi cố định phiên bản trong `requirements.txt` của bạn (`ocrcloud==2.1.0`) để tránh các thay đổi gây lỗi không mong muốn sau này. + +## Bước 2: Tạo và **configure OCR engine python** cho Chế độ Đám mây + +Bây giờ chúng ta thực sự **configure OCR engine python**. Engine mặc định khởi động ở chế độ cục bộ; chuyển sang chế độ đám mây cho phép bạn chuyển tải phân tích hình ảnh nặng sang các máy chủ mạnh. + +```python +# Step 2: Instantiate the engine +engine = OcrEngine() + +# Activate cloud processing +engine.use_cloud(True) +``` + +**Giải thích:** +- `OcrEngine()` tạo một đối tượng engine mới—hãy nghĩ nó như một canvas trống. +- `use_cloud(True)` bật công tắc, báo cho engine gửi hình ảnh qua HTTPS thay vì xử lý cục bộ. Điều này rất quan trọng để đạt kết quả độ chính xác cao trên các phông chữ phức tạp hoặc ảnh độ phân giải thấp. + +## Bước 3: Xác thực với Khóa API Đám mây của Bạn + +Hầu hết các dịch vụ OCR đám mây yêu cầu một khóa API. Bước này cho thấy cách chèn an toàn thông tin xác thực. + +```python +# Step 3: Provide your cloud API key +engine.set_api_key("YOUR_CLOUD_API_KEY") +``` + +**Lưu ý bảo mật:** Không bao giờ hard‑code khóa trong một repo công khai. Trong môi trường production, bạn sẽ lấy nó từ biến môi trường: + +```python +import os +engine.set_api_key(os.getenv("OCR_API_KEY")) +``` + +## Bước 4: **recognize text from image** – Gửi Ảnh Từ Xa để Xử lý + +Với engine đã được cấu hình, cuối cùng chúng ta có thể **recognize text from image**. Phương thức `recognize_image()` nhận một đường dẫn hoặc URL và trả về một đối tượng chứa văn bản đã trích xuất. + +```python +# Step 4: Recognize text from the remote image +result = engine.recognize_image("YOUR_DIRECTORY/remote_image.jpg") +``` + +**Điều gì xảy ra bên trong?** +Các byte của ảnh được tải lên endpoint của nhà cung cấp, được mô hình deep‑learning xử lý, và kết quả dạng văn bản thuần được truyền lại. Nếu ảnh lớn, dịch vụ có thể tự động giảm kích thước để tăng tốc quá trình. + +## Bước 5: Xuất Kết quả **extract text from image** + +Bây giờ OCR service đã hoàn thành công việc, chúng ta chỉ cần in ra văn bản. Trong các ứng dụng thực tế, bạn có thể lưu nó vào cơ sở dữ liệu hoặc truyền cho một hàm khác. + +```python +# Step 5: Print the recognized text +print(result.text) +``` + +**Kết quả mong đợi:** (ví dụ) + +``` +Invoice #12345 +Date: 2024-11-02 +Total: $1,250.00 +Thank you for your business! +``` + +Nếu kết quả hiển thị rối, hãy kiểm tra lại ảnh có rõ ràng và bạn đã chọn mô hình ngôn ngữ đúng (nhiều dịch vụ cho phép bạn chỉ định `engine.set_language("en")`). + +## Xử lý Các Trường hợp Cạnh và Những Cạm Bẫy Thông thường + +### 1. Thiếu hoặc Khóa API Không hợp lệ +Nếu bạn gặp lỗi xác thực, hãy chắc chắn: +- Khóa đang hoạt động và chưa hết hạn. +- Nó được đọc đúng từ biến môi trường. +- Mạng của bạn cho phép lưu lượng HTTPS ra ngoài. + +### 2. Định dạng Hình ảnh Không được Hỗ trợ +Hầu hết các API OCR chấp nhận JPEG, PNG và PDF. Thử BMP hoặc TIFF có thể gây phản hồi “định dạng không được hỗ trợ”. Chuyển đổi bằng Pillow nếu cần: + +```python +from PIL import Image +Image.open("source.tif").convert("RGB").save("converted.jpg", "JPEG") +``` + +### 3. Giới hạn Tốc độ +Các dịch vụ đám mây thường giới hạn số yêu cầu mỗi phút. Nếu bạn vượt giới hạn, hãy triển khai exponential back‑off: + +```python +import time +retry = 0 +while retry < 5: + try: + result = engine.recognize_image(path) + break + except TooManyRequestsError: + time.sleep(2 ** retry) + retry += 1 +``` + +### 4. Dự phòng sang OCR Cục bộ +Nếu dịch vụ đám mây ngừng hoạt động, bạn có thể chuyển lại: + +```python +engine.use_cloud(False) # revert to local mode +``` + +Có dự phòng giúp ứng dụng của bạn luôn ổn định. + +## Ví dụ Hoạt động Đầy đủ + +Kết hợp tất cả lại, đây là script bạn có thể chạy ngay bây giờ (chỉ cần thay các giá trị placeholder). + +```python +# ocr_demo.py +import os +from ocrcloud import OcrEngine + +def main(): + # 1️⃣ Create and configure the OCR engine + engine = OcrEngine() + engine.use_cloud(True) # use cloud processing + engine.set_api_key(os.getenv("OCR_API_KEY")) # secure key handling + + # 2️⃣ Path to the image you want to process + image_path = "samples/remote_image.jpg" + + # 3️⃣ Perform OCR + try: + result = engine.recognize_image(image_path) + print("\n--- Recognized Text ---") + print(result.text) + except Exception as e: + print(f"❌ OCR failed: {e}") + +if __name__ == "__main__": + main() +``` + +**Chạy nó:** + +```bash +export OCR_API_KEY="your‑actual‑key-here" +python ocr_demo.py +``` + +Bạn sẽ thấy văn bản đã trích xuất được in ra console, xác nhận rằng bạn đã thành công **recognize text from image** và **extract text from image** bằng quy trình **configure OCR engine python** đúng cách. + +## Kết luận + +Chúng tôi vừa đi qua một quy trình hoàn chỉnh, đầu‑tới‑đầu cho phép bạn **recognize text from image** trong Python, từ việc cài đặt thư viện, xác thực dịch vụ đám mây cho đến cuối cùng **extract text from image** bằng một lời gọi hàm duy nhất. Bằng cách **configure OCR engine python** đúng cách, bạn có được cả tính linh hoạt (đám mây vs. cục bộ) và độ tin cậy (xử lý lỗi hợp lý). + +Tiếp theo gì? Hãy thử xử lý hàng loạt một thư mục biên lai, thêm phát hiện ngôn ngữ, hoặc thử nghiệm với PDF làm đầu vào. Không gì là không thể khi bạn đã nắm vững các kiến thức cơ bản. + +Chúc lập trình vui vẻ, và đừng ngại đặt câu hỏi trong phần bình luận—không gì sánh bằng việc học cùng nhau! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng dựa trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Trích xuất Văn bản từ Hình ảnh với Aspose OCR – Hướng dẫn Từng bước](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Trích xuất Văn bản từ Hình ảnh – Nhận dạng Dòng với Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) +- [Cách Trích xuất Văn bản từ Hình ảnh bằng cách Chuẩn bị Các Hình chữ nhật trong OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..634ca46a1 --- /dev/null +++ b/ocr/vietnamese/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,338 @@ +--- +category: general +date: 2026-06-06 +description: Chạy OCR trên hình ảnh bằng Python và xem các điểm tin cậy. Tìm hiểu + cách lọc các từ có độ tin cậy thấp, đặt ngưỡng và xử lý các trường hợp đặc biệt. +draft: false +keywords: +- run OCR on image +- Python OCR tutorial +- OCR confidence threshold +- low‑confidence word detection +- image text extraction +language: vi +og_description: Chạy OCR trên hình ảnh bằng Python, kiểm tra mức độ tin cậy và lọc + các từ có độ tin cậy thấp. Hướng dẫn này sẽ dẫn bạn qua một ví dụ hoàn chỉnh, có + thể chạy được. +og_title: Chạy OCR trên hình ảnh bằng Python – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-06' + description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + headline: Run OCR on Image with Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Run OCR on image using Python and see confidence scores. Learn how + to filter low‑confidence words, set thresholds, and handle edge cases. + name: Run OCR on Image with Python – Complete Step‑by‑Step Guide + steps: + - name: Install and Import the OCR Engine + text: First, make sure the OCR library is available. **EasyOCR** works out‑of‑the‑box + for many languages and gives you a confidence score per word. + - name: Run OCR on the Image + text: Now we actually **run OCR on image**. The `recognize_image` method from + the original example is replaced with EasyOCR’s `readtext` call, which returns + a list of `(bbox, text, confidence)` tuples. + - name: Summarize Overall Confidence + text: 'Unlike the earlier snippet that printed a single `confidence` attribute, + EasyOCR gives a confidence per word. To get an overall sense, we’ll average + them:' + - name: List Low‑Confidence Words + text: Now comes the part that directly answers the “list words whose confidence + is below the desired threshold” requirement. We’ll set a **OCR confidence threshold** + of 0.80 (80 %) by default, but you can adjust it. + - name: Edge Cases & Variations + text: 1. **Batch Processing** – If you need to **run OCR on image** files in bulk, + wrap the above logic in a loop that iterates over a directory. 2. **Multiple + Languages** – Pass a list like `['en', 'fr']` to `easyocr.Reader` and the engine + will detect both. 3. **Alternative Engines** – Want to try **pyte + type: HowTo +- questions: + - answer: Not directly. Convert each PDF page to an image first (e.g., with `pdf2image`) + and then feed the PNG/JPEG into the script. + question: Does this work with PDFs? + - answer: 'Try image preprocessing: increase contrast, remove background noise, + or rotate the image to a horizontal baseline. EasyOCR also accepts a `contrast_ths` + parameter you can tweak.' + question: My confidence numbers are all low—what can I do? + - answer: Absolutely. After the low‑confidence loop, write `ocr_results` to a `csv.DictWriter` + where each row contains `text`, `confidence`, and bounding‑box coordinates. + question: Can I export the results to CSV? + - answer: 'EasyOCR automatically uses CUDA if a compatible GPU and PyTorch are installed. + Verify with `torch.cuda.is_available()` before running the script. --- ## Conclusion + We’ve just **run OCR on image** using Python, inspected the overall confidence, + and isolated any low‑confidence words that need a {{< /b' + question: Is there a GPU‑accelerated version? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +title: Chạy OCR trên hình ảnh bằng Python – Hướng dẫn chi tiết từng bước +url: /vi/python-java/general/run-ocr-on-image-with-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chạy OCR trên Hình ảnh bằng Python – Hướng dẫn chi tiết từng bước + +Bạn đã bao giờ cần **run OCR on image** nhưng không chắc làm sao để lấy văn bản đáng tin cậy từ chúng? Bạn không đơn độc—nhiều nhà phát triển gặp cùng một vấn đề khi các từ được trích xuất trông không ổn và điểm confidence là một bí ẩn. + +Trong hướng dẫn này, chúng ta sẽ đi thẳng vào một giải pháp hoạt động: bạn sẽ thấy cách **run OCR on image**, đọc confidence tổng thể, và lấy ra các từ có confidence thấp có thể cần xem xét thủ công. Khi kết thúc, bạn sẽ có một script có thể tái sử dụng, hiểu vì sao mỗi dòng quan trọng, và biết cách điều chỉnh ngưỡng confidence cho dự án của mình. + +## Những gì hướng dẫn này bao gồm + +Chúng ta sẽ đi qua toàn bộ quy trình—từ tải hình ảnh đến in ra báo cáo gọn gàng về các từ có confidence dưới mức 80 % confidence mark. Along the way we’ll discuss: + +* Chọn một engine OCR vững chắc (chúng tôi sẽ sử dụng **EasyOCR**, một thư viện OCR Python phổ biến) +* Giải thích thuộc tính `confidence` mà mọi kết quả OCR trả về +* Lọc các từ bằng ngưỡng **OCR confidence threshold** tùy chỉnh +* Mở rộng script cho xử lý hàng loạt hoặc các engine thay thế như **pytesseract** + +Không cần kinh nghiệm OCR trước, chỉ cần quen thuộc cơ bản với Python và môi trường làm việc (khuyến nghị Python 3.9+). + +Sẵn sàng biến các ảnh chụp mờ thành văn bản sạch, có thể tìm kiếm? Hãy bắt đầu. + +--- + +## ## Cách chạy OCR trên hình ảnh bằng Python + +Phần cốt lõi của hướng dẫn là đoạn mã ba bước phản ánh code bạn đã thấy. Dưới đây chúng tôi sẽ phân tích từng dòng, giải thích lý do, và cung cấp một script đầy đủ, sẵn sàng sao chép. + +### Bước 1: Cài đặt và nhập Engine OCR + +Đầu tiên, đảm bảo thư viện OCR đã sẵn sàng. **EasyOCR** hoạt động ngay lập tức cho nhiều ngôn ngữ và cung cấp điểm confidence cho mỗi từ. + +```bash +pip install easyocr +``` + +```python +import easyocr # The engine that will run OCR on image files +import os +``` + +*Why EasyOCR?* It bundles a deep‑learning model that’s been trained on diverse datasets, so you typically get higher confidence values than the older Tesseract engine, especially on mixed‑quality images. + +> **Pro tip:** If you’re on a constrained environment (e.g., a tiny Docker container), `pytesseract` might be lighter, but you’ll lose some of the modern accuracy EasyOCR provides. + +### Bước 2: Chạy OCR trên hình ảnh + +Bây giờ chúng ta thực sự **run OCR on image**. Phương thức `recognize_image` từ ví dụ gốc được thay thế bằng lời gọi `readtext` của EasyOCR, trả về một danh sách các tuple `(bbox, text, confidence)`. + +```python +# Initialize the OCR reader for English (you can add more languages as needed) +reader = easyocr.Reader(['en']) + +# Path to the image you want to process +image_path = os.path.join("YOUR_DIRECTORY", "mixed_quality.png") + +# Perform OCR – this is the step where we run OCR on image +ocr_results = reader.readtext(image_path, detail=1, paragraph=False) +``` + +Mỗi mục trong `ocr_results` trông như sau: + +```python +[ + ((x1, y1, x2, y2, x3, y3, x4, y4), "Detected text", 0.92), + ... +] +``` + +Phần tử thứ ba (`0.92` trong ví dụ) là điểm confidence, giá trị từ 0 đến 1. + +### Bước 3: Tổng hợp Confidence Tổng thể + +Khác với đoạn mã trước đây chỉ in một thuộc tính `confidence` duy nhất, EasyOCR cung cấp confidence cho mỗi từ. Để có cái nhìn tổng thể, chúng ta sẽ tính trung bình chúng: + +```python +# Extract just the confidence numbers +confidences = [item[2] for item in ocr_results] + +# Compute the mean confidence (overall confidence) +overall_confidence = sum(confidences) / len(confidences) if confidences else 0 + +print(f"Overall confidence: {overall_confidence:.2%}") +``` + +*Why average?* It gives you a quick health check—if the overall confidence is below, say, 70 %, you probably need to improve the image (better lighting, preprocessing, etc.). + +### Bước 4: Liệt kê các từ có Confidence thấp + +Bây giờ là phần trả lời trực tiếp yêu cầu “liệt kê các từ có confidence dưới ngưỡng mong muốn”. Chúng ta sẽ đặt **OCR confidence threshold** mặc định là 0.80 (80 %), nhưng bạn có thể điều chỉnh. + +```python +# Define the confidence threshold – tweak as needed +THRESHOLD = 0.80 + +print("\nLow‑confidence words:") +low_confidence_found = False +for bbox, text, conf in ocr_results: + if conf < THRESHOLD: + low_confidence_found = True + print(f" • '{text}' ({conf:.2%})") +if not low_confidence_found: + print(" All words meet the confidence threshold.") +``` + +Vòng lặp in ra mỗi từ không đạt ngưỡng, kèm theo confidence dưới dạng phần trăm. Đây là tương đương chính xác với vòng lặp gốc `for recognized_word in recognition_result.words`, nhưng bây giờ hoạt động với định dạng đầu ra của EasyOCR. + +--- + +## ## Hiểu về Điểm Confidence trong OCR + +Confidence không phải là một con số ma thuật; nó là ước lượng của mô hình về mức độ chắc chắn đối với một bản sao cụ thể. Dưới đây là một vài điểm cần lưu ý: + +| Tình huống | Confidence điển hình | Cần làm gì | +|-----------|-------------------|------------| +| Quét rõ, độ phân giải cao | 0.95 – 1.00 | Không cần công việc bổ sung | +| Mờ nhẹ hoặc ánh sáng không đồng đều | 0.80 – 0.94 | Xem xét tiền xử lý nhẹ (tăng độ tương phản) | +| Nhiễu mạnh, văn bản bị quay | < 0.70 | Áp dụng tiền xử lý hình ảnh (điều chỉnh góc, giảm nhiễu) hoặc chuyển sang engine OCR khác | + +> **Cảnh báo:** Một số ngôn ngữ (ví dụ, chữ viết tay cursive) tự nhiên cho điểm thấp hơn. Điều chỉnh ngưỡng cho phù hợp. + +### Các trường hợp đặc biệt & Biến thể + +1. **Xử lý hàng loạt** – Nếu bạn cần **run OCR on image** nhiều tệp, hãy bọc logic trên trong một vòng lặp duyệt qua thư mục. +2. **Nhiều ngôn ngữ** – Truyền một danh sách như `['en', 'fr']` vào `easyocr.Reader` và engine sẽ phát hiện cả hai. +3. **Engine thay thế** – Muốn thử **pytesseract**? Thay thế khối reader bằng: + + ```python + import pytesseract + from PIL import Image + + img = Image.open(image_path) + raw_text = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) + # raw_text['text'] contains the full string, + # raw_text['conf'] holds per‑character confidence. + ``` + + Bạn sẽ cần tổng hợp confidence từng ký tự thành giá trị confidence cho mỗi từ—một chút công việc nhưng có thể thực hiện. + +4. **Mẹo tiền xử lý** – Áp dụng các bộ lọc OpenCV (`cv2.threshold`, `cv2.GaussianBlur`) có thể tăng confidence cho các bản quét nhiễu. + +--- + +## ## Script đầy đủ, sẵn sàng chạy + +Dưới đây là file Python hoàn chỉnh bạn có thể đưa vào dự án. Lưu dưới tên `ocr_report.py` và chạy `python ocr_report.py`. Đảm bảo đường dẫn hình ảnh trỏ tới một tệp thực tế. + +```python +#!/usr/bin/env python3 +""" +run_ocr_on_image.py + +A self‑contained script that: + 1. Runs OCR on an image using EasyOCR. + 2. Prints the overall confidence. + 3. Lists any words whose confidence falls below a configurable threshold. + +Author: Your Name +Date: 2026‑06‑06 +""" + +import os +import easyocr + +# --------------------------- Configuration --------------------------- # +IMAGE_DIR = "YOUR_DIRECTORY" # <-- Change to your folder +IMAGE_NAME = "mixed_quality.png" # <-- Change to your file name +THRESHOLD = 0.80 # Confidence threshold (0‑1) + +# --------------------------- Helper Functions ----------------------- # +def load_image_path(): + """Construct the absolute path to the target image.""" + return os.path.join(IMAGE_DIR, IMAGE_NAME) + +def run_ocr(image_path): + """Run OCR on the image and return detailed results.""" + reader = easyocr.Reader(['en']) + return reader.readtext(image_path, detail=1, paragraph=False) + +def compute_overall_confidence(results): + """Return the mean confidence across all detected words.""" + if not results: + return 0.0 + confidences = [item[2] for item in results] + return sum(confidences) / len(confidences) + +def report_low_confidence_words(results, threshold): + """Print words whose confidence is below the given threshold.""" + low_conf = [(text, conf) for _, text, conf in results if conf < threshold] + if not low_conf: + print("All words meet the confidence threshold.") + else: + for text, conf in low_conf: + print(f"Low‑confidence word: '{text}' ({conf:.2%})") + +# --------------------------- Main Execution ------------------------ # +def main(): + image_path = load_image_path() + if not os.path.isfile(image_path): + print(f"❌ Image not found: {image_path}") + return + + # Step 1: Run OCR on image + ocr_results = run_ocr(image_path) + + # Step 2: Show overall confidence + overall = compute_overall_confidence(ocr_results) + print(f"Overall confidence: {overall:.2%}") + + # Step 3: List low‑confidence words + print("\n--- Low‑confidence words (threshold: {0:.0%}) ---".format(THRESHOLD)) + report_low_confidence_words(ocr_results, THRESHOLD) + +if __name__ == "__main__": + main() +``` + +**Kết quả mong đợi** (các số của bạn có thể khác): + +``` +Overall confidence: 78.45% + +--- Low‑confidence words (threshold: 80%) --- +Low‑confidence word: 'recgnition' (62.13%) +Low‑confidence word: 'imgae' (57.90%) +``` + +Nếu mọi từ đều vượt qua ngưỡng 80 % bạn sẽ thấy thông báo thân thiện “All words meet the confidence threshold.” thay vì. + +--- + +## ## Câu hỏi thường gặp (FAQ) + +**Q: Điều này có hoạt động với PDF không?** +A: Không trực tiếp. Chuyển mỗi trang PDF thành hình ảnh trước (ví dụ, bằng `pdf2image`) rồi đưa PNG/JPEG vào script. + +**Q: Các số confidence của tôi đều thấp—tôi có thể làm gì?** +A: Thử tiền xử lý hình ảnh: tăng độ tương phản, loại bỏ nhiễu nền, hoặc xoay ảnh thành chiều ngang. EasyOCR cũng chấp nhận tham số `contrast_ths` mà bạn có thể điều chỉnh. + +**Q: Tôi có thể xuất kết quả ra CSV không?** +A: Chắc chắn. Sau vòng lặp low‑confidence, ghi `ocr_results` vào một `csv.DictWriter` trong đó mỗi hàng chứa `text`, `confidence`, và tọa độ bounding‑box. + +**Q: Có phiên bản tăng tốc bằng GPU không?** +A: EasyOCR tự động sử dụng CUDA nếu có GPU tương thích và PyTorch được cài đặt. Kiểm tra bằng `torch.cuda.is_available()` trước khi chạy script. + +--- + +## Kết luận + +Chúng tôi vừa **run OCR on image** bằng Python, kiểm tra confidence tổng thể, và tách ra các từ có confidence thấp cần một + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ code hoàn chỉnh với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách đặt giá trị ngưỡng trong nhận dạng OCR hình ảnh](/ocr/english/net/ocr-settings/set-threshold-value/) +- [Cách sử dụng Aspose OCR để nhận kết quả JSON trong nhận dạng hình ảnh](/ocr/english/net/text-recognition/get-result-as-json/) +- [Trích xuất văn bản từ hình ảnh – Tối ưu hóa OCR với Aspose.OCR cho .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file