From d6993d2bfbc54a82f9fab44b9c24f9c86dbc5a07 Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Fri, 19 Jun 2026 16:19:58 +0000 Subject: [PATCH] Add 8 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: - Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide - Perform OCR on Image in Python – Full Text Extraction Guide - Improve OCR Accuracy in Python – Complete Guide - Extract Text from Images in Python – Full Batch OCR Guide - How to Extract PDF Text with OCR in Python – Complete Guide - Create Searchable PDF in Python – Complete Step‑by‑Step Guide - extract text from images in Python – Full OCR Guide - How to Use OCR in Java with Aspose – Complete Guide Auto-generated by Professionalize.Tutorials Agent --- .../_index.md | 293 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 277 +++++++++++++++ .../_index.md | 243 +++++++++++++ .../_index.md | 257 ++++++++++++++ .../_index.md | 317 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 288 ++++++++++++++++ .../_index.md | 275 +++++++++++++++ .../_index.md | 232 +++++++++++++ .../_index.md | 280 +++++++++++++++ .../_index.md | 315 +++++++++++++++++ .../_index.md | 300 ++++++++++++++++ .../_index.md | 253 ++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 270 +++++++++++++++ .../_index.md | 279 +++++++++++++++ .../_index.md | 232 +++++++++++++ .../_index.md | 284 ++++++++++++++++ .../_index.md | 318 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../_index.md | 296 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 233 +++++++++++++ .../_index.md | 285 ++++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 292 ++++++++++++++++ .../_index.md | 278 +++++++++++++++ .../_index.md | 244 +++++++++++++ .../_index.md | 283 ++++++++++++++++ .../_index.md | 318 +++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 270 +++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 246 ++++++++++++++ .../_index.md | 285 ++++++++++++++++ .../_index.md | 320 ++++++++++++++++++ .../_index.md | 306 +++++++++++++++++ .../_index.md | 270 +++++++++++++++ .../_index.md | 296 ++++++++++++++++ .../_index.md | 292 ++++++++++++++++ .../_index.md | 275 +++++++++++++++ .../_index.md | 242 +++++++++++++ .../_index.md | 285 ++++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../_index.md | 294 ++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 279 +++++++++++++++ .../_index.md | 245 ++++++++++++++ .../_index.md | 261 ++++++++++++++ .../_index.md | 298 ++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 265 +++++++++++++++ .../_index.md | 293 ++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 233 +++++++++++++ .../_index.md | 260 ++++++++++++++ .../_index.md | 318 +++++++++++++++++ .../_index.md | 288 ++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 287 ++++++++++++++++ .../_index.md | 275 +++++++++++++++ .../_index.md | 241 +++++++++++++ .../_index.md | 257 ++++++++++++++ .../_index.md | 313 +++++++++++++++++ .../_index.md | 300 ++++++++++++++++ .../_index.md | 267 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 246 ++++++++++++++ .../_index.md | 260 ++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 278 +++++++++++++++ .../_index.md | 245 ++++++++++++++ .../_index.md | 285 ++++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../_index.md | 294 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 278 +++++++++++++++ .../_index.md | 244 +++++++++++++ .../_index.md | 284 ++++++++++++++++ .../_index.md | 318 +++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../_index.md | 292 ++++++++++++++++ .../_index.md | 286 ++++++++++++++++ .../_index.md | 274 +++++++++++++++ .../_index.md | 241 +++++++++++++ .../_index.md | 258 ++++++++++++++ .../_index.md | 313 +++++++++++++++++ .../_index.md | 300 ++++++++++++++++ .../_index.md | 267 +++++++++++++++ .../_index.md | 292 ++++++++++++++++ .../_index.md | 288 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 232 +++++++++++++ .../_index.md | 283 ++++++++++++++++ .../_index.md | 317 +++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 269 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 275 +++++++++++++++ .../_index.md | 233 +++++++++++++ .../_index.md | 259 ++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 289 ++++++++++++++++ .../_index.md | 256 ++++++++++++++ .../_index.md | 294 ++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 275 +++++++++++++++ .../_index.md | 233 +++++++++++++ .../_index.md | 262 ++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 270 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 275 +++++++++++++++ .../_index.md | 244 +++++++++++++ .../_index.md | 261 ++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../_index.md | 297 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 277 +++++++++++++++ .../_index.md | 242 +++++++++++++ .../_index.md | 259 ++++++++++++++ .../_index.md | 320 ++++++++++++++++++ .../_index.md | 288 ++++++++++++++++ .../_index.md | 270 +++++++++++++++ .../_index.md | 293 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 243 +++++++++++++ .../_index.md | 285 ++++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 253 ++++++++++++++ .../_index.md | 293 ++++++++++++++++ .../_index.md | 288 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 243 +++++++++++++ .../_index.md | 257 ++++++++++++++ .../_index.md | 316 +++++++++++++++++ .../_index.md | 284 ++++++++++++++++ .../_index.md | 269 +++++++++++++++ .../_index.md | 297 ++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 276 +++++++++++++++ .../_index.md | 232 +++++++++++++ .../_index.md | 262 ++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 291 ++++++++++++++++ .../_index.md | 278 +++++++++++++++ .../_index.md | 233 +++++++++++++ .../_index.md | 285 ++++++++++++++++ .../_index.md | 319 +++++++++++++++++ .../_index.md | 306 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ 184 files changed, 51850 insertions(+) create mode 100644 ocr/arabic/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/arabic/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/arabic/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/arabic/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/arabic/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/arabic/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/arabic/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/arabic/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/chinese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/chinese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/chinese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/chinese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/chinese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/chinese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/chinese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/chinese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/czech/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/czech/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/czech/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/czech/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/czech/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/czech/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/czech/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/czech/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/dutch/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/dutch/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/dutch/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/dutch/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/dutch/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/dutch/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/dutch/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/dutch/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/english/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/english/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/english/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/english/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/english/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/english/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/english/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/english/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/french/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/french/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/french/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/french/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/french/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/french/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/french/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/french/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/german/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/german/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/german/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/german/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/german/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/german/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/german/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/german/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/greek/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/greek/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/greek/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/greek/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/greek/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/greek/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/greek/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/greek/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/hindi/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hindi/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/hindi/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/hindi/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/hindi/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/hindi/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/hindi/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/hindi/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/hongkong/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/hongkong/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/hungarian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/hungarian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/indonesian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/indonesian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/italian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/italian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/italian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/italian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/italian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/italian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/italian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/italian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/japanese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/japanese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/japanese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/japanese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/japanese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/japanese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/japanese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/japanese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/korean/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/korean/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/korean/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/korean/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/korean/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/korean/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/korean/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/korean/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/polish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/polish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/polish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/polish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/polish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/polish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/polish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/polish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/portuguese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/portuguese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/russian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/russian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/russian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/russian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/russian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/russian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/russian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/russian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/spanish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/spanish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/spanish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/spanish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/spanish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/spanish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/spanish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/spanish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/swedish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/swedish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/swedish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/swedish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/swedish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/swedish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/swedish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/swedish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/thai/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/thai/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/thai/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/thai/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/thai/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/thai/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/thai/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/thai/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/turkish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/turkish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/turkish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/turkish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/turkish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/turkish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/turkish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/turkish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md create mode 100644 ocr/vietnamese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md create mode 100644 ocr/vietnamese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md diff --git a/ocr/arabic/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2f92bb2e7 --- /dev/null +++ b/ocr/arabic/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-19 +description: إنشاء ملف PDF قابل للبحث من صورة باستخدام OCR في بايثون. تعلم كيفية تحويل + OCR إلى PDF، استخراج النص من الصورة، وإجراء OCR على الصورة بسرعة. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: ar +og_description: إنشاء ملف PDF قابل للبحث من صورة باستخدام OCR في بايثون. يوضح هذا + الدليل كيفية تحويل OCR إلى PDF، واستخراج النص من الصورة، وإجراء OCR على الصورة. +og_title: إنشاء ملف PDF قابل للبحث في بايثون – دليل برمجي كامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: إنشاء ملف PDF قابل للبحث في بايثون – دليل كامل خطوة بخطوة +url: /ar/python-java/general/create-searchable-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 قابل للبحث** من إيصال ممسوح ضوئيًا لكنك لم تكن متأكدًا من أين تبدأ؟ لست وحدك — كثير من المطورين يواجهون نفس المشكلة عندما يحاولون لأول مرة تحويل صورة نص إلى ملف PDF يمكنك فعليًا البحث فيه. + +في هذا الدرس سنستعرض حلًا عمليًا يتيح لك **تنفيذ OCR على الصورة**، تحويل نتيجة OCR إلى **PDF قابل للبحث**، وحتى استخراج النص الأصلي إذا كنت تحتاجه لمعالجة إضافية. لا إطالة، مجرد مثال عملي يمكنك نسخه‑ولصقه في مشروعك اليوم. + +## ما ستتعلمه + +- كيفية إعداد محرك OCR خفيف الوزن في بايثون +- الخطوات الدقيقة **لتحويل OCR إلى PDF** وحفظه كمستند قابل للبحث +- طرق **استخراج النص من الصورة** للتحليل اللاحق +- نصائح للتعامل مع المشكلات الشائعة مثل اتجاه الصورة والملفات الكبيرة +- برنامج كامل قابل للتنفيذ يمكنك تكييفه مع حالتك الخاصة + +### المتطلبات المسبقة + +- تثبيت Python 3.8+ على جهازك +- إلمام أساسي بـ pip وبيئات افتراضية (اختياري لكن يُنصح به) +- ملف صورة (PNG، JPEG، إلخ) يحتوي على نص واضح يمكن قراءته آليًا + +إذا كان لديك كل ذلك، لنبدأ. + +## الخطوة 1: تثبيت المكتبة المطلوبة + +المقتطف البرمجي الذي رأيته سابقًا يستخدم حزمة `ocr` خيالية، لكن الفكرة نفسها تنطبق على مكتبات حقيقية مثل **EasyOCR**، **pytesseract**، أو **pdfminer.six**. في هذا الدليل سنستخدم **EasyOCR** لأنها بايثون خالص، تدعم العديد من اللغات، وتوفر طريقة تحويل PDF مفيدة عبر مساعد إضافي. + +```bash +pip install easyocr pillow +``` + +> **نصيحة احترافية:** قم بالتثبيت داخل بيئة افتراضية (`python -m venv venv && source venv/bin/activate`) للحفاظ على نظافة الاعتمادات. + +## الخطوة 2: تهيئة محرك OCR – تنفيذ OCR على الصورة + +الآن بعد أن أصبحت المكتبة جاهزة، ننشئ محرك OCR ونخبره بالعمل مع النص الإنجليزي. هذا هو المكان الأول الذي **ننفذ فيه OCR على الصورة**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +لماذا نحتاج كائن قارئ مخصص؟ EasyOCR يحمل نماذج اللغات مسبقًا، لذا إعادة استخدام نفس `reader` لعدة صور أكثر كفاءة من إعادة تهيئته في كل مرة. + +## الخطوة 3: تحميل الصورة – استخراج النص من الصورة + +لنُدخل الصورة إلى الذاكرة. هذه الخطوة هي التي **نستخرج فيها النص من الصورة** لاحقًا، لكن الآن نكتفي بتحميلها. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +إذا كانت صورتك مقلوبة أو مائلة، فكر في استخدام طرق `rotate` أو `transpose` الخاصة بـ Pillow قبل تمريرها إلى محرك OCR. فحص بصري سريع يمكن أن يوفر لك ساعات من تصحيح الأخطاء لاحقًا. + +## الخطوة 4: تشغيل محرك OCR والتقاط النتائج + +هذا هو جوهر العملية—إرسال الصورة إلى محرك OCR والحصول على بيانات مُنظمة. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +علامة `detail=1` تُعطينا صناديق الإحاطة، والتي سنحتاجها عندما **نحول OCR إلى PDF** لاحقًا. إذا كنت تهتم فقط بالسلاسل النصية الخام، اضبط `detail=0`. + +## الخطوة 5: تحويل نتيجة OCR إلى PDF قابل للبحث – تحويل OCR إلى PDF + +EasyOCR لا توفر كاتب PDF مباشر، لكن يمكننا تجميع PDF بأنفسنا باستخدام Pillow ومكتبة `reportlab`. لتقليل وزن الدرس، سنستخدم `fpdf2`، التي تسمح لنا بدمج الصورة الأصلية وتراكب نص غير مرئي. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +ماذا حدث للتو؟ وضعنا الصورة الممسوحة كطبقة مرئية، ثم كتبنا الكلمات المُعترف بها فوقها بنص أبيض يندمج مع الخلفية البيضاء. لا تزال أدوات البحث تقرأ الطبقة المخفية، لذا يصبح PDF **قابلًا للبحث** دون تغيير المظهر البصري. + +## الخطوة 6: حفظ بايتات PDF – تحويل الصورة إلى PDF + +إذا كنت تفضل التعامل مع PDF في الذاكرة (مثلاً إرساله عبر API)، يمكنك التقاط البايتات بدلاً من الكتابة مباشرة إلى القرص. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +هذا السطر يوضح سير عمل **تحويل الصورة إلى PDF** الكلاسيكي: تبدأ بصورة، تشغل OCR، تراكب النص، وأخيرًا تُصدر تدفق PDF. + +## الخطوة 7: التحقق من النتيجة – فحوصات سريعة + +بعد تشغيل السكريبت، افتح `receipt_searchable.pdf` في أي عارض PDF وجرب صندوق البحث (Ctrl + F). اكتب كلمة تعرف أنها موجودة في الإيصال—إذا انتقل إلى الموضع الصحيح، فقد نجحت في **إنشاء PDF قابل للبحث**! + +إذا فشل البحث، تحقق مرة أخرى من: + +1. درجات ثقة OCR (`conf` values). الثقة المنخفضة قد تعني أن الصورة غير واضحة. +2. إحداثيات صناديق الإحاطة—أحيانًا تُبلغ EasyOCR عنها بزاوية مختلفة. +3. أن عارض PDF ليس في وضع “صورة‑فقط” (نادر، لكن بعض العارضات لديها هذا الخيار). + +## البرنامج الكامل القابل للتنفيذ + +بتجميع كل شيء معًا، إليك ملف بايثون الكامل الجاهز للتنفيذ: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +احفظه باسم `searchable_pdf.py`، استبدل القيم `YOUR_DIRECTORY` بالمسارات الفعلية، ثم شغّله: + +```bash +python searchable_pdf.py +``` + +ستظهر لك رسالة تأكيد وملف PDF جديد قابل للبحث في مجلدك. + +## أسئلة شائعة وحالات خاصة + +**ماذا لو كانت الصورة ملونة؟** +EasyOCR يعمل مع الصور بالرمادي والملونة، لكن تحويلها إلى رمادي (`pil_image.convert("L")`) قد يحسن الدقة في المسحات الضوضائية. + +**هل يمكنني معالجة ملفات PDF متعددة الصفحات؟** +نعم—قم بالتكرار على كل صورة صفحة، شغّل خطوات OCR، وأضف كل صفحة إلى نفس كائن `FPDF`. فقط تذكر إعادة ضبط المؤشر (`self.add_page()`) لكل صورة جديدة. + +**هل هناك طريقة للحفاظ على طبقة النص الأصلية بدلاً من النص الأبيض غير المرئي؟** +إذا كنت تحتاج إلى PDF “نص‑تحت‑الصورة” حقيقي (مثلاً لأغراض الوصول)، فكر في استخدام `pdfminer` أو `pikepdf` لدمج طبقة نص مخفية مع وسوم PDF صحيحة. هذا أكثر تقدمًا، لكن المبدأ يبقى نفسه: صورة خلفية + نص متراكب. + +**ماذا لو كانت ثقة OCR منخفضة؟** +يمكنك تصفية الكلمات ذات الثقة المنخفضة: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## الخلاصة – ما حققناه + +بدأنا بصورة إيصال بسيطة، **نفذنا OCR على الصورة**، استخرجنا السلاسل المُعترف بها، وأخيرًا **أنشأنا PDF قابل للبحث** يتصرف كأي مستند ممسوح ضوئيًا احترافي. غطى العملية جميع الكلمات الثانوية—**تحويل OCR إلى PDF**، **استخراج النص من الصورة**، **تحويل الصورة إلى PDF**، و**تنفيذ OCR على الصورة**—وبالتالي لديك الآن صندوق أدوات قابل لإعادة الاستخدام لأي مشروع مماثل. + +### الخطوات التالية + +- جرّب لغات أخرى بتمرير رموز ISO الخاصة بها إلى `easyocr.Reader(['en', 'es'])`. +- استبدل EasyOCR بـ Tesseract إذا كنت تحتاج حلًا يعمل بالكامل دون اتصال؛ باقي خط الأنابيب يبقى كما هو. +- أضف تصورًا لثقة OCR (ارسم صناديق الإحاطة على الصورة) لتصحيح المسحات المشكلة. + +هل لديك تعديل ترغب بمشاركته؟ اترك تعليقًا، أو قم بعمل fork + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/arabic/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..630bd18a0 --- /dev/null +++ b/ocr/arabic/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: استخراج النص من الصور في بايثون باستخدام محرك OCR بسيط. تعلم كيفية تحويل + الصور الممسوحة ضوئياً إلى نص، التعرف على النص من الصور، وقائمة ملفات الصور في بايثون + بكفاءة. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: ar +og_description: استخراج النص من الصور باستخدام بايثون ومحرك OCR خفيف الوزن. يوضح لك + هذا الدليل كيفية تحويل الصور الممسوحة ضوئياً إلى نص، والتعرف على النص من الصور، + وإدراج ملفات الصور في بايثون في بضع خطوات. +og_title: استخراج النص من الصور في بايثون – دليل OCR شامل للدفعات +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: استخراج النص من الصور في بايثون – دليل كامل لتقنية OCR الدفعي +url: /ar/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استخراج النص من الصور باستخدام بايثون – دليل OCR شامل للدفعات + +هل احتجت يوماً إلى **استخراج النص من الصور** لكن لم تعرف من أين تبدأ؟ لست وحدك—المطورون يواجهون باستمرار تحدي تحويل ملفات PDF الممسوحة ضوئياً، الإيصالات المصورة، أو لقطات الشاشة إلى نص قابل للبحث. في هذا الدرس سنستعرض مثالاً كاملاً جاهزاً للتنفيذ يوضح كيفية **تحويل الصور الممسوحة إلى نص**، التعرف على النص من الصور، وحتى **قائمة ملفات الصور بأسلوب بايثون**. في النهاية ستحصل على سكريبت قابل لإعادة الاستخدام يعالج مجلدًا كاملاً دفعة واحدة. + +سنغطي كل ما تحتاجه: المكتبات المطلوبة، لماذا كل خطوة مهمة، التعامل مع الحالات الخاصة، وبعض النصائح لحل المشكلات. لا حاجة للبحث في وثائق خارجية؛ الكود أدناه مكتمل، والشروحات تجيب على سؤال "كيف" *و* "لماذا". افتح بيئة التطوير المفضلة لديك، ولنبدأ. + +--- + +## ما ستبنيه + +- تهيئة محرك OCR (سنستخدم حزمة `ocr` للتوضيح). +- مسح دليل وإ **قائمة ملفات الصور بأسلوب بايثون**، مع تصفية PNG، JPG، و TIFF. +- تشغيل عملية **OCR دفعي** على جميع الصور المكتشفة. +- طباعة النص المستخرج لكل ملف مع تسمية واضحة. + +> **نصيحة محترف:** إذا لم تكن مكتبة `ocr` مثبتة لديك، يمكنك استبدالها بـ `pytesseract` مع بعض التعديلات البسيطة—المنطق الأساسي يبقى كما هو. + +--- + +## المتطلبات المسبقة + +- Python 3.8+ (السكريبت يستخدم f‑strings وتلميحات الأنواع). +- مكتبة OCR توفر `OcrEngine` مع `recognize_batch`. في هذا الدليل نفترض وجود حزمة خيالية `ocr`، لكن النمط يعمل مع المكتبات الحقيقية. +- مجلد يحتوي على ملفات صور تريد معالجتها (`.png`, `.jpg`, `.tif`). + +--- + +## الخطوة 1 – تثبيت واستيراد الوحدات المطلوبة + +أولاً، تأكد من توفر حزمة OCR. إذا كنت تستخدم مكتبة حقيقية مثل `pytesseract`، استبدل الاستيراد وفقًا لذلك. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **لماذا هذا مهم:** استيراد `os` يمنحنا معالجة مسارات متوافقة مع جميع الأنظمة، بينما `typing.List` يساعد في إكمال الكود في IDE ويجعل الكود مستقبليًا. + +--- + +## الخطوة 2 – **استخراج النص من الصور**: تهيئة محرك OCR + +إنشاء المحرك هو الخطوة الأولى لأي عمل OCR. نضبط اللغة على الكشف التلقائي حتى يتمكن المحرك من التعامل مع المستندات متعددة اللغات. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **شرح:** من خلال تغليف إنشاء المحرك في دالة نحافظ على modularity الكود. إذا احتجت لاحقًا لتعديل DPI أو وضع OCR، يمكنك تعديل هذا المكان فقط. + +--- + +## الخطوة 3 – **قائمة ملفات الصور بايثون**: جمع الملفات من دليل + +الآن نحتاج إلى تحديد كل صورة نريد معالجتها. تعبير القائمة التالي يعكس نمط “قائمة ملفات الصور بايثون” الشائع. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **معالجة الحالات الخاصة:** تتجاهل الدالة المجلدات الفرعية (يمكنك إضافة التكرار لاحقًا) وتستبعد الملفات المخفية تلقائيًا لأنها عادةً لا تنتهي بالامتدادات المدعومة. + +--- + +## الخطوة 4 – **تحويل الصور الممسوحة إلى نص**: تشغيل OCR دفعي + +معظم مكتبات OCR توفر طريقة دفعية أسرع بكثير من معالجة صورة واحدة في كل مرة. إليك كيفية استدعائها. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **لماذا الدفعة؟** إرسال جميع الصور مرة واحدة يقلل من الحمل الزائد (مثل تحميل نموذج OCR مرارًا) وغالبًا ما يحسن استغلال CPU/GPU. + +--- + +## الخطوة 5 – **التعرف على النص من الصور**: عرض النتائج + +أخيرًا، نمر على أزواج أسماء الملفات ونتائج OCR، ونطبع عنوانًا واضحًا لكل صورة. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **نصيحة:** `strip()` يزيل المسافات الزائدة في البداية والنهاية التي يضيفها OCR غالبًا. + +--- + +## السكريبت الكامل – جمع كل الأجزاء معًا + +فيما يلي البرنامج الكامل القابل للتنفيذ. احفظه باسم `batch_ocr.py` وشغّله باستخدام `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### النتيجة المتوقعة + +با افتراض أن المجلد يحتوي على `invoice1.png` و `receipt.jpg`، قد ترى ما يلي: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +كل كتلة مُعلمة بوضوح، مما يجعل المعالجة اللاحقة (مثل الحفظ في قاعدة بيانات) سهلة. + +--- + +## معالجة المشكلات الشائعة + +| المشكلة | لماذا تحدث | الحل السريع | +|---------|------------|------------| +| **لا يظهر نص** | لغة OCR غير مكتشفة أو الصورة ذات تباين منخفض. | فرض لغة (`engine.language = ocr.Language.English`) أو تحسين الصور (زيادة التباين). | +| **خطأ ذاكرة في دفعات كبيرة** | المحرك يحاول تحميل جميع الصور مرة واحدة. | قسّم `image_files` إلى أجزاء (`batch_size = 20`) واستدعِ `recognize_batch` بشكل متكرر. | +| **صيغة ملف غير مدعومة** | أضفت `.gif` أو `.bmp`. | وسّع مجموعة `supported_exts` أو حوّل الصور إلى PNG/JPG مسبقًا. | +| **تشويه Unicode** | OCR يُعيد بايتات بدلاً من سلاسل. | تأكد من أن مكتبة OCR تُخرج Unicode (`result.text.decode('utf‑8')` إذا لزم). | + +--- + +## توسيع سير العمل + +الآن بعد أن أصبحت قادرًا على **استخراج النص من الصور**، فكر في الخطوات التالية: + +- **تصدير إلى CSV** – كتابة كل اسم ملف والنص المستخرج إلى جدول للتحاليل. +- **معالجة متوازية** – استخدم `concurrent.futures.ThreadPoolExecutor` لمعالجة دفعات متعددة في آن واحد. +- **الدمج مع OCR سحابي** – استبدل المحرك المحلي بـ Google Vision أو Azure OCR للحصول على دقة أعلى في التخطيطات المعقدة. +- **إضافة معالجة مسبقة للصور** – مكتبات مثل Pillow أو OpenCV يمكنها تصحيح الميل، إزالة الضوضاء، أو تطبيق عتبة قبل OCR، مما يحسن النتائج. + +كل هذه الأفكار تعتمد على نفس الدوال الأساسية التي بنيناها، لذا لن تحتاج للبدء من الصفر. + +--- + +## الخلاصة + +لقد استعرضنا حلًا كاملاً لـ **استخراج النص من الصور** باستخدام بايثون، بدءًا من **قائمة ملفات الصور بايثون** إلى **التعرف على النص من الصور** وأخيرًا **تحويل الصور الممسوحة إلى نص** في دفعة منظمة. السكريبت بسيط لكنه مرن بما يكفي ليكون أساسًا لمشروعات أكبر—سواءً كنت تُرقم إيصالات، تبني أرشيفًا قابلاً للبحث، أو تشغّل خط أنابيب لاستخراج البيانات. + +جرّبه، عدّل خطوات المعالجة المسبقة، وشاهد تحسين دقة OCR. إذا واجهت أي عوائق، راجع جدول “معالجة المشكلات الشائعة”؛ غالبًا ما تُحل القضايا بتغييرات إعدادات بسيطة. + +هل أنت مستعد للتحدي التالي؟ جرّب إضافة خطوة تحويل PDF إلى صور باستخدام `pdf2image`، ثم مرر تلك الصور إلى نفس الخط الأنابيب. السماء هي الحد عندما تجمع OCR مع نظام بايثون الغني. + +برمجة سعيدة، ولتكن نصوصك دائمًا مقروءة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [استخراج النص من صورة باستخدام Aspose OCR – دليل خطوة بخطوة](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [استخراج نص الصور – أساسيات OCR مع Aspose.OCR للـ Java](/ocr/english/java/ocr-basics/) +- [كيفية استخراج النص من صورة عبر URL باستخدام Aspose.OCR للـ Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/arabic/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..612e092c4 --- /dev/null +++ b/ocr/arabic/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-19 +description: استخراج النص من الصور باستخدام OCR في بايثون. تعلم الكشف التلقائي عن + اللغة، المعالجة المتوازية، والتعرف على النصوص على دفعات في دليل مختصر. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: ar +og_description: استخراج النص من الصور باستخدام OCR في بايثون. يوضح هذا الدليل الكشف + التلقائي عن اللغة، المعالجة المتوازية، والتعرف على النصوص على دفعات في دليل واحد. +og_title: استخراج النص من الصور في بايثون – دليل OCR كامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: استخراج النص من الصور في بايثون – دليل OCR الكامل +url: /ar/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استخراج النص من الصور في بايثون – دليل OCR كامل + +هل تساءلت يومًا كيف **تستخرج النص من الصور** دون الحاجة إلى كتابة كل كلمة يدويًا؟ لست وحدك. سواء كنت تقوم برقمنة الإيصالات القديمة، أو تبني أرشيفًا مستندًا للبحث، أو مجرد تجربة حيل الذكاء الاصطناعي الرائعة، فإن القدرة على سحب النص من الصور هي مهارة أساسية لأي مطور بايثون اليوم. + +في هذا الدرس سنستعرض مثالًا كاملًا جاهزًا للتنفيذ **يستخرج النص من الصور** باستخدام محرك OCR شائع. سنغطي الكشف التلقائي عن اللغة، المعالجة المتوازية للسرعة، والتعرف على دفعات الصور حتى تتمكن من معالجة عشرات الملفات في ثوانٍ. هل يبدو هذا ما تحتاجه؟ لنبدأ. + +## ما ستتعلمه + +- كيفية إنشاء محرك OCR باستخدام `ocr.OcrEngine`. +- تفعيل **الكشف التلقائي عن اللغة** بحيث يختار المحرك اللغة المناسبة تلقائيًا. +- إعداد **معالجة OCR المتوازية** باستخدام مجموعة خيوط مخصصة. +- تشغيل **التعرف على دفعة من الصور** على قائمة من الملفات. +- طباعة النص المستخرج لكل صورة، جاهز للحفظ أو الفهرسة. + +لا حاجة لأي وثائق خارجية—كل ما تحتاجه موجود هنا، والكود يعمل مباشرةً مع حزمة `ocr` (قم بتثبيتها عبر `pip install ocr`). + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من وجود ما يلي: + +1. Python 3.8 أو أحدث مثبت. +2. حزمة `ocr` (`pip install ocr`). +3. مجلد يحتوي على صور PNG (أو JPG) تريد معالجتها. +4. إلمام أساسي بدوال وحلقات بايثون. + +هذا كل ما تحتاجه—بدون تبعيات ثقيلة، بدون سحر الـ GPU، فقط بايثون عادي. + +![مثال لاستخراج النص من الصور](https://example.com/ocr-demo.png "لقطة شاشة تُظهر ناتج استخراج النص من الصور") + +*نص بديل: مثال لاستخراج النص من الصور* + +## الخطوة 1 – إعداد محرك OCR (الكلمة المفتاحية الأساسية في التنفيذ) + +أولًا: أنشئ مثالًا لمحرك OCR. فكر في `ocr.OcrEngine()` كالعقل وراء العملية؛ فهو يعرف كيف يقرأ الأحرف، السطور، والفقرات. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +لماذا نحتاج إلى محرك صريح؟ لأن **استخدام ocr.OcrEngine** يمنحك تحكمًا دقيقًا في إعدادات اللغة، الخيوط، وأكثر. إنه أكثر مرونة لاستخراج النص من الصور مقارنةً بالمساعدات ذات السطر الواحد. + +## الخطوة 2 – السماح للمحرك بالكشف عن اللغات تلقائيًا + +معظم مكتبات OCR تتطلب منك تحديد اللغة التي يبحث عنها. هذا مناسب لمشروع بلغة واحدة، لكنه مرهق لدفعات متعددة اللغات. لحسن الحظ، تدعم حزمة `ocr` **الكشف التلقائي عن اللغة**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +ضبط `engine.language` إلى `ocr.Language.Auto` يخبر المحرك بفحص كل صورة واختيار نموذج اللغة المناسب. هذه السطر الصغير يوفر لك ساعات من الإعداد اليدوي عندما تتعامل مع مستندات دولية. + +## الخطوة 3 – تسريع العملية باستخدام معالجة OCR المتوازية + +إذا كان لديك أربعة نوى CPU أو أكثر، لماذا لا تستفيد منها؟ يمكن للمحرك إنشاء مجموعة خيوط، مما يسمح بمعالجة عدة صور في الوقت نفسه. هنا يبرز **معالجة OCR المتوازية**. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +يمكنك تعديل العدد `4` وفقًا لجهازك. المزيد من الخيوط → تشغيل دفعات أسرع، لكن تذكر أن كل خيط يستهلك ذاكرة، لذا ابحث عن التوازن المناسب لبيئتك. + +## الخطوة 4 – جمع الصور التي تريد معالجتها + +الآن نحتاج إلى قائمة بمسارات الملفات. يمكنك بناء هذه القائمة يدويًا، قراءتها من CSV، أو استخدام `glob`. للتوضيح، سنكتب قائمة قصيرة مباشرةً: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +استبدل `YOUR_DIRECTORY` بالمسار الفعلي على نظامك. إذا كان لديك عشرات الملفات، فإن `glob.glob("*.png")` سيفعل معظم العمل. + +## الخطوة 5 – تشغيل التعرف على دفعة من الصور + +هذا هو جوهر الدرس: استدعاء واحد يعالج كل صورة في `files` ويعيد قائمة من كائنات النتيجة. هذه هي ميزة **التعرف على دفعة من الصور** التي تجعل OCR على نطاق واسع عمليًا. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +خلف الكواليس، يوزع المحرك كل ملف على الخيوط الأربعة التي أعددناها مسبقًا، مع الكشف التلقائي عن اللغة لكل صورة. تُعيد الطريقة قائمة حيث يحتوي كل عنصر على النص المستخرج والبيانات الوصفية. + +## الخطوة 6 – طباعة (أو تخزين) النص المستخرج + +أخيرًا، نمر على النتائج ونطبع النص. في مشروع حقيقي ربما تكتب ذلك إلى قاعدة بيانات أو ملف CSV، لكن الطباعة تبقي المثال بسيطًا. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**الناتج المتوقع** (مقتطع للوضوح): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +كل كتلة تُظهر اسم الملف متبوعًا بالسلسلة المستخرجة من OCR. إذا احتوت الصورة على لغات متعددة، سترى الأحرف المناسبة بفضل خطوة **الكشف التلقائي عن اللغة** السابقة. + +## نصائح احترافية ومخاطر شائعة + +- **جودة الصورة مهمة** – الصور الضبابية أو ذات التباين المنخفض ستنتج نفايات. عالجها مسبقًا باستخدام OpenCV (`cv2.threshold`, `cv2.resize`) إذا لزم الأمر. +- **عدد الخيوط مقابل I/O** – إذا كانت صورك مخزنة على قرص شبكة بطيء، قد لا تساعد زيادة الخيوط. راقب استهلاك CPU باستخدام `top` أو **Task Manager**. +- **معالجة Unicode** – `result.text` هو سلسلة Unicode. عند الكتابة إلى ملفات، افتحها بـ `encoding="utf‑8"` لتجنب `UnicodeEncodeError`. +- **استهلاك الذاكرة** – ملفات PDF الكبيرة قد تستهلك الكثير من RAM. إذا واجهت `MemoryError`، قلل حجم مجموعة الخيوط أو عالج الصور على دفعات أصغر. + +## السكريبت الكامل العامل + +فيما يلي السكريبت الكامل جاهز للنسخ واللصق والذي يدمج كل خطوة ناقشناها. احفظه باسم `batch_ocr.py` وشغّله بـ `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +شغّله هكذا: + +```bash +python batch_ocr.py ./my_images 4 +``` + +سترى كتلة نص منسقة بشكل جميل لكل صورة، مما يثبت أنك تستطيع **استخراج النص من الصور** على نطاق واسع. + +## ما التالي؟ + +الآن بعد أن أتقنت أساسيات **استخراج النص من الصور** باستخدام بايثون، فكر في استكشاف: + +- **ما بعد المعالجة**: نظّف مخرجات OCR باستخدام regex أو مكتبات معالجة اللغة الطبيعية. +- **تحويل PDF**: أدخل السلاسل المستخرجة في مولد PDF لإنشاء ملفات PDF قابلة للبحث. +- **خدمات OCR السحابية**: قارن نتائج `ocr` المحلية مع Google Vision أو Azure OCR للحصول على دقة في الحالات الخاصة. +- **واجهة GUI**: أنشئ تطبيقًا صغيرًا بـ Flask أو FastAPI يتيح للمستخدمين رفع الصور ورؤية النص المستخرج فورًا. + +كل هذه المواضيع تبني على أساس **مكتبة OCR بايثون** التي أعددتها، وتستفيد جميعها من نفس حيل **معالجة 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 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/arabic/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/arabic/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..a4e3b65e1 --- /dev/null +++ b/ocr/arabic/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-19 +description: كيفية استخراج PDF باستخدام OCR في بايثون – دليل خطوة بخطوة يغطي استخراج + النص من PDF، التعرف على النص من الصورة، ومثال على OCR باستخدام بايثون. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: ar +og_description: كيفية استخراج ملفات PDF باستخدام OCR في بايثون. تعلم استخراج النص + من PDF، التعرف على النص من الصورة، وشاهد مثالًا كاملاً على OCR باستخدام بايثون. +og_title: كيفية استخراج نص PDF باستخدام OCR في بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: كيفية استخراج نص PDF باستخدام OCR في بايثون – دليل شامل +url: /ar/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية استخراج نص PDF باستخدام OCR في بايثون – دليل كامل + +هل تساءلت يومًا **كيف تستخرج محتوى PDF** عندما يكون الملف مجرد صورة ممسوحة ضوئيًا؟ لست وحدك. في العديد من المشاريع الواقعية—مثل العقود، الفواتير، أو الأرشيفات التاريخية—الـ PDF الذي تستلمه لا يحتوي على نص قابل للتحديد. الخبر السار؟ بضع أسطر من بايثون يمكنها تحويل تلك الصفحات التي لا تحتوي على نص إلى نص قابل للبحث والتحرير. + +في هذا الدرس سنستعرض مثالًا عمليًا **OCR Python** يقرأ PDF، يُحوِّل صفحته الأولى إلى صورة، ثم **يستخرج النص من PDF** باستخدام محرك OCR. بنهاية الدرس ستعرف بالضبط **كيفية قراءة PDF باستخدام OCR**، لماذا كل خطوة مهمة، وكيفية تعديل الكود للتعامل مع مستندات متعددة الصفحات أو لغات مختلفة. + +## ما ستتعلمه + +- تثبيت وإعداد مكتبة OCR موثوقة لبايثون. +- تحويل صفحات PDF إلى صور مناسبة لـ OCR. +- **التعرف على النص من الصورة** واستخراج سلاسل Unicode نظيفة. +- المشكلات الشائعة (PDF منخفض الدقة، الصفحات المائلة) وكيفية تجنبها. +- توسيع السكربت لمعالجة صفحات متعددة أو دفعات. + +**المتطلبات المسبقة**: بايثون 3.8+، pip، وفهم أساسي للبيئات الافتراضية. لا تحتاج إلى خبرة سابقة في OCR—فقط اتبع الخطوات. + +--- + +## ## كيفية استخراج نص PDF باستخدام OCR في بايثون + +هذا العنوان H2 يحتوي على الكلمة المفتاحية الأساسية حيث تحب محركات البحث رؤيتها. لنبدأ مباشرةً بالكود. + +### الخطوة 1 – تثبيت الحزم المطلوبة + +أولًا، نحتاج إلى محرك OCR. المثال أدناه يستخدم حزمة **ocr** الشهيرة (غلاف خفيف حول Tesseract). إذا كنت تفضّل خلفية مختلفة، تبقى المفاهيم نفسها. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **نصيحة احترافية:** على لينكس، ستحتاج أيضًا إلى ملف Tesseract الثنائي: `sudo apt-get install tesseract-ocr`. يمكن لمستخدمي macOS الحصول عليه عبر Homebrew: `brew install tesseract`. + +### الخطوة 2 – تهيئة محرك OCR وتحديد اللغة + +الآن نقوم بتشغيل المحرك ونخبره بالبحث عن الأحرف الإنجليزية. يمكنك استبدال `ocr.Language.English` بأي رمز لغة مدعوم. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**لماذا هذا مهم:** تحديد اللغة يحسّن الدقة بشكل كبير لأن المحرك يستطيع تطبيق القواميس والنماذج الخاصة بتلك اللغة. + +### الخطوة 3 – تحميل صفحة PDF كصورة + +يعمل OCR على الصور النقطية، وليس على كائنات PDF. الدالة `ocr.Image.from_pdf` تُحوِّل الصفحة المختارة إلى بت ماب. عدّل `page_number` للصفحات الأخرى (فهرسة تبدأ من 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **حالة حدية:** إذا كان PDF يحتوي على رسومات متجهية بدلاً من صور ممسوحة، قد تحصل على رسم واضح. بالنسبة للماسحات منخفضة الدقة، فكر في زيادة DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### الخطوة 4 – التعرف على النص من الصورة المُحوَّلة + +هذا هو جوهر **ocr python example**. المحرك يعالج البت ماب ويعيد كائنًا يحتوي على السلسلة المستخرجة. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +الخاصية `ocr_result.text` تحتفظ بالنص العادي، مع الحفاظ على فواصل الأسطر حيثما أمكن. + +### الخطوة 5 – طباعة أو حفظ النص المستخرج + +أخيرًا، نعرض النتيجة. في تطبيق حقيقي ربما تكتب إلى ملف أو قاعدة بيانات. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +تشغيل السكربت يجب أن يُظهر شيئًا مثل: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +هذا هو سير عمل كامل **استخراج النص من pdf** باستخدام OCR. + +--- + +## ## التعرف على النص من الصورة – تحسين الدقة + +إذا كنت مهتمًا فقط بـ **التعرف على النص من الصورة** (مثل صورة JPEG لإيصال)، يمكنك تخطي خطوة تحويل PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**نصائح للحصول على نتائج أفضل:** + +- **معالجة مسبقة** للصورة: تحويلها إلى تدرج رمادي، تطبيق العتبة، أو تصحيح الميل. مكتبة Pillow تجعل ذلك سهلًا. +- **زيادة DPI** أثناء تحويل PDF: الدقة الأعلى تعطي محرك OCR تفاصيل أكثر. +- **تمكين إعدادات محرك OCR** لتقسيم الصفحة (`ocr_engine.config = "--psm 6"` للكتل المتجانسة). + +--- + +## ## قراءة PDF باستخدام OCR – معالجة صفحات متعددة + +معظم العقود تمتد لعدة صفحات. التكرار على كل صفحة سهل: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +هذه الدالة **تقرأ PDF باستخدام OCR**، تُدمج المخرجات، وتضيف علامة فاصل صفحة واضحة. يمكنك بعد ذلك تمرير `full_text` إلى فهرس بحث أو حفظه كملف `.txt`. + +--- + +## ## المشكلات الشائعة وكيفية إصلاحها + +| العرض | السبب المحتمل | الحل | +|---------|--------------|-----| +| أحرف مشوشة، الكثير من `?` | لغة خاطئة أو ملفات بيانات لغة مفقودة | تثبيت حزمة لغة Tesseract الصحيحة (`tesseract-ocr-`) وتعيين `ocr_engine.language`. | +| سطور مفقودة أو كلمات مقطوعة | DPI منخفض (أقل من 150) | تحويل PDF بدقة 300 DPI أو أعلى (`dpi=300`). | +| النص مائل أو مقلوب | الصفحة الممسوحة غير موجهة بشكل صحيح | استخدم `ocr.Image.deskew(page_image)` قبل التعرف. | +| معالجة بطيئة على ملفات PDF كبيرة | معالجة الصفحات تسلسليًا على خيط واحد | استخدم `concurrent.futures.ThreadPoolExecutor` للتوازي. | + +--- + +## ## توسيع مثال OCR Python + +- **تصدير إلى PDF/A**: بعد الاستخراج، يمكنك دمج النص مرة أخرى في PDF قابل للبحث باستخدام `reportlab` أو `pypdf2`. +- **اكتشاف اللغة**: استخدم `langdetect` على ناتج OCR لتبديل `ocr_engine.language` تلقائيًا. +- **معالجة دفعات**: استعرض دليلًا باستخدام `os.listdir` وطبق `extract_all_pages` على كل ملف. + +--- + +## ## النتيجة المتوقعة والتحقق + +عند تشغيل السكربت على مسح واضح باللغة الإنجليزية، يجب أن ترى كتلة نصية نظيفة مع علامات ترقيم صحيحة. للتحقق: + +1. قارن بضع أسطر مع الصورة الممسوحة الأصلية. +2. نفّذ عدّ كلمات بسيط (`len(ocr_result.text.split())`) للتأكد من أن المخرجات ليست فارغة. +3. اختياريًا، مرّر النتيجة إلى مدقق إملائي مثل `pyspellchecker` لاكتشاف أخطاء OCR. + +--- + +## الخلاصة + +غطّينا **كيفية استخراج محتوى PDF** عندما يفشل التحليل التقليدي، وعرضنا مثالًا كاملًا **ocr python example**، وشرحنا كيف **نتعرف على النص من الصورة** و**نقرأ PDF باستخدام OCR** للصفحات الفردية والمتعددة. باستخدام مقتطفات الكود أعلاه يمكنك الآن تحويل أي PDF ممسوح إلى نص قابل للبحث والتحرير—دون الحاجة لإعادة كتابة يدوية. + +الخطوات التالية؟ جرّب تغيير اللغة إلى الإسبانية (`ocr.Language.Spanish`) أو جرب تقنيات المعالجة المسبقة للصور لتعزيز الدقة. إذا كنت تبني نظام إدارة مستندات، فكر في فهرسة النص المستخرج باستخدام Elasticsearch للبحث الفائق السرعة. + +هل لديك أسئلة أو صادفت PDF غريب؟ اترك تعليقًا، وتمنياتنا لك ببرمجة سعيدة! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/arabic/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..7bebb971b --- /dev/null +++ b/ocr/arabic/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-06-19 +description: تعلم كيفية استخدام OCR في جافا مع Aspose. يغطي هذا الدليل خطوة بخطوة + تصحيح الميل التلقائي للصور، واكتشاف اللغة تلقائيًا، واستخراج النص من الصورة بسهولة. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: ar +og_description: 'كيفية استخدام OCR في جافا مع Aspose: دليل شامل يغطي تصحيح الميلان + التلقائي للصور، الكشف التلقائي عن اللغة، واستخراج النص من الصور.' +og_title: كيفية استخدام OCR في جافا مع Aspose – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: كيفية استخدام OCR في جافا مع Aspose – دليل شامل +url: /ar/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية استخدام OCR في Java مع Aspose – دليل شامل + +هل تساءلت يومًا **كيف تستخدم OCR** في مشروع Java دون أن تجهد نفسك في الإعدادات؟ لست وحدك. يواجه العديد من المطورين صعوبة عندما يحتاجون إلى **استخراج نص من صورة** بسرعة، خاصةً عندما تكون عمليات المسح المصدرية مائلة أو مكتوبة بلغة غير معروفة. + +في هذا الدرس سنستعرض مثالًا عمليًا يوضح لك بالضبط كيف تستخدم OCR مع Aspose، بما في ذلك **auto deskew images**، **auto language detection**، وسلسلة **ocr image preprocessing** الكاملة. في النهاية ستحصل على مقطع جاهز للتنفيذ يطبع النص المعترف به على وحدة التحكم، وستفهم لماذا كل إعداد مهم. + +> **ما ستحصل عليه:** برنامج Java كامل قابل للتنفيذ، شروحات لكل سطر، نصائح للتعامل مع الحالات الخاصة، وأفكار لتوسيع الحل لمعالجة الدُفعات أو ملفات PDF. + +--- + +## المتطلبات المسبقة + +- Java 17 (أو أي JDK حديث) مثبت ومُكوَّن. +- Maven أو Gradle لإدارة التبعيات (سنظهر إحداثيات Maven). +- ملف ترخيص Aspose OCR for Java (`Aspose.OCR.Java.lic`). إذا كنت تختبر فقط، يمكنك تخطي خطوة الترخيص، لكن النسخة التجريبية المجانية ستضيف علامة مائية. +- صورة نموذجية (`your_image.png`) موضوعة في مكان يمكن للكود الوصول إليه. + +> **نصيحة احترافية:** احفظ صورك في مجلد `resources` مخصص وحمّلها عبر classpath؛ فهذا يتجنب مشاكل المسارات على أنظمة تشغيل مختلفة. + +## الخطوة 1: إعداد المشروع وإضافة تبعية Aspose OCR + +أنشئ مشروع Maven جديد (أو استخدم مشروعك الحالي) وأضف ما يلي إلى ملف `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +شغّل `mvn clean install` لجلب المكتبة. إذا كنت تفضّل Gradle، فالبديل هو: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +الآن لديك فئات **ocr image preprocessing** على classpath الخاص بك. + +## الخطوة 2: تطبيق ترخيص Aspose OCR الخاص بك (اختياري لكن يُنصح به) + +إذا كان لديك ترخيص، طبّقها في بداية طريقة `main`. تخطي هذه الخطوة يعمل، لكن النسخة المجانية تضيف علامة مائية “Demo” على الناتج. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **لماذا هذا مهم:** النسخة المرخصة تزيل حدود الاستخدام وتعطل العلامة المائية، مما يمنحك نتائج نظيفة وجاهزة للإنتاج. + +## الخطوة 3: إنشاء مثيل محرك OCR + +المحرك هو قلب العملية. إنشاء مثيل له يمنحك الوصول إلى جميع خيارات **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +في هذه المرحلة يكون المحرك جاهزًا، لكنه سيستخدم الإعدادات الافتراضية التي قد لا تكون مثالية للمستندات الممسوحة. لنقم بضبط بعض الإعدادات. + +## الخطوة 4: تمكين Auto Deskew Images للحصول على مسحات أنظف + +المسحات المائلة هي مشكلة شائعة. توفر Aspose ميزة **auto deskew images** التي تقوم تلقائيًا بتصحيح الصورة قبل التعرف. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **كيف يعمل:** يحلل الخوارزمية زوايا خط أساس النص ويُدوّر الصورة إلى الاتجاه العمودي الأكثر احتمالًا. هذا يحسن الدقة بشكل كبير للصور الملتقطة بالهاتف. + +## الخطوة 5: تفعيل Auto Language Detection + +إذا لم تكن تعرف لغة الصورة المصدر، دع المحرك يكتشفها. هذا هو إعداد **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +عند تفعيل ذلك، تقوم Aspose بمسح الرموز وتختار نموذج اللغة الأكثر احتمالًا، مع دعم أكثر من 30 لغة جاهزة. + +## الخطوة 6: تحميل الصورة التي تريد التعرف عليها + +يمكنك تحميل صورة من القرص، أو URL، أو حتى مصفوفة بايت. للتبسيط، سنقرأ من ملف محلي. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **نصيحة:** إذا كنت تتعامل مع صور كبيرة، فكر في تقليل حجمها أولاً باستخدام `engine.getImagePreprocessing().setResizeFactor(0.5)` لتسريع المعالجة دون فقدان الكثير من التفاصيل. + +## الخطوة 7: تنفيذ التعرف على OCR واستخراج نص الصورة + +الآن يقوم المحرك بسحره. تُعيد طريقة `recognize` كائن `OcrResult` الذي يحتوي على النص المعترف به، درجات الثقة، وأكثر. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +ستظهر وحدة التحكم النص العادي المستخرج من الصورة—هذا هو النتيجة الأساسية لـ **extract text image** التي سعى لتحقيقها. + +## مثال كامل يعمل + +فيما يلي الفئة الكاملة في Java التي تجمع كل شيء معًا. انسخ‑الصقها إلى `src/main/java/com/example/OcrDemo.java` وشغّلها. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### النتيجة المتوقعة + +إذا كانت الصورة تحتوي على العبارة “Hello World” في مسح نظيف، سترى: + +``` +=== Recognized Text === +Hello World +``` + +بالنسبة للمستندات الأكثر تعقيدًا (مثل الفواتير متعددة اللغات)، سيشمل الناتج فواصل أسطر ورمز اللغة المكتشف. + +## الأخطاء الشائعة & نصائح احترافية + +| المشكلة | سبب حدوثه | الحل | +|-------|----------------|-----| +| **حروف غير مفهومة** | الصورة مظلمة جدًا أو تحتوي على ضوضاء. | فعّل `engine.getImagePreprocessing().setBinarization(true)` أو اضبط التباين يدويًا. | +| **لغة خاطئة** | الكشف التلقائي يخطئ في الصفحات متعددة اللغات. | عيّن `engine.setLanguage(Language.English)` (أو التعداد المناسب) لإجبار لغة محددة. | +| **معالجة بطيئة** | صور ذات دقة عالية جدًا. | قلل الحجم باستخدام `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **أخطاء نفاد الذاكرة** | دفعة كبيرة من الصور محمّلة مرة واحدة. | عالج الصور تسلسليًا واستدعِ `engine.dispose()` بعد كل تشغيل. | + +> **تذكر:** محرك OCR آمن للاستخدام متعدد الخيوط للعمليات القراءة فقط، لكن إنشاء مثيل جديد لكل خيط يتجنب الأخطاء المخفية في الحالة. + +## توسيع الحل + +الآن بعد أن عرفت **كيفية استخدام OCR** مع Aspose، قد ترغب في: + +1. معالجة ملفات PDF – تحويل كل صفحة PDF إلى صورة (`PdfConverter`) ثم تمريرها إلى نفس السلسلة. +2. معالجة دفعة لمجلد – التكرار عبر الملفات في دليل، تطبيق نفس الخطوات، وكتابة النتائج إلى ملف CSV. +3. الدمج مع خدمة ويب – إظهار منطق OCR عبر `@RestController` في Spring Boot الذي يقبل تحميلات multipart. + +جميع هذه السيناريوهات تعيد استخدام نفس إعداد **ocr image preprocessing** الذي بنيناه هنا. + +## الخلاصة + +لقد غطينا **كيفية استخدام OCR** في Java مع Aspose من البداية حتى النهاية: تطبيق الترخيص، إنشاء المحرك، تفعيل **auto deskew images**، تمكين **auto language detection**، تحميل صورة، وأخيرًا **extract text image** باستخدام `System.out.println` واحد. الكود مكتمل ذاتيًا، يعمل على أي JDK حديث، ويظهر أفضل الممارسات للدقة والأداء. + +جرّبه مع صورك الخاصة—ربما عقدًا ممسوحًا أو لقطة شاشة لإيصال. عدّل علامات المعالجة المسبقة، جرب لغات مختلفة، وسترى سريعًا لماذا مكتبة OCR من Aspose خيار قوي لاستخراج النص في بيئات الإنتاج. + +هل لديك أسئلة أو تريد مشاركة نتائجك؟ اترك تعليقًا أدناه أو راسلني على GitHub. برمجة سعيدة! + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شاملة للكود مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية استخراج نص الصورة مع اللغة باستخدام Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [استخراج النص من صورة Java باستخدام Aspose.OCR وضع اكتشاف المناطق](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [كيفية استخدام OCR - تقنيات متقدمة مع Aspose.OCR لـ Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/arabic/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..cd1a3655c --- /dev/null +++ b/ocr/arabic/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,317 @@ +--- +category: general +date: 2026-06-19 +description: تحسين دقة OCR في بايثون باستخدام Aspose OCR. تعلم كيفية تعيين لغة OCR، + تحميل الصورة للـ OCR، واستخراج النص من الصورة باستخدام قاموس مخصص. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: ar +og_description: تحسين دقة OCR في بايثون عن طريق ضبط لغة OCR، تحميل صورة للـ OCR، واستخراج + النص من الصورة باستخدام قاموس مخصص. +og_title: تحسين دقة التعرف الضوئي على الأحرف في بايثون – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: تحسين دقة OCR في بايثون – دليل كامل +url: /ar/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحسين دقة OCR في بايثون – دليل شامل + +هل تساءلت يومًا كيف **تحسن دقة OCR** عندما يحتوي النص الذي تقوم بمسحه على رموز غريبة أو رموز منتجات أو أسماء علامات تجارية؟ لست وحدك. في العديد من المشاريع ينتج المحرك الافتراضي نصًا غير مفهوم، وهذا يقتل الإنتاجية حقًا. + +في هذا الدرس سنستعرض مثالًا عمليًا من البداية إلى النهاية يوضح لك كيفية **تحديد لغة OCR**، **تحميل الصورة للـ OCR**، **إجراء OCR على الصورة**، وأخيرًا **استخراج النص من الصورة** باستخدام قاموس مخصص يعزز معدلات التعرف. في النهاية ستحصل على سكريبت جاهز للتنفيذ يمكنك إدراجه في أي مشروع بايثون. + +## ما ستستفيده + +- سكريبت بايثون كامل الوظائف يستخدم Aspose OCR لقراءة ملف PNG. +- القدرة على **تحسين دقة OCR** من خلال تكوين اللغة وقائمة كلمات مخصصة. +- شروحات واضحة لأسباب أهمية كل إعداد، بالإضافة إلى نصائح للتعامل مع الحالات الخاصة مثل الأحرف غير اللاتينية. +- قائمة مراجعة سريعة لاستكشاف الأخطاء الشائعة في OCR. + +### المتطلبات المسبقة + +- Python 3.8 أو أحدث مثبت على جهازك. +- حزمة `aspose-ocr` (تثبيت عبر `pip install aspose-ocr`). +- صورة نموذجية (`technical_doc.png`) تحتوي على النص الذي تريد قراءته. +- إلمام أساسي ببايثون—لا شيء معقد مطلوب. + +> **نصيحة احترافية:** إذا كنت تعمل في بيئة افتراضية، فعّلها قبل تثبيت الحزمة. هذا يحافظ على نظافة الاعتمادات ويتجنب تعارض الإصدارات. + +--- + +## الخطوة 1: تثبيت واستيراد Aspose OCR + +أولًا، لنقم بإضافة المكتبة إلى بيئتنا واستيراد المكونات التي نحتاجها. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +مساحة الاسم `aspose.ocr` تمنحك الوصول إلى الفئة `OcrEngine`، وهي قلب عملية OCR. استيرادها هنا يبقي باقي السكريبت نظيفًا وسهل القراءة. + +--- + +## الخطوة 2: إنشاء محرك OCR و **تحديد لغة OCR** + +لماذا اللغة مهمة؟ تعتمد محركات OCR على نماذج مخصصة للغة لتعرف أشكال الأحرف وأنماط الكلمات. إذا أخبرت المحرك أنك تمسح نصًا إنجليزيًا، سيتجاهل الحروف السيريلية ويركز على الأبجدية اللاتينية، مما يؤدي إلى **تحسين دقة OCR** بشكل ملحوظ. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **ملاحظة:** يدعم Aspose OCR أكثر من 50 لغة. استبدل `ocr.Language.English` بـ `ocr.Language.Spanish` أو `ocr.Language.French` وغيرها إذا لم يكن مستندك إنجليزيًا. + +--- + +## الخطوة 3: تعريف **قاموس مخصص** لتعزيز الدقة + +تخيل أنك تمسح فواتير تحتوي على كلمة “AsposeOCR” أو رموز منتجات مثل “SKU12345”. المحرك لا يعرف هذه المصطلحات، فيخمنها بشكل غير صحيح. توفير قائمة كلمات مخصصة يخبر المحرك: *“هذه السلاسل صحيحة—لا تحاول تصحيحها.”* وهذا يُعد فوزًا سريعًا لـ **تحسين دقة OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +يمكنك تحميل هذه القائمة من ملف أو قاعدة بيانات إذا كان لديك مئات الإدخالات—فقط احتفظ بها في قائمة بايثون للتبسيط. + +--- + +## الخطوة 4: **تحميل الصورة للـ OCR** + +الآن نحتاج إلى صورة. طريقة `Image.load` تقبل مسارًا لأي تنسيق نقطي مدعوم (PNG، JPEG، BMP، إلخ). إذا تعذر العثور على الملف، يرمي المحرك استثناءً، لذا سنحمي الكود من ذلك. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **لماذا هذه الخطوة مهمة:** تحميل الصورة بشكل صحيح يضمن أن المحرك يعمل على بيانات البكسل الدقيقة التي تريد تحليلها. الملفات التالفة أو المسارات الخاطئة هي مصدر شائع للإحباط. + +--- + +## الخطوة 5: **إجراء OCR على الصورة** واستخراج النتائج + +مع تكوين المحرك وتحضير الصورة، يصبح التعرف الفعلي استدعاء طريقة واحدة. يحتوي كائن النتيجة على النص الخام، درجات الثقة، وحتى معلومات التخطيط إذا احتجت إليها لاحقًا. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +إذا أردت **استخراج النص من الصورة** سطرًا بسطر، يمكنك التقسيم بناءً على أحرف السطر الجديد: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## الخطوة 6: التحقق من المخرجات – هل حقًا **تحسن دقة OCR**؟ + +لنطبع النتيجة ونرى إذا ما كان القاموس المخصص قد أحدث فرقًا. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +المخرجات النموذجية للصورة التجريبية قد تبدو هكذا: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +لاحظ كيف يظهر اسم العلامة التجارية، الحرف اليوناني، ورمز المنتج تمامًا كما عرّفناها. بدون القاموس المخصص، كان المحرك سيحاول “تصحيح” هذه العناصر، غالبًا ما ينتج شيء مثل “Aspose OCR” أو “SKU 1234”. + +--- + +## المشكلات الشائعة وكيفية التعامل معها + +| المشكلة | السبب | الحل | +|-------|----------------|-----| +| **حروف غير مفهومة** | تعيين لغة خاطئة أو صورة منخفضة الدقة | تأكد من أن `engine.language` يطابق لغة المصدر واستخدم مسحًا بدقة عالية (300 dpi أو أعلى). | +| **تجاهل الكلمات المخصصة** | القاموس غير مرفق أو هناك خطأ إملائي في اسم الخاصية | راجع `engine.text_processing.custom_dictionary = …`. | +| **الملف غير موجود** | مسار غير صحيح أو أذونات ملف مفقودة | استخدم `os.path.abspath()` للتحقق من المسار المطلق؛ شغّل السكريبت بأذونات مناسبة. | +| **بطء المعالجة** | صور كبيرة أو صفحات متعددة | عالج الصورة مسبقًا (قص، تغيير حجم) أو استخدم `engine.recognize(image, max_threads=4)` للتنفيذ المتوازي. | + +--- + +## التعمق: تحسينات متقدمة لـ **تحسين دقة OCR** + +1. **المعالجة المسبقة** – طبّق تحسين التباين أو التحويل إلى أبيض وأسود باستخدام Pillow قبل تمرير الصورة إلى Aspose OCR. +2. **عدة لغات** – عيّن `engine.language = ocr.Language.English | ocr.Language.French` لتمكين التعرف الثنائي اللغة. +3. **OCR قائم على المنطقة** – إذا كنت تحتاج فقط إلى جزء محدد (مثل جدول)، قص الصورة أولًا لتقليل الضوضاء. +4. **تصفية الثقة** – `result.confidence` يعطي درجة ثقة لكل حرف؛ يمكنك استبعاد النتائج ذات الثقة المنخفضة برمجيًا. + +--- + +## السكريبت الكامل القابل للتنفيذ + +فيما يلي السكريبت الكامل جاهز للنسخ واللصق والذي يدمج كل خطوة ناقشناها. احفظه باسم `improve_ocr_accuracy.py` وشغّله من سطر الأوامر. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +شغّله: + +```bash +python improve_ocr_accuracy.py +``` + +سترى المخرجات المنسقة بشكل جميل التي عرضناها سابقًا. + +--- + +## الخلاصة + +لقد غطينا طريقة بسيطة لـ **تحسين دقة OCR** في بايثون من خلال: + +1. **تحديد لغة OCR** لتطابق مستندك. +2. **تحميل الصورة بشكل صحيح** حتى يرى المحرك البكسلات المطلوبة. +3. **إجراء OCR على الصورة** باستدعاء طريقة واحدة. +4. **استخراج النص من الصورة** وتأكيد النتيجة. +5. **إضافة قاموس مخصص** لتثبيت المصطلحات الخاصة بالمجال. + +هذا هو سير العمل الكامل—from الصورة الخام إلى نص نظيف قابل للبحث—معبأ في سكريبت قابل لإعادة الاستخدام. + +إذا كنت مستعدًا للتحدي التالي، جرّب تجربة المعالجة المسبقة للصور (التباين، تصحيح الميل) أو انتقل إلى إعداد متعدد اللغات باستخدام `ocr.Language.English | ocr.Language.German`. نفس المبادئ تنطبق، وستستمر في **تحسين دقة OCR** عبر مجموعة أوسع من المستندات. + +هل لديك أسئلة أو حالة خاصة غريبة؟ اترك تعليقًا أدناه، وتمنياتنا لك ببرمجة سعيدة! + +![improve OCR accuracy + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/arabic/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..946a03d5b --- /dev/null +++ b/ocr/arabic/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-06-19 +description: قم بإجراء التعرف الضوئي على الأحرف (OCR) على الصورة باستخدام مكتبة OCR + في بايثون. تعلّم كيفية اكتشاف النص من الصورة، التعرف على النص من ملف JPEG، واستخراج + النص من الصورة الممسوحة ضوئياً بكفاءة. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: ar +og_description: قم بإجراء التعرف الضوئي على الأحرف (OCR) على الصورة باستخدام بايثون + واستخراج النص من الملفات الممسوحة ضوئياً. يشرح هذا الدليل خطوة بخطوة كيفية تحميل + الصور، وتصحيح الميل، والتعرف على النص. +og_title: إجراء التعرف الضوئي على الأحرف (OCR) على صورة في بايثون – دليل استخراج النص + الكامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: إجراء OCR على صورة في بايثون – دليل استخراج النص الكامل +url: /ar/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إجراء OCR على صورة في بايثون – دليل استخراج النص الكامل + +هل احتجت يوماً إلى **perform OCR on image** ملفات لكن واجهت صعوبة لأن الكود كان غامضاً؟ لست وحدك. سواءً كنت تحول مجموعة من الإيصالات الممسوحة إلى ملفات PDF قابلة للبحث أو تستخرج العناوين من صورة JPEG لمشروع علم بيانات، فإن القدرة على التعرف على النص من JPEG وغيرها من الصيغ هي مهارة أساسية لأي مطور اليوم. + +في هذا الدرس سنستعرض مثالاً كاملاً قابلاً للتنفيذ يوضح لك كيفية **detect text from image** الملفات، **extract text from scanned image** المستندات، وحتى **load image for OCR** في بضع أسطر فقط. في النهاية ستحصل على مقطع شفرة جاهز للإنتاج يمكنك إدراجه في مشاريعك—بدون استيرادات مفقودة، دون اختصارات “انظر الوثائق”. + +## ما ستبنيه + +- برنامج بايثون صغير يخلق محرك OCR، يفعّل auto‑deskew، يحمل صورة JPEG (أو أي صيغة مدعومة)، ويطبع النص المُعترف به. +- شروحات حول **why** كل إعداد مهم، وليس فقط **how** تكتبه. +- نصائح للتعامل مع ملفات PDF متعددة الصفحات، اللغات غير الإنجليزية، ومشكلات شائعة مثل الصور الضبابية. + +### المتطلبات المسبقة + +- تثبيت Python 3.8+ (المثال يستخدم حزمة `ocr` المتوفرة عبر `pip install ocr-lib` – استبدلها باسم المكتبة الفعلي لديك). +- معرفة أساسية بدوال بايثون والبيئات الافتراضية. +- ملف صورة (JPEG, PNG, TIFF) تريد معالجته؛ سنستخدم `skewed_page.jpg` كعنصر نائب. + +> **Pro tip:** إذا كنت على نظام Windows، شغّل الطرفية كمسؤول عند تثبيت مكتبة OCR لتجنب مشاكل الأذونات. + +--- + +## إجراء OCR على صورة – الإعداد والتكوين + +أول شيء تحتاجه هو نسخة نظيفة من محرك OCR. فكر فيه كالعقل وراء العملية؛ بدون تكوين صحيح، حتى أكثر الصور وضوحاً ستعيد نصاً غير مفهوم. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters:** +إعداد `engine.language` يحد من مجموعة الأحرف التي يتوقعها محرك OCR، مما يعزز الدقة بشكل كبير. إذا تخطيت هذا الإعداد، سيحاول المحرك التخمين، وغالباً ما يخطئ في قراءة الكلمات البسيطة. + +--- + +## تمكين التصحيح التلقائي للانحراف – إصلاح المسحات المائلة + +الصفحات الممسوحة نادراً ما تكون مسطحة تماماً. الانحراف الطفيف قد يخلّ بتقسيم الأحرف، محوّلاً “Hello” إلى “H3llo”. علم `auto_deskew` يقوم بالعمل الشاق نيابةً عنك. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** إذا كنت تعلم أن صورك مستقيمة بالفعل، يمكن إلغاء تفعيل التصحيح لتقليل بضع مليثانية من زمن المعالجة—مفيد عند معالجة آلاف الصفحات في مهمة دفعة. + +--- + +## تحميل صورة للـ OCR – دعم JPEG, PNG, TIFF + +الآن نقوم فعلياً بـ **load image for OCR**. طريقة `ocr.Image.load` مرنة؛ تقبل مساراً لأي صيغة نقطية مدعومة. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial:** المكتبة تقرأ الملف إلى bitmap داخلي، وتطبق أي تحويل ضروري لمساحة الألوان. تخطي هذه الخطوة وتمرير تدفق بايتات خام سيسبّب `FileNotFoundError` أو، الأسوأ، ينتج نتائج فارغة بصمت. + +إذا كنت بحاجة إلى **recognize text from JPEG** تحديداً، تأكد فقط من أن امتداد الملف هو `.jpeg` أو `.jpg`. نفس الاستدعاء يعمل مع PNG (`.png`) أو TIFF (`.tif`) دون تعديل. + +--- + +## إجراء OCR على صورة – تشغيل المحرك + +مع تحضير المحرك وتحميل الصورة في الذاكرة، حان الوقت لـ **perform OCR on image** البيانات. هذا السطر الواحد يقوم بالمعالجة الكاملة: ما قبل المعالجة، التقسيم، التصنيف، وتجميع النص. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood?** +- المحرك يطبق تحويل التصحيح (إذا كان مفعّلاً). +- يشغّل شبكة عصبية أو محرك Tesseract لتحديد الأحرف. +- أخيراً، يربط الأحرف لتكوّن كلمات وأسطر، ويعيد كائن `result` غني. + +--- + +## استخراج النص من صورة ممسوحة – إخراج النتائج + +الخطوة الأخيرة هي **extract text from scanned image** وعرضه. الخاصية `result.text` تحتوي على تمثيل النص العادي. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +الناتج النموذجي يبدو هكذا: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +إذا فشل محرك OCR في العثور على أي أحرف، ستكون `result.text` سلسلة فارغة. في هذه الحالة، أعد فحص جودة الصورة أو فكر في تعديل خاصية `engine.confidence_threshold` (إذا كانت مكتبتك تدعم ذلك). + +--- + +## معالجة الاختلافات الشائعة + +### التعرف على النص من JPEG مقابل PNG + +كلا الصيغتين مدعومتان، لكن ضغط JPEG قد يضيف تشويهات تُربك المحرك. إذا لاحظت أخطاءً متكررة في التعرف، جرّب تحويل JPEG إلى PNG أولاً: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### اكتشاف النص من صورة بعدة لغات + +إذا كان مستندك يخلط بين الإنجليزية والإسبانية، فعّل وضع متعدد اللغات: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +سيتعامل المحرك حينها مع كلا الأبجديتين أثناء التعرف. + +### استخراج النص من ملفات PDF ممسوحة + +بالنسبة لملفات PDF، تحتاج إلى تحويل كل صفحة إلى صورة أولاً. مكتبات مثل `pdf2image` تجعل العملية سهلة: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## مثال عملي كامل + +فيما يلي السكريبت الكامل الذي يمكنك نسخه‑لصقه في ملف `ocr_demo.py`. يتضمن معالجة الأخطاء ومساعد صغير لقياس زمن التنفيذ. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (assuming a clear scan): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## الأسئلة المتكررة + +**Q: Can I run this on a headless server?** +A: بالتأكيد. المكتبة تعمل بدون واجهة رسومية؛ فقط تأكد من تثبيت الثنائيات الأصلية اللازمة (مثل Tesseract) على الخادم. + +**Q: What if the image is blurry?** +A: فكر في إضافة مرشح شحذ قبل `engine.recognize`. العديد من مكتبات OCR تكشف عن `image_preprocessing.sharpen = True` أو يمكنك استخدام `cv2.GaussianBlur` من OpenCV بشكل عكسي. + +**Q: Does the script support batch processing?** +A: نعم. غلف `perform_ocr` داخل حلقة تمر على قائمة مسارات الملفات، + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/arabic/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..1c526527a --- /dev/null +++ b/ocr/arabic/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-19 +description: قم بإجراء التعرف الضوئي على الأحرف (OCR) على الصورة باستخدام Aspose OCR + Java. تعلّم كيفية تحميل الصورة للتعرف الضوئي على الأحرف، واستخدام ترخيص Aspose، + واستخراج النص من الصورة في دقائق. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: ar +og_description: قم بإجراء التعرف الضوئي على الأحرف (OCR) على صورة باستخدام Aspose + OCR Java. يوضح هذا الدليل كيفية استخدام ترخيص Aspose، وتحميل الصورة للتعرف الضوئي + على الأحرف، واستخراج النص من الصورة بكفاءة. +og_title: إجراء التعرف الضوئي على الحروف في الصورة باستخدام Aspose OCR Java – دليل + كامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: إجراء OCR على صورة باستخدام Aspose OCR Java – دليل كامل خطوة بخطوة +url: /ar/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إجراء OCR على الصورة باستخدام Aspose OCR Java – دليل خطوة بخطوة كامل + +هل احتجت يوماً إلى **perform OCR on image** لكنك لم تكن متأكدًا أي مكتبة ستمنحك نتائج موثوقة دون إعدادات معقدة؟ لست وحدك. في العديد من المشاريع الواقعية—مثل مسح جوازات السفر، تحويل الفواتير إلى رقمية، أو استخراج النص من لقطات الشاشة—تُعد القدرة على التعرف السريع على بيانات النص في الصورة عاملًا محوريًا. + +في هذا الدرس سنستعرض مثالًا عمليًا يوضح بالضبط كيفية **perform OCR on image** باستخدام Aspose OCR for Java. سنغطي كل شيء من تطبيق رخصة Aspose إلى تحميل الصورة، تشغيل المحرك، وأخيرًا **extract text from image** لتتمكن من استخدامها لاحقًا. لا إطالة، مجرد حل عملي يمكنك نسخه ولصقه. + +## ما ستتعلمه بعد الانتهاء + +- صورة واضحة عن كيفية **use Aspose license** في مشروع Java. +- الكود الدقيق المطلوب **load image for OCR** والسماح للمحرك باكتشاف اللغات تلقائيًا. +- تعليمات خطوة بخطوة **recognize text image** بأمان و**extract text from image**. +- نصائح للتعامل مع المشكلات الشائعة (نتائج فارغة، صيغ غير مدعومة، ومشكلات الذاكرة). + +> **المتطلبات المسبقة** – Java 8 أو أحدث، Maven أو Gradle لإدارة الاعتمادات، وملف رخصة Aspose OCR for Java (أو يمكنك التشغيل في وضع التقييم). + +--- + +## كيفية إجراء OCR على الصورة باستخدام Aspose OCR Java + +فيما يلي البرنامج الكامل القابل للتنفيذ بلغة Java الذي يوضح سير العمل بالكامل. احفظه باسم `AsposeOcrDemo.java` وشغّله من بيئة التطوير المتكاملة أو سطر الأوامر. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### ناتج وحدة التحكم المتوقع + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +إذا شغّلت البرنامج بدون ملف رخصة، سيظهر السطر الأول ببساطة أنه في وضع التقييم، لكن OCR سيعمل كما هو. + +--- + +## إعداد واستخدام رخصة Aspose + +### لماذا الرخصة مهمة + +تشغيل المكتبة في وضع التقييم مناسب للاختبارات السريعة، لكنه يضيف علامة مائية إلى الناتج ويقيد عدد الصفحات التي يمكنك معالجتها في كل تشغيل. خطوة **use aspose license** تزيل هذه القيود وتُظهر لـ Aspose أنك عميل مدفوع. + +### كيفية الحصول عليها وتطبيقها + +1. اشترِ رخصة من متجر Aspose. +2. حمّل ملف `Aspose.OCR.Java.lic`. +3. ضع الملف في مكان يمكن لتطبيقك قراءته—عادةً مجلد `src/main/resources`. +4. استدعِ `new License().setLicense("Aspose.OCR.Java.lic");` قبل أي عملية OCR، كما هو موضح في الكود أعلاه. + +> **نصيحة احترافية:** إذا كنت تنشر على خادم، استخدم مسارًا مطلقًا أو محمل موارد على مسار الفئة لتجنب `FileNotFoundException`. + +--- + +## تحميل الصورة لمعالجة OCR + +السطر `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` هو جوهر خطوة **load image for OCR**. تدعم Aspose OCR مجموعة واسعة من الصيغ: PNG، JPEG، BMP، TIFF، وحتى ملفات PDF متعددة الصفحات (عند دمجها مع Aspose.Pdf). + +### مشكلات شائعة + +| Issue | Symptom | Fix | +|-------|---------|-----| +| Wrong file path | `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent separators. | +| Unsupported format | `UnsupportedOperationException` | Convert the image to PNG or JPEG before loading. | +| Huge image ( > 10 MP) | Out‑of‑memory errors | Downscale the image using `java.awt.Image` before feeding it to Aspose. | + +--- + +## استخراج النص من الصورة ومعالجة النتائج + +بعد انتهاء محرك OCR، يحتوي كائن `OcrResult` على السلسلة المعترف بها. هنا نستخدم **extract text from image** للمعالجة اللاحقة—حفظه في قاعدة بيانات، إرساله إلى فهرس بحث، أو تمريره إلى خط أنابيب NLP. + +### التعامل مع لغات متعددة + +نظرًا لأننا عيّنّا `engine.setLanguage(Language.Auto)`، سيحاول Aspose اكتشاف اللغات تلقائيًا. إذا كنت تعرف اللغة مسبقًا (مثلاً جميع المستندات روسية)، يمكنك استبدال `Language.Auto` بـ `Language.Russian` لتحسين الأداء. + +### نصائح ما بعد المعالجة + +- **Trim whitespace**: `result.getText().trim()`. +- **Normalize line endings**: `result.getText().replace("\r\n", "\n")`. +- **Remove non‑printable characters**: use a regex like `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## التعرف على نص الصورة باستخدام خيارات متقدمة (اختياري) + +إذا كنت تحتاج إلى تحكم أدق، توفر Aspose OCR خصائص إضافية: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +هذه التعديلات مفيدة عندما تتعامل مع مستندات ممسوحة تعاني من الميل أو انخفاض التباين. + +--- + +## ملخص المثال الكامل العامل + +بتجميع كل شيء معًا، يقوم البرنامج النهائي بالخطوات التالية بالترتيب: + +1. **Perform OCR on image** – بإنشاء كائن `OcrEngine`. +2. **Use Aspose license** – اختياري لكنه موصى به. +3. **Load image for OCR** – عبر `Image.load`. +4. **Set language detection** – `Language.Auto` لتـ **recognize text image** تلقائيًا. +5. **Extract text from image** – طباعة النتيجة ومعالجة الردود الفارغة بلطف. + +يمكنك نسخ كتلة الكود أعلاه مباشرةً إلى مشروع Maven مع الاعتماد التالي: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +شغّل الأمر `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` وسترى النص المعترف به يُعرض في وحدة التحكم. + +--- + +## الخلاصة + +لقد أوضحنا لك كيفية **perform OCR on image** باستخدام Aspose OCR for Java، بدءًا من تطبيق الرخصة إلى **loading the image for OCR**، **recognizing text image**، وأخيرًا **extracting text from image** للاستخدام اللاحق. النهج بسيط، يدعم عدة لغات مباشرة، ويمكن توسيعه بخيارات ما قبل المعالجة المتقدمة عند الحاجة. + +ما الخطوة التالية؟ جرّب إرسال ناتج OCR إلى فهرس بحث، أنشئ ملفات PDF بالنص المستخرج، أو جرب صيغ صور مختلفة. الإمكانيات لا حصر لها، ومع API القوي من Aspose ستقضي وقتًا أكثر في بناء الميزات وأقل في التعامل مع تعقيدات OCR. + +هل لديك أسئلة أو واجهت حالة خاصة؟ اترك تعليقًا أدناه—نتمنى لك برمجة سعيدة! + +## ما الذي يجب أن تتعلمه لاحقًا؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية استخراج النص من صورة عبر URL باستخدام Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [تحويل الصورة إلى نص في Java باستخدام Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [استخراج النص من صورة Java باستخدام وضع اكتشاف المناطق في Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..82a0a567e --- /dev/null +++ b/ocr/chinese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Python OCR 将图像创建可搜索的 PDF。学习将 OCR 转换为 PDF、从图像提取文本,并快速对图像执行 OCR。 +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: zh +og_description: 使用 Python OCR 将图像转换为可搜索的 PDF。本指南展示了如何将 OCR 转为 PDF、从图像中提取文本以及对图像进行 + OCR。 +og_title: 使用 Python 创建可搜索的 PDF – 完整编程演练 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: 在 Python 中创建可搜索的 PDF – 完整的逐步指南 +url: /zh/python-java/general/create-searchable-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 – 完整分步指南 + +是否曾需要从扫描的收据**创建可搜索的 PDF**但不知从何入手?你并不孤单——许多开发者在第一次尝试将文字图片转换为真正可搜索的 PDF 时都会遇到同样的难题。 + +在本教程中,我们将演示一个实用方案,让你**对图像执行 OCR**,将 OCR 结果转化为**可搜索的 PDF**,并在需要时提取原始文本进行后续处理。没有冗余,只是一个可以直接复制粘贴到项目中的可运行示例。 + +## 您将学到的内容 + +- 如何在 Python 中搭建轻量级的 OCR 引擎 +- 将 **OCR 转换为 PDF** 并保存为可搜索文档的完整步骤 +- 如何 **从图像中提取文本** 以用于下游分析 +- 处理常见坑点(如图像方向、文件过大)的技巧 +- 一个完整的可运行脚本,方便你根据自己的使用场景进行改造 + +### 前置条件 + +- 在机器上已安装 Python 3.8+ +- 对 pip 和虚拟环境有基本了解(可选但推荐) +- 一张包含清晰、机器可读文本的图片文件(PNG、JPEG 等) + +如果你已经具备这些条件,下面我们开始吧。 + +## 步骤 1:安装所需库 + +你之前看到的代码片段使用了一个虚构的 `ocr` 包,但相同的思路同样适用于真实的库,例如 **EasyOCR**、**pytesseract** 或 **pdfminer.six**。本指南将使用 **EasyOCR**,因为它纯 Python 实现,支持多语言,并通过辅助工具提供便利的 PDF 转换方法。 + +```bash +pip install easyocr pillow +``` + +> **专业提示:** 在虚拟环境中安装 (`python -m venv venv && source venv/bin/activate`) 可以保持依赖整洁。 + +## 步骤 2:初始化 OCR 引擎 – 对图像执行 OCR + +库准备好后,我们创建一个 OCR 引擎并指定使用英文文本。这是第一次**对图像执行 OCR**的地方。 + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +为什么需要专门的 reader 对象?EasyOCR 会预加载语言模型,复用同一个 `reader` 处理多张图片比每次重新初始化要高效得多。 + +## 步骤 3:加载图像 – 从图像中提取文本 + +把图片加载到内存中。此步骤后面会**从图像中提取文本**,但现在我们仅仅是把它读进来。 + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +如果你的图片是倒置或倾斜的,考虑在送入 OCR 引擎前使用 Pillow 的 `rotate` 或 `transpose` 方法进行校正。快速的目视检查可以为后续调试节省大量时间。 + +## 步骤 4:运行 OCR 引擎并捕获结果 + +下面是核心流程——将图像发送给 OCR 引擎并获取结构化数据。 + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +`detail=1` 参数会返回边界框,这在后面**将 OCR 转换为 PDF**时会用到。如果你只关心原始字符串,可将其设为 `detail=0`。 + +## 步骤 5:将 OCR 结果转换为可搜索的 PDF – 将 OCR 转换为 PDF + +EasyOCR 并未直接提供 PDF 写入功能,但我们可以使用 Pillow 和 `reportlab` 库自行拼接 PDF。为保持教程轻量,我们采用 `fpdf2`,它可以嵌入原始图像并覆盖不可见的文本层。 + +```bash +pip install fpdf2 +``` +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +刚才发生了什么?我们把扫描的图像作为可见层放置,然后用白色文字(与白色背景融合)写入识别出的单词。搜索工具仍然能够读取隐藏的文字层,从而在不改变视觉效果的前提下,使 PDF **可搜索**。 + +## 步骤 6:保存 PDF 字节 – 将图像转换为 PDF + +如果你更倾向于在内存中处理 PDF(例如通过 API 发送),可以捕获字节流而不是直接写入磁盘。 + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +这行代码演示了经典的 **将图像转换为 PDF** 工作流:先有图像,运行 OCR,覆盖文本,最后输出 PDF 流。 + +## 步骤 7:验证结果 – 快速检查 + +运行脚本后,用任意 PDF 查看器打开 `receipt_searchable.pdf` 并尝试搜索框(Ctrl + F)。输入收据中已知出现的词汇——如果能跳转到正确位置,说明你已经成功**创建可搜索的 PDF**! + +如果搜索失败,请检查: + +1. OCR 置信度分数(`conf` 值)。低置信度可能意味着图像模糊。 +2. 边界框坐标——有时 EasyOCR 会以不同的方向返回。 +3. PDF 查看器是否被设置为“仅图像”模式(虽然少见,但有些查看器有此选项)。 + +## 完整可运行脚本 + +将所有步骤组合起来,这就是完整、可直接运行的 Python 文件: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +将其保存为 `searchable_pdf.py`,将 `YOUR_DIRECTORY` 占位符替换为真实路径,然后执行: + +```bash +python searchable_pdf.py +``` + +你应该会看到确认信息,并在文件夹中得到一个全新的可搜索 PDF。 + +## 常见问题与边缘情况 + +**如果图像是彩色的怎么办?** +EasyOCR 同时支持灰度和彩色图像,但将图像转换为灰度 (`pil_image.convert("L")`) 有时能提升噪声扫描的识别准确率。 + +**能处理多页 PDF 吗?** +可以——遍历每一页的图像,执行 OCR 步骤,然后将每页追加到同一个 `FPDF` 对象中。记得在每张新图像前调用 `self.add_page()` 重置页面。 + +**有没有办法保留原始文本层而不是使用不可见的白色文字?** +如果需要真正的“文字在图像下方”PDF(例如用于可访问性),可以考虑使用 `pdfminer` 或 `pikepdf` 嵌入带有正确 PDF 标签的隐藏文本层。这属于更高级的做法,但原理仍然是:背景图像 + 覆盖文字。 + +**如果 OCR 置信度低怎么办?** +可以过滤掉低置信度的单词: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## 总结 – 我们的成果 + +我们从一张简单的收据图片开始,**对图像执行 OCR**,提取识别出的字符串,最终**创建可搜索的 PDF**,其行为与任何专业扫描文档相同。整个过程覆盖了所有次要关键词——**将 OCR 转换为 PDF**、**从图像中提取文本**、**将图像转换为 PDF**、以及**对图像执行 OCR**——因此你现在拥有一个可复用的工具箱,可用于任何类似项目。 + +### 下一步 + +- 通过向 `easyocr.Reader(['en', 'es'])` 传入其他语言的 ISO 代码来尝试多语言识别。 +- 如果需要完全离线的解决方案,可将 EasyOCR 替换为 Tesseract;其余流水线保持不变。 +- 添加 OCR 置信度可视化(在图像上绘制边界框),以便调试有问题的扫描件。 + +有想法想分享吗?留下评论,或者 fork 本项目。 + +## 接下来应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在自己的项目中进一步掌握 API 功能并探索替代实现方式。每篇资源都提供完整的可运行代码示例和逐步解释。 + +- [使用 Aspose OCR 从图像中提取文本 – 分步指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [C# 将图像转换为 PDF – 保存多页 OCR 结果](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [如何进行图像 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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/chinese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..faddaca1e --- /dev/null +++ b/ocr/chinese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-19 +description: 使用简单的 OCR 引擎在 Python 中提取图像文本。了解如何将扫描图像转换为文字、从图片中识别文本,并高效列出图像文件。 +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: zh +og_description: 使用轻量级 OCR 引擎在 Python 中提取图像文本。本指南展示了如何将扫描图像转换为文本、从图片中识别文字,并在几步内列出 Python + 的图像文件。 +og_title: 使用 Python 从图像中提取文本 – 完整批量 OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: 使用 Python 从图像中提取文本 – 完整批量 OCR 指南 +url: /zh/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 从图像中提取文本(Python) – 完整批量 OCR 指南 + +是否曾需要 **从图像中提取文本**,却不知从何入手?你并不孤单——开发者经常面临将扫描的 PDF、拍摄的收据或截图转换为可搜索文本的挑战。在本教程中,我们将演示一个完整、可直接运行的示例,展示如何 **将扫描图像转换为文本**、从图片中识别文字,甚至 **以 python 方式列出图像文件**。完成后,你将拥有一个可一次性处理整个文件夹的可复用脚本。 + +我们会覆盖所有必需内容:所需库、每一步的意义、边缘情况处理以及一些故障排除。无需查阅外部文档;下面的代码是自包含的,解释同时回答 “怎么做” 与 “为什么”。打开你喜欢的 IDE,开始动手吧。 + +--- + +## 你将构建的内容 + +- 初始化 OCR 引擎(本文示例使用 `ocr` 包)。 +- 扫描目录并 **以 python 方式列出图像文件**,过滤 PNG、JPG 和 TIFF。 +- 对所有找到的图片执行 **批量 OCR** 操作。 +- 为每个文件打印提取的文本,并加上清晰的标签。 + +> **专业提示:** 如果你没有安装 `ocr` 库,可以改用 `pytesseract`,只需做少量修改——核心逻辑保持不变。 + +--- + +## 前置条件 + +- Python 3.8+(脚本使用 f‑strings 和类型提示)。 +- 一个提供 `OcrEngine` 且拥有 `recognize_batch` 方法的 OCR 库。本文假设一个虚构的 `ocr` 包,但该模式同样适用于真实库。 +- 一个包含待处理图像文件的文件夹(`.png`、`.jpg`、`.tif`)。 + +--- + +## 步骤 1 – 安装并导入所需模块 + +首先,确保 OCR 包已可用。如果使用真实库如 `pytesseract`,相应替换导入语句。 + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **为什么重要:** 导入 `os` 可实现跨平台路径处理,而 `typing.List` 有助于 IDE 自动补全并提升代码的可维护性。 + +--- + +## 步骤 2 – **从图像中提取文本**:初始化 OCR 引擎 + +创建引擎是进行任何 OCR 工作的第一步。我们还将语言设置为自动检测,以便引擎能够处理混合语言文档。 + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **解释:** 将引擎创建封装在函数中可以保持代码的模块化。如果以后需要调整 DPI 或 OCR 模式,只需修改这一处。 + +--- + +## 步骤 3 – **以 Python 方式列出图像文件**:从目录收集文件 + +现在需要定位所有待处理的图片。下面的列表推导式对应常见的 “list image files python” 用法。 + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **边缘情况处理:** 该函数会忽略子文件夹(如需递归可后续添加),并自动过滤隐藏文件,因为它们通常不以受支持的扩展名结尾。 + +--- + +## 步骤 4 – **将扫描图像转换为文本**:执行批量 OCR + +大多数 OCR 库都提供批量方法,速度远快于逐张处理。下面演示如何调用它。 + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **为什么使用批量?** 一次性发送所有图像可减少开销(例如重复加载 OCR 模型),并且通常能获得更好的 CPU/GPU 利用率。 + +--- + +## 步骤 5 – **从图片中识别文本**:显示结果 + +最后,我们遍历文件名与 OCR 结果的配对,为每张图片打印整洁的标题。 + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **小技巧:** `strip()` 会去除 OCR 常常附加的前后空白字符。 + +--- + +## 完整脚本 – 综合全部代码 + +下面是完整、可直接运行的程序。将其保存为 `batch_ocr.py`,然后执行 `python batch_ocr.py `。 + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### 预期输出 + +假设文件夹中包含 `invoice1.png` 和 `receipt.jpg`,可能会看到: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +每个块都有明确标签,便于后续处理(例如保存到数据库)。 + +--- + +## 常见问题处理 + +| 问题 | 产生原因 | 快速解决方案 | +|------|----------|--------------| +| **没有出现文本** | OCR 语言未检测到或图像对比度太低。 | 强制指定语言 (`engine.language = ocr.Language.English`) 或对图像进行预处理(提升对比度)。 | +| **大批量时内存错误** | 引擎一次性加载所有图像。 | 将 `image_files` 分块(如 `batch_size = 20`),并多次调用 `recognize_batch`。 | +| **不支持的文件格式** | 添加了 `.gif` 或 `.bmp`。 | 扩展 `supported_exts` 元组,或事先将图像转换为 PNG/JPG。 | +| **Unicode 乱码** | OCR 返回字节而非字符串。 | 确保 OCR 库输出 Unicode(如有必要使用 `result.text.decode('utf-8')`)。 | + +--- + +## 扩展工作流 + +既然已经能够 **从图像中提取文本**,可以考虑以下后续步骤: + +- **导出为 CSV** – 将每个文件名及其提取的文本写入电子表格,便于分析。 +- **并行处理** – 使用 `concurrent.futures.ThreadPoolExecutor` 同时处理多个批次。 +- **集成云 OCR** – 将本地引擎替换为 Google Vision 或 Azure OCR,以获得更高的复杂布局识别准确率。 +- **添加图像预处理** – 使用 Pillow 或 OpenCV 对图像进行去倾斜、去噪或二值化,在 OCR 前提升效果。 + +所有这些思路都基于我们已经构建的核心函数,无需从头开始。 + +--- + +## 结论 + +我们已经完整演示了如何在 Python 中 **从图像中提取文本**,涵盖了从 **以 python 方式列出图像文件** 到 **从图片中识别文本**,再到 **将扫描图像转换为文本** 的整套批量流程。该脚本故意保持简洁,却足够灵活,可作为更大项目的基础——无论是数字化收据、构建可搜索档案,还是驱动数据抽取管道。 + +动手试一试,调整预处理步骤,观察 OCR 准确率的提升。如果遇到问题,回顾 “常见问题处理” 表格;大多数问题都能通过微调配置解决。 + +准备好迎接下一个挑战了吗?尝试使用 `pdf2image` 添加 PDF‑转‑图像步骤,然后将生成的图像直接喂入同一管道。结合 OCR 与 Python 丰富的生态系统,可能性无限。 + +祝编码愉快,愿你的文本永远清晰可读! + + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在已有技巧之上进一步提升。每篇资源都提供完整可运行的代码示例和逐步解释,助你掌握更多 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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/chinese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..4c7ce415c --- /dev/null +++ b/ocr/chinese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Python OCR 从图像中提取文本。在简明教程中学习自动语言检测、并行处理和批量识别。 +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: zh +og_description: 使用 Python OCR 从图像中提取文本。本指南在一个教程中展示自动语言检测、并行处理和批量识别。 +og_title: 在 Python 中从图像提取文本 – 完整 OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 使用Python从图像中提取文本 – 完整OCR指南 +url: /zh/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 从图像中提取文本 – 完整 OCR 指南 + +是否曾想过 **从图像中提取文本** 而不必手动输入每个单词?你并不孤单。无论是数字化旧收据、构建可搜索的文档档案,还是仅仅玩转酷炫的 AI 技巧,从图片中提取文字都是当今任何 Python 开发者的必备技能。 + +在本教程中,我们将演示一个完整、可直接运行的示例,使用流行的 OCR 引擎 **从图像中提取文本**。我们会涵盖自动语言检测、并行处理加速以及批量图像识别,让你在几秒钟内处理数十个文件。听起来正是你需要的?让我们开始吧。 + +## 你将学到 + +- 如何使用 `ocr.OcrEngine` 实例化 OCR 引擎。 +- 启用 **自动语言检测**,让引擎自行选择合适的语言。 +- 使用自定义线程池配置 **并行处理 OCR**。 +- 对文件列表执行 **批量图像识别**。 +- 为每张图像打印识别出的文本,便于保存或建立索引。 + +无需外部文档——所有内容都在这里,代码开箱即用,只需安装 `ocr` 包(通过 `pip install ocr`)。 + +## 前置条件 + +在开始之前,请确保你已具备: + +1. 已安装 Python 3.8 或更高版本。 +2. 已安装 `ocr` 包(`pip install ocr`)。 +3. 一个存放 PNG(或 JPG)图像的文件夹。 +4. 对 Python 函数和循环有基本了解。 + +就是这么简单——没有繁重的依赖,没有 GPU 魔法,纯粹的 Python。 + +![从图像中提取文本示例](https://example.com/ocr-demo.png "显示从图像中提取文本输出的截图") + +*Alt text: 从图像中提取文本演示截图* + +## 第一步 – 设置 OCR 引擎(关键字示例) + +首先,创建一个 OCR 引擎实例。把 `ocr.OcrEngine()` 当作背后的“大脑”;它知道如何读取字符、行和段落。 + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +为什么需要显式创建引擎?因为 **ocr.OcrEngine 的使用** 让你能够细粒度地控制语言设置、线程等。相较于一行代码的快捷方式,这是最灵活的 **从图像中提取文本** 方式。 + +## 第二步 – 让引擎自动检测语言 + +大多数 OCR 库都要求你手动指定语言。这对单语言项目还算可以,但对混合语言的批处理来说非常繁琐。幸运的是,`ocr` 包支持 **自动语言检测**。 + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +将 `engine.language` 设置为 `ocr.Language.Auto`,引擎会嗅探每张图像并挑选合适的语言模型。当你处理国际化文档时,这一行代码可以为你省去数小时的手动配置。 + +## 第三步 – 使用并行处理加速 OCR + +如果你的机器有四核或以上的 CPU,何不充分利用它们?引擎可以启动线程池,让多张图像同时被处理。这正是 **并行处理 OCR** 发光发热的地方。 + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +根据你的机器自行调整数字 `4`。线程数越多 → 批处理越快,但请记住每个线程都会占用内存,找到适合你环境的平衡点。 + +## 第四步 – 收集待处理的图像 + +现在我们需要一个文件路径列表。你可以手动构建、从 CSV 读取,或使用 `glob`。为保持清晰,这里直接硬编码一个短列表: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +将 `YOUR_DIRECTORY` 替换为你系统中的实际路径。如果文件数量很多,使用 `glob.glob("*.png")` 可以轻松完成收集。 + +## 第五步 – 运行批量图像识别 + +下面是教程的核心:一次调用即可处理 `files` 中的所有图像,并返回结果对象列表。这就是让大规模 OCR 成为可能的 **批量图像识别** 功能。 + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +在内部,引擎会把每个文件分配到之前配置的四个工作线程,同时为每张图片自动检测语言。该方法返回的列表中,每个元素都包含识别出的文本及其元数据。 + +## 第六步 – 打印(或存储)提取的文本 + +最后,我们遍历结果并打印文本。在真实项目中,你可能会把它写入数据库或 CSV 文件,但这里直接打印更便于演示。 + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**预期输出**(为简洁起见已截断): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +每个块显示文件名后跟 OCR 生成的字符串。如果图像包含多种语言,你会看到相应的字符出现,这得益于前面的 **自动语言检测** 步骤。 + +## 专业技巧与常见陷阱 + +- **图像质量至关重要**——模糊或低对比度的图片会产生垃圾输出。必要时可使用 OpenCV(`cv2.threshold`、`cv2.resize`)进行预处理。 +- **线程数 vs. I/O**——如果图像存放在慢速网络磁盘上,增加线程数可能帮助不大。使用 `top` 或任务管理器监控 CPU 使用率。 +- **Unicode 处理**——`result.text` 为 Unicode 字符串。写入文件时请使用 `encoding="utf‑8"`,避免 `UnicodeEncodeError`。 +- **内存占用**——大批量 PDF 可能消耗大量 RAM。若出现 `MemoryError`,请降低线程池大小或分批处理图像。 + +## 完整可运行脚本 + +以下是完整的、可直接复制粘贴的脚本,囊括了我们讨论的所有步骤。将其保存为 `batch_ocr.py` 并运行 `python batch_ocr.py`。 + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +运行方式如下: + +```bash +python batch_ocr.py ./my_images 4 +``` + +你将看到每张图像对应的整齐文本块,证明你可以 **大规模从图像中提取文本**。 + +## 接下来可以做什么? + +掌握了使用 Python **从图像中提取文本** 的基础后,建议进一步探索: + +- **后处理**:使用正则或自然语言库清理 OCR 输出。 +- **PDF 转换**:将提取的字符串喂入 PDF 生成器,制作可搜索的 PDF。 +- **云 OCR 服务**:将本地 `ocr` 结果与 Google Vision、Azure OCR 等云服务对比,提升边缘案例的准确率。 +- **GUI 前端**:构建一个小型 Flask 或 FastAPI 应用,让用户上传图像并即时看到提取的文本。 + +这些主题都基于你刚刚搭建的 **Python OCR 库** 基础,并且同样受益于我们在本教程中使用的 **并行处理 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 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/chinese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/chinese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..078b212c8 --- /dev/null +++ b/ocr/chinese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-19 +description: 如何使用 OCR 在 Python 中提取 PDF – 步骤详解教程,涵盖从 PDF 提取文本、从图像识别文本以及 OCR Python + 示例。 +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: zh +og_description: 如何使用 Python 通过 OCR 提取 PDF。学习从 PDF 中提取文本、从图像中识别文本,并查看完整的 OCR Python + 示例。 +og_title: 如何使用 Python OCR 提取 PDF 文本 – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: 如何在 Python 中使用 OCR 提取 PDF 文本——完整指南 +url: /zh/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 OCR 在 Python 中提取 PDF 文本 – 完整指南 + +是否曾想过 **如何提取 PDF** 内容,而文件仅是扫描的图像?你并不孤单。在许多真实项目中——比如合同、发票或历史档案——收到的 PDF 没有可选取的文本。好消息是,只需几行 Python 代码,就能将这些仅图像的页面转换为可搜索、可编辑的文本。 + +在本教程中,我们将通过一个实用的 **OCR Python 示例**,演示如何读取 PDF、将其首页渲染为图像,然后使用 OCR 引擎 **从 PDF 中提取文本**。完成后,你将清楚地了解 **如何使用 OCR 读取 PDF**、每一步的意义,以及如何将代码扩展到多页文档或不同语言。 + +## 您将学习的内容 + +- 为 Python 安装并配置可靠的 OCR 库。 +- 将 PDF 页面转换为适合 OCR 的图像。 +- **从图像识别文本** 并获取干净的 Unicode 字符串。 +- 常见陷阱(低分辨率 PDF、页面旋转)及其规避方法。 +- 扩展脚本以处理多页或批量处理。 + +**前置条件**:Python 3.8+、pip,以及对虚拟环境的基本了解。无需任何 OCR 经验——只需跟随操作即可。 + +--- + +## ## 使用 OCR 在 Python 中提取 PDF 文本 + +此 H2 标题正好包含我们的主要关键词,符合搜索引擎的喜好。让我们直接进入代码。 + +### Step 1 – Install the Required Packages + +首先,我们需要一个 OCR 引擎。下面的示例使用流行的 **ocr** 包(Tesseract 的轻量封装)。如果你更倾向于其他后端,概念保持不变。 + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **专业提示:** 在 Linux 上,你还需要安装 Tesseract 二进制文件:`sudo apt-get install tesseract-ocr`。macOS 用户可以通过 Homebrew 安装:`brew install tesseract`。 + +### Step 2 – Initialize the OCR Engine and Set Language + +现在我们启动引擎并指定使用英文字符。你可以将 `ocr.Language.English` 替换为任意受支持的语言代码。 + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**为什么重要:** 指定语言可以显著提升准确率,因为引擎能够使用语言特定的词典和字符模型。 + +### Step 3 – Load a PDF Page as an Image + +OCR 只能处理光栅图像,而不是 PDF 对象。`ocr.Image.from_pdf` 辅助函数会将指定页面渲染为位图。通过修改 `page_number` 可选择其他页面(从 0 开始计数)。 + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **特殊情况:** 如果 PDF 包含矢量图形而非扫描图像,你可能会得到清晰的渲染。对于低分辨率扫描,建议提升 DPI:`ocr.Image.from_pdf(..., dpi=300)`。 + +### Step 4 – Recognize Text from the Rendered Image + +下面是 **ocr python 示例** 的核心。引擎处理位图并返回包含提取字符串的对象。 + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +`ocr_result.text` 属性保存纯文本输出,并在可能的情况下保留换行。 + +### Step 5 – Print or Store the Extracted Text + +最后,我们输出结果。在实际应用中,你可能会将其写入文件或数据库。 + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +运行脚本后应显示类似如下内容: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +这就是使用 OCR 完整的 **从 PDF 提取文本** 工作流。 + +--- + +## ## 从图像识别文本 – 调整准确度 + +如果你只关心 **从图像识别文本**(例如收据的 JPEG),可以跳过 PDF 转换步骤: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**提升效果的技巧:** + +- **预处理** 图像:转换为灰度、应用阈值或去倾斜。Pillow 可以轻松完成。 +- **提升 DPI**:在 PDF 渲染时使用更高分辨率,可为 OCR 引擎提供更多细节。 +- **启用 OCR 引擎的页面分割配置**(`ocr_engine.config = "--psm 6"` 用于均匀块)。 + +## ## 使用 OCR 读取 PDF – 处理多页 + +大多数合同都有多页。遍历每一页非常简单: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +此函数 **使用 OCR 读取 PDF**,将输出拼接,并插入明确的分页标记。随后你可以将 `full_text` 导入搜索索引或保存为 `.txt` 文件。 + +## ## 常见问题及解决方案 + +| 症状 | 可能原因 | 解决办法 | +|------|----------|----------| +| 字符乱码,出现大量 `?` | 语言设置错误或缺少语言数据文件 | 安装正确的 Tesseract 语言包(`tesseract-ocr-`)并设置 `ocr_engine.language`。 | +| 行缺失或单词截断 | DPI 过低(低于 150) | 将 PDF 渲染为 300 DPI 或更高(`dpi=300`)。 | +| 文本旋转或倒置 | 扫描页未正向放置 | 在识别前使用 `ocr.Image.deskew(page_image)` 进行去倾斜。 | +| 大型 PDF 处理缓慢 | 单线程顺序处理页面 | 使用 `concurrent.futures.ThreadPoolExecutor` 并行化。 | + +## ## 扩展 OCR Python 示例 + +- **导出为 PDF/A**:提取后,可使用 `reportlab` 或 `pypdf2` 将文本嵌入可搜索的 PDF。 +- **语言检测**:利用 `langdetect` 对 OCR 输出进行检测,动态切换 `ocr_engine.language`。 +- **批量处理**:使用 `os.listdir` 遍历目录,对每个文件调用 `extract_all_pages`。 + +## ## 预期输出与验证 + +对清晰的英文扫描件运行脚本时,应看到带有正确标点的整洁文本块。验证方法: + +1. 将几行文本与原始扫描图像对比。 +2. 运行简单的词数统计(`len(ocr_result.text.split())`),确保输出非空。 +3. 可选:将结果送入 `pyspellchecker` 等拼写检查器,发现 OCR 错误。 + +## 结论 + +我们已经介绍了在传统解析失效时 **如何提取 PDF** 内容,演示了完整的 **ocr python 示例**,并说明了如何 **从图像识别文本** 与 **使用 OCR 读取 PDF**,无论是单页还是多页场景。借助上述代码片段,你现在可以将任何扫描 PDF 转换为可搜索、可编辑的文本——再也不需要手动重新输入。 + +下一步?尝试将语言切换为西班牙语(`ocr.Language.Spanish`),或实验图像预处理技术以提升准确度。如果你在构建文档管理系统,考虑使用 Elasticsearch 对提取的文本进行索引,以实现闪电般的搜索。 + +有问题或遇到奇怪的 PDF?留下评论,祝编码愉快! + +![使用 OCR 在 Python 中提取 PDF](image.png "使用 OCR 在 Python 中提取 PDF") + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题。每个资源都提供完整可运行的代码示例,并配有逐步解释,帮助你掌握更多 API 功能并在自己的项目中探索替代实现方案。 + +- [使用 Aspose OCR 从图像提取文本 – 步骤指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [识别 PDF 文本 – Aspose.OCR for Java 的 OCR 操作](/ocr/english/java/ocr-operations/) +- [使用 Aspose.OCR 进行语言选择的 C# 图像文字提取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/chinese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..3e2e8e324 --- /dev/null +++ b/ocr/chinese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-19 +description: 学习如何在 Java 中使用 Aspose 的 OCR。本分步指南涵盖自动纠正图像倾斜、自动语言检测以及轻松提取图像文字。 +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: zh +og_description: 如何在 Java 中使用 Aspose 进行 OCR:完整教程,涵盖自动纠正倾斜图像、自动语言检测以及从图片中提取文本。 +og_title: 如何在 Java 中使用 Aspose 进行 OCR – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: 如何在 Java 中使用 Aspose 进行 OCR – 完整指南 +url: /zh/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Java 中使用 Aspose OCR – 完整指南 + +是否曾经想过 **如何在 Java 项目中使用 OCR** 而不被繁琐的配置弄得抓狂?你并不是唯一的遇到这种情况的人。许多开发者在需要 **提取图像文字** 数据时会卡住,尤其是当源扫描图像倾斜或使用未知语言时。 + +在本教程中,我们将通过一个动手示例,完整展示如何使用 Aspose 的 OCR,包括 **自动纠正倾斜图像**、**自动语言检测**,以及完整的 **ocr 图像预处理** 流程。结束时,你将拥有一个可直接运行的代码片段,它会将识别的文本打印到控制台,并且你会明白每个设置背后的意义。 + +> **你将获得:** 一个完整、可运行的 Java 程序,对每行代码的解释,处理边缘情况的技巧,以及将解决方案扩展到批处理或 PDF 的思路。 + +--- + +## 前置条件 + +- 已安装并配置 Java 17(或任意较新 JDK)。 +- 用于依赖管理的 Maven 或 Gradle(我们将展示 Maven 坐标)。 +- Aspose OCR for Java 授权文件 (`Aspose.OCR.Java.lic`)。如果仅作测试,可以跳过授权步骤,但免费试用版会添加水印。 +- 一个示例图像 (`your_image.png`),放置在代码可访问的位置。 + +> **专业提示:** 将图像放在专用的 `resources` 文件夹中,并通过类路径加载;这样可以避免在不同操作系统上出现路径相关的麻烦。 + +--- + +## 第一步:创建项目并添加 Aspose OCR 依赖 + +创建一个新的 Maven 项目(或使用已有项目),并在 `pom.xml` 中加入以下内容: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +运行 `mvn clean install` 拉取库。如果你更喜欢 Gradle,等价写法是: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +现在,**ocr 图像预处理** 类已经在你的类路径上。 + +--- + +## 第二步:应用 Aspose OCR 授权(可选但推荐) + +如果你拥有授权文件,请在 `main` 方法的开头立即应用它。跳过此步骤也能运行,但免费版会在输出上加上 “Demo” 水印。 + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **为什么重要:** 授权版移除使用限制并关闭水印,能够得到干净、可用于生产的结果。 + +--- + +## 第三步:创建 OCR 引擎实例 + +引擎是整个流程的核心。实例化它后,你即可访问所有 **ocr 图像预处理** 选项。 + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +此时引擎已准备就绪,但会使用默认设置,这些设置对扫描文档并不一定最佳。接下来我们对几项参数进行微调。 + +--- + +## 第四步:启用自动纠正倾斜图像以获得更清晰的扫描 + +倾斜的扫描图像是常见痛点。Aspose 提供 **自动纠正倾斜图像** 功能,能够在识别前自动将图片校正为正向。 + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **工作原理:** 算法分析文本基线角度并将图像旋转到最可能的正立方向。这对使用手机拍摄的照片准确率提升显著。 + +--- + +## 第五步:开启自动语言检测 + +如果你不知道源图像的语言,让引擎自行判断。这就是 **自动语言检测** 设置。 + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +开启后,Aspose 会扫描字形并选取最可能的语言模型,开箱即支持超过 30 种语言。 + +--- + +## 第六步:加载待识别的图像 + +你可以从磁盘、URL,甚至字节数组加载图像。为简便起见,这里从本地文件读取。 + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **提示:** 若处理大图像,建议先使用 `engine.getImagePreprocessing().setResizeFactor(0.5)` 降采样,以加快处理速度且细节损失不大。 + +--- + +## 第七步:执行 OCR 识别并提取文本图像 + +现在引擎开始工作。`recognize` 方法返回一个 `OcrResult` 对象,里面包含识别的文本、置信度分数等信息。 + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +控制台将显示从图片中提取的纯文本——这正是我们期望实现的 **提取图像文字** 结果。 + +--- + +## 完整可运行示例 + +下面是把所有步骤串联起来的完整 Java 类。复制粘贴到 `src/main/java/com/example/OcrDemo.java` 并运行它。 + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### 预期输出 + +如果图像中包含 “Hello World” 且扫描清晰,你会看到: + +``` +=== Recognized Text === +Hello World +``` + +对于更复杂的文档(例如多语言收据),输出会包含换行符以及检测到的语言代码。 + +--- + +## 常见陷阱与专业技巧 + +| 问题 | 产生原因 | 解决方案 | +|------|----------|----------| +| **出现乱码** | 图像过暗或噪声过多。 | 启用 `engine.getImagePreprocessing().setBinarization(true)` 或手动调节对比度。 | +| **语言识别错误** | 自动检测在混合语言页面上失效。 | 使用 `engine.setLanguage(Language.English)`(或相应的枚举)强制指定语言。 | +| **处理速度慢** | 超高分辨率图像。 | 使用 `engine.getImagePreprocessing().setResizeFactor(0.5)` 降低分辨率。 | +| **内存溢出** | 一次性加载大量图像。 | 顺序处理图像,并在每次运行后调用 `engine.dispose()`。 | + +> **记住:** OCR 引擎对只读操作是线程安全的,但为每个线程创建新实例可以避免隐藏的状态错误。 + +--- + +## 扩展方案 + +既然已经掌握了 **如何使用 Aspose OCR**,你可以进一步: + +1. **处理 PDF** – 使用 `PdfConverter` 将每页 PDF 转为图像,再送入相同的流水线。 +2. **批量处理文件夹** – 遍历目录中的文件,执行相同步骤,并将结果写入 CSV。 +3. **集成到 Web 服务** – 通过 Spring Boot `@RestController` 暴露 OCR 逻辑,接受 multipart 上传。 + +上述所有场景都复用了我们在本指南中构建的 **ocr 图像预处理** 配置。 + +--- + +## 结论 + +我们从头到尾完整演示了 **如何在 Java 中使用 Aspose OCR**:应用授权、创建引擎、开启 **自动纠正倾斜图像**、启用 **自动语言检测**、加载图像,最后通过单行 `System.out.println` **提取图像文字**。代码独立完整,可在任何近期 JDK 上运行,并展示了准确性与性能的最佳实践。 + +试着用自己的图片跑一遍——比如扫描的合同或收据截图。调节预处理标志,尝试不同语言,你会快速体会到 Aspose OCR 库在生产级文本提取中的优势。 + +有问题或想分享成果?在下方留言或在 GitHub 上私信我。祝编码愉快! + +--- + +![在 Java 中使用 OCR 示例](/images/ocr-java-example.png "在 Java 中使用 OCR – Aspose 演示截图") + + +## 接下来你应该学习什么? + +以下教程与本指南所示技术紧密相关,帮助你进一步掌握 API 功能并探索在项目中的其他实现方式,每篇都附有完整可运行的代码示例和逐步说明。 + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/chinese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..ff26c4d30 --- /dev/null +++ b/ocr/chinese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Aspose OCR 在 Python 中提升 OCR 准确率。学习如何设置 OCR 语言、加载用于 OCR 的图像,以及使用自定义词典从图像中提取文本。 +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: zh +og_description: 通过设置 OCR 语言、加载 OCR 图像,并使用自定义词典从图像中提取文本,提升 Python 中的 OCR 准确率。 +og_title: 在 Python 中提升 OCR 准确率 – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: 在Python中提升OCR准确率 – 完整指南 +url: /zh/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中提升 OCR 准确率 – 完整指南 + +是否曾想过在扫描的文本中出现奇怪符号、产品代码或品牌名称时,**提升 OCR 准确率**?你并不孤单。在许多项目中,默认引擎只会输出乱码,这会严重影响生产力。 + +在本教程中,我们将通过一个实用的端到端示例,展示如何 **设置 OCR 语言**、**加载 OCR 图像**、**对图像执行 OCR**,以及最终 **使用自定义词典提取图像文本**,从而提升识别率。完成后,你将拥有一个可直接运行的脚本,能够嵌入任何 Python 代码库。 + +## 你将收获什么 + +- 一个完整的 Python 脚本,使用 Aspose OCR 读取 PNG 文件。 +- 通过配置语言和自定义词表来 **提升 OCR 准确率** 的能力。 +- 对每个设置为何重要的清晰解释,以及处理非拉丁字符等边缘情况的技巧。 +- 常见 OCR 陷阱的快速排查清单。 + +### 前置条件 + +- 已在机器上安装 Python 3.8 或更高版本。 +- `aspose-ocr` 包(通过 `pip install aspose-ocr` 安装)。 +- 包含待读取文本的示例图像(`technical_doc.png`)。 +- 对 Python 有基本了解——无需高级技巧。 + +> **专业提示:** 如果你在虚拟环境中工作,请在安装包之前激活它。这可以保持依赖整洁,避免版本冲突。 + +--- + +## 第一步:安装并导入 Aspose OCR + +首先——将库加入我们的环境并导入所需组件。 + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr` 命名空间提供了 `OcrEngine` 类,它是 OCR 过程的核心。在这里导入它可以让脚本其余部分保持简洁易读。 + +--- + +## 第二步:创建 OCR 引擎并 **设置 OCR 语言** + +语言为何重要?OCR 引擎依赖语言特定的模型来识别字符形状和词汇模式。如果告诉引擎你正在扫描英文文本,它会忽略西里尔字形,专注于拉丁字母,从而显著 **提升 OCR 准确率**。 + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **注意:** Aspose OCR 支持超过 50 种语言。若文档不是英文,可将 `ocr.Language.English` 替换为 `ocr.Language.Spanish`、`ocr.Language.French` 等。 + +--- + +## 第三步:定义 **自定义词典** 以提升准确率 + +想象你在扫描包含 “AsposeOCR” 或类似 “SKU12345” 的发票。引擎不认识这些词,会错误猜测。提供自定义词表相当于告诉引擎:*“这些字符串是合法的——不要尝试纠正它们。”* 这是一种快速提升 **OCR 准确率** 的方法。 + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +如果有上百条条目,你可以从文件或数据库加载——这里为简便起见直接使用 Python 列表。 + +--- + +## 第四步:**加载 OCR 图像** + +现在我们需要一张图像。`Image.load` 方法接受任意受支持的光栅格式路径(PNG、JPEG、BMP 等)。若文件未找到,引擎会抛出异常,因此我们需要进行防护。 + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **此步骤重要原因:** 正确加载图像可确保引擎使用你想要分析的像素数据。损坏的文件或错误的路径是常见的烦恼来源。 + +--- + +## 第五步:**对图像执行 OCR** 并提取结果 + +在引擎配置好且图像准备就绪后,实际识别只需一次方法调用。结果对象包含原始文本、置信度分数,甚至还有布局信息(如需后续使用)。 + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +如果需要 **逐行提取图像文本**,可以按换行符拆分: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## 第六步:验证输出 – 真正 **提升 OCR 准确率** 了吗? + +让我们打印结果,看看自定义词典是否产生了效果。 + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +示例图像的典型输出可能如下: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +可以看到品牌名、希腊字符以及产品代码都准确呈现。若没有自定义词典,引擎会尝试“纠正”,常出现 “Aspose OCR” 或 “SKU 1234” 等错误。 + +--- + +## 常见陷阱及解决方案 + +| 问题 | 产生原因 | 解决办法 | +|------|----------|----------| +| **乱码字符** | 语言设置错误或分辨率过低 | 确保 `engine.language` 与源语言匹配,并使用高 DPI 扫描(300 dpi 以上)。 | +| **自定义词被忽略** | 词典未关联或属性名拼写错误 | 再次检查 `engine.text_processing.custom_dictionary = …`。 | +| **文件未找到** | 路径错误或缺少文件权限 | 使用 `os.path.abspath()` 验证绝对路径;以合适权限运行脚本。 | +| **处理慢** | 图像过大或页数过多 | 预处理图像(裁剪、缩放)或使用 `engine.recognize(image, max_threads=4)` 并行化。 | + +--- + +## 更进一步:针对 **提升 OCR 准确率** 的高级调优 + +1. **预处理** – 在将图像交给 Aspose OCR 前,使用 Pillow 进行对比度增强或二值化。 +2. **多语言** – 设置 `engine.language = ocr.Language.English | ocr.Language.French` 以实现双语识别。 +3. **区域 OCR** – 若只需特定区域(如表格),先裁剪图像以降低噪声。 +4. **置信度过滤** – `result.confidence` 提供每个字符的分数,可编程剔除低置信度结果。 + +--- + +## 完整可运行脚本 + +下面是完整的、可直接复制粘贴的脚本,涵盖我们讨论的所有步骤。将其保存为 `improve_ocr_accuracy.py` 并在命令行运行。 + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +运行方式: + +```bash +python improve_ocr_accuracy.py +``` + +你应当会看到前文展示的整齐输出。 + +--- + +## 结论 + +我们刚刚介绍了一种在 Python 中 **提升 OCR 准确率** 的简洁方法,步骤如下: + +1. **设置 OCR 语言** 以匹配文档。 +2. **正确加载图像**,确保引擎读取到正确像素。 +3. **对图像执行 OCR**,只需一次方法调用。 +4. **提取图像文本** 并验证结果。 +5. **添加自定义词典**,锁定领域专有词汇。 + +这就是从原始图片到干净、可搜索文本的完整工作流,封装在一个整洁、可复用的脚本中。 + +如果你准备好迎接下一个挑战,尝试对图像进行预处理(对比度、去倾斜),或使用 `ocr.Language.English | ocr.Language.German` 进行多语言设置。相同的原则同样适用于更广泛的文档,帮助你持续 **提升 OCR 准确率**。 + +有疑问或遇到奇怪的边缘情况?在下方留言吧,祝编码愉快! + +![improve OCR accuracy + + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在已有技巧之上进一步深入。每篇资源都提供完整可运行的代码示例以及逐步解释,助你掌握更多 API 功能并探索项目中的替代实现方式。 + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/chinese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..b445d25c4 --- /dev/null +++ b/ocr/chinese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Python 的 OCR 库对图像进行 OCR。学习如何从图像中检测文本、从 JPEG 中识别文本,以及高效地从扫描图像中提取文本。 +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: zh +og_description: 使用 Python 对图像进行 OCR 并从扫描文件中提取文本。本指南将一步步带您完成图像加载、去倾斜和文本识别。 +og_title: 在 Python 中对图像进行 OCR – 完整文本提取指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: 在 Python 中对图像进行 OCR – 完整文本提取指南 +url: /zh/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中对图像执行 OCR – 完整文本提取指南 + +是否曾经需要**对图像执行 OCR**但因为代码晦涩而卡住?你并不是唯一遇到这种情况的人。无论是将一堆扫描的收据转换为可搜索的 PDF,还是从 JPEG 中提取标题用于数据科学项目,能够识别 JPEG 等格式中的文本是当今每个开发者必备的技能。 + +在本教程中,我们将逐步演示一个完整且可运行的示例,展示如何**从图像中检测文本**文件、**从扫描图像中提取文本**文档,甚至**加载图像进行 OCR**,仅需几行代码。完成后,你将拥有一个可靠的、可直接用于生产环境的代码片段,能够直接嵌入自己的项目——无需缺失的导入,也不需要模糊的“查看文档”快捷方式。 + +## 你将构建的内容 + +- 一个小型的 Python 脚本,用于创建 OCR 引擎、启用自动去倾斜、加载 JPEG(或任何受支持的格式),并打印识别的文本。 +- 解释每个设置**为何**重要,而不仅仅是**如何**编写。 +- 提供处理多页 PDF、非英文语言以及常见问题(如模糊扫描)的技巧。 + +### 前置条件 + +- 已安装 Python 3.8+(示例使用通过 `pip install ocr-lib` 获得的 `ocr` 包——请替换为实际使用的库名)。 +- 对 Python 函数和虚拟环境有基本了解。 +- 一张你想要处理的图像文件(JPEG、PNG、TIFF),我们将使用 `skewed_page.jpg` 作为占位符。 + +> **专业提示:**如果你使用 Windows,在安装 OCR 库时请以管理员身份运行终端,以避免权限问题。 + +--- + +## 对图像执行 OCR – 设置与配置 + +首先,你需要一个干净的 OCR 引擎实例。可以把它看作操作背后的“大脑”;如果配置不当,即使是最清晰的图像也会返回乱码。 + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**为什么这很重要:** +设置 `engine.language` 可以限定 OCR 引擎预期的字符集,显著提升准确率。如果省略此设置,引擎会自行猜测,常常误读简单词汇。 + +--- + +## 启用自动去倾斜 – 修正倾斜扫描 + +扫描的页面很少是完全平整的。轻微的倾斜会导致字符分割错误,把 “Hello” 变成 “H3llo”。`auto_deskew` 标志会为你完成这项繁重的工作。 + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**边缘情况:**如果你确信图像已经是正的,禁用去倾斜可以节省几毫秒的处理时间——在批量处理数千页时非常有用。 + +--- + +## 加载图像进行 OCR – 支持 JPEG、PNG、TIFF + +现在我们真正**加载图像进行 OCR**。`ocr.Image.load` 方法非常灵活;它接受任意受支持的栅格格式的路径。 + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **为什么此步骤至关重要:**库会将文件读取为内部位图,并进行必要的颜色空间转换。如果跳过此步骤直接传入原始字节流,会抛出 `FileNotFoundError`,甚至更糟,悄悄产生空结果。 + +如果你需要专门**从 JPEG 文件中识别文本**,只需确保文件扩展名为 `.jpeg` 或 `.jpg`。同样的调用对 PNG(`.png`)或 TIFF(`.tif`)同样适用,无需修改。 + +--- + +## 对图像执行 OCR – 运行引擎 + +引擎已准备好且图像已加载到内存,现在是**对图像执行 OCR**的时刻。这一行代码完成了繁重的工作:预处理、分割、分类以及文本组装。 + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**内部发生了什么?** +- 引擎应用去倾斜变换(如果已启用)。 +- 它运行神经网络或 Tesseract 后端来识别字符。 +- 最后,它将字符拼接成单词和行,返回一个丰富的 `result` 对象。 + +--- + +## 从扫描图像中提取文本 – 输出结果 + +最后一步是**从扫描图像中提取文本**并显示。`result.text` 属性包含纯文本表示。 + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +典型的输出如下: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +如果 OCR 引擎未能找到任何字符,`result.text` 将为空字符串。此时,请再次检查图像质量,或考虑调整 `engine.confidence_threshold` 属性(如果你的库支持)。 + +--- + +## 处理常见变体 + +### 从 JPEG 与 PNG 识别文本 + +两种格式均受支持,但 JPEG 压缩可能产生干扰引擎的伪影。如果你发现频繁误识别,尝试先将 JPEG 转为 PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### 检测多语言图像文本 + +如果文档中混合了英语和西班牙语,请设置多语言模式: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +引擎将在识别时同时考虑这两套字母表。 + +### 从扫描的 PDF 中提取文本 + +对于 PDF,需要先将每页栅格化为图像。`pdf2image` 等库可以轻松完成此操作: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## 完整可运行示例 + +下面是完整的脚本,你可以复制粘贴到 `ocr_demo.py` 文件中。它包括错误处理以及一个用于测量执行时间的小助手。 + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**预期输出**(假设扫描清晰): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## 常见问题 + +**Q: 我可以在无头服务器上运行吗?** +A: 当然可以。该库无需 GUI 即可工作,只需确保服务器上已安装必要的本地二进制文件(例如 Tesseract)。 + +**Q: 如果图像模糊怎么办?** +A: 可以在 `engine.recognize` 之前添加锐化滤镜。许多 OCR 库提供 `image_preprocessing.sharpen = True`,或者你可以使用 OpenCV 的 `cv2.GaussianBlur` 的逆操作。 + +**Q: 脚本支持批量处理吗?** +A: 支持。将 `perform_ocr` 包裹在遍历文件路径列表的循环中, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/chinese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..b521facb6 --- /dev/null +++ b/ocr/chinese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Aspose OCR Java 对图像进行 OCR。了解如何加载图像进行 OCR、使用 Aspose 许可证,并在几分钟内从图像中提取文本。 +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: zh +og_description: 使用 Aspose OCR Java 对图像执行 OCR。本指南展示如何使用 Aspose 许可证、加载图像进行 OCR,并高效提取图像中的文本。 +og_title: 使用 Aspose OCR Java 对图像进行 OCR – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: 使用 Aspose OCR Java 对图像进行 OCR – 完整的逐步指南 +url: /zh/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose OCR Java 对图像执行 OCR – 完整分步指南 + +是否曾需要对图像文件进行 **perform OCR on image**,但不确定哪个库能在无需大量配置的情况下提供可靠的结果?你并不孤单。在许多实际项目中——比如扫描护照、数字化发票或从截图中提取文本——快速识别图像文字数据的能力是改变游戏规则的关键。 + +在本教程中,我们将通过一个动手示例,准确展示如何使用 Aspose OCR for Java **perform OCR on image**。我们将涵盖从应用 Aspose 许可证到加载图片、运行引擎,最后 **extract text from image** 以便在后续使用的全部步骤。没有冗余,只提供一个可直接复制粘贴的可运行解决方案。 + +## 您将收获的内容 + +- 在 Java 项目中如何 **use Aspose license** 的清晰概念。 +- 需要的 **load image for OCR** 代码,并让引擎自动检测语言。 +- 逐步说明如何安全地 **recognize text image** 内容以及 **extract text from image**。 +- 处理常见陷阱的技巧(空结果、不支持的格式和内存问题)。 + +> **先决条件** – Java 8 或更高版本,Maven 或 Gradle 用于依赖管理,以及 Aspose OCR for Java 许可证文件(或可在评估模式下运行)。 + +## 如何使用 Aspose OCR Java 对图像执行 OCR + +下面是完整的、可直接运行的 Java 程序,演示整个流程。将其保存为 `AsposeOcrDemo.java` 并在 IDE 或命令行中运行。 + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### 预期的控制台输出 + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +如果在没有许可证文件的情况下运行程序,第一行只会说明你处于评估模式,但 OCR 仍然可以工作。 + +## 设置并使用 Aspose 许可证 + +### 为什么许可证很重要 + +在评估模式下运行库对于快速测试来说没问题,但它会在输出中添加水印,并限制每次运行可处理的页数。执行 **use aspose license** 步骤可移除这些限制,并向 Aspose 表明您是付费客户。 + +### 如何获取并应用许可证 + +1. 从 Aspose 商店购买许可证。 +2. 下载 `Aspose.OCR.Java.lic` 文件。 +3. 将其放置在应用程序可读取的位置——通常是 `src/main/resources` 文件夹。 +4. 在任何 OCR 操作之前调用 `new License().setLicense("Aspose.OCR.Java.lic");`,如上面的代码所示。 + +> **专业提示**:如果部署到服务器,使用绝对路径或类路径资源加载器以避免 `FileNotFoundException`。 + +## 加载用于 OCR 处理的图像 + +`Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` 这一行是 **load image for OCR** 步骤的核心。Aspose OCR 支持多种格式:PNG、JPEG、BMP、TIFF,甚至在结合 Aspose.Pdf 时支持多页 PDF。 + +### 常见陷阱 + +| Issue | Symptom | Fix | +|-------|---------|-----| +| 错误的文件路径 | `FileNotFoundException` | 再次检查路径;使用 `Paths.get(...)` 以获得跨 OS 的分隔符。 | +| 不支持的格式 | `UnsupportedOperationException` | 在加载前将图像转换为 PNG 或 JPEG。 | +| 大图像(> 10 MP) | 内存不足错误 | 使用 `java.awt.Image` 在提供给 Aspose 前先缩小图像。 | + +## 从图像提取文本并处理结果 + +OCR 引擎完成后,`OcrResult` 对象包含识别出的字符串。这就是我们 **extract text from image** 用于后续处理的地方——保存到数据库、写入搜索索引或供下游 NLP 流水线使用。 + +### 处理多语言 + +由于我们设置了 `engine.setLanguage(Language.Auto)`,Aspose 将实时尝试检测语言。如果您事先知道语言(例如所有文档都是俄语),可以将 `Language.Auto` 替换为 `Language.Russian` 以提升性能。 + +### 后处理技巧 + +- **Trim whitespace**:`result.getText().trim()`。 +- **Normalize line endings**:`result.getText().replace("\r\n", "\n")`。 +- **Remove non‑printable characters**:使用正则表达式,例如 `result.getText().replaceAll("[^\\p{Print}]", "")`。 + +## 使用高级选项识别文本图像(可选) + +如果需要更精细的控制,Aspose OCR 提供了额外的属性: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +当处理倾斜或对比度低的扫描文档时,这些调节非常实用。 + +## 完整工作示例回顾 + +将所有内容整合在一起,最终程序按以下顺序执行: + +1. **Perform OCR on image** – 通过创建 `OcrEngine`。 +2. **Use Aspose license** – 可选但推荐。 +3. **Load image for OCR** – 通过 `Image.load`。 +4. **Set language detection** – 使用 `Language.Auto` 自动 **recognize text image**。 +5. **Extract text from image** – 打印结果,并优雅地处理空响应。 + +您可以直接将上面的代码块复制到包含以下依赖的 Maven 项目中: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +运行 `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"`,即可在控制台看到识别的文本。 + +## 结论 + +我们刚刚演示了如何使用 Aspose OCR for Java 对 **perform OCR on image** 文件进行操作,从应用许可证到 **loading the image for OCR**、**recognizing text image** 内容,最后 **extracting text from image** 以供下游使用。该方法简洁明了,开箱即支持多语言,并且在需要时可以通过高级预处理选项进行扩展。 + +接下来可以做什么?尝试将 OCR 输出写入搜索索引,使用提取的文本生成 PDF,或尝试不同的图像格式。可能性无限,凭借 Aspose 强大的 API,您将把更多时间用于构建功能,而不是与 OCR 的各种怪癖纠缠。 + +有疑问或遇到特殊情况?在下方留言——祝编码愉快! + +## 接下来您应该学习什么? + +以下教程涵盖与本指南演示的技术密切相关的主题。每个资源都包含完整的可运行代码示例和逐步解释,帮助您掌握更多 API 功能,并在自己的项目中探索替代实现方案。 + +- [如何使用 Aspose.OCR for Java 从 URL 提取图像文本](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [使用 Aspose.OCR BufferedImage 将图像转换为文本(Java)](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [使用 Aspose.OCR 检测区域模式在 Java 中提取图像文本](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/czech/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..a8c859ae7 --- /dev/null +++ b/ocr/czech/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Vytvořte prohledávatelný PDF z obrázku pomocí Python OCR. Naučte se převádět + OCR do PDF, extrahovat text z obrázku a rychle provádět OCR na obrázku. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: cs +og_description: Vytvořte prohledávatelný PDF z obrázku pomocí OCR v Pythonu. Tento + průvodce ukazuje, jak převést OCR na PDF, extrahovat text z obrázku a provést OCR + na obrázku. +og_title: Vytvořte prohledávatelný PDF v Pythonu – kompletní programovací průvodce +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Vytvořte prohledávatelný PDF v Pythonu – kompletní krok‑za‑krokem průvodce +url: /cs/python-java/general/create-searchable-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 >}} + +# Vytvoření prohledávatelného PDF v Pythonu – Kompletní krok‑za‑krokem průvodce + +Už jste někdy potřebovali **vytvořit prohledávatelné PDF** ze skenovaného účtenky, ale nevedeli jste, kde začít? Nejste sami – mnoho vývojářů narazí na stejnou překážku, když poprvé zkusí převést obrázek textu na PDF, které můžete skutečně prohledávat. + +V tomto tutoriálu vás provedeme praktickým řešením, které vám umožní **provést OCR na obrázku**, převést výsledek OCR na **prohledávatelné PDF** a dokonce získat surový text, pokud ho potřebujete pro další zpracování. Žádné zbytečnosti, jen funkční příklad, který můžete dnes zkopírovat a vložit do svého projektu. + +## Co se naučíte + +- Jak nastavit lehký OCR engine v Pythonu +- Přesné kroky k **převodu OCR na PDF** a uložení jako prohledávatelný dokument +- Způsoby, jak **extrahovat text z obrázku** pro následnou analýzu +- Tipy pro řešení běžných problémů, jako je orientace obrázku a velké soubory +- Kompletní, spustitelný skript, který můžete přizpůsobit svému vlastnímu případu použití + +### Požadavky + +- Python 3.8+ nainstalovaný na vašem počítači +- Základní znalost pip a virtuálních prostředí (volitelné, ale doporučené) +- Obrázkový soubor (PNG, JPEG, atd.), který obsahuje jasný, strojově čitelný text + +Pokud je máte, pojďme na to. + +## Krok 1: Instalace požadované knihovny + +Ukázkový kód, který jste viděli dříve, používá fiktivní balíček `ocr`, ale stejné principy platí pro reálné knihovny jako **EasyOCR**, **pytesseract** nebo **pdfminer.six**. Pro tento průvodce použijeme **EasyOCR**, protože je čistě v Pythonu, podporuje mnoho jazyků a poskytuje užitečnou metodu pro převod do PDF pomocí pomocného nástroje. + +```bash +pip install easyocr pillow +``` + +> **Tip:** Instalujte uvnitř virtuálního prostředí (`python -m venv venv && source venv/bin/activate`), aby byly vaše závislosti přehledné. + +## Krok 2: Inicializace OCR engine – Provést OCR na obrázku + +Jakmile je knihovna připravena, vytvoříme OCR engine a řekneme mu, aby pracoval s anglickým textem. Toto je první místo, kde **provádíme OCR na obrázku**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Proč potřebujeme dedikovaný objekt čtečky? EasyOCR přednačítá jazykové modely, takže opětovné použití stejného `reader` pro více obrázků je mnohem efektivnější než jeho opakovaná inicializace při každém použití. + +## Krok 3: Načtení obrázku – Extrahovat text z obrázku + +Načteme obrázek do paměti. Tento krok je místem, kde později **extrahujeme text z obrázku**, ale nejprve jej jen načteme. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Pokud je váš obrázek vzhůru nohama nebo nakřivo, zvažte použití metod `rotate` nebo `transpose` z Pillow před předáním OCR engine. Rychlá vizuální kontrola vám může později ušetřit hodiny ladění. + +## Krok 4: Spuštění OCR engine a zachycení výsledků + +Zde je jádro procesu – odeslání obrázku do OCR engine a získání strukturovaných dat. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Příznak `detail=1` nám poskytuje ohraničující rámečky, které budeme později potřebovat při **převodu OCR na PDF**. Pokud vás zajímají jen surové řetězce, nastavte `detail=0`. + +## Krok 5: Převod výsledku OCR na prohledávatelné PDF – Převod OCR na PDF + +EasyOCR neposkytuje přímý PDF zapisovač, ale můžeme PDF sestavit sami pomocí Pillow a knihovny `reportlab`. Aby byl tutoriál lehký, použijeme `fpdf2`, který nám umožní vložit původní obrázek a překrýt jej neviditelným textem. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Co se právě stalo? Umístili jsme naskenovaný obrázek jako viditelnou vrstvu a poté jsme na něj napsali rozpoznaná slova pomocí bílého textu, který se slévá s bílým pozadím. Vyhledávací nástroje stále čtou skrytou vrstvu, takže PDF se stane **prohledávatelným** bez změny vizuálního vzhledu. + +## Krok 6: Uložení PDF bajtů – Převod obrázku na PDF + +Pokud dáváte přednost práci s PDF v paměti (např. odesílání přes API), můžete zachytit bajty místo přímého zápisu na disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Tento řádek ukazuje klasický workflow **převodu obrázku na PDF**: začnete obrázkem, spustíte OCR, překryjete text a nakonec vytvoříte PDF stream. + +## Krok 7: Ověření výsledku – Rychlé kontroly + +Po spuštění skriptu otevřete `receipt_searchable.pdf` v libovolném PDF prohlížeči a vyzkoušejte vyhledávací pole (Ctrl + F). Zadejte slovo, o kterém víte, že se v účtence vyskytuje – pokud skočí na správné místo, úspěšně jste **vytvořili prohledávatelné PDF**! + +Pokud vyhledávání selže, zkontrolujte: + +1. Skóre důvěryhodnosti OCR (`conf` hodnoty). Nízká důvěra může znamenat, že je obrázek rozmazaný. +2. Souřadnice ohraničujících rámečků – někdy EasyOCR hlásí jiné orientace. +3. Že PDF prohlížeč není nastaven do režimu „pouze obrázek“ (vzácné, ale některé prohlížeče tuto možnost mají). + +## Kompletní funkční skript + +Spojením všeho dohromady, zde je kompletní, připravený ke spuštění Python soubor: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Uložte to jako `searchable_pdf.py`, nahraďte zástupné řetězce `YOUR_DIRECTORY` skutečnými cestami a spusťte: + +```bash +python searchable_pdf.py +``` + +Měli byste vidět potvrzovací zprávu a zcela nové prohledávatelné PDF ve vaší složce. + +## Časté otázky a okrajové případy + +**Co když je obrázek barevný?** +EasyOCR funguje jak s odstíny šedi, tak s barevnými obrázky, ale převod na odstíny šedi (`pil_image.convert("L")`) může někdy zlepšit přesnost u špinavých skenů. + +**Mohu zpracovávat vícestránkové PDF?** +Ano – projděte každým obrázkem stránky, spusťte kroky OCR a přidejte každou stránku do stejného objektu `FPDF`. Jen nezapomeňte resetovat kurzor (`self.add_page()`) pro každý nový obrázek. + +**Existuje způsob, jak zachovat původní textovou vrstvu místo neviditelného bílého textu?** +Pokud potřebujete skutečné PDF „text‑pod‑obrázkem“ (např. pro přístupnost), zvažte použití `pdfminer` nebo `pikepdf` k vložení skryté textové vrstvy s odpovídajícími PDF tagy. Je to pokročilejší, ale princip zůstává stejný: obrázek na pozadí + překrytý text. + +**Co když je důvěra OCR nízká?** +Můžete filtrovat slova s nízkou důvěrou: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Závěr – Co jsme dosáhli + +Začali jsme s jednoduchým obrázkem účtenky, **provedli OCR na obrázku**, extrahovali rozpoznané řetězce a nakonec **vytvořili prohledávatelné PDF**, které se chová jako jakýkoli profesionálně skenovaný dokument. Proces pokryl všechna sekundární klíčová slova – **convert OCR to PDF**, **extract text from image**, **convert image to PDF** a **perform OCR on image** – takže nyní máte znovupoužitelnou sadu nástrojů pro jakýkoli podobný projekt. + +### Další kroky + +- Experimentujte s dalšími jazyky předáním jejich ISO kódů do `easyocr.Reader(['en', 'es'])`. +- Vyměňte EasyOCR za Tesseract, pokud potřebujete plně offline řešení; zbytek pipeline zůstává stejný. +- Přidejte vizualizaci důvěry OCR (nakreslete ohraničující rámečky na obrázek) pro ladění problematických skenů. + +Máte nápad, který byste chtěli sdílet? Zanechte komentář, fork + + +## 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, 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/) +- [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/) +- [Jak OCR obrázek – Provést OCR na obrázku v OCR rozpoznávání obrázků](/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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/czech/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..0a928f92a --- /dev/null +++ b/ocr/czech/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-19 +description: Extrahujte text z obrázků v Pythonu pomocí jednoduchého OCR enginu. Naučte + se, jak převést naskenované obrázky na text, rozpoznávat text z fotografií a efektivně + vypisovat soubory obrázků v Pythonu. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: cs +og_description: Extrahujte text z obrázků v Pythonu pomocí lehkého OCR enginu. Tento + průvodce vám ukáže, jak převést naskenované obrázky na text, rozpoznat text z fotografií + a vypsat soubory obrázků v Pythonu během několika kroků. +og_title: Extrahujte text z obrázků v Pythonu – Kompletní průvodce hromadným OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Extrahování textu z obrázků v Pythonu – Kompletní průvodce dávkovým OCR +url: /cs/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahovat text z obrázků v Pythonu – Kompletní průvodce hromadným OCR + +Už jste někdy potřebovali **extrahovat text z obrázků**, ale nebyli jste si jisti, kde začít? Nejste sami — vývojáři neustále čelí výzvě převádět naskenované PDF, vyfocené účtenky nebo snímky obrazovky na prohledávatelný text. V tomto tutoriálu projdeme kompletním, připraveným k spuštění příkladem, který ukazuje, jak **převést naskenované obrázky na text**, rozpoznat text z fotografií a dokonce **list image files python**‑style. Na konci budete mít znovupoužitelný skript, který zpracuje celý adresář najednou. + +Probereme vše, co potřebujete: požadované knihovny, proč je každý krok důležitý, ošetření okrajových případů a trochu ladění. Není nutné hledat externí dokumentaci; kód níže je samostatný a vysvětlení odpovídají na „jak“ *i* „proč“. Vezměte si své oblíbené IDE a pojďme na to. + +--- + +## Co vytvoříte + +- Inicializovat OCR engine (pro ilustraci použijeme balíček `ocr`). +- Prohledat adresář a **list image files python**‑style, filtrovat PNG, JPG a TIFF. +- Spustit **batch OCR** operaci na všech nalezených obrázcích. +- Vytisknout extrahovaný text pro každý soubor, jasně označený. + +> **Tip:** Pokud nemáte nainstalovanou knihovnu `ocr`, můžete ji nahradit `pytesseract` s několika drobnými změnami — základní logika zůstává stejná. + +## Požadavky + +- Python 3.8+ (skript používá f‑stringy a typové nápovědy). +- OCR knihovna, která poskytuje `OcrEngine` s metodou `recognize_batch`. Pro tento průvodce předpokládáme fiktivní balíček `ocr`, ale vzor funguje i s reálnými knihovnami. +- Adresář obsahující obrázkové soubory, které chcete zpracovat (`.png`, `.jpg`, `.tif`). + +## Krok 1 – Instalace a import požadovaných modulů + +Nejprve se ujistěte, že je OCR balíček k dispozici. Pokud používáte skutečnou knihovnu jako `pytesseract`, nahraďte import odpovídajícím způsobem. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Proč je to důležité:** Importování `os` nám poskytuje multiplatformní práci s cestami, zatímco `typing.List` pomáhá s automatickým doplňováním v IDE a budoucí rozšiřitelností. + +## Krok 2 – **Extract Text from Images**: Inicializace OCR engine + +Vytvoření engine je prvním krokem k jakékoli práci s OCR. Také nastavíme jazyk na automatické rozpoznání, aby engine mohl zpracovávat dokumenty s více jazyky. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Vysvětlení:** Zapouzdřením vytvoření engine do funkce udržujeme kód modulární. Pokud později potřebujete upravit DPI nebo režim OCR, stačí změnit toto jediné místo. + +## Krok 3 – **List Image Files Python**: Shromáždění souborů z adresáře + +Nyní musíme najít každý obrázek, který chceme zpracovat. Následující list comprehension odráží běžný vzor “list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Ošetření okrajových případů:** Funkce ignoruje podadresáře (rekursi můžete přidat později) a automaticky filtruje skryté soubory, protože obvykle nekončí podporovanými příponami. + +## Krok 4 – **Convert Scanned Images to Text**: Spuštění hromadného OCR + +Většina OCR knihoven poskytuje metodu batch, která je mnohem rychlejší než zpracování jednoho obrázku po druhém. Zde je, jak ji voláme. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Proč batch?** Odeslání všech obrázků najednou snižuje režii (např. opakované načítání OCR modelu) a často vede k lepšímu využití CPU/GPU. + +## Krok 5 – **Recognize Text from Pictures**: Zobrazení výsledků + +Nakonec iterujeme přes párovaná jména souborů a výsledky OCR, přičemž pro každý obrázek vytiskneme čistý nadpis. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** `strip()` odstraňuje úvodní/koncové mezery, které OCR často přidává. + +## Kompletní skript – Spojení všeho dohromady + +Níže je kompletní spustitelný program. Uložte jej jako `batch_ocr.py` a spusťte `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Očekávaný výstup + +Předpokládejme, že adresář obsahuje `invoice1.png` a `receipt.jpg`, můžete vidět: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Každý blok je jasně označený, což usnadňuje následné zpracování (např. uložení do databáze). + +## Řešení běžných problémů + +| Problém | Proč se to děje | Rychlé řešení | +|-------|----------------|-----------| +| **Žádný text se nezobrazí** | OCR jazyk nebyl detekován nebo je obrázek příliš nízkého kontrastu. | Vynutit jazyk (`engine.language = ocr.Language.English`) nebo předzpracovat obrázky (zvýšit kontrast). | +| **Chyba paměti u velkých batchů** | Engine se snaží načíst všechny obrázky najednou. | Rozdělit `image_files` na úseky (`batch_size = 20`) a opakovaně volat `recognize_batch`. | +| **Nepožadovaný formát souboru** | Přidali jste `.gif` nebo `.bmp`. | Rozšířit n-tici `supported_exts` nebo předem převést obrázky na PNG/JPG. | +| **Zkreslení Unicode** | OCR vrací bajty místo řetězců. | Zajistit, aby OCR knihovna vracela Unicode (`result.text.decode('utf‑8')` pokud je potřeba). | + +## Rozšíření workflow + +Nyní, když můžete **extrahovat text z obrázků**, zvažte následující kroky: + +- **Export do CSV** – Zapište každé jméno souboru a jeho extrahovaný text do tabulky pro analytiku. +- **Paralelní zpracování** – Použijte `concurrent.futures.ThreadPoolExecutor` k simultánnímu zpracování více batchů. +- **Integrace s cloudovým OCR** – Vyměňte lokální engine za Google Vision nebo Azure OCR pro vyšší přesnost u složitých rozvržení. +- **Přidání předzpracování obrázků** – Knihovny jako Pillow nebo OpenCV mohou vyrovnat, odšumět nebo aplikovat prahování na obrázky před OCR, čímž zlepší výsledky. + +Všechny tyto nápady přirozeně využívají stejné základní funkce, které jsme vytvořili, takže nebudete muset začínat od nuly. + +## Závěr + +Právě jsme prošli kompletním řešením pro **extrahování textu z obrázků** v Pythonu, pokrývajícím vše od **list image files python** po **recognize text from pictures** a nakonec **convert scanned images to text** v přehledném batchi. Skript je úmyslně jednoduchý, ale dostatečně flexibilní, aby sloužil jako základ pro větší projekty — ať už digitalizujete účtenky, budujete prohledávatelný archiv nebo poháníte pipeline pro extrakci dat. + +Vyzkoušejte jej, upravte kroky předzpracování a sledujte, jak se zvyšuje přesnost OCR. Pokud narazíte na problémy, podívejte se znovu na tabulku „Řešení běžných problémů“; většina problémů se vyřeší malou změnou konfigurace. + +Jste připraveni na další výzvu? Zkuste přidat krok konverze PDF na obrázek pomocí `pdf2image` a poté tyto obrázky přímo vložit do stejného pipeline. Možnosti jsou neomezené, když kombinujete OCR s bohatým ekosystémem Pythonu. + +Šťastné kódování a ať je váš text vždy čitelný! + +## 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í příklady 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/) +- [Extrahovat text z obrázků – základy OCR s Aspose.OCR pro Java](/ocr/english/java/ocr-basics/) +- [Jak extrahovat text z obrázku z URL pomocí Aspose.OCR pro Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/czech/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..2b65aa1ee --- /dev/null +++ b/ocr/czech/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-19 +description: Extrahujte text z obrázků pomocí Python OCR. Naučte se automatické rozpoznávání + jazyka, paralelní zpracování a dávkové rozpoznávání v stručném tutoriálu. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: cs +og_description: Extrahujte text z obrázků pomocí Python OCR. Tento průvodce ukazuje + automatické rozpoznávání jazyka, paralelní zpracování a dávkové rozpoznávání v jednom + tutoriálu. +og_title: Extrahovat text z obrázků v Pythonu – Kompletní průvodce OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Extrahování textu z obrázků v Pythonu – Kompletní průvodce OCR +url: /cs/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# extrahovat text z obrázků v Pythonu – Kompletní průvodce OCR + +Už jste se někdy zamýšleli, jak **extrahovat text z obrázků** bez ručního přepisování každého slova? Nejste v tom sami. Ať už digitalizujete staré účtenky, budujete prohledávatelný archiv dokumentů, nebo si jen hrajete s cool AI triky, schopnost získat text z obrázků je dnes nezbytnou dovedností pro každého vývojáře v Pythonu. + +V tomto tutoriálu projdeme kompletním, připraveným příkladem, který **extrahuje text z obrázků** pomocí populárního OCR enginu. Pokryjeme automatickou detekci jazyka, paralelní zpracování pro vyšší rychlost a hromadné rozpoznávání obrázků, takže můžete během několika sekund zpracovat desítky souborů. Zní to jako to, co potřebujete? Pojďme na to. + +## Co se naučíte + +- Jak vytvořit instanci OCR enginu pomocí `ocr.OcrEngine`. +- Povolení **automatické detekce jazyka**, aby engine sám vybral správný jazyk. +- Konfiguraci **paralelního zpracování OCR** pomocí vlastního thread poolu. +- Spuštění **hromadného rozpoznávání obrázků** na seznamu souborů. +- Výpis rozpoznaného textu pro každý obrázek, připravený k uložení nebo indexaci. + +Žádná externí dokumentace není potřeba — vše, co potřebujete, je zde, a kód funguje hned po instalaci balíčku `ocr` (nainstalujte jej pomocí `pip install ocr`). + +## Předpoklady + +Než začneme, ujistěte se, že máte: + +1. Python 3.8 nebo novější. +2. Balíček `ocr` (`pip install ocr`). +3. Složku s PNG (nebo JPG) obrázky, které chcete zpracovat. +4. Základní znalosti funkcí a smyček v Pythonu. + +A to je vše — žádné těžké závislosti, žádná GPU magie, jen čistý Python. + +![extract text from images example](https://example.com/ocr-demo.png "Screenshot showing extract text from images output") + +*Alt text: ukázka výstupu extrahování textu z obrázků* + +## Krok 1 – Nastavení OCR enginu (Primární klíčové slovo v akci) + +První věc na řadě: vytvořte instanci OCR enginu. `ocr.OcrEngine()` je mozek celého procesu; umí číst znaky, řádky i odstavce. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Proč potřebujeme explicitní engine? Protože **ocr.OcrEngine usage** vám dává jemnou kontrolu nad nastavením jazyka, vláknováním a dalšími parametry. Je to nejflexibilnější způsob, jak **extrahovat text z obrázků**, ve srovnání s jednorázovými pomocníky. + +## Krok 2 – Nechte engine automaticky detekovat jazyky + +Většina OCR knihoven vyžaduje, abyste jim řekli, jaký jazyk mají hledat. To je v pořádku pro projekt s jedním jazykem, ale u smíšených jazykových batchů to může být obtížné. Naštěstí balíček `ocr` podporuje **automatickou detekci jazyka**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Nastavením `engine.language` na `ocr.Language.Auto` řeknete enginu, aby prohledal každý obrázek a vybral odpovídající jazykový model. Tento malý řádek vám ušetří hodiny ruční konfigurace, když pracujete s mezinárodními dokumenty. + +## Krok 3 – Zrychlete pomocí paralelního zpracování OCR + +Máte-li čtyři nebo více CPU jader, proč je nevyužít? Engine může spustit thread pool, který umožní zpracovávat více obrázků najednou. Zde **paralelní zpracování OCR** opravdu zazáří. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Klidně upravte číslo `4` podle výkonu vašeho počítače. Více vláken → rychlejší batch běhy, ale pamatujte, že každé vlákno spotřebovává paměť, takže najděte optimální nastavení pro své prostředí. + +## Krok 4 – Shromážděte obrázky, které chcete zpracovat + +Teď potřebujeme seznam cest k souborům. Můžete jej vytvořit ručně, načíst z CSV, nebo použít `glob`. Pro přehlednost ukážeme krátký hard‑coded seznam: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Nahraďte `YOUR_DIRECTORY` skutečnou cestou ve vašem systému. Pokud máte desítky souborů, rychlé `glob.glob("*.png")` udělá těžkou práci za vás. + +## Krok 5 – Spusťte hromadné rozpoznávání obrázků + +Tady je jádro tutoriálu: jediný volání, které zpracuje každý obrázek v `files` a vrátí seznam objektů s výsledky. To je funkce **hromadného rozpoznávání obrázků**, která dělá OCR ve velkém praktickým. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Engine v pozadí rozdělí každý soubor mezi čtyři pracovní vlákna, která jsme dříve nakonfigurovali, a zároveň automaticky detekuje jazyk pro každý obrázek. Metoda vrací seznam, kde každý prvek obsahuje rozpoznaný text a metadata. + +## Krok 6 – Vytiskněte (nebo uložte) extrahovaný text + +Nakonec projdeme výsledky a vytiskneme text. V reálném projektu byste pravděpodobně zapisovali do databáze nebo CSV souboru, ale výpis udržuje příklad jednoduchý. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Očekávaný výstup** (zkrácený pro stručnost): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Každý blok ukazuje název souboru následovaný řetězcem získaným OCR. Pokud obrázek obsahuje více jazyků, uvidíte odpovídající znaky díky předchozímu kroku **automatické detekce jazyka**. + +## Tipy a časté úskalí + +- **Kvalita obrázku má význam** — rozmazané nebo nízkokontrastní snímky budou produkovat odpad. Předzpracujte je pomocí OpenCV (`cv2.threshold`, `cv2.resize`), pokud je to potřeba. +- **Počet vláken vs. I/O** — pokud jsou vaše obrázky na pomalém síťovém disku, více vláken možná nepomůže. Sledujte využití CPU pomocí `top` nebo `Task Manager`. +- **Zpracování Unicode** — `result.text` je Unicode řetězec. Při zápisu do souborů otevřete soubory s `encoding="utf‑8"`, abyste předešli `UnicodeEncodeError`. +- **Spotřeba paměti** — velké PDF mohou spotřebovat hodně RAM. Pokud narazíte na `MemoryError`, snižte velikost thread poolu nebo zpracovávejte obrázky po menších částech. + +## Kompletní funkční skript + +Níže je kompletní skript připravený ke zkopírování a vložení, který zahrnuje všechny kroky, o kterých jsme mluvili. Uložte jej jako `batch_ocr.py` a spusťte `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Spusťte jej takto: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Uvidíte pěkně naformátovaný blok textu pro každý obrázek, což dokazuje, že můžete **extrahovat text z obrázků** ve velkém měřítku. + +## Co dál? + +Teď, když ovládáte základy **extrahování textu z obrázků** v Pythonu, můžete zkusit: + +- **Post‑processing**: vyčistit OCR výstup pomocí regexu nebo knihoven pro zpracování přirozeného jazyka. +- **Konverze PDF**: vložit získané řetězce do generátoru PDF pro prohledávatelné PDF soubory. +- **Cloud OCR služby**: porovnat on‑prem `ocr` výsledky s Google Vision nebo Azure OCR pro řešení okrajových případů. +- **GUI front‑end**: vytvořit malou Flask nebo FastAPI aplikaci, která uživatelům umožní nahrát obrázky a okamžitě zobrazit extrahovaný text. + +Všechny tyto témata staví na **Python OCR knihovně**, kterou jste právě nastavili, a všechny těží ze stejných **paralelních zpracování OCR** triků, které jsme zde použili. + +--- + +*Šťastné kódování! Pokud narazíte na problémy, zanechte komentář níže — rád pomohu s laděním OCR.* + + +## 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, abyste si osvojili další funkce API a prozkoumali alternativní implementační přístupy ve svých 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 Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/czech/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..89b30b433 --- /dev/null +++ b/ocr/czech/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-19 +description: Jak extrahovat PDF pomocí OCR v Pythonu – krok za krokem tutoriál pokrývající + extrakci textu z PDF, rozpoznávání textu z obrázku a příklad OCR v Pythonu. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: cs +og_description: Jak extrahovat PDF pomocí OCR v Pythonu. Naučte se extrahovat text + z PDF, rozpoznávat text z obrázku a podívejte se na kompletní příklad OCR v Pythonu. +og_title: Jak extrahovat text z PDF pomocí OCR v Pythonu – kompletní návod +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Jak extrahovat text z PDF pomocí OCR v Pythonu – Kompletní průvodce +url: /cs/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak extrahovat text z PDF pomocí OCR v Pythonu – Kompletní průvodce + +Už jste se někdy zamýšleli **jak extrahovat PDF** obsah, když je soubor jen naskenovaný obrázek? Nejste v tom sami. V mnoha reálných projektech—například smlouvy, faktury nebo historické archivy—PDF, které obdržíte, neobsahuje žádný vybratelný text. Dobrá zpráva? Několik řádků Pythonu může převést tyto stránky jen s obrázkem na prohledávatelný, editovatelný text. + +V tomto tutoriálu projdeme praktickým **OCR Python příkladem**, který načte PDF, vykreslí jeho první stránku jako obrázek a poté **extrahuje text z PDF** pomocí OCR enginu. Na konci přesně vědět, jak **číst PDF s OCR**, proč je každý krok důležitý a jak přizpůsobit kód pro více‑stránkové dokumenty nebo různé jazyky. + +## Co se naučíte + +- Nainstalujte a nastavte spolehlivou OCR knihovnu pro Python. +- Převěďte stránky PDF na obrázky vhodné pro OCR. +- **Rozpoznat text z obrázku** a získat čisté Unicode řetězce. +- Běžné úskalí (PDF s nízkým rozlišením, otočené stránky) a jak se jim vyhnout. +- Rozšíření skriptu pro zpracování více stránek nebo dávkové zpracování. + +**Požadavky**: Python 3.8+, pip a základní pochopení virtuálních prostředí. Předchozí zkušenosti s OCR nejsou potřeba—stačí sledovat. + +--- + +## ## Jak extrahovat text z PDF pomocí OCR v Pythonu + +Tento H2 nadpis obsahuje naše hlavní klíčové slovo právě tam, kde ho vyhledávače milují. Ponořme se rovnou do kódu. + +### Krok 1 – Instalace požadovaných balíčků + +Nejprve potřebujeme OCR engine. Níže uvedený příklad používá populární balíček **ocr** (tenký wrapper kolem Tesseract). Pokud dáváte přednost jinému backendu, koncepty zůstávají stejné. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Tip:** Na Linuxu budete také potřebovat binární soubor Tesseract: `sudo apt-get install tesseract-ocr`. Uživatelé macOS si jej mohou stáhnout přes Homebrew: `brew install tesseract`. + +### Krok 2 – Inicializace OCR enginu a nastavení jazyka + +Nyní spustíme engine a řekneme mu, aby hledal anglické znaky. Můžete nahradit `ocr.Language.English` libovolným podporovaným kódem jazyka. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Proč je to důležité:** Specifikace jazyka výrazně zvyšuje přesnost, protože engine může použít jazykově specifické slovníky a modely znaků. + +### Krok 3 – Načtení stránky PDF jako obrázku + +OCR funguje na rastrových obrázcích, ne na PDF objektech. Pomocná funkce `ocr.Image.from_pdf` vykreslí vybranou stránku do bitmapy. Pro jiné stránky upravte `page_number` (indexování od 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Hraniční případ:** Pokud PDF obsahuje vektorovou grafiku místo naskenovaných obrázků, můžete získat ostré vykreslení. Pro skeny s nízkým rozlišením zvažte zvýšení DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Krok 4 – Rozpoznání textu z vykresleného obrázku + +Zde je jádro **ocr python příkladu**. Engine zpracuje bitmapu a vrátí objekt obsahující extrahovaný řetězec. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Atribut `ocr_result.text` obsahuje výstup plain‑textu, kde je to možné zachovává konce řádků. + +### Krok 5 – Vytisknout nebo uložit extrahovaný text + +Nakonec výsledek vypíšeme. Ve skutečné aplikaci byste pravděpodobně zapisovali do souboru nebo databáze. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Spuštění skriptu by mělo zobrazit něco jako: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +To je kompletní workflow **extrahování textu z pdf** pomocí OCR. + +--- + +## ## Rozpoznat text z obrázku – vyladění přesnosti + +Pokud vás zajímá jen **rozpoznat text z obrázku** (např. JPEG účtenky), můžete krok konverze PDF přeskočit: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tipy pro lepší výsledky:** + +- **Předzpracovat** obrázek: převést na odstíny šedi, aplikovat prahování nebo deskew. Pillow to usnadňuje. +- **Zvýšit DPI** během vykreslování PDF: vyšší rozlišení poskytuje OCR engine více detailů. +- **Povolit konfiguraci OCR enginu** pro segmentaci stránek (`ocr_engine.config = "--psm 6"` pro jednotné bloky). + +## ## Číst PDF s OCR – zpracování více stránek + +Většina smluv má několik stránek. Procházet každou stránku je jednoduché: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Tato funkce **čte PDF s OCR**, spojuje výstup a vkládá jasný marker pro zalomení stránky. Pak můžete `full_text` předat do vyhledávacího indexu nebo uložit jako soubor `.txt`. + +## ## Běžná úskalí a jak je opravit + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Zkreslené znaky, spousta `?` | Špatný jazyk nebo chybějící soubory jazykových dat | Nainstalujte správný jazykový balíček Tesseract (`tesseract-ocr-`) a nastavte `ocr_engine.language`. | +| Chybějící řádky nebo oříznutá slova | Nízké DPI (méně než 150) | Vykreslete PDF při 300 DPI nebo vyšším (`dpi=300`). | +| Text je otočený nebo vzhůru nohama | Naskenovaná stránka není orientována | Použijte `ocr.Image.deskew(page_image)` před rozpoznáním. | +| Pomalejší zpracování velkých PDF | Zpracování stránek sekvenčně v jednom vlákně | Paralelizujte pomocí `concurrent.futures.ThreadPoolExecutor`. | + +## ## Rozšíření OCR Python příkladu + +- **Export do PDF/A**: Po extrakci můžete vložit text zpět do prohledávatelného PDF pomocí `reportlab` nebo `pypdf2`. +- **Detekce jazyka**: Použijte `langdetect` na výstup OCR pro dynamické přepínání `ocr_engine.language`. +- **Dávkové zpracování**: Procházejte adresář pomocí `os.listdir` a aplikujte `extract_all_pages` na každý soubor. + +## ## Očekávaný výstup a ověření + +Když spustíte skript na čistém skenu v angličtině, měli byste vidět čistý blok textu s správnou interpunkcí. Ověřte tím, že: + +1. Porovnáte několik řádků s originálním naskenovaným obrázkem. +2. Spustíte jednoduchý počet slov (`len(ocr_result.text.split())`), abyste se ujistili, že výstup není prázdný. +3. Volitelně předáte výsledek do kontrolora pravopisu jako `pyspellchecker`, abyste odhalili OCR chyby. + +## Závěr + +Probrali jsme **jak extrahovat PDF** obsah, když tradiční parsování selže, ukázali kompletní **ocr python příklad** a vysvětlili, jak **rozpoznat text z obrázku** a **číst PDF s OCR** pro jednostránkové i více‑stránkové scénáře. S výše uvedenými úryvky kódu můžete nyní převést jakýkoli naskenovaný PDF do prohledávatelného, editovatelného textu—už žádné ruční přepisování. + +Další kroky? Zkuste změnit jazyk na španělštinu (`ocr.Language.Spanish`) nebo experimentujte s technikami předzpracování obrázků pro zvýšení přesnosti. Pokud budujete systém pro správu dokumentů, zvažte indexování extrahovaného textu pomocí Elasticsearch pro bleskově rychlé vyhledávání. + +Máte otázky nebo narazíte na podivný PDF? Zanechte komentář a šťastné programování! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + +## 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/) +- [Rozpoznat text PDF – OCR operace s Aspose.OCR pro Java](/ocr/english/java/ocr-operations/) +- [Extrahovat text z obrázku v C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/czech/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..a5d71406e --- /dev/null +++ b/ocr/czech/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-19 +description: Naučte se, jak používat OCR v Javě s Aspose. Tento krok‑za‑krokem průvodce + zahrnuje automatické vyrovnání obrázků, automatickou detekci jazyka a snadné získání + textu z obrázku. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: cs +og_description: 'Jak používat OCR v Javě s Aspose: kompletní průvodce zahrnující automatické + vyrovnání obrázků, automatickou detekci jazyka a extrahování textu z obrázků.' +og_title: Jak používat OCR v Javě s Aspose – kompletní průvodce +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Jak používat OCR v Javě s Aspose – Kompletní průvodce +url: /cs/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak používat OCR v Javě s Aspose – Kompletní průvodce + +Už jste se někdy zamýšleli **jak používat OCR** v Java projektu, aniž byste si trhali vlasy kvůli konfiguraci? Nejste v tom sami. Mnoho vývojářů narazí na problém, když potřebují rychle **extrahovat text z obrázku**, zejména když jsou zdrojové skeny šikmé nebo psány v neznámém jazyce. + +V tomto tutoriálu projdeme praktickým příkladem, který vám přesně ukáže, jak použít OCR s Aspose, včetně **auto deskew images**, **auto language detection** a celé **ocr image preprocessing** pipeline. Na konci budete mít připravený útržek kódu, který vypíše rozpoznaný text do konzole, a pochopíte, proč každé nastavení má význam. + +> **Co získáte:** kompletní, spustitelný Java program, vysvětlení každého řádku, tipy pro řešení okrajových případů a nápady, jak rozšířit řešení na dávkové zpracování nebo PDF. + +--- + +## Požadavky + +- Java 17 (nebo jakýkoli recentní JDK) nainstalovaný a nakonfigurovaný. +- Maven nebo Gradle pro správu závislostí (ukážeme Maven koordináty). +- Licenční soubor Aspose OCR pro Java (`Aspose.OCR.Java.lic`). Pokud jen testujete, můžete krok s licencí přeskočit, ale bezplatná zkušební verze přidá vodoznak. +- Ukázkový obrázek (`your_image.png`) umístěný na místě přístupném kódu. + +> **Pro tip:** uložte své obrázky do vyhrazené složky `resources` a načítejte je přes classpath; tím se vyhnete problémům s cestami na různých OS. + +--- + +## Krok 1: Nastavte projekt a přidejte závislost Aspose OCR + +Vytvořte nový Maven projekt (nebo použijte ten existující) a přidejte následující do souboru `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Spusťte `mvn clean install` pro stažení knihovny. Pokud dáváte přednost Gradlu, ekvivalent je: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Nyní máte třídy **ocr image preprocessing** na classpathu. + +--- + +## Krok 2: Aplikujte svou licenci Aspose OCR (volitelné, ale doporučené) + +Pokud vlastníte licenci, aplikujte ji hned na začátku vaší metody `main`. Přeskočení tohoto kroku funguje, ale bezplatná verze přidá na výstup vodoznak „Demo“. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Proč je to důležité:** Licencovaná verze odstraňuje omezení používání a vypíná vodoznak, takže získáte čisté, produkčně připravené výsledky. + +--- + +## Krok 3: Vytvořte instanci OCR enginu + +Engine je srdcem celého procesu. Jeho vytvoření vám poskytne přístup ke všem možnostem **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +V tomto okamžiku je engine připraven, ale použije výchozí nastavení, která nemusí být pro skenované dokumenty optimální. Provedeme několik úprav. + +--- + +## Krok 4: Povolte automatické vyrovnání obrázků pro čistší skeny + +Šikmé skeny jsou častý problém. Aspose nabízí funkci **auto deskew images**, která automaticky narovná obrázek před rozpoznáním. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Jak to funguje:** Algoritmus analyzuje úhly základní linie textu a otočí obrázek do nejpravděpodobnější svislé orientace. To dramaticky zvyšuje přesnost u fotografií pořízených telefonem. + +--- + +## Krok 5: Zapněte automatickou detekci jazyka + +Pokud neznáte jazyk zdrojového obrázku, nechte engine zjistit to za vás. Toto je nastavení **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Když toto povolíte, Aspose prozkoumá glyfy a vybere nejpravděpodobnější jazykový model, podporující více než 30 jazyků přímo z krabice. + +--- + +## Krok 6: Načtěte obrázek, který chcete rozpoznat + +Obrázek můžete načíst z disku, URL nebo i z pole bajtů. Pro jednoduchost načteme lokální soubor. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** Pokud pracujete s velkými obrázky, zvažte jejich předběžné zmenšení pomocí `engine.getImagePreprocessing().setResizeFactor(0.5)`, čímž urychlíte zpracování bez výrazné ztráty detailů. + +--- + +## Krok 7: Proveďte OCR rozpoznání a extrahujte text z obrázku + +Nyní engine provede své kouzlo. Metoda `recognize` vrací objekt `OcrResult`, který obsahuje rozpoznaný text, skóre důvěry a další informace. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Konzole zobrazí čistý text extrahovaný z obrázku – to je hlavní výsledek **extract text image**, který jsme chtěli dosáhnout. + +--- + +## Kompletní funkční příklad + +Níže je kompletní Java třída, která vše spojuje. Zkopírujte ji do `src/main/java/com/example/OcrDemo.java` a spusťte. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Očekávaný výstup + +Pokud obrázek obsahuje frázi „Hello World“ na čistém skenu, uvidíte: + +``` +=== Recognized Text === +Hello World +``` + +U složitějších dokumentů (např. vícejazykové účtenky) výstup zahrne zalomení řádků a detekovaný kód jazyka. + +--- + +## Časté problémy a tipy + +| Problém | Proč se to děje | Řešení | +|-------|----------------|-----| +| **Špatné znaky** | Obrázek je příliš tmavý nebo šumivý. | Povolte `engine.getImagePreprocessing().setBinarization(true)` nebo ručně upravte kontrast. | +| **Nesprávný jazyk** | Automatická detekce selže u smíšených jazykových stránek. | Nastavte `engine.setLanguage(Language.English)` (nebo příslušný enum) pro vynucení konkrétního jazyka. | +| **Pomalé zpracování** | Velmi vysoké rozlišení obrázků. | Zmenšete pomocí `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Chyby out‑of‑memory** | Velká dávka obrázků načtených najednou. | Zpracovávejte obrázky sekvenčně a po každém běhu zavolejte `engine.dispose()`. | + +> **Pamatujte:** OCR engine je thread‑safe pro operace jen ke čtení, ale vytvoření nové instance pro každý vláken se vyhne skrytým stavovým chybám. + +--- + +## Rozšíření řešení + +Nyní, když víte **jak používat OCR** s Aspose, můžete: + +1. **Zpracovávat PDF** – převést každou stránku PDF na obrázek (`PdfConverter`) a předat ji do stejné pipeline. +2. **Dávkové zpracování složky** – projít soubory ve složce, aplikovat stejné kroky a zapisovat výsledky do CSV. +3. **Integrace s webovou službou** – vystavit OCR logiku přes Spring Boot `@RestController`, který přijímá multipart uploady. + +Všechny tyto scénáře znovu využívají stejnou konfiguraci **ocr image preprocessing**, kterou jsme zde vytvořili. + +--- + +## Závěr + +Prošli jsme **jak používat OCR** v Javě s Aspose od začátku do konce: aplikace licence, vytvoření enginu, povolení **auto deskew images**, zapnutí **auto language detection**, načtení obrázku a nakonec **extract text image** pomocí jediného `System.out.println`. Kód je zcela samostatný, běží na jakémkoli recentním JDK a ukazuje osvědčené postupy pro přesnost i výkon. + +Vyzkoušejte to s vlastními obrázky – třeba naskenovanou smlouvu nebo snímek účtenky. Pozměňujte předzpracovatelské příznaky, experimentujte s různými jazyky a rychle zjistíte, proč je knihovna OCR od Aspose solidní volbou pro produkční extrakci textu. + +Máte otázky nebo chcete sdílet výsledky? Zanechte komentář níže nebo mě kontaktujte na GitHubu. Šťastné programování! + +--- + +![Jak používat OCR v Javě příklad](/images/ocr-java-example.png "Jak používat OCR v Javě – ukázkový screenshot Aspose") + + +## 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. + +- [Jak OCR text z obrázku s jazykem pomocí Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extrahovat text z obrázku v Javě s Aspose.OCR Detekce oblastí](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Jak používat OCR – pokročilé techniky s Aspose.OCR pro Javu](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/czech/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..3c5a3693b --- /dev/null +++ b/ocr/czech/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,318 @@ +--- +category: general +date: 2026-06-19 +description: Zlepšete přesnost OCR v Pythonu pomocí Aspose OCR. Naučte se, jak nastavit + jazyk OCR, načíst obrázek pro OCR a extrahovat text z obrázku pomocí vlastního slovníku. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: cs +og_description: Zvyšte přesnost OCR v Pythonu nastavením jazyka OCR, načtením obrázku + pro OCR a extrakcí textu z obrázku pomocí vlastního slovníku. +og_title: Zlepšete přesnost OCR v Pythonu – průvodce krok za krokem +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Zlepšete přesnost OCR v Pythonu – kompletní průvodce +url: /cs/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zlepšení přesnosti OCR v Pythonu – Kompletní průvodce + +Už jste se někdy zamýšleli, jak **zlepšit přesnost OCR**, když text, který skenujete, obsahuje podivné symboly, kódy produktů nebo značky? Nejste v tom sami. V mnoha projektech výchozí engine jenom vrhá nesmysly a to je skutečný zabiják produktivity. + +V tomto tutoriálu projdeme praktickým, end‑to‑end příkladem, který vám ukáže, jak **nastavit jazyk OCR**, **načíst obrázek pro OCR**, **provést OCR na obrázku** a nakonec **extrahovat text z obrázku** s vlastním slovníkem, který zvyšuje míru rozpoznání. Na konci budete mít připravený skript, který můžete vložit do libovolného Python kódu. + +## Co získáte + +- Plně funkční Python skript, který používá Aspose OCR k načtení PNG souboru. +- Schopnost **zlepšit přesnost OCR** konfigurací jazyka a vlastního seznamu slov. +- Jasná vysvětlení, proč každé nastavení má význam, plus tipy pro řešení okrajových případů jako ne‑latinské znaky. +- Rychlý kontrolní seznam pro odstraňování běžných OCR problémů. + +### Požadavky + +- Python 3.8 nebo novější nainstalovaný na vašem počítači. +- Balíček `aspose-ocr` (instalace pomocí `pip install aspose-ocr`). +- Vzorek obrázku (`technical_doc.png`), který obsahuje text, který chcete přečíst. +- Základní znalost Pythonu – nic složitého není potřeba. + +> **Pro tip:** Pokud pracujete ve virtuálním prostředí, aktivujte ho před instalací balíčku. Udrží to vaše závislosti přehledné a zabrání konfliktům verzí. + +--- + +## Krok 1: Instalace a import Aspose OCR + +Nejprve si přidejme knihovnu do našeho prostředí a importujme potřebné komponenty. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Namespace `aspose.ocr` vám poskytuje přístup ke třídě `OcrEngine`, která je srdcem OCR procesu. Importování zde udržuje zbytek skriptu čistý a čitelný. + +--- + +## Krok 2: Vytvoření OCR enginu a **nastavení jazyka OCR** + +Proč na tom záleží? OCR enginy používají jazykově specifické modely k rozpoznání tvarů znaků a vzorů slov. Pokud engine řeknete, že skenujete anglický text, bude ignorovat cyrilické glyfy a soustředit se na latinku, což dramaticky **zlepšuje přesnost OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Poznámka:** Aspose OCR podporuje více než 50 jazyků. Vyměňte `ocr.Language.English` za `ocr.Language.Spanish`, `ocr.Language.French` atd., pokud váš dokument není v angličtině. + +--- + +## Krok 3: Definování **vlastního slovníku** pro zvýšení přesnosti + +Představte si, že skenujete faktury, kde se vyskytuje slovo „AsposeOCR“ nebo kódy produktů jako „SKU12345“. Engine tyto termíny nezná, takže je hádá špatně. Poskytnutí vlastního seznamu slov říká engine: *„Hej, tyto řetězce jsou legitní – nepokoušej se je opravovat.“* To je rychlý způsob, jak **zlepšit přesnost OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Seznam můžete načíst ze souboru nebo databáze, pokud máte stovky položek – pro jednoduchost ho nechte jako Python list. + +--- + +## Krok 4: **Načtení obrázku pro OCR** + +Teď potřebujeme obrázek. Metoda `Image.load` přijímá cestu k libovolnému podporovanému rastrovému formátu (PNG, JPEG, BMP, atd.). Pokud soubor nelze najít, engine vyhodí výjimku, takže se proti tomu ochráníme. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Proč je tento krok důležitý:** Správné načtení obrázku zajišťuje, že engine pracuje s přesnými pixelovými daty, která chcete analyzovat. Poškozené soubory nebo špatné cesty jsou častým zdrojem frustrace. + +--- + +## Krok 5: **Provést OCR na obrázku** a získat výsledky + +S nakonfigurovaným enginem a připraveným obrázkem je samotné rozpoznání jedním voláním metody. Objekt výsledku obsahuje surový text, skóre důvěry a dokonce i informace o rozložení, pokud je později potřebujete. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Pokud potřebujete **extrahovat text z obrázku** řádek po řádku, můžete rozdělit podle znaků nového řádku: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Krok 6: Ověření výstupu – Opravdu **zlepšuje OCR přesnost**? + +Vytiskněme výsledek a podívejme se, jestli náš vlastní slovník udělal rozdíl. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Typický výstup pro ukázkový obrázek může vypadat takto: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Všimněte si, že název značky, řecký znak a kód produktu jsou přesně tak, jak jsme je definovali. Bez vlastního slovníku by engine zkusil „opravit“ tyto položky, často výsledkem by byl například „Aspose OCR“ nebo „SKU 1234“. + +--- + +## Časté problémy a jak je řešit + +| Problém | Proč se to děje | Řešení | +|-------|----------------|-----| +| **Špatné znaky** | Nesprávně nastavený jazyk nebo obrázek s nízkým rozlišením | Ujistěte se, že `engine.language` odpovídá zdrojovému jazyku a použijte sken s vysokým DPI (300 dpi nebo více). | +| **Vlastní slova ignorována** | Slovník není připojen nebo je překlep v názvu vlastnosti | Zkontrolujte `engine.text_processing.custom_dictionary = …`. | +| **Soubor nenalezen** | Špatná cesta nebo chybějící oprávnění k souboru | Použijte `os.path.abspath()` k ověření absolutní cesty; spusťte skript s potřebnými oprávněními. | +| **Pomalé zpracování** | Velké obrázky nebo mnoho stránek | Předzpracujte obrázek (oříznutí, změna velikosti) nebo použijte `engine.recognize(image, max_threads=4)` pro paralelizaci. | + +--- + +## Dále: Pokročilé úpravy pro **zlepšení OCR přesnosti** + +1. **Předzpracování** – Použijte Pillow k vylepšení kontrastu nebo binarizaci před předáním obrázku do Aspose OCR. +2. **Více jazyků** – Nastavte `engine.language = ocr.Language.English | ocr.Language.French` pro dvoujazyčné rozpoznání. +3. **OCR podle oblasti** – Pokud potřebujete jen konkrétní část (např. tabulku), nejprve ořízněte obrázek, čímž snížíte šum. +4. **Filtrování podle důvěry** – `result.confidence` poskytuje skóre pro každý znak; nízkodůvěryhodné výsledky můžete programově zahodit. + +--- + +## Plný funkční skript + +Níže je kompletní skript připravený ke zkopírování a vložení. Uložte ho jako `improve_ocr_accuracy.py` a spusťte z příkazové řádky. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Spusťte: + +```bash +python improve_ocr_accuracy.py +``` + +Měli byste vidět pěkně naformátovaný výstup, který jsme ukázali výše. + +--- + +## Závěr + +Právě jsme prošli jednoduchým způsobem, jak **zlepšit přesnost OCR** v Pythonu: + +1. **Nastavení jazyka OCR** tak, aby odpovídal vašemu dokumentu. +2. **Správné načtení obrázku**, aby engine viděl správné pixely. +3. **Provést OCR na obrázku** jedním voláním metody. +4. **Extrahovat text z obrázku** a potvrdit výsledek. +5. **Přidat vlastní slovník** pro zachování specifických termínů. + +To je celý workflow – od surového obrázku po čistý, prohledávatelný text – zabalený do přehledného, znovupoužitelného skriptu. + +Jste připraveni na další výzvu? Zkuste experimentovat s předzpracováním obrazu (kontrast, deskew) nebo přejděte na vícejazykové nastavení pomocí `ocr.Language.English | ocr.Language.German`. Principy zůstávají stejné a budete **zlepšovat OCR přesnost** napříč širší škálou dokumentů. + +Máte otázky nebo zvláštní okrajový případ? Zanechte komentář níže a šťastné kódování! + +![improve OCR accuracy + + +## 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 vašich projektech. + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/czech/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..55ebe3ec3 --- /dev/null +++ b/ocr/czech/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Proveďte OCR na obrázku pomocí knihovny OCR v Pythonu. Naučte se, jak + detekovat text na obrázku, rozpoznávat text z JPEG a efektivně extrahovat text ze + skenovaného obrázku. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: cs +og_description: Proveďte OCR na obrázku pomocí Pythonu a extrahujte text ze skenovaných + souborů. Tento průvodce vás provede načítáním obrázků, korekcí sklonu a rozpoznáváním + textu krok za krokem. +og_title: Proveďte OCR na obrázku v Pythonu – Kompletní průvodce extrakcí textu +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Proveďte OCR na obrázku v Pythonu – Kompletní průvodce extrakcí textu +url: /cs/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Proveďte OCR na obrázku v Pythonu – Kompletní průvodce extrakcí textu + +Už jste někdy potřebovali **provést OCR na obrázku**, ale kód vám připadal nejasný? Nejste v tom sami. Ať už převádíte hromadu naskenovaných účtenek na prohledávatelné PDF nebo vytahujete titulky z JPEG pro datový projekt, schopnost rozpoznávat text z JPEG a dalších formátů je dnes nezbytnou dovedností každého vývojáře. + +V tomto tutoriálu projdeme kompletním, spustitelným příkladem, který vám ukáže, jak **detekovat text z obrázku**, **extrahovat text ze skenovaného obrázku** a dokonce **načíst obrázek pro OCR** během několika řádků. Na konci budete mít solidní, produkčně připravený úryvek, který můžete vložit do svých projektů – bez chybějících importů, bez vágních odkazů „viz dokumentace“. + +## Co si vytvoříte + +- Malý Python skript, který vytvoří OCR engine, povolí automatické vyrovnání, načte JPEG (nebo jakýkoli podporovaný formát) a vytiskne rozpoznaný text. +- Vysvětlení **proč** každé nastavení má význam, ne jen **jak** ho napsat. +- Tipy pro práci s vícestránkovými PDF, neanglickými jazyky a běžnými úskalími, jako jsou rozmazané skeny. + +### Předpoklady + +- Nainstalovaný Python 3.8+ (příklad používá balíček `ocr` dostupný přes `pip install ocr-lib` – nahraďte názvem své knihovny). +- Základní znalost Python funkcí a virtuálních prostředí. +- Soubor s obrázkem (JPEG, PNG, TIFF), který chcete zpracovat; použijeme `skewed_page.jpg` jako zástupný název. + +> **Pro tip:** Pokud používáte Windows, spusťte terminál jako Administrátor při instalaci OCR knihovny, abyste se vyhnuli problémům s oprávněními. + +--- + +## Proveďte OCR na obrázku – Nastavení a konfigurace + +Prvním krokem je čistá instance OCR engine. Představte si ji jako mozek operace; bez správné konfigurace i nejostřejší obrázek vrátí nesmysly. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Proč je to důležité:** +Nastavení `engine.language` zužuje množinu znaků, které OCR engine očekává, což dramaticky zvyšuje přesnost. Pokud to vynecháte, engine se bude hádat a často špatně přečte jednoduchá slova. + +--- + +## Povolit automatické vyrovnání – Oprava nakloněných skenů + +Naskenované stránky zřídka jsou dokonale rovné. Mírný náklon může narušit segmentaci znaků a proměnit „Hello“ na „H3llo“. Příznak `auto_deskew` udělá těžkou práci za vás. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Hraniční případ:** Pokud víte, že vaše obrázky jsou již rovné, vypnutí deskewu může ušetřit několik milisekund – užitečné při zpracování tisíců stránek v dávkovém režimu. + +--- + +## Načíst obrázek pro OCR – Podpora JPEG, PNG, TIFF + +Nyní skutečně **načteme obrázek pro OCR**. Metoda `ocr.Image.load` je flexibilní; přijímá cestu k libovolnému podporovanému rastrovému formátu. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Proč je tento krok klíčový:** Knihovna načte soubor do interní bitmapy a provede případnou konverzi barevného prostoru. Vynechání tohoto kroku a předání surového proudu bajtů vyvolá `FileNotFoundError` nebo, ještě hůř, tiše vrátí prázdné výsledky. + +Pokud potřebujete **rozpoznat text z JPEG** souborů konkrétně, ujistěte se, že přípona souboru je `.jpeg` nebo `.jpg`. Stejné volání funguje i pro PNG (`.png`) nebo TIFF (`.tif`) bez úprav. + +--- + +## Proveďte OCR na obrázku – Spuštění engine + +S připraveným enginem a obrázkem v paměti je čas **provést OCR na obrázku**. Tento jediný řádek udělá těžkou práci: předzpracování, segmentaci, klasifikaci a sestavení textu. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Co se děje pod kapotou?** +- Engine aplikuje transformaci deskew (pokud je povolena). +- Spustí neuronovou síť nebo backend Tesseract k identifikaci znaků. +- Nakonec spojí znaky do slov a řádků a vrátí bohatý objekt `result`. + +--- + +## Extrahovat text ze skenovaného obrázku – Výstup výsledků + +Poslední krok je **extrahovat text ze skenovaného obrázku** a zobrazit jej. Atribut `result.text` obsahuje čistý textový řetězec. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Typický výstup vypadá takto: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Pokud OCR engine nenajde žádné znaky, `result.text` bude prázdný řetězec. V takovém případě zkontrolujte kvalitu obrázku nebo zvažte úpravu vlastnosti `engine.confidence_threshold` (pokud vaše knihovna tuto možnost podporuje). + +--- + +## Řešení běžných variant + +### Rozpoznat text z JPEG vs PNG + +Oba formáty jsou podporovány, ale komprese JPEG může zavést artefakty, které engine zmátou. Pokud zaznamenáte časté chyby rozpoznávání, zkuste nejprve převést JPEG na PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detekovat text z obrázku s více jazyky + +Pokud váš dokument kombinuje angličtinu a španělštinu, nastavte vícejazyčný režim: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Engine pak bude při rozpoznávání zvažovat oba abecedy. + +### Extrahovat text ze skenovaných PDF + +U PDF je nejprve potřeba rasterizovat každou stránku na obrázek. Knihovny jako `pdf2image` to usnadní: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Kompletní funkční příklad + +Níže je celý skript, který můžete zkopírovat do souboru `ocr_demo.py`. Obsahuje ošetření chyb a malý pomocník pro měření doby běhu. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Očekávaný výstup** (při čistém skenu): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Často kladené otázky + +**Q: Můžu to spustit na serveru bez grafického rozhraní?** +A: Rozhodně. Knihovna funguje bez GUI; jen se ujistěte, že jsou nainstalovány potřebné nativní binárky (např. Tesseract) na serveru. + +**Q: Co když je obrázek rozmazaný?** +A: Zvažte přidání filtru pro zaostření před voláním `engine.recognize`. Mnoho OCR knihoven nabízí `image_preprocessing.sharpen = True` nebo můžete použít OpenCV `cv2.GaussianBlur` obráceně. + +**Q: Podporuje skript dávkové zpracování?** +A: Ano. Zabalte `perform_ocr` do smyčky přes seznam cest k souborům, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/czech/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..eb6854d0c --- /dev/null +++ b/ocr/czech/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Proveďte OCR na obrázku pomocí Aspose OCR Java. Naučte se, jak načíst + obrázek pro OCR, použít licenci Aspose a během několika minut extrahovat text z + obrázku. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: cs +og_description: Provádějte OCR na obrázku pomocí Aspose OCR Java. Tento průvodce ukazuje, + jak použít licenci Aspose, načíst obrázek pro OCR a efektivně extrahovat text z + obrázku. +og_title: Provádějte OCR na obrázku s Aspose OCR Java – kompletní tutoriál +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Proveďte OCR na obrázku pomocí Aspose OCR Java – Kompletní krok‑za‑krokem průvodce +url: /cs/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Provádění OCR na obrázku pomocí Aspose OCR Java – Kompletní krok‑za‑krokem průvodce + +Už jste někdy potřebovali **perform OCR on image** soubory, ale nebyli jste si jisti, která knihovna vám poskytne spolehlivé výsledky bez spousty konfigurace? Nejste v tom sami. V mnoha reálných projektech—například skenování pasů, digitalizace faktur nebo získávání textu ze screenshotů—je schopnost rychle rozpoznat text z obrázku skutečným průlomem. + +V tomto tutoriálu vás provedeme praktickým příkladem, který přesně ukazuje, jak **perform OCR on image** pomocí Aspose OCR pro Java. Probereme vše od aplikace vaší Aspose licence po načtení obrázku, spuštění enginu a nakonec **extract text from image**, abyste jej mohli použít dále. Žádné zbytečnosti, jen funkční řešení, které můžete zkopírovat a vložit. + +## Co se naučíte + +- Jasný obrázek, jak **use Aspose license** v Java projektu. +- Přesný kód potřebný k **load image for OCR** a nechat engine automaticky detekovat jazyky. +- Krok‑za‑krokem instrukce k **recognize text image** obsahu a **extract text from image** bezpečně. +- Tipy pro řešení běžných úskalí (prázdné výsledky, nepodporované formáty a problémy s pamětí). + +> **Prerequisites** – Java 8 nebo novější, Maven nebo Gradle pro správu závislostí a soubor licence Aspose OCR pro Java (nebo můžete spustit v evaluačním režimu). + +--- + +## Jak provést OCR na obrázku pomocí Aspose OCR Java + +Níže je kompletní, připravený Java program, který demonstruje celý proces. Uložte jej jako `AsposeOcrDemo.java` a spusťte jej z vašého IDE nebo z příkazové řádky. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Očekávaný výstup v konzoli + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Pokud spustíte program bez souboru licence, první řádek jednoduše uvede, že jste v evaluačním režimu, ale OCR stále funguje. + +--- + +## Nastavení a použití Aspose licence + +### Proč licence má význam + +Spouštění knihovny v evaluačním režimu je v pořádku pro rychlé testy, ale přidává vodoznak do výstupu a omezuje počet stránek, které můžete během jednoho běhu zpracovat. Aplikování kroku **use aspose license** odstraňuje tato omezení a signalizuje Aspose, že jste platící zákazník. + +### Jak získat a aplikovat licenci + +1. Zakupte licenci v obchodě Aspose. +2. Stáhněte soubor `Aspose.OCR.Java.lic`. +3. Umístěte jej na místo, kde ho aplikace může číst—obvykle do složky `src/main/resources`. +4. Zavolejte `new License().setLicense("Aspose.OCR.Java.lic");` před jakoukoli OCR prací, jak je ukázáno v kódu výše. + +> **Pro tip:** Pokud nasazujete na server, použijte absolutní cestu nebo načítač zdrojů z class‑path, abyste se vyhnuli `FileNotFoundException`. + +--- + +## Načtení obrázku pro OCR zpracování + +Řádek `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` je jádrem kroku **load image for OCR**. Aspose OCR podporuje širokou škálu formátů: PNG, JPEG, BMP, TIFF a dokonce i více‑stránkové PDF (při kombinaci s Aspose.Pdf). + +### Časté úskalí + +| Problém | Symptom | Řešení | +|-------|---------|-----| +| Špatná cesta k souboru | `FileNotFoundException` | Zkontrolujte cestu; použijte `Paths.get(...)` pro OS‑nezávislé oddělovače. | +| Nepodporovaný formát | `UnsupportedOperationException` | Převěďte obrázek na PNG nebo JPEG před načtením. | +| Obrovský obrázek ( > 10 MP) | Chyby nedostatku paměti | Zmenšete obrázek pomocí `java.awt.Image` před předáním Aspose. | + +--- + +## Extrahování textu z obrázku a zpracování výsledků + +Jakmile OCR engine dokončí, objekt `OcrResult` obsahuje rozpoznaný řetězec. Zde **extract text from image** pro další zpracování—uložení do databáze, napájení vyhledávacího indexu nebo downstream NLP pipeline. + +### Práce s více jazyky + +Protože jsme nastavili `engine.setLanguage(Language.Auto)`, Aspose se pokusí detekovat jazyky za běhu. Pokud znáte jazyk předem (např. všechny dokumenty jsou v ruštině), můžete nahradit `Language.Auto` za `Language.Russian` pro zvýšení výkonu. + +### Tipy na post‑processing + +- **Trim whitespace**: `result.getText().trim()`. +- **Normalize line endings**: `result.getText().replace("\r\n", "\n")`. +- **Remove non‑printable characters**: použijte regex jako `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Rozpoznání textu z obrázku s pokročilými možnostmi (volitelné) + +Pokud potřebujete jemnější kontrolu, Aspose OCR nabízí další vlastnosti: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Tyto úpravy jsou užitečné, když pracujete s naskenovanými dokumenty, které trpí zkosením nebo nízkým kontrastem. + +--- + +## Shrnutí kompletního funkčního příkladu + +Když spojíme vše dohromady, finální program provede následující kroky v pořadí: + +1. **Perform OCR on image** – vytvořením `OcrEngine`. +2. **Use Aspose license** – volitelné, ale doporučené. +3. **Load image for OCR** – pomocí `Image.load`. +4. **Set language detection** – `Language.Auto` pro **recognize text image** automaticky. +5. **Extract text from image** – vytisknout výsledek, s elegantním zpracováním prázdných odpovědí. + +Můžete zkopírovat výše uvedený blok kódu přímo do Maven projektu s touto závislostí: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Spusťte `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` a sledujte, jak konzole zobrazí rozpoznaný text. + +--- + +## Závěr + +Právě jsme vám ukázali, jak **perform OCR on image** soubory pomocí Aspose OCR pro Java, od aplikace licence po **loading the image for OCR**, **recognizing text image** obsah a nakonec **extracting text from image** pro downstream použití. Přístup je jednoduchý, funguje s více jazyky hned z krabice a lze jej rozšířit o pokročilé předzpracování podle potřeby. + +Co dál? Zkuste nasměrovat výstup OCR do vyhledávacího indexu, generovat PDF s extrahovaným textem nebo experimentovat s různými formáty obrázků. Možnosti jsou neomezené a s robustním API Aspose strávíte více času vývojem funkcí než bojem s OCR problémy. + +Máte otázky nebo narazíte na ohraničený případ? Zanechte komentář níže—šť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, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak extrahovat text z obrázku z URL pomocí Aspose.OCR pro Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Převod obrázku na text v Javě pomocí Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extrahování textu z obrázku v Javě s Aspose.OCR Detekcí oblastí](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..bf644a3e2 --- /dev/null +++ b/ocr/dutch/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-06-19 +description: Maak een doorzoekbare PDF van een afbeelding met Python OCR. Leer hoe + je OCR naar PDF converteert, tekst uit een afbeelding haalt en snel OCR op een afbeelding + uitvoert. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: nl +og_description: Maak doorzoekbare PDF van een afbeelding met Python OCR. Deze gids + laat zien hoe je OCR naar PDF converteert, tekst uit een afbeelding haalt en OCR + op een afbeelding uitvoert. +og_title: Maak een doorzoekbare PDF in Python – Volledige programmeerhandleiding +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Maak een doorzoekbare PDF in Python – Complete stapsgewijze handleiding +url: /nl/python-java/general/create-searchable-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 >}} + +# Maak doorzoekbare PDF in Python – Complete stapsgewijze gids + +Heb je ooit een **create searchable PDF** moeten maken van een gescande bon, maar wist je niet waar je moest beginnen? Je bent niet de enige—veel ontwikkelaars lopen tegen dezelfde muur aan wanneer ze voor het eerst proberen een foto van tekst om te zetten in een PDF die je daadwerkelijk kunt doorzoeken. + +In deze tutorial lopen we een praktische oplossing door die je laat **perform OCR on image**, het OCR‑resultaat omzetten in een **searchable PDF**, en zelfs de ruwe tekst eruit halen als je die nodig hebt voor verdere verwerking. Geen poespas, alleen een werkend voorbeeld dat je vandaag nog kunt copy‑paste in je project. + +## Wat je zult leren + +- Hoe je een lichtgewicht OCR‑engine in Python instelt +- De exacte stappen om **convert OCR to PDF** uit te voeren en op te slaan als een doorzoekbaar document +- Manieren om **extract text from image** te doen voor downstream‑analyse +- Tips voor het omgaan met veelvoorkomende valkuilen zoals beeldoriëntatie en grote bestanden +- Een complete, uitvoerbare script die je kunt aanpassen aan je eigen use‑case + +### Vereisten + +- Python 3.8+ geïnstalleerd op je machine +- Basiskennis van pip en virtuele omgevingen (optioneel maar aanbevolen) +- Een afbeeldingsbestand (PNG, JPEG, etc.) dat duidelijke, machinaal leesbare tekst bevat + +Als je die hebt, laten we duiken. + +## Stap 1: Installeer de vereiste bibliotheek + +De code‑snippet die je eerder zag gebruikt een fictief `ocr`‑pakket, maar dezelfde ideeën gelden voor echte bibliotheken zoals **EasyOCR**, **pytesseract**, of **pdfminer.six**. Voor deze gids gebruiken we **EasyOCR** omdat het pure Python is, veel talen ondersteunt, en een handige PDF‑conversiemethode teruggeeft via een hulpfunctie. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Installeer binnen een virtuele omgeving (`python -m venv venv && source venv/bin/activate`) om je afhankelijkheden netjes te houden. + +## Stap 2: Initialiseert de OCR‑engine – Perform OCR on Image + +Nu de bibliotheek klaar is, maken we een OCR‑engine aan en vertellen we deze om met Engelse tekst te werken. Dit is de eerste plek waar we **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Waarom hebben we een dedicated reader‑object nodig? EasyOCR laadt taalmodellen vooraf, dus het hergebruiken van dezelfde `reader` voor meerdere afbeeldingen is veel efficiënter dan deze elke keer opnieuw te initialiseren. + +## Stap 3: Laad de afbeelding – Extract Text from Image + +Laten we de afbeelding in het geheugen laden. Deze stap is waar we later **extract text from image** doen, maar eerst laden we hem alleen. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Als je afbeelding ondersteboven of scheef staat, overweeg dan om Pillow’s `rotate` of `transpose` methoden te gebruiken voordat je hem naar de OCR‑engine stuurt. Een snelle visuele controle kan je later uren debugging besparen. + +## Stap 4: Voer de OCR‑engine uit en vang resultaten op + +Dit is de kern van het proces—de afbeelding naar de OCR‑engine sturen en gestructureerde data terugkrijgen. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +De `detail=1`‑vlag geeft ons bounding boxes, die we later nodig hebben wanneer we **convert OCR to PDF**. Als je alleen ruwe strings wilt, stel dan `detail=0` in. + +## Stap 5: Converteer OCR‑resultaat naar een searchable PDF – Convert OCR to PDF + +EasyOCR biedt geen directe PDF‑schrijver, maar we kunnen de PDF zelf samenstellen met Pillow en de `reportlab`‑bibliotheek. Om de tutorial lichtgewicht te houden, gebruiken we `fpdf2`, waarmee we de originele afbeelding kunnen embedden en onzichtbare tekst kunnen overlayen. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Wat is er net gebeurd? We plaatsten de gescande afbeelding als de zichtbare laag, en schreven vervolgens de herkende woorden erboven met witte tekst die opgaat in de witte achtergrond. Zoektools lezen nog steeds de verborgen laag, dus wordt de PDF **searchable** zonder de visuele weergave te wijzigen. + +## Stap 6: Sla de PDF‑bytes op – Convert Image to PDF + +Als je de PDF liever in het geheugen verwerkt (bijv. versturen via een API), kun je de bytes vastleggen in plaats van direct naar schijf te schrijven. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Die regel toont de klassieke **convert image to PDF** workflow: je begint met een afbeelding, voert OCR uit, overlayt tekst, en geeft uiteindelijk een PDF‑stream uit. + +## Stap 7: Verifieer het resultaat – Snelle controles + +Nadat je het script hebt uitgevoerd, open `receipt_searchable.pdf` in een PDF‑viewer en probeer de zoekbalk (Ctrl + F). Typ een woord waarvan je weet dat het in de bon staat—als het naar de juiste plek springt, heb je succesvol **create searchable pdf**! + +Als de zoekopdracht mislukt, controleer dan: + +1. De OCR‑vertrouwensscores (`conf`‑waarden). Een lage confidence kan betekenen dat de afbeelding onscherp is. +2. Bounding‑box coördinaten—soms rapporteert EasyOCR ze in een andere oriëntatie. +3. Dat de PDF‑viewer niet is ingesteld op ‘alleen afbeelding’-modus (zeldzaam, maar sommige viewers hebben die optie). + +## Volledig werkend script + +Alles samengevoegd, hier is het volledige, kant‑klaar Python‑bestand: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Sla dit op als `searchable_pdf.py`, vervang de `YOUR_DIRECTORY`‑placeholders door echte paden, en voer uit: + +```bash +python searchable_pdf.py +``` + +Je zou een bevestigingsbericht moeten zien en een gloednieuwe searchable PDF in je map. + +## Veelgestelde vragen & randgevallen + +**Wat als de afbeelding in kleur is?** +EasyOCR werkt met zowel grijswaarden als kleurenafbeeldingen, maar omzetten naar grijswaarden (`pil_image.convert("L")`) kan soms de nauwkeurigheid verbeteren bij ruisende scans. + +**Kan ik multi‑page PDF’s verwerken?** +Ja—loop over elke paginabeeld, voer de OCR‑stappen uit, en voeg elke pagina toe aan hetzelfde `FPDF`‑object. Vergeet niet de cursor te resetten (`self.add_page()`) voor elke nieuwe afbeelding. + +**Is er een manier om de originele tekstlaag te behouden in plaats van onzichtbare witte tekst?** +Als je een echte “text‑under‑image” PDF nodig hebt (bijv. voor toegankelijkheid), overweeg dan `pdfminer` of `pikepdf` te gebruiken om een verborgen tekstlaag met juiste PDF‑tags in te sluiten. Dat is geavanceerder, maar het principe blijft hetzelfde: achtergrondafbeelding + overlay‑tekst. + +**Wat als de OCR‑confidence laag is?** +Je kunt woorden met lage confidence filteren: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Samenvatting – Wat we hebben bereikt + +We begonnen met een eenvoudige afbeelding van een bon, **performed OCR on image**, haalden de herkende strings op, en uiteindelijk **create searchable pdf** die zich gedraagt als elk professioneel gescande document. Het proces besloeg elk secundair trefwoord—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, en **perform OCR on image**—zodat je nu een herbruikbare toolbox hebt voor elk vergelijkbaar project. + +### Volgende stappen + +- Experimenteer met andere talen door hun ISO‑codes door te geven aan `easyocr.Reader(['en', 'es'])`. +- Vervang EasyOCR door Tesseract als je een volledig offline oplossing nodig hebt; de rest van de pijplijn blijft hetzelfde. +- Voeg OCR‑confidence visualisatie toe (teken bounding boxes op de afbeelding) om problematische scans te debuggen. + +Heb je een twist die je wilt delen? Laat een reactie achter, fork + + +## 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 stapsgewijze 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/dutch/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..b10f41afe --- /dev/null +++ b/ocr/dutch/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: Haal tekst uit afbeeldingen in Python met een eenvoudige OCR‑engine. + Leer hoe je gescande afbeeldingen naar tekst converteert, tekst uit foto's herkent + en efficiënt afbeeldingsbestanden in Python opsomt. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: nl +og_description: Haal tekst uit afbeeldingen in Python met een lichtgewicht OCR‑engine. + Deze gids laat zien hoe je gescande afbeeldingen naar tekst converteert, tekst uit + foto's herkent en afbeeldingsbestanden in Python opsomt in een paar stappen. +og_title: Tekst uit afbeeldingen halen in Python – Complete batch OCR‑gids +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Tekst extraheren uit afbeeldingen in Python – Complete batch‑OCR‑gids +url: /nl/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tekst extraheren uit afbeeldingen in Python – Volledige batch‑OCR‑gids + +Heb je ooit **tekst uit afbeeldingen** moeten extraheren maar wist je niet waar te beginnen? Je bent niet de enige—ontwikkelaars staan voortdurend voor de uitdaging om gescande PDF’s, gefotografeerde bonnetjes of screenshots om te zetten in doorzoekbare tekst. In deze tutorial lopen we een compleet, kant‑klaar voorbeeld door dat laat zien hoe je **gescande afbeeldingen naar tekst** kunt **converteren**, tekst uit foto's kunt herkennen, en zelfs **list image files python**‑style. Aan het einde heb je een herbruikbaar script dat een hele map in één keer verwerkt. + +We behandelen alles wat je nodig hebt: vereiste libraries, waarom elke stap belangrijk is, edge‑case‑afhandeling en een beetje foutopsporing. Geen nood om externe documentatie te zoeken; de code hieronder is zelf‑voorzienend, en de uitleg beantwoordt zowel het “hoe” *als* het “waarom”. Pak je favoriete IDE en laten we beginnen. + +--- + +## Wat je gaat bouwen + +- Initialiseert een OCR‑engine (we gebruiken het `ocr`‑pakket ter illustratie). +- Scant een map en **list image files python**‑style, met filter op PNG, JPG en TIFF. +- Voert een **batch OCR**‑operatie uit op alle gevonden afbeeldingen. +- Print de geëxtraheerde tekst voor elk bestand, duidelijk gelabeld. + +> **Pro tip:** Als je de `ocr`‑bibliotheek niet geïnstalleerd hebt, kun je deze vervangen door `pytesseract` met een paar kleine aanpassingen—de kernlogica blijft hetzelfde. + +--- + +## Vereisten + +- Python 3.8+ (het script gebruikt f‑strings en type‑hints). +- Een OCR‑bibliotheek die een `OcrEngine` met `recognize_batch` aanbiedt. Voor deze gids gaan we uit van een fictief `ocr`‑pakket, maar het patroon werkt met echte libraries. +- Een map met afbeeldingsbestanden die je wilt verwerken (`.png`, `.jpg`, `.tif`). + +--- + +## Stap 1 – Installeer & importeer vereiste modules + +Eerst zorg je ervoor dat het OCR‑pakket beschikbaar is. Als je een echte library zoals `pytesseract` gebruikt, vervang dan de import overeenkomstig. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Waarom dit belangrijk is:** Het importeren van `os` geeft ons platform‑onafhankelijke padafhandeling, terwijl `typing.List` helpt bij IDE‑autocomplete en toekomstbestendigheid. + +--- + +## Stap 2 – **Tekst extraheren uit afbeeldingen**: Initialiseer de OCR‑engine + +Het aanmaken van de engine is de eerste stap naar elke OCR‑taak. We stellen de taal in op auto‑detectie zodat de engine documenten met meerdere talen kan verwerken. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Uitleg:** Door de engine‑creatie in een functie te kapselen houden we de code modulair. Als je later DPI of OCR‑modus moet aanpassen, wijzig je alleen deze plek. + +--- + +## Stap 3 – **List Image Files Python**: Bestanden verzamelen uit een map + +Nu moeten we elke afbeelding vinden die we willen verwerken. De list‑comprehensie hieronder weerspiegelt een veelvoorkomend “list image files python”‑patroon. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge‑case‑afhandeling:** De functie negeert sub‑mappen (je kunt later recursie toevoegen) en filtert automatisch verborgen bestanden omdat deze meestal niet eindigen op ondersteunde extensies. + +--- + +## Stap 4 – **Convert Scanned Images to Text**: Batch‑OCR uitvoeren + +De meeste OCR‑libraries bieden een batch‑methode die veel sneller is dan het één‑voor‑één verwerken van afbeeldingen. Zo roepen we het aan. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Waarom batch?** Het in één keer verzenden van alle afbeeldingen vermindert overhead (bijv. het herhaaldelijk laden van het OCR‑model) en levert vaak een betere CPU/GPU‑benutting op. + +--- + +## Stap 5 – **Recognize Text from Pictures**: Resultaten weergeven + +Tot slot itereren we over de gekoppelde bestandsnamen en OCR‑resultaten, en printen we een nette header voor elke afbeelding. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** `strip()` verwijdert voor‑ en achtervoegsels van witruimte die OCR vaak toevoegt. + +--- + +## Volledig script – Alles samenvoegen + +Hieronder staat het complete, uitvoerbare programma. Sla het op als `batch_ocr.py` en voer uit met `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Verwachte output + +Als de map `invoice1.png` en `receipt.jpg` bevat, zie je mogelijk: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Elk blok is duidelijk gelabeld, waardoor downstream verwerking (bijv. opslaan in een database) eenvoudig is. + +--- + +## Veelvoorkomende valkuilen behandelen + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **No text appears** | OCR‑taal niet gedetecteerd of afbeelding heeft te weinig contrast. | Forceer een taal (`engine.language = ocr.Language.English`) of pre‑process de afbeeldingen (verhoog contrast). | +| **Memory error on large batches** | De engine probeert alle afbeeldingen tegelijk te laden. | Splits `image_files` in delen (`batch_size = 20`) en roep `recognize_batch` herhaaldelijk aan. | +| **Unsupported file format** | Je hebt een `.gif` of `.bmp` toegevoegd. | Breid de `supported_exts`‑tuple uit of converteer afbeeldingen vooraf naar PNG/JPG. | +| **Unicode garbling** | OCR retourneert bytes in plaats van strings. | Zorg dat de OCR‑bibliotheek Unicode output (`result.text.decode('utf‑8')` indien nodig). | + +--- + +## Workflow uitbreiden + +Nu je **tekst uit afbeeldingen** kunt extraheren, overweeg je de volgende stappen: + +- **Exporteren naar CSV** – Schrijf elke bestandsnaam en de geëxtraheerde tekst naar een spreadsheet voor analyse. +- **Parallel processing** – Gebruik `concurrent.futures.ThreadPoolExecutor` om meerdere batches gelijktijdig af te handelen. +- **Integreren met cloud‑OCR** – Vervang de lokale engine door Google Vision of Azure OCR voor hogere nauwkeurigheid bij complexe lay-outs. +- **Afbeeldings‑preprocessing toevoegen** – Bibliotheken zoals Pillow of OpenCV kunnen afbeeldingen rechtzetten, ruis verwijderen of drempelen vóór OCR, waardoor de resultaten verbeteren. + +Al deze ideeën maken gebruik van dezelfde kernfuncties die we hebben gebouwd, dus je hoeft niet vanaf nul te beginnen. + +--- + +## Conclusie + +We hebben zojuist een volledige oplossing doorlopen om **tekst uit afbeeldingen** te **extraheren** in Python, van **list image files python** tot **recognize text from pictures** en uiteindelijk **convert scanned images to text** in een nette batch. Het script is bewust eenvoudig maar flexibel genoeg om als basis te dienen voor grotere projecten—of je nu bonnetjes digitaliseert, een doorzoekbaar archief bouwt, of een data‑extractie‑pipeline aandrijft. + +Probeer het, pas de preprocessing‑stappen aan, en zie je OCR‑nauwkeurigheid stijgen. Als je tegen problemen aanloopt, raadpleeg dan de tabel “Veelvoorkomende valkuilen behandelen”; de meeste issues lossen zich op met een kleine configuratiewijziging. + +Klaar voor de volgende uitdaging? Voeg een PDF‑naar‑afbeelding‑conversiestap toe met `pdf2image`, en voed die afbeeldingen direct in dezelfde pipeline. De mogelijkheden zijn eindeloos wanneer je OCR combineert met het rijke ecosysteem van Python. + +Happy coding, and may your text be ever legible! + +## 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 complete 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/) +- [Tekstafbeeldingen extraheren – OCR‑basisprincipes met Aspose.OCR voor Java](/ocr/english/java/ocr-basics/) +- [Hoe tekst uit een afbeelding via URL extraheren met Aspose.OCR voor Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/dutch/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..e2124d13a --- /dev/null +++ b/ocr/dutch/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: tekst extraheren uit afbeeldingen met Python OCR. Leer automatische taaldetectie, + parallelle verwerking en batchherkenning in een beknopte tutorial. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: nl +og_description: tekst extraheren uit afbeeldingen met Python OCR. Deze gids toont + automatische taaldetectie, parallelle verwerking en batchherkenning in één tutorial. +og_title: tekst extraheren uit afbeeldingen in Python – volledige OCR-gids +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: tekst uit afbeeldingen halen in Python – volledige OCR-gids +url: /nl/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tekst uit afbeeldingen extraheren in Python – Volledige OCR-gids + +Heb je je ooit afgevraagd hoe je **tekst uit afbeeldingen** kunt **extraheren** zonder elk woord handmatig te typen? Je bent niet de enige. Of je nu oude bonnen digitaliseert, een doorzoekbaar documentarchief opzet, of gewoon speelt met coole AI-trucs, de mogelijkheid om tekst uit plaatjes te halen is een onmisbare vaardigheid voor elke Python‑ontwikkelaar van vandaag. + +In deze tutorial lopen we stap voor stap door een compleet, kant‑klaar voorbeeld dat **tekst uit afbeeldingen** haalt met een populaire OCR‑engine. We behandelen automatische taalherkenning, parallelle verwerking voor snelheid, en batch‑beeldherkenning zodat je tientallen bestanden in seconden kunt verwerken. Klinkt dit als wat je nodig hebt? Laten we beginnen. + +## Wat je gaat leren + +- Hoe je de OCR‑engine instantiateert met `ocr.OcrEngine`. +- Het inschakelen van **automatische taalherkenning** zodat de engine zelf de juiste taal kiest. +- Het configureren van **parallelle verwerking OCR** met een aangepaste thread‑pool. +- Het uitvoeren van **batch‑beeldherkenning** op een lijst met bestanden. +- Het afdrukken van de herkende tekst voor elke afbeelding, klaar om op te slaan of te indexeren. + +Geen externe documentatie nodig—alles wat je nodig hebt staat hier, en de code werkt direct uit de doos met het `ocr`‑pakket (installeer het via `pip install ocr`). + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +1. Python 3.8 of nieuwer geïnstalleerd. +2. Het `ocr`‑pakket (`pip install ocr`). +3. Een map met PNG‑ (of JPG‑) afbeeldingen die je wilt verwerken. +4. Basiskennis van Python‑functies en loops. + +Dat is alles—geen zware afhankelijkheden, geen GPU‑magie, gewoon pure Python. + +![voorbeeld van tekst uit afbeeldingen extraheren](https://example.com/ocr-demo.png "Schermafbeelding die de uitvoer van tekst uit afbeeldingen extraheren toont") + +*Alt‑tekst: voorbeeld van tekst uit afbeeldingen‑demo‑schermafbeelding* + +## Stap 1 – De OCR‑engine instellen (Primaire trefwoord in actie) + +Allereerst: maak een OCR‑engine‑instantie. Beschouw `ocr.OcrEngine()` als het brein achter de operatie; het weet hoe karakters, regels en alinea’s gelezen moeten worden. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Waarom hebben we een expliciete engine nodig? Omdat het **ocr.OcrEngine‑gebruik** je fijnmazige controle geeft over taalinstellingen, threading en meer. Het is de meest flexibele manier om **tekst uit afbeeldingen** te **extraheren** vergeleken met één‑regelige helpers. + +## Stap 2 – Laat de engine automatisch talen detecteren + +De meeste OCR‑bibliotheken vragen je expliciet welke taal ze moeten zoeken. Dat is prima voor een enkel‑taalproject, maar omslachtig voor een batch met gemengde talen. Gelukkig ondersteunt het `ocr`‑pakket **automatische taalherkenning**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Door `engine.language` in te stellen op `ocr.Language.Auto` vertel je de engine elke afbeelding te sniffen en het juiste taalmodel te kiezen. Deze ene regel bespaart je uren handmatige configuratie wanneer je met internationale documenten werkt. + +## Stap 3 – Versnel met parallelle verwerking OCR + +Heb je vier of meer CPU‑kernen? Gebruik ze dan! De engine kan een thread‑pool opzetten, waardoor meerdere afbeeldingen tegelijk verwerkt worden. Hier komt **parallelle verwerking OCR** tot zijn recht. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Voel je vrij om het getal `4` aan te passen op basis van je machine. Meer threads → snellere batch‑runs, maar onthoud dat elke thread geheugen verbruikt, dus vind een evenwicht voor jouw omgeving. + +## Stap 4 – Verzamel de afbeeldingen die je wilt verwerken + +Nu hebben we een lijst met bestandspaden nodig. Je kunt deze lijst handmatig opbouwen, uit een CSV lezen, of `glob` gebruiken. Voor de duidelijkheid coderen we een korte lijst hard‑coded: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Vervang `YOUR_DIRECTORY` door het daadwerkelijke pad op jouw systeem. Als je tientallen bestanden hebt, doet een snelle `glob.glob("*.png")` het zware werk. + +## Stap 5 – Batch‑beeldherkenning uitvoeren + +Hier is het hart van de tutorial: één enkele aanroep die elke afbeelding in `files` verwerkt en een lijst met resultaatobjecten teruggeeft. Dit is de **batch‑beeldherkenning**‑functie die grootschalige OCR praktisch maakt. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Achter de schermen verdeelt de engine elk bestand over de vier werk‑threads die we eerder configureerden, terwijl hij ook automatisch de taal voor elke afbeelding detecteert. De methode retourneert een lijst waarbij elk element de herkende tekst en metadata bevat. + +## Stap 6 – De geëxtraheerde tekst afdrukken (of opslaan) + +Tot slot lopen we door de resultaten en printen we de tekst. In een echt project zou je dit waarschijnlijk naar een database of CSV‑bestand schrijven, maar afdrukken houdt het voorbeeld simpel. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Verwachte output** (afgekapt voor beknoptheid): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Elk blok toont de bestandsnaam gevolgd door de door OCR afgeleide string. Als een afbeelding meerdere talen bevat, zie je de juiste tekens verschijnen dankzij de eerdere stap **automatische taalherkenning**. + +## Pro‑tips & Veelvoorkomende valkuilen + +- **Afbeeldingskwaliteit is cruciaal** – wazige of laag‑contrast afbeeldingen leveren rommelige resultaten. Pre‑process met OpenCV (`cv2.threshold`, `cv2.resize`) indien nodig. +- **Thread‑aantal vs. I/O** – Als je afbeeldingen op een trage netwerkschijf staan, helpt meer threads misschien niet. Houd CPU‑gebruik in de gaten met `top` of **Task Manager**. +- **Unicode‑afhandeling** – `result.text` is een Unicode‑string. Open bestanden met `encoding="utf‑8"` om `UnicodeEncodeError`s te vermijden. +- **Geheugengebruik** – Grote PDF’s kunnen veel RAM verbruiken. Bij een `MemoryError` verklein je de thread‑pool of verwerk je afbeeldingen in kleinere batches. + +## Volledig werkend script + +Hieronder vind je het complete, copy‑and‑paste‑klare script dat elke stap die we besproken hebben bevat. Sla het op als `batch_ocr.py` en voer `python batch_ocr.py` uit. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Voer het zo uit: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Je ziet een netjes geformatteerd tekstblok voor elke afbeelding, waarmee bewezen wordt dat je **tekst uit afbeeldingen** op schaal kunt **extraheren**. + +## Wat is het vervolg? + +Nu je de basis van **tekst uit afbeeldingen extraheren** met Python onder de knie hebt, kun je overwegen om te verkennen: + +- **Post‑processing**: maak OCR‑output schoon met regex of natural‑language‑libraries. +- **PDF‑conversie**: voer de geëxtraheerde strings in een PDF‑generator voor doorzoekbare PDF’s. +- **Cloud‑OCR‑services**: vergelijk on‑prem `ocr`‑resultaten met Google Vision of Azure OCR voor rand‑case nauwkeurigheid. +- **GUI‑frontend**: bouw een kleine Flask‑ of FastAPI‑app die gebruikers afbeeldingen laat uploaden en direct de geëxtraheerde tekst toont. + +Al deze onderwerpen bouwen voort op de **Python OCR‑library**‑basis die je zojuist hebt opgezet, en ze profiteren allemaal van dezelfde **parallelle verwerking OCR**‑trucs die we hier hebben gebruikt. + +--- + +*Happy coding! Als je ergens vastloopt, laat dan een reactie achter—ik help graag met het oplossen van OCR‑eigenaardigheden.* + +## 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. + +- [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 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/dutch/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/dutch/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..a66f18eed --- /dev/null +++ b/ocr/dutch/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-06-19 +description: Hoe PDF te extraheren met OCR in Python – stapsgewijze tutorial over + het extraheren van tekst uit PDF, het herkennen van tekst uit afbeelding en een + OCR‑Python‑voorbeeld. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: nl +og_description: Hoe PDF te extraheren met OCR in Python. Leer tekst uit PDF te extraheren, + tekst uit afbeelding te herkennen en bekijk een volledig OCR‑Python‑voorbeeld. +og_title: Hoe PDF-tekst te extraheren met OCR in Python – Volledige tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Hoe PDF-tekst te extraheren met OCR in Python – Complete gids +url: /nl/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe PDF-tekst te extraheren met OCR in Python – Complete gids + +Heb je je ooit afgevraagd **hoe je PDF**-inhoud kunt extraheren wanneer het bestand alleen een gescande afbeelding is? Je bent niet de enige. In veel real‑world projecten—denk aan contracten, facturen of historische archieven—heeft de PDF die je ontvangt geen selecteerbare tekst. Het goede nieuws? Een paar regels Python kunnen die alleen‑afbeeldingspagina's omzetten in doorzoekbare, bewerkbare tekst. + +In deze tutorial lopen we een praktisch **OCR Python voorbeeld** door dat een PDF leest, de eerste pagina rendert als een afbeelding, en vervolgens **tekst uit PDF** extraheert met een OCR‑engine. Aan het einde weet je precies hoe je **PDF met OCR kunt lezen**, waarom elke stap belangrijk is, en hoe je de code kunt aanpassen voor documenten met meerdere pagina's of verschillende talen. + +## Wat je zult leren + +- Installeer en configureer een betrouwbare OCR‑bibliotheek voor Python. +- Converteer PDF‑pagina's naar afbeeldingen die geschikt zijn voor OCR. +- **Herken tekst uit afbeelding** en haal schone Unicode‑strings op. +- Veelvoorkomende valkuilen (low‑resolution PDF's, gedraaide pagina's) en hoe je ze kunt vermijden. +- Breid het script uit om meerdere pagina's of batchverwerking te verwerken. + +**Prerequisites**: Python 3.8+, pip, en een basisbegrip van virtuele omgevingen. Geen eerdere OCR‑ervaring vereist—volg gewoon mee. + +--- + +## ## Hoe PDF-tekst te extraheren met OCR in Python + +Deze H2‑kop bevat ons primaire zoekwoord precies waar zoekmachines het graag zien. Laten we meteen in de code duiken. + +### Stap 1 – Installeer de vereiste pakketten + +Eerst hebben we een OCR‑engine nodig. Het voorbeeld hieronder gebruikt het populaire **ocr**‑pakket (een dunne wrapper rond Tesseract). Als je een andere backend verkiest, blijven de concepten hetzelfde. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** Op Linux heb je ook de Tesseract‑binary nodig: `sudo apt-get install tesseract-ocr`. macOS‑gebruikers kunnen het via Homebrew halen: `brew install tesseract`. + +### Stap 2 – Initialiseert de OCR‑engine en stel de taal in + +Nu starten we de engine en vertellen we hem om naar Engelse tekens te zoeken. Je kunt `ocr.Language.English` vervangen door elke ondersteunde taalcodes. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Waarom dit belangrijk is:** Het specificeren van de taal verbetert de nauwkeurigheid drastisch omdat de engine taal‑specifieke woordenboeken en tekensmodellen kan toepassen. + +### Stap 3 – Laad een PDF‑pagina als afbeelding + +OCR werkt op rasterafbeeldingen, niet op PDF‑objecten. De `ocr.Image.from_pdf`‑helper rendert de gekozen pagina naar een bitmap. Pas `page_number` aan voor andere pagina's (0‑gebaseerde indexering). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** Als de PDF vector‑graphics bevat in plaats van gescande afbeeldingen, kun je een scherpe rendering krijgen. Voor low‑resolution scans, overweeg de DPI te verhogen: `ocr.Image.from_pdf(..., dpi=300)`. + +### Stap 4 – Herken tekst uit de gerenderde afbeelding + +Hier is het hart van het **ocr python voorbeeld**. De engine verwerkt de bitmap en retourneert een object dat de geëxtraheerde string bevat. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Het attribuut `ocr_result.text` bevat de platte‑tekst output, waarbij waar mogelijk regeleinden behouden blijven. + +### Stap 5 – Print of sla de geëxtraheerde tekst op + +Tot slot geven we het resultaat weer. In een echte applicatie zou je waarschijnlijk naar een bestand of een database schrijven. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Het uitvoeren van het script zou iets moeten weergeven als: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Dat is een volledige **extract text from pdf** workflow met OCR. + +--- + +## ## Herken tekst uit afbeelding – Nauwkeurigheid aanpassen + +Als je alleen geïnteresseerd bent in **recognize text from image** (bijvoorbeeld een JPEG van een bon), kun je de PDF‑conversiestap overslaan: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips voor betere resultaten:** + +- **Pre‑process** de afbeelding: converteer naar grijswaarden, pas drempeling toe, of deskew. Pillow maakt dit eenvoudig. +- **Increase DPI** tijdens PDF‑rendering: hogere resolutie geeft de OCR‑engine meer detail. +- **Enable OCR engine’s config** voor paginasegmentatie (`ocr_engine.config = "--psm 6"` voor uniforme blokken). + +## ## PDF met OCR lezen – Meerdere pagina's verwerken + +De meeste contracten beslaan meerdere pagina's. Over elke pagina itereren is eenvoudig: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Deze functie **reads PDF with OCR**, voegt de output samen en voegt een duidelijke paginabreak‑markering toe. Je kunt vervolgens `full_text` in een zoekindex voeren of opslaan als een `.txt`‑bestand. + +## ## Veelvoorkomende valkuilen en hoe ze op te lossen + +| Symptoom | Waarschijnlijke oorzaak | Oplossing | +|----------|--------------------------|-----------| +| Vervormde tekens, veel `?` | Verkeerde taal of ontbrekende taal‑databestanden | Installeer het juiste Tesseract‑taalpakket (`tesseract-ocr-`) en stel `ocr_engine.language` in. | +| Ontbrekende regels of afgekorte woorden | Lage DPI (onder 150) | Render de PDF op 300 DPI of hoger (`dpi=300`). | +| Tekst is gedraaid of ondersteboven | Gescante pagina niet rechtop | Gebruik `ocr.Image.deskew(page_image)` vóór herkenning. | +| Trage verwerking bij grote PDF's | Pagina's sequentieel verwerken op één thread | Paralleliseer met `concurrent.futures.ThreadPoolExecutor`. | + +## ## Het OCR Python voorbeeld uitbreiden + +- **Export to PDF/A**: Na extractie kun je de tekst terug inbedden in een doorzoekbare PDF met `reportlab` of `pypdf2`. +- **Language detection**: Gebruik `langdetect` op de OCR‑output om `ocr_engine.language` dynamisch te wisselen. +- **Batch processing**: Loop door een map met `os.listdir` en pas `extract_all_pages` toe op elk bestand. + +## ## Verwachte output en verificatie + +Wanneer je het script uitvoert op een duidelijke, Engelstalige scan, zou je een schoon tekstblok met juiste interpunctie moeten zien. Verifieer door: + +1. Een paar regels vergelijken met de originele gescande afbeelding. +2. Een eenvoudige woordtelling uitvoeren (`len(ocr_result.text.split())`) om te zorgen dat de output niet leeg is. +3. Optioneel de resultaten doorvoeren naar een spell‑checker zoals `pyspellchecker` om OCR‑fouten te vinden. + +## Conclusie + +We hebben **how to extract PDF** inhoud behandeld wanneer traditionele parsing faalt, een volledig **ocr python example** gedemonstreerd, en uitgelegd hoe je **recognize text from image** en **read PDF with OCR** kunt toepassen voor zowel enkel‑pagina als multi‑pagina scenario's. Met de bovenstaande code‑fragmenten kun je nu elke gescande PDF omzetten in doorzoekbare, bewerkbare tekst—geen handmatig overtypen meer. + +Volgende stappen? Probeer de taal te wisselen naar Spaans (`ocr.Language.Spanish`) of experimenteer met beeld‑pre‑processing technieken om de nauwkeurigheid te verhogen. Als je een document‑managementsysteem bouwt, overweeg dan om de geëxtraheerde tekst te indexeren met Elasticsearch voor razendsnelle zoekopdrachten. + +Heb je vragen of loop je tegen een eigenzinnige PDF aan? Laat een reactie achter, en happy coding! + +![Hoe PDF te extraheren met OCR in Python](image.png "Hoe PDF te extraheren met OCR in Python") + +## 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 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. + +- [Tekst extraheren uit afbeelding met Aspose OCR – Stapsgewijze gids](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [PDF-tekst herkennen – OCR‑operaties met Aspose.OCR voor Java](/ocr/english/java/ocr-operations/) +- [Afbeeldingstekst extraheren C# met taalkeuze met behulp van Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/dutch/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..db52be75b --- /dev/null +++ b/ocr/dutch/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-19 +description: Leer hoe je OCR in Java met Aspose kunt gebruiken. Deze stapsgewijze + gids behandelt automatisch kantelen van afbeeldingen, automatische taalherkenning + en het eenvoudig extraheren van tekst uit afbeeldingen. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: nl +og_description: 'Hoe OCR te gebruiken in Java met Aspose: een volledige walkthrough + die automatische kantelcorrectie van afbeeldingen, automatische taaldetectie en + het extraheren van tekst uit afbeeldingen behandelt.' +og_title: Hoe OCR in Java te gebruiken met Aspose – Complete gids +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Hoe OCR in Java met Aspose te gebruiken – Complete gids +url: /nl/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe OCR te gebruiken in Java met Aspose – Complete gids + +Heb je je ooit afgevraagd **hoe je OCR** in een Java‑project kunt gebruiken zonder je haar te verliezen aan configuratie? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur wanneer ze snel **tekst uit afbeelding** moeten extraheren, vooral als de bron‑scans scheef staan of in een onbekende taal zijn geschreven. + +In deze tutorial lopen we stap voor stap een praktisch voorbeeld door dat precies laat zien hoe je OCR met Aspose gebruikt, inclusief **auto deskew images**, **auto language detection** en de volledige **ocr image preprocessing**‑pipeline. Aan het einde heb je een kant‑klaar code‑fragment dat de herkende tekst naar de console print, en begrijp je waarom elke instelling belangrijk is. + +> **Wat je krijgt:** een compleet, uitvoerbaar Java‑programma, uitleg van elke regel, tips voor het omgaan met randgevallen, en ideeën om de oplossing uit te breiden naar batch‑verwerking of PDF‑bestanden. + +--- + +## Vereisten + +- Java 17 (of een recente JDK) geïnstalleerd en geconfigureerd. +- Maven of Gradle voor dependency‑beheer (we laten de Maven‑coördinaten zien). +- Een Aspose OCR for Java‑licentiebestand (`Aspose.OCR.Java.lic`). Als je alleen test, kun je de licentiestap overslaan, maar de gratis proefversie voegt een watermerk toe. +- Een voorbeeldafbeelding (`your_image.png`) ergens toegankelijk voor de code geplaatst. + +> **Pro tip:** bewaar je afbeeldingen in een speciale `resources`‑map en laad ze via het classpath; dat voorkomt pad‑gerelateerde hoofdpijn op verschillende besturingssystemen. + +--- + +## Stap 1: Het project opzetten en Aspose OCR‑dependency toevoegen + +Maak een nieuw Maven‑project (of gebruik je bestaande) en voeg het volgende toe aan je `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Voer `mvn clean install` uit om de bibliotheek te downloaden. Als je Gradle verkiest, is het equivalent: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Nu heb je de **ocr image preprocessing**‑klassen op je classpath. + +--- + +## Stap 2: Je Aspose OCR‑licentie toepassen (optioneel maar aanbevolen) + +Als je een licentie bezit, pas deze dan direct aan het begin van je `main`‑methode toe. Deze stap overslaan werkt, maar de gratis versie plaatst een “Demo”‑watermerk op de output. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Waarom dit belangrijk is:** De gelicentieerde versie verwijdert gebruikslimieten en schakelt het watermerk uit, waardoor je schone, productie‑klare resultaten krijgt. + +--- + +## Stap 3: Maak een OCR‑engine‑instantie + +De engine is het hart van het proces. Door een instantie te maken krijg je toegang tot alle **ocr image preprocessing**‑opties. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Op dit moment is de engine klaar, maar hij gebruikt standaardinstellingen die mogelijk niet optimaal zijn voor gescande documenten. Laten we een paar instellingen aanpassen. + +--- + +## Stap 4: Auto Deskew Images inschakelen voor schonere scans + +Scheef gescande afbeeldingen zijn een veelvoorkomend probleem. Aspose biedt een **auto deskew images**‑functie die de foto automatisch rechtzet vóór herkenning. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Hoe het werkt:** Het algoritme analyseert de hoeken van de tekstbasis en roteert de afbeelding naar de meest waarschijnlijke rechtop‑oriëntatie. Dit verbetert de nauwkeurigheid enorm voor foto’s die met een telefoon zijn genomen. + +--- + +## Stap 5: Auto Language Detection inschakelen + +Als je de taal van de bronafbeelding niet kent, laat de engine het zelf uitzoeken. Dit is de **auto language detection**‑instelling. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Wanneer je dit inschakelt, scant Aspose de glyphs en selecteert het meest waarschijnlijke taamodel, met ondersteuning voor meer dan 30 talen out‑of‑the‑box. + +--- + +## Stap 6: Laad de afbeelding die je wilt herkennen + +Je kunt een afbeelding van schijf, een URL of zelfs een byte‑array laden. Voor de eenvoud lezen we van een lokaal bestand. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** Als je met grote afbeeldingen werkt, overweeg dan eerst te down‑samplen met `engine.getImagePreprocessing().setResizeFactor(0.5)` om de verwerking te versnellen zonder veel detail te verliezen. + +--- + +## Stap 7: Voer OCR‑herkenning uit en extraheer de tekst + +Nu doet de engine zijn magie. De `recognize`‑methode retourneert een `OcrResult`‑object dat de herkende tekst, vertrouwensscores en meer bevat. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +De console toont de platte tekst die uit de afbeelding is gehaald — dit is het kernresultaat **extract text image** dat we wilden bereiken. + +--- + +## Volledig werkend voorbeeld + +Hieronder vind je de complete Java‑klasse die alles samenbrengt. Kopieer‑en‑plak het naar `src/main/java/com/example/OcrDemo.java` en voer het uit. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Verwachte output + +Bevat de afbeelding de tekst “Hello World” op een schone scan, dan zie je: + +``` +=== Recognized Text === +Hello World +``` + +Voor complexere documenten (bijv. meertalige bonnetjes) zal de output regeleinden en de gedetecteerde taalcodes bevatten. + +--- + +## Veelvoorkomende valkuilen & Pro‑tips + +| Probleem | Waarom het gebeurt | Oplossing | +|----------|--------------------|-----------| +| **Onzinnige tekens** | Afbeelding is te donker of ruisig. | Schakel `engine.getImagePreprocessing().setBinarization(true)` in of pas het contrast handmatig aan. | +| **Verkeerde taal** | Auto‑detectie faalt bij pagina’s met meerdere talen. | Stel `engine.setLanguage(Language.English)` (of de juiste enum) in om een specifieke taal af te dwingen. | +| **Trage verwerking** | Zeer hoge resolutie‑afbeeldingen. | Schaal down met `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Out‑of‑memory‑fouten** | Grote batch afbeeldingen tegelijk geladen. | Verwerk afbeeldingen één voor één en roep `engine.dispose()` aan na elke run. | + +> **Onthoud:** De OCR‑engine is thread‑safe voor alleen‑lezen operaties, maar een nieuwe instantie per thread voorkomt verborgen status‑bugs. + +--- + +## De oplossing uitbreiden + +Nu je weet **hoe je OCR** met Aspose gebruikt, kun je overwegen om: + +1. **PDF’s te verwerken** – Converteer elke PDF‑pagina naar een afbeelding (`PdfConverter`) en voer die door dezelfde pipeline. +2. **Een map batch‑matig te verwerken** – Loop door bestanden in een directory, pas dezelfde stappen toe en schrijf de resultaten naar een CSV. +3. **Integreren met een webservice** – Expose de OCR‑logica via een Spring Boot `@RestController` die multipart‑uploads accepteert. + +Al deze scenario’s hergebruiken dezelfde **ocr image preprocessing**‑configuratie die we hier hebben opgebouwd. + +--- + +## Conclusie + +We hebben stap voor stap behandeld **hoe je OCR** in Java met Aspose gebruikt: een licentie toepassen, de engine maken, **auto deskew images** inschakelen, **auto language detection** activeren, een afbeelding laden, en tenslotte **extract text image** met één `System.out.println`. De code is volledig zelf‑voorzienend, draait op elke recente JDK en laat best practices zien voor nauwkeurigheid en prestaties. + +Probeer het met je eigen afbeeldingen — bijvoorbeeld een gescande overeenkomst of een screenshot van een bon. Pas de preprocessing‑vlaggen aan, experimenteer met verschillende talen, en je zult snel zien waarom Aspose’s OCR‑bibliotheek een solide keuze is voor productie‑klare tekstextractie. + +Vragen of resultaten om te delen? Laat een reactie achter of stuur me een bericht op GitHub. Veel programmeerplezier! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## Wat kun 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. + +- [Hoe OCR‑afbeeldingstekst met taal te gebruiken met Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Tekst uit afbeelding extraheren in Java met Aspose.OCR Detect Areas‑modus](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Hoe OCR te gebruiken – Geavanceerde technieken met Aspose.OCR voor Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/dutch/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..9ac61da9f --- /dev/null +++ b/ocr/dutch/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Verbeter de OCR‑nauwkeurigheid in Python met Aspose OCR. Leer hoe je + de OCR‑taal instelt, een afbeelding laadt voor OCR en tekst uit een afbeelding haalt + met een aangepast woordenboek. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: nl +og_description: Verbeter de OCR‑nauwkeurigheid in Python door de OCR‑taal in te stellen, + een afbeelding voor OCR te laden en tekst uit de afbeelding te extraheren met een + aangepast woordenboek. +og_title: Verbeter de OCR‑nauwkeurigheid in Python – Stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Verbeter OCR-nauwkeurigheid in Python – Complete gids +url: /nl/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Verbeter OCR-nauwkeurigheid in Python – Complete gids + +Heb je je ooit afgevraagd hoe je **OCR-nauwkeurigheid kunt verbeteren** wanneer de tekst die je scant vreemde symbolen, productcodes of merknamen bevat? Je bent niet de enige. In veel projecten geeft de standaardengine gewoon onzin weer, en dat is een echte productiviteitskiller. + +In deze tutorial lopen we een praktisch, end‑to‑end voorbeeld door dat je laat zien hoe je **OCR-taal instelt**, **afbeelding laadt voor OCR**, **OCR uitvoert op een afbeelding**, en uiteindelijk **tekst uit afbeelding haalt** met een aangepast woordenboek dat de herkenningspercentages verhoogt. Aan het einde heb je een kant‑klaar script dat je in elke Python‑codebase kunt gebruiken. + +## Wat je zult meenemen + +- Een volledig functioneel Python‑script dat Aspose OCR gebruikt om een PNG‑bestand te lezen. +- Het vermogen om **OCR-nauwkeurigheid te verbeteren** door de taal en een aangepast woordenlijst te configureren. +- Duidelijke uitleg waarom elke instelling belangrijk is, plus tips voor het omgaan met randgevallen zoals niet‑Latijnse tekens. +- Een snelle checklist voor het oplossen van veelvoorkomende OCR‑valkuilen. + +### Vereisten + +- Python 3.8 of nieuwer geïnstalleerd op je machine. +- `aspose-ocr`‑pakket (installeren via `pip install aspose-ocr`). +- Een voorbeeldafbeelding (`technical_doc.png`) die de tekst bevat die je wilt lezen. +- Basiskennis van Python—geen geavanceerde kennis vereist. + +> **Pro tip:** Als je in een virtuele omgeving werkt, activeer deze dan vóór het installeren van het pakket. Het houdt je afhankelijkheden netjes en voorkomt versieconflicten. + +--- + +## Stap 1: Installeer en importeer Aspose OCR + +Allereerst—laten we de bibliotheek in onze omgeving krijgen en de benodigde onderdelen importeren. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +De `aspose.ocr`‑namespace geeft je toegang tot de `OcrEngine`‑klasse, die het hart van het OCR‑proces vormt. Het hier importeren houdt de rest van het script schoon en leesbaar. + +--- + +## Stap 2: Maak een OCR‑engine en **stel OCR‑taal in** + +Waarom is de taal belangrijk? OCR‑engines vertrouwen op taalspecifieke modellen om tekenvormen en woordpatronen te herkennen. Als je de engine vertelt dat je Engelse tekst scant, negeert hij Cyrillische tekens en richt hij zich op het Latijnse alfabet, waardoor de **OCR‑nauwkeurigheid** drastisch **verbeterd** wordt. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Opmerking:** Aspose OCR ondersteunt meer dan 50 talen. Vervang `ocr.Language.English` door `ocr.Language.Spanish`, `ocr.Language.French`, enz., als je document niet Engels is. + +--- + +## Stap 3: Definieer een **aangepast woordenboek** om de nauwkeurigheid te verhogen + +Stel je voor dat je facturen scant die het woord “AsposeOCR” of productcodes zoals “SKU12345” bevatten. De engine kent die termen niet, dus raadt hij onjuist. Het leveren van een aangepaste woordenlijst vertelt de engine, *“Hé, deze strings zijn legitiem—probeer ze niet te corrigeren.”* Dat is een snelle winst voor **OCR‑nauwkeurigheid verbeteren**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Je kunt deze lijst laden vanuit een bestand of een database als je honderden items hebt—bewaar het gewoon in een Python‑lijst voor de eenvoud. + +--- + +## Stap 4: **Afbeelding laden voor OCR** + +Nu hebben we een afbeelding nodig. De `Image.load`‑methode accepteert een pad naar elk ondersteund rasterformaat (PNG, JPEG, BMP, enz.). Als het bestand niet gevonden kan worden, gooit de engine een uitzondering, dus we zullen hiertegen beschermen. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Waarom deze stap belangrijk is:** Het correct laden van de afbeelding zorgt ervoor dat de engine werkt met de exacte pixelgegevens die je wilt analyseren. Beschadigde bestanden of verkeerde paden zijn een veelvoorkomende bron van frustratie. + +--- + +## Stap 5: **OCR uitvoeren op afbeelding** en resultaten extraheren + +Met de engine geconfigureerd en de afbeelding klaar, is de daadwerkelijke herkenning één enkele methode‑aanroep. Het resultaatsobject bevat de ruwe tekst, vertrouwensscores en zelfs lay‑outinformatie als je die later nodig hebt. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Als je **tekst uit afbeelding** regel voor regel wilt **extraheren**, kun je splitsen op nieuwe‑regeltekens: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Stap 6: Verifieer de output – Verbetert het echt **OCR‑nauwkeurigheid**? + +Laten we het resultaat afdrukken en kijken of ons aangepaste woordenboek een verschil maakt. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Typische output voor de voorbeeldafbeelding kan er als volgt uitzien: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Let op hoe de merknaam, het Griekse teken en de productcode precies verschijnen zoals we ze hebben gedefinieerd. Zonder het aangepaste woordenboek zou de engine geprobeerd hebben ze te “corrigeren”, vaak resulterend in iets als “Aspose OCR” of “SKU 1234”. + +--- + +## Veelvoorkomende valkuilen & hoe ze aan te pakken + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Onzinnige tekens** | Verkeerde taal ingesteld of afbeelding met lage resolutie | Zorg ervoor dat `engine.language` overeenkomt met de brontaal en gebruik een scan met hoge DPI (300 dpi of hoger). | +| **Aangepaste woorden genegeerd** | Woordenboek niet gekoppeld of typefout in eigenschapsnaam | Controleer `engine.text_processing.custom_dictionary = …` nogmaals. | +| **Bestand niet gevonden** | Onjuist pad of ontbrekende bestandsrechten | Gebruik `os.path.abspath()` om het absolute pad te verifiëren; voer het script uit met de juiste rechten. | +| **Trage verwerking** | Grote afbeeldingen of veel pagina's | Pre‑process de afbeelding (bijsnijden, verkleinen) of gebruik `engine.recognize(image, max_threads=4)` om te paralleliseren. | + +--- + +## Verder gaan: Geavanceerde aanpassingen voor **OCR‑nauwkeurigheid verbeteren** + +1. **Pre‑processing** – Pas contrastverbetering of binarisatie toe met Pillow voordat je de afbeelding aan Aspose OCR levert. +2. **Meerdere talen** – Stel `engine.language = ocr.Language.English | ocr.Language.French` in om tweetalige herkenning mogelijk te maken. +3. **Region‑gebaseerde OCR** – Als je alleen een specifiek gebied nodig hebt (bijv. een tabel), snijd de afbeelding dan eerst bij om ruis te verminderen. +4. **Confidence‑filtering** – `result.confidence` geeft een score per teken; je kunt resultaten met een lage vertrouwensscore programmatically verwijderen. + +--- + +## Volledig werkend script + +Hieronder vind je het volledige, kant‑klaar script dat elke stap die we hebben besproken bevat. Sla het op als `improve_ocr_accuracy.py` en voer het uit vanaf de opdrachtregel. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Voer het uit: + +```bash +python improve_ocr_accuracy.py +``` + +Je zou de netjes geformatteerde output moeten zien die we eerder hebben getoond. + +--- + +## Conclusie + +We hebben zojuist een eenvoudige manier behandeld om **OCR‑nauwkeurigheid te verbeteren** in Python door: + +1. **De OCR‑taal in te stellen** zodat deze overeenkomt met je document. +2. **De afbeelding correct te laden** zodat de engine de juiste pixels ziet. +3. **OCR uit te voeren op de afbeelding** met één methode‑aanroep. +4. **Tekst uit de afbeelding te extraheren** en het resultaat te bevestigen. +5. **Een aangepast woordenboek toe te voegen** om domeinspecifieke termen vast te leggen. + +Dat is de volledige workflow—van ruwe afbeelding tot schone, doorzoekbare tekst—samengebracht in een net, herbruikbaar script. + +Als je klaar bent voor de volgende uitdaging, experimenteer dan met beeld‑pre‑processing (contrast, kanteling corrigeren) of schakel over naar een meertalige configuratie met `ocr.Language.English | ocr.Language.German`. Dezelfde principes gelden, en je blijft **OCR‑nauwkeurigheid verbeteren** over een bredere reeks documenten. + +Heb je vragen of een vreemd randgeval? Laat een reactie achter hieronder, en veel plezier met coderen! + +![improve OCR accuracy + + +## 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 stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [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/) +- [Hoe drempelwaarde in te stellen bij OCR‑afbeeldingsherkenning](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/dutch/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..fe1f98568 --- /dev/null +++ b/ocr/dutch/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Voer OCR uit op een afbeelding met behulp van de OCR‑bibliotheek van + Python. Leer hoe je tekst uit een afbeelding detecteert, tekst uit een JPEG herkent + en efficiënt tekst uit een gescande afbeelding extraheert. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: nl +og_description: Voer OCR uit op een afbeelding met Python en haal tekst uit gescande + bestanden. Deze gids leidt je stap voor stap door het laden van afbeeldingen, het + corrigeren van scheefstand en het herkennen van tekst. +og_title: Voer OCR uit op afbeelding in Python – Volledige gids voor tekstextractie +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Voer OCR uit op afbeelding in Python – Volledige gids voor teksteextractie +url: /nl/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Voer OCR uit op afbeelding in Python – Complete gids voor teksterkenning + +Heb je ooit **OCR op afbeelding**‑bestanden moeten uitvoeren, maar liep je tegen een muur omdat de code cryptisch leek? Je bent niet de enige. Of je nu een stapel gescande bonnen omzet in doorzoekbare PDF’s of bijschriften uit een JPEG haalt voor een data‑science project, de mogelijkheid om tekst uit JPEG’s en andere formaten te herkennen is een onmisbare vaardigheid voor elke ontwikkelaar vandaag. + +In deze tutorial lopen we stap voor stap door een volledig, uitvoerbaar voorbeeld dat laat zien hoe je **tekst van afbeelding**‑bestanden kunt **detecteren**, **tekst uit gescande afbeelding**‑documenten kunt **extraheren**, en zelfs **afbeelding voor OCR kunt laden** in slechts een handvol regels code. Aan het einde heb je een solide, productie‑klaar fragment dat je in je eigen projecten kunt gebruiken — zonder ontbrekende imports, zonder vage “zie docs” shortcuts. + +## Wat je gaat bouwen + +- Een klein Python‑script dat een OCR‑engine maakt, auto‑deskew inschakelt, een JPEG (of elk ondersteund formaat) laadt, en de herkende tekst afdrukt. +- Uitleg over **waarom** elke instelling belangrijk is, niet alleen **hoe** je het moet typen. +- Tips voor het omgaan met multi‑page PDF’s, niet‑Engelse talen, en veelvoorkomende valkuilen zoals wazige scans. + +### Vereisten + +- Python 3.8+ geïnstalleerd (het voorbeeld gebruikt het `ocr`‑pakket dat beschikbaar is via `pip install ocr-lib` – vervang dit door de daadwerkelijke bibliotheeknaam). +- Basiskennis van Python‑functies en virtuele omgevingen. +- Een afbeeldingsbestand (JPEG, PNG, TIFF) dat je wilt verwerken; we gebruiken `skewed_page.jpg` als placeholder. + +> **Pro tip:** Als je Windows gebruikt, voer je terminal dan uit als Administrator bij het installeren van de OCR‑bibliotheek om permissie‑problemen te vermijden. + +--- + +## OCR op afbeelding uitvoeren – Installatie en configuratie + +Het eerste wat je nodig hebt is een schone OCR‑engine‑instantie. Beschouw het als het brein achter de operatie; zonder juiste configuratie levert zelfs de scherpste afbeelding onzin op. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Waarom dit belangrijk is:** +Het instellen van `engine.language` beperkt de tekenset die de OCR‑engine verwacht, wat de nauwkeurigheid drastisch verhoogt. Als je dit overslaat, zal de engine proberen te raden, vaak met foutieve woorden. + +--- + +## Automatische Deskew inschakelen – Kantelen van scans corrigeren + +Gescannde pagina’s zijn zelden perfect vlak. Een lichte kanteling kan de karaktersegmentatie verstoren, waardoor “Hello” wordt “H3llo”. De `auto_deskew`‑vlag doet het zware werk voor je. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Randgeval:** Als je weet dat je afbeeldingen al recht zijn, kun je deskew uitschakelen om een paar milliseconden verwerkingstijd te besparen — handig bij het verwerken van duizenden pagina’s in een batch‑taak. + +--- + +## Afbeelding voor OCR laden – Ondersteuning voor JPEG, PNG, TIFF + +Nu **laden we de afbeelding voor OCR**. De `ocr.Image.load`‑methode is flexibel; hij accepteert een pad naar elk ondersteund rasterformaat. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Waarom deze stap cruciaal is:** De bibliotheek leest het bestand in een interne bitmap, past eventuele kleur‑ruimte‑conversies toe. Als je dit overslaat en een ruwe byte‑stroom doorgeeft, krijg je een `FileNotFoundError` of, erger, stille lege resultaten. + +Als je specifiek **tekst uit JPEG**‑bestanden wilt **herkennen**, zorg er dan voor dat de bestandsextensie `.jpeg` of `.jpg` is. Dezelfde aanroep werkt voor PNG (`.png`) of TIFF (`.tif`) zonder wijziging. + +--- + +## OCR op afbeelding uitvoeren – Engine laten draaien + +Met de engine klaar en de afbeelding in het geheugen, is het tijd om **OCR op afbeelding**‑data uit te voeren. Deze ene regel doet het zware werk: pre‑processing, segmentatie, classificatie en tekstassemblage. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Wat er onder de motorkap gebeurt:** +- De engine past de deskew‑transformatie toe (indien ingeschakeld). +- Hij draait een neuraal netwerk of Tesseract‑backend om karakters te identificeren. +- Ten slotte worden karakters aan elkaar geplakt tot woorden en regels, en wordt een rijk `result`‑object geretourneerd. + +--- + +## Tekst uit gescande afbeelding extraheren – Resultaten weergeven + +De laatste stap is om **tekst uit gescande afbeelding** te **extraheren** en weer te geven. Het attribuut `result.text` bevat de platte‑tekst representatie. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Typische output ziet er als volgt uit: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Als de OCR‑engine geen karakters vindt, is `result.text` een lege string. Controleer in dat geval de beeldkwaliteit of pas de eigenschap `engine.confidence_threshold` aan (als je bibliotheek dit ondersteunt). + +--- + +## Veelvoorkomende variaties afhandelen + +### Tekst herkennen uit JPEG vs PNG + +Beide formaten worden ondersteund, maar JPEG‑compressie kan artefacten introduceren die de engine verwarren. Als je vaak verkeerde herkenningen ziet, probeer de JPEG eerst naar PNG te converteren: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Tekst detecteren uit afbeelding met meerdere talen + +Als je document Engels en Spaans combineert, stel dan een meertalige modus in: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +De engine houdt dan beide alfabetten in overweging tijdens de herkenning. + +### Tekst extraheren uit gescande PDF’s + +Voor PDF’s moet je elke pagina eerst rasteren naar een afbeelding. Bibliotheken zoals `pdf2image` maken dit moeiteloos: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Volledig werkend voorbeeld + +Hieronder staat het complete script dat je kunt kopiëren‑plakken in een `ocr_demo.py`‑bestand. Het bevat foutafhandeling en een kleine helper om de uitvoeringstijd te meten. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Verwachte output** (bij een heldere scan): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Veelgestelde vragen + +**V: Kan ik dit op een headless server draaien?** +A: Absoluut. De bibliotheek werkt zonder GUI; zorg er alleen voor dat de benodigde native binaries (bijv. Tesseract) op de server geïnstalleerd zijn. + +**V: Wat als de afbeelding wazig is?** +A: Overweeg een verscherpingsfilter toe te passen vóór `engine.recognize`. Veel OCR‑bibliotheken bieden `image_preprocessing.sharpen = True` of je kunt OpenCV’s `cv2.GaussianBlur` in omgekeerde richting gebruiken. + +**V: Ondersteunt het script batch‑verwerking?** +A: Ja. Plaats `perform_ocr` in een lus over een lijst met bestandspaden, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/dutch/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..4a3b76eb6 --- /dev/null +++ b/ocr/dutch/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-19 +description: Voer OCR uit op een afbeelding met Aspose OCR Java. Leer hoe je een afbeelding + laadt voor OCR, de Aspose‑licentie gebruikt en tekst uit een afbeelding haalt in + enkele minuten. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: nl +og_description: Voer OCR uit op een afbeelding met Aspose OCR Java. Deze gids laat + zien hoe je de Aspose‑licentie gebruikt, een afbeelding laadt voor OCR en efficiënt + tekst uit de afbeelding extraheert. +og_title: Voer OCR uit op afbeelding met Aspose OCR Java – Volledige tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Voer OCR uit op een afbeelding met Aspose OCR Java – Complete stap‑voor‑stap + gids +url: /nl/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR uitvoeren op afbeelding met Aspose OCR Java – Complete stapsgewijze handleiding + +Heb je ooit **OCR op afbeelding** moeten uitvoeren, maar wist je niet welke bibliotheek betrouwbare resultaten levert zonder veel configuratie? Je bent niet de enige. In veel real‑world projecten—denk aan het scannen van paspoorten, digitaliseren van facturen, of tekst uit screenshots halen—maakt de mogelijkheid om snel tekst uit afbeeldingsdata te herkennen een enorm verschil. + +In deze tutorial lopen we een praktische voorbeeld stap voor stap door dat precies laat zien hoe je **OCR op afbeelding** uitvoert met Aspose OCR voor Java. We behandelen alles van het toepassen van je Aspose‑licentie tot het laden van de afbeelding, het draaien van de engine, en uiteindelijk **tekst uit afbeelding extraheren** zodat je het downstream kunt gebruiken. Geen poespas, alleen een werkende oplossing die je kunt copy‑pasten. + +## Wat je zult leren + +- Een duidelijk beeld van hoe je **Aspose‑licentie** gebruikt in een Java‑project. +- De exacte code die nodig is om een **afbeelding te laden voor OCR** en de engine automatisch talen te laten detecteren. +- Stapsgewijze instructies om **tekst in afbeelding** te **herkennen** en veilig **tekst uit afbeelding** te **extraheren**. +- Tips voor het omgaan met veelvoorkomende valkuilen (lege resultaten, niet‑ondersteunde formaten en geheugenproblemen). + +> **Prerequisites** – Java 8 of nieuwer, Maven of Gradle voor dependency‑beheer, en een Aspose OCR voor Java licentiebestand (of je kunt in evaluatiemodus draaien). + +--- + +## Hoe OCR uit te voeren op afbeelding met Aspose OCR Java + +Hieronder staat het volledige, kant‑klaar Java‑programma dat de volledige stroom demonstreert. Sla het op als `AsposeOcrDemo.java` en voer het uit vanuit je IDE of de commandoregel. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Verwachte console‑output + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Als je het programma zonder licentiebestand draait, zal de eerste regel simpelweg aangeven dat je in evaluatiemodus bent, maar de OCR werkt nog steeds. + +--- + +## Instellen en gebruiken van Aspose‑licentie + +### Waarom een licentie belangrijk is + +Het draaien van de bibliotheek in evaluatiemodus is prima voor snelle tests, maar het voegt een watermerk toe aan de output en beperkt het aantal pagina's dat je per run kunt verwerken. Het toepassen van de **use aspose license** stap verwijdert deze beperkingen en signaleert aan Aspose dat je een betalende klant bent. + +### Hoe je het verkrijgt en toepast + +1. Koop een licentie via de Aspose‑winkel. +2. Download het `Aspose.OCR.Java.lic`‑bestand. +3. Plaats het op een locatie die je applicatie kan lezen—meestal de `src/main/resources` map. +4. Roep `new License().setLicense("Aspose.OCR.Java.lic");` aan vóór enige OCR‑werk, zoals getoond in de code hierboven. + +> **Pro tip:** Als je naar een server deployt, gebruik dan een absoluut pad of een class‑path resource loader om `FileNotFoundException` te vermijden. + +--- + +## Afbeelding laden voor OCR‑verwerking + +De regel `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` is het hart van de **load image for OCR** stap. Aspose OCR ondersteunt een breed scala aan formaten: PNG, JPEG, BMP, TIFF, en zelfs multi‑page PDF’s (wanneer gecombineerd met Aspose.Pdf). + +### Common Pitfalls + +| Probleem | Symptoom | Oplossing | +|----------|----------|-----------| +| Verkeerd bestandspad | `FileNotFoundException` | Controleer het pad; gebruik `Paths.get(...)` voor OS‑onafhankelijke scheidingstekens. | +| Niet‑ondersteund formaat | `UnsupportedOperationException` | Converteer de afbeelding naar PNG of JPEG voordat je deze laadt. | +| Grote afbeelding ( > 10 MP) | Out‑of‑memory errors | Verklein de afbeelding met `java.awt.Image` voordat je deze aan Aspose doorgeeft. | + +--- + +## Tekst uit afbeelding extraheren en resultaten verwerken + +Zodra de OCR‑engine klaar is, bevat het `OcrResult`‑object de herkende string. Dit is waar we **tekst uit afbeelding** extraheren voor verdere verwerking—opslaan in een database, voeden van een zoekindex, of doorgeven aan een downstream NLP‑pipeline. + +### Omgaan met meerdere talen + +Omdat we `engine.setLanguage(Language.Auto)` instellen, zal Aspose proberen talen on‑the‑fly te detecteren. Als je de taal van tevoren kent (bijv. alle documenten zijn Russisch), kun je `Language.Auto` vervangen door `Language.Russian` voor een prestatie‑boost. + +### Tips voor post‑processing + +- **Verwijder witruimte**: `result.getText().trim()`. +- **Normaliseer regeleinden**: `result.getText().replace("\r\n", "\n")`. +- **Verwijder niet‑printbare tekens**: gebruik een regex zoals `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Tekst in afbeelding herkennen met geavanceerde opties (optioneel) + +Als je fijnere controle nodig hebt, biedt Aspose OCR extra eigenschappen: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Deze aanpassingen zijn handig wanneer je werkt met gescande documenten die last hebben van scheefstand of laag contrast. + +--- + +## Samenvatting van volledig werkend voorbeeld + +Alles samengevoegd doet het uiteindelijke programma het volgende in volgorde: + +1. **OCR uitvoeren op afbeelding** – door een `OcrEngine` te maken. +2. **Aspose‑licentie gebruiken** – optioneel maar aanbevolen. +3. **Afbeelding laden voor OCR** – via `Image.load`. +4. **Taaldetectie instellen** – `Language.Auto` om **tekst in afbeelding** automatisch te herkennen. +5. **Tekst uit afbeelding extraheren** – print het resultaat, en verwerk lege antwoorden op een nette manier. + +Je kunt het bovenstaande code‑blok direct in een Maven‑project plaatsen met deze dependency: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Voer `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` uit en zie hoe de console de herkende tekst weergeeft. + +--- + +## Conclusie + +We hebben je net laten zien hoe je **OCR op afbeelding** bestanden uitvoert met Aspose OCR voor Java, van het toepassen van een licentie tot **de afbeelding voor OCR laden**, **tekst in afbeelding** herkennen, en uiteindelijk **tekst uit afbeelding** extraheren voor downstream gebruik. De aanpak is eenvoudig, werkt met meerdere talen out‑of‑the‑box, en kan worden uitgebreid met geavanceerde pre‑processing opties wanneer nodig. + +Wat nu? Probeer de OCR‑output te voeden aan een zoekindex, genereer PDF’s met de geëxtraheerde tekst, of experimenteer met verschillende afbeeldingsformaten. De mogelijkheden zijn eindeloos, en met Aspose’s robuuste API besteed je meer tijd aan het bouwen van functionaliteit dan aan het worstelen met OCR‑eigenaardigheden. + +Heb je vragen of loop je tegen een edge case aan? Laat een reactie achter—happy coding! + +## 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 tekst uit afbeelding te extraheren vanaf URL met Aspose.OCR voor Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Afbeelding naar tekst converteren in Java met Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Tekst uit afbeelding extraheren in Java met Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/english/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e08d9adb8 --- /dev/null +++ b/ocr/english/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: en +og_description: Create searchable PDF from an image with Python OCR. This guide shows + how to convert OCR to PDF, extract text from image, and perform OCR on image. +og_title: Create Searchable PDF in Python – Full Programming Walkthrough +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Create Searchable PDF in Python – Complete Step‑by‑Step Guide +url: /python-java/general/create-searchable-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 >}} + +# Create Searchable PDF in Python – Complete Step‑by‑Step Guide + +Ever needed to **create searchable PDF** from a scanned receipt but weren’t sure where to begin? You’re not alone—many developers hit the same wall when they first try to turn a picture of text into a PDF you can actually search. + +In this tutorial we’ll walk through a practical solution that lets you **perform OCR on image**, turn that OCR result into a **searchable PDF**, and even pull the raw text out if you need it for further processing. No fluff, just a working example you can copy‑paste into your project today. + +## What You’ll Learn + +- How to set up a lightweight OCR engine in Python +- The exact steps to **convert OCR to PDF** and save it as a searchable document +- Ways to **extract text from image** for downstream analysis +- Tips for handling common pitfalls like image orientation and large files +- A complete, runnable script that you can adapt to your own use‑case + +### Prerequisites + +- Python 3.8+ installed on your machine +- Basic familiarity with pip and virtual environments (optional but recommended) +- An image file (PNG, JPEG, etc.) that contains clear, machine‑readable text + +If you’ve got those, let’s dive in. + +## Step 1: Install the Required Library + +The code snippet you saw earlier uses a fictional `ocr` package, but the same ideas apply to real‑world libraries such as **EasyOCR**, **pytesseract**, or **pdfminer.six**. For this guide we’ll use **EasyOCR** because it’s pure Python, supports many languages, and returns a handy PDF conversion method via an auxiliary helper. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Install inside a virtual environment (`python -m venv venv && source venv/bin/activate`) to keep your dependencies tidy. + +## Step 2: Initialize the OCR Engine – Perform OCR on Image + +Now that the library is ready, we create an OCR engine and tell it to work with English text. This is the first place where we **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Why do we need a dedicated reader object? EasyOCR pre‑loads language models, so re‑using the same `reader` for multiple images is far more efficient than re‑initializing it each time. + +## Step 3: Load the Image – Extract Text from Image + +Let’s bring the picture into memory. This step is where we **extract text from image** later, but first we just load it. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +If your image is upside‑down or skewed, consider using Pillow’s `rotate` or `transpose` methods before feeding it to the OCR engine. A quick visual check can save you hours of debugging later. + +## Step 4: Run the OCR Engine and Capture Results + +Here’s the core of the process—sending the image to the OCR engine and getting back structured data. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +The `detail=1` flag gives us bounding boxes, which we’ll need when we later **convert OCR to PDF**. If you only care about raw strings, set `detail=0`. + +## Step 5: Convert OCR Result to a Searchable PDF – Convert OCR to PDF + +EasyOCR doesn’t provide a direct PDF writer, but we can stitch together the PDF ourselves using Pillow and the `reportlab` library. To keep the tutorial lightweight, we’ll use `fpdf2`, which lets us embed the original image and overlay invisible text. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +What just happened? We placed the scanned image as the visible layer, then wrote the recognized words on top using white text that blends into the white background. Search tools still read the hidden layer, so the PDF becomes **searchable** without altering the visual appearance. + +## Step 6: Save the PDF Bytes – Convert Image to PDF + +If you prefer to handle the PDF in memory (e.g., sending it over an API), you can capture the bytes instead of writing directly to disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +That line demonstrates the classic **convert image to PDF** workflow: you start with an image, run OCR, overlay text, and finally emit a PDF stream. + +## Step 7: Verify the Result – Quick Checks + +After you run the script, open `receipt_searchable.pdf` in any PDF viewer and try the search box (Ctrl + F). Type a word you know appears in the receipt—if it jumps to the right spot, you’ve successfully **create searchable pdf**! + +If the search fails, double‑check: + +1. The OCR confidence scores (`conf` values). Low confidence may mean the image is blurry. +2. Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. +3. That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers have that option). + +## Full Working Script + +Putting everything together, here’s the complete, ready‑to‑run Python file: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Save this as `searchable_pdf.py`, replace the `YOUR_DIRECTORY` placeholders with real paths, and run: + +```bash +python searchable_pdf.py +``` + +You should see a confirmation message and a brand‑new searchable PDF sitting in your folder. + +## Common Questions & Edge Cases + +**What if the image is in color?** +EasyOCR works with both grayscale and color images, but converting to grayscale (`pil_image.convert("L")`) can sometimes improve accuracy on noisy scans. + +**Can I handle multi‑page PDFs?** +Yes—loop over each page image, run the OCR steps, and append each page to the same `FPDF` object. Just remember to reset the cursor (`self.add_page()`) for each new image. + +**Is there a way to keep the original text layer instead of invisible white text?** +If you need a true “text‑under‑image” PDF (e.g., for accessibility), consider using `pdfminer` or `pikepdf` to embed a hidden text layer with proper PDF tags. That’s more advanced, but the principle remains the same: background image + overlay text. + +**What if OCR confidence is low?** +You can filter out low‑confidence words: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Wrap‑Up – What We Achieved + +We started with a simple image of a receipt, **performed OCR on image**, extracted the recognized strings, and finally **create searchable pdf** that behaves like any professionally scanned document. The process covered every secondary keyword—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, and **perform OCR on image**—so you now have a reusable toolbox for any similar project. + +### Next Steps + +- Experiment with other languages by passing their ISO codes to `easyocr.Reader(['en', 'es'])`. +- Swap EasyOCR for Tesseract if you need a fully offline solution; the rest of the pipeline stays the same. +- Add OCR confidence visualisation (draw bounding boxes on the image) to debug problematic scans. + +Got a twist you’d like to share? Drop a comment, fork + + +## 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/english/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..5111a6d29 --- /dev/null +++ b/ocr/english/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-19 +description: Extract text from images in Python with a simple OCR engine. Learn how + to convert scanned images to text, recognize text from pictures, and list image + files python efficiently. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: en +og_description: Extract text from images in Python using a lightweight OCR engine. + This guide shows you how to convert scanned images to text, recognize text from + pictures, and list image files python in a few steps. +og_title: Extract Text from Images in Python – Full Batch OCR Guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Extract Text from Images in Python – Full Batch OCR Guide +url: /python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Images in Python – Full Batch OCR Guide + +Ever needed to **extract text from images** but weren’t sure where to start? You’re not alone—developers constantly face the challenge of turning scanned PDFs, photographed receipts, or screenshots into searchable text. In this tutorial we’ll walk through a complete, ready‑to‑run example that shows how to **convert scanned images to text**, recognize text from pictures, and even **list image files python**‑style. By the end you’ll have a reusable script that processes an entire folder in one go. + +We’ll cover everything you need: required libraries, why each step matters, edge‑case handling, and a bit of troubleshooting. No need to chase external docs; the code below is self‑contained, and the explanations answer the “how” *and* the “why”. Grab your favorite IDE, and let’s get cracking. + +--- + +## What You’ll Build + +- Initialize an OCR engine (we’ll use the `ocr` package for illustration). +- Scan a directory and **list image files python**‑style, filtering PNG, JPG, and TIFF. +- Run a **batch OCR** operation on all found pictures. +- Print the extracted text for each file, clearly labeled. + +> **Pro tip:** If you don’t have the `ocr` library installed, you can swap it for `pytesseract` with a few minor changes—the core logic stays the same. + +--- + +## Prerequisites + +- Python 3.8+ (the script uses f‑strings and type hints). +- An OCR library that exposes an `OcrEngine` with `recognize_batch`. For this guide we assume a fictional `ocr` package, but the pattern works with real libraries. +- A folder containing image files you want to process (`.png`, `.jpg`, `.tif`). + +--- + +## Step 1 – Install & Import Required Modules + +First, make sure the OCR package is available. If you’re using a real library like `pytesseract`, replace the import accordingly. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Why this matters:** Importing `os` gives us cross‑platform path handling, while `typing.List` helps with IDE autocomplete and future‑proofing. + +--- + +## Step 2 – **Extract Text from Images**: Initialize the OCR Engine + +Creating the engine is the first step toward any OCR work. We also set the language to auto‑detect so the engine can handle mixed‑language documents. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explanation:** By encapsulating engine creation in a function we keep the code modular. If you later need to tweak DPI or OCR mode, you only edit this one spot. + +--- + +## Step 3 – **List Image Files Python**: Gather Files from a Directory + +Now we need to locate every picture we want to process. The list comprehension below mirrors a common “list image files python” pattern. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge case handling:** The function ignores sub‑folders (you can add recursion later) and filters out hidden files automatically because they typically don’t end with supported extensions. + +--- + +## Step 4 – **Convert Scanned Images to Text**: Run Batch OCR + +Most OCR libraries provide a batch method that’s far faster than processing one image at a time. Here’s how we call it. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Why batch?** Sending all images at once reduces overhead (e.g., loading the OCR model repeatedly) and often yields better CPU/GPU utilization. + +--- + +## Step 5 – **Recognize Text from Pictures**: Display the Results + +Finally, we iterate over the paired file names and OCR results, printing a clean header for each image. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** `strip()` removes leading/trailing whitespace that OCR often adds. + +--- + +## Full Script – Put It All Together + +Below is the complete, runnable program. Save it as `batch_ocr.py` and run `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Expected Output + +Assuming the folder contains `invoice1.png` and `receipt.jpg`, you might see: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Each block is clearly labeled, making downstream processing (e.g., saving to a database) straightforward. + +--- + +## Handling Common Pitfalls + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **No text appears** | OCR language not detected or image is too low‑contrast. | Force a language (`engine.language = ocr.Language.English`) or preprocess images (increase contrast). | +| **Memory error on large batches** | The engine tries to load all images at once. | Split `image_files` into chunks (`batch_size = 20`) and call `recognize_batch` repeatedly. | +| **Unsupported file format** | You added a `.gif` or `.bmp`. | Extend `supported_exts` tuple or convert images to PNG/JPG beforehand. | +| **Unicode garbling** | OCR returns bytes instead of strings. | Ensure the OCR library outputs Unicode (`result.text.decode('utf‑8')` if needed). | + +--- + +## Extending the Workflow + +Now that you can **extract text from images**, consider these next steps: + +- **Export to CSV** – Write each filename and its extracted text to a spreadsheet for analytics. +- **Parallel processing** – Use `concurrent.futures.ThreadPoolExecutor` to handle multiple batches simultaneously. +- **Integrate with cloud OCR** – Swap the local engine for Google Vision or Azure OCR for higher accuracy on complex layouts. +- **Add image preprocessing** – Libraries like Pillow or OpenCV can deskew, denoise, or threshold images before OCR, boosting results. + +All of these ideas naturally involve the same core functions we built, so you won’t have to start from scratch. + +--- + +## Conclusion + +We’ve just walked through a complete solution to **extract text from images** in Python, covering everything from **list image files python** to **recognize text from pictures** and finally **convert scanned images to text** in a tidy batch. The script is deliberately simple yet flexible enough to serve as a foundation for larger projects—whether you’re digitizing receipts, building a searchable archive, or powering a data‑extraction pipeline. + +Give it a spin, tweak the preprocessing steps, and watch your OCR accuracy climb. If you run into hiccups, revisit the “Handling Common Pitfalls” table; most issues are resolved with a tiny configuration change. + +Ready for the next challenge? Try adding a PDF‑to‑image conversion step using `pdf2image`, then feed those images straight into the same pipeline. The sky’s the limit when you combine OCR with Python’s rich ecosystem. + +Happy coding, and may your text be ever legible! + + +## 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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/english/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..84dea8b5c --- /dev/null +++ b/ocr/english/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-06-19 +description: extract text from images using Python OCR. Learn automatic language detection, + parallel processing, and batch recognition in a concise tutorial. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: en +og_description: extract text from images with Python OCR. This guide shows automatic + language detection, parallel processing, and batch recognition in a single tutorial. +og_title: extract text from images in Python – Full OCR Guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: extract text from images in Python – Full OCR Guide +url: /python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# extract text from images in Python – Full OCR Guide + +Ever wondered how to **extract text from images** without manually typing every word? You’re not the only one. Whether you’re digitizing old receipts, building a searchable document archive, or just playing with cool AI tricks, the ability to pull text from pictures is a must‑have skill for any Python developer today. + +In this tutorial we’ll walk through a complete, ready‑to‑run example that **extracts text from images** using a popular OCR engine. We’ll cover automatic language detection, parallel processing for speed, and batch image recognition so you can handle dozens of files in seconds. Sound like what you need? Let’s dive in. + +## What You’ll Learn + +- How to instantiate the OCR engine with `ocr.OcrEngine`. +- Enabling **automatic language detection** so the engine picks the right language on its own. +- Configuring **parallel processing OCR** with a custom thread pool. +- Running **batch image recognition** on a list of files. +- Printing the recognized text for each image, ready to be saved or indexed. + +No external documentation required—everything you need is right here, and the code works out of the box with the `ocr` package (install it via `pip install ocr`). + +## Prerequisites + +Before we start, make sure you have: + +1. Python 3.8 or newer installed. +2. The `ocr` package (`pip install ocr`). +3. A folder of PNG (or JPG) images you want to process. +4. Basic familiarity with Python functions and loops. + +That’s it—no heavy dependencies, no GPU magic, just plain Python. + +![extract text from images example](https://example.com/ocr-demo.png "Screenshot showing extract text from images output") + +*Alt text: extract text from images demo screenshot* + +## Step 1 – Set Up the OCR Engine (Primary Keyword in Action) + +First thing’s first: create an OCR engine instance. Think of `ocr.OcrEngine()` as the brain behind the operation; it knows how to read characters, lines, and paragraphs. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Why do we need an explicit engine? Because the **ocr.OcrEngine usage** gives you fine‑grained control over language settings, threading, and more. It’s the most flexible way to **extract text from images** compared to one‑liner helpers. + +## Step 2 – Let the Engine Detect Languages Automatically + +Most OCR libraries require you to tell them which language to look for. That’s fine for a single‑language project, but cumbersome for a mixed‑language batch. Luckily, the `ocr` package supports **automatic language detection**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Setting `engine.language` to `ocr.Language.Auto` tells the engine to sniff each image and pick the appropriate language model. This tiny line saves you hours of manual configuration when you’re dealing with international documents. + +## Step 3 – Speed Things Up with Parallel Processing OCR + +If you have four or more CPU cores, why not use them? The engine can spin up a thread pool, letting multiple images be processed at the same time. This is where **parallel processing OCR** shines. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Feel free to adjust the number `4` based on your machine. More threads → faster batch runs, but remember that each thread consumes memory, so find a sweet spot for your environment. + +## Step 4 – Gather the Images You Want to Process + +Now we need a list of file paths. You can build this list manually, read it from a CSV, or use `glob`. For clarity, we’ll hard‑code a short list: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Replace `YOUR_DIRECTORY` with the actual path on your system. If you have dozens of files, a quick `glob.glob("*.png")` will do the heavy lifting. + +## Step 5 – Run Batch Image Recognition + +Here’s the heart of the tutorial: a single call that processes every image in `files` and returns a list of result objects. This is the **batch image recognition** feature that makes large‑scale OCR practical. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Behind the scenes, the engine distributes each file across the four worker threads we configured earlier, while also auto‑detecting the language for each picture. The method returns a list where each element holds the recognized text and metadata. + +## Step 6 – Print (or Store) the Extracted Text + +Finally, we loop over the results and print the text. In a real project you’d probably write this to a database or a CSV file, but printing keeps the example simple. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Expected output** (truncated for brevity): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Each block shows the filename followed by the OCR‑derived string. If an image contains multiple languages, you’ll see the appropriate characters appear thanks to the earlier **automatic language detection** step. + +## Pro Tips & Common Pitfalls + +- **Image quality matters** – blurry or low‑contrast pictures will produce garbage. Pre‑process with OpenCV (`cv2.threshold`, `cv2.resize`) if needed. +- **Thread count vs. I/O** – If your images live on a slow network drive, more threads might not help. Keep an eye on CPU usage with `top` or `Task Manager`. +- **Unicode handling** – The `result.text` is a Unicode string. When writing to files, open them with `encoding="utf‑8"` to avoid `UnicodeEncodeError`s. +- **Memory usage** – Large PDFs can consume a lot of RAM. If you hit `MemoryError`, reduce the thread pool size or process images in smaller chunks. + +## Full Working Script + +Below is the complete, copy‑and‑paste‑ready script that incorporates every step we discussed. Save it as `batch_ocr.py` and run `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Run it like this: + +```bash +python batch_ocr.py ./my_images 4 +``` + +You’ll see a nicely formatted block of text for each image, proving that you can **extract text from images** at scale. + +## What’s Next? + +Now that you’ve mastered the basics of **extract text from images** with Python, consider exploring: + +- **Post‑processing**: clean up OCR output with regex or natural‑language libraries. +- **PDF conversion**: feed the extracted strings into a PDF generator for searchable PDFs. +- **Cloud OCR services**: compare on‑prem `ocr` results with Google Vision or Azure OCR for edge‑case accuracy. +- **GUI front‑end**: build a tiny Flask or FastAPI app that lets users upload images and instantly see the extracted text. + +Each of these topics builds on the **Python OCR library** foundation you just set up, and they all benefit from the same **parallel processing OCR** tricks we used here. + +--- + +*Happy coding! If you hit any snags, drop a comment below—I'm always up for troubleshooting OCR quirks.* + + +## 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 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/english/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/english/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..babc3496c --- /dev/null +++ b/ocr/english/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-06-19 +description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: en +og_description: How to extract PDF using OCR in Python. Learn to extract text from + PDF, recognize text from image, and see a complete OCR Python example. +og_title: How to Extract PDF Text with OCR in Python – Full Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: How to Extract PDF Text with OCR in Python – Complete Guide +url: /python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Extract PDF Text with OCR in Python – Complete Guide + +Ever wondered **how to extract PDF** contents when the file is just a scanned image? You're not the only one. In many real‑world projects—think contracts, invoices, or historic archives—the PDF you receive has no selectable text. The good news? A few lines of Python can turn those image‑only pages into searchable, editable text. + +In this tutorial we’ll walk through a practical **OCR Python example** that reads a PDF, renders its first page as an image, and then **extracts text from PDF** using an OCR engine. By the end you’ll know exactly how to **read PDF with OCR**, why each step matters, and how to adapt the code for multi‑page documents or different languages. + +## What You’ll Learn + +- Install and set up a reliable OCR library for Python. +- Convert PDF pages to images suitable for OCR. +- **Recognize text from image** and retrieve clean Unicode strings. +- Common pitfalls (low‑resolution PDFs, rotated pages) and how to avoid them. +- Extending the script to handle multiple pages or batch processing. + +**Prerequisites**: Python 3.8+, pip, and a basic understanding of virtual environments. No prior OCR experience required—just follow along. + +--- + +## ## How to Extract PDF Text with OCR in Python + +This H2 header contains our primary keyword right where search engines love to see it. Let’s dive straight into the code. + +### Step 1 – Install the Required Packages + +First, we need an OCR engine. The example below uses the popular **ocr** package (a thin wrapper around Tesseract). If you prefer a different backend, the concepts stay the same. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** On Linux, you’ll also need the Tesseract binary: `sudo apt-get install tesseract-ocr`. macOS users can grab it via Homebrew: `brew install tesseract`. + +### Step 2 – Initialize the OCR Engine and Set Language + +Now we spin up the engine and tell it to look for English characters. You can swap `ocr.Language.English` for any supported language code. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Why this matters:** Specifying the language dramatically improves accuracy because the engine can apply language‑specific dictionaries and character models. + +### Step 3 – Load a PDF Page as an Image + +OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based indexing). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** If the PDF contains vector graphics rather than scanned images, you might get a crisp rendering. For low‑resolution scans, consider increasing the DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Step 4 – Recognize Text from the Rendered Image + +Here’s the heart of the **ocr python example**. The engine processes the bitmap and returns an object containing the extracted string. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +The `ocr_result.text` attribute holds the plain‑text output, preserving line breaks where possible. + +### Step 5 – Print or Store the Extracted Text + +Finally, we output the result. In a real application you’d probably write to a file or a database. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Running the script should display something like: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +That’s a complete **extract text from pdf** workflow using OCR. + +--- + +## ## Recognize Text from Image – Tweaking Accuracy + +If you’re only interested in **recognize text from image** (say, a JPEG of a receipt), you can skip the PDF conversion step: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips for better results:** + +- **Pre‑process** the image: convert to grayscale, apply thresholding, or deskew. Pillow makes this easy. +- **Increase DPI** during PDF rendering: higher resolution gives the OCR engine more detail. +- **Enable OCR engine’s config** for page segmentation (`ocr_engine.config = "--psm 6"` for uniform blocks). + +--- + +## ## Read PDF with OCR – Handling Multiple Pages + +Most contracts span several pages. Looping over each page is straightforward: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +This function **reads PDF with OCR**, concatenates the output, and inserts a clear page break marker. You can then feed `full_text` into a search index or store it as a `.txt` file. + +--- + +## ## Common Pitfalls and How to Fix Them + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Garbled characters, lots of `?` | Wrong language or missing language data files | Install the correct Tesseract language pack (`tesseract-ocr-`) and set `ocr_engine.language`. | +| Missing lines or truncated words | Low DPI (under 150) | Render PDF at 300 DPI or higher (`dpi=300`). | +| Text is rotated or upside‑down | Scanned page not upright | Use `ocr.Image.deskew(page_image)` before recognition. | +| Slow processing on large PDFs | Processing pages sequentially on a single thread | Parallelize with `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Extending the OCR Python Example + +- **Export to PDF/A**: After extraction, you can embed the text back into a searchable PDF using `reportlab` or `pypdf2`. +- **Language detection**: Use `langdetect` on the OCR output to switch `ocr_engine.language` dynamically. +- **Batch processing**: Walk a directory with `os.listdir` and apply `extract_all_pages` to every file. + +--- + +## ## Expected Output and Verification + +When you run the script against a clear, English‑language scan, you should see a clean block of text with proper punctuation. Verify by: + +1. Comparing a few lines to the original scanned image. +2. Running a simple word count (`len(ocr_result.text.split())`) to ensure the output isn’t empty. +3. Optionally, feeding the result into a spell‑checker like `pyspellchecker` to spot OCR errors. + +--- + +## Conclusion + +We’ve covered **how to extract PDF** content when traditional parsing fails, demonstrated a full **ocr python example**, and explained how to **recognize text from image** and **read PDF with OCR** for both single‑page and multi‑page scenarios. With the code snippets above you can now turn any scanned PDF into searchable, editable text—no more manual re‑typing. + +Next steps? Try swapping the language to Spanish (`ocr.Language.Spanish`) or experiment with image pre‑processing techniques to boost accuracy. If you’re building a document‑management system, consider indexing the extracted text with Elasticsearch for lightning‑fast search. + +Got questions or run into a quirky PDF? Drop a comment, and happy coding! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + + +## 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/english/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..4cb146358 --- /dev/null +++ b/ocr/english/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,283 @@ +--- +category: general +date: 2026-06-19 +description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: en +og_description: 'How to use OCR in Java with Aspose: a full walkthrough covering auto + deskew images, auto language detection, and extract text image from pictures.' +og_title: How to Use OCR in Java with Aspose – Complete Guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: How to Use OCR in Java with Aspose – Complete Guide +url: /python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Use OCR in Java with Aspose – Complete Guide + +Ever wondered **how to use OCR** in a Java project without pulling your hair out over configuration? You're not the only one. Many developers hit a wall when they need to **extract text image** data quickly, especially when the source scans are crooked or written in an unknown language. + +In this tutorial we’ll walk through a hands‑on example that shows you exactly how to use OCR with Aspose, including **auto deskew images**, **auto language detection**, and the full **ocr image preprocessing** pipeline. By the end you’ll have a ready‑to‑run snippet that prints the recognized text to the console, and you’ll understand why each setting matters. + +> **What you’ll get:** a complete, runnable Java program, explanations of every line, tips for handling edge cases, and ideas for extending the solution to batch processing or PDFs. + +--- + +## Prerequisites + +- Java 17 (or any recent JDK) installed and configured. +- Maven or Gradle for dependency management (we’ll show the Maven coordinates). +- An Aspose OCR for Java license file (`Aspose.OCR.Java.lic`). If you’re just testing, you can skip the license step, but the free trial will add a watermark. +- A sample image (`your_image.png`) placed somewhere accessible to the code. + +> **Pro tip:** keep your images in a dedicated `resources` folder and load them via the classpath; it avoids path‑related headaches on different OSes. + +--- + +## Step 1: Set Up the Project and Add Aspose OCR Dependency + +Create a new Maven project (or use your existing one) and add the following to your `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Run `mvn clean install` to pull the library. If you prefer Gradle, the equivalent is: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Now you have the **ocr image preprocessing** classes on your classpath. + +--- + +## Step 2: Apply Your Aspose OCR License (Optional but Recommended) + +If you own a license, apply it right at the start of your `main` method. Skipping this step works, but the free version stamps a “Demo” watermark on the output. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Why this matters:** The licensed version removes usage limits and disables the watermark, giving you clean, production‑ready results. + +--- + +## Step 3: Create the OCR Engine Instance + +The engine is the heart of the process. Instantiating it gives you access to all the **ocr image preprocessing** options. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +At this point the engine is ready, but it will use default settings which might not be optimal for scanned documents. Let’s tweak a few. + +--- + +## Step 4: Enable Auto Deskew Images for Cleaner Scans + +Tilted scans are a common pain point. Aspose provides an **auto deskew images** feature that automatically straightens the picture before recognition. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **How it works:** The algorithm analyses the text baseline angles and rotates the image to the most probable upright orientation. This dramatically improves accuracy for photos taken with a phone. + +--- + +## Step 5: Turn On Auto Language Detection + +If you don’t know the language of the source image, let the engine figure it out. This is the **auto language detection** setting. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +When you enable this, Aspose scans the glyphs and selects the most likely language model, supporting over 30 languages out of the box. + +--- + +## Step 6: Load the Image You Want to Recognize + +You can load an image from disk, a URL, or even a byte array. For simplicity, we’ll read from a local file. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** If you’re dealing with large images, consider down‑sampling them first with `engine.getImagePreprocessing().setResizeFactor(0.5)` to speed up processing without losing much detail. + +--- + +## Step 7: Perform OCR Recognition and Extract Text Image + +Now the engine does its magic. The `recognize` method returns an `OcrResult` object that contains the recognized text, confidence scores, and more. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +The console will display the plain text extracted from the picture—this is the core **extract text image** outcome we set out to achieve. + +--- + +## Full Working Example + +Below is the complete Java class that ties everything together. Copy‑paste it into `src/main/java/com/example/OcrDemo.java` and run it. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Expected Output + +If the image contains the phrase “Hello World” on a clean scan, you’ll see: + +``` +=== Recognized Text === +Hello World +``` + +For more complex documents (e.g., multilingual receipts), the output will include line breaks and the detected language code. + +--- + +## Common Pitfalls & Pro Tips + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | Image is too dark or noisy. | Enable `engine.getImagePreprocessing().setBinarization(true)` or adjust the contrast manually. | +| **Wrong language** | Auto detection misfires on mixed‑language pages. | Set `engine.setLanguage(Language.English)` (or the appropriate enum) to force a specific language. | +| **Slow processing** | Very high‑resolution images. | Downscale with `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Out‑of‑memory errors** | Large batch of images loaded at once. | Process images sequentially and call `engine.dispose()` after each run. | + +> **Remember:** The OCR engine is thread‑safe for read‑only operations, but creating a new instance per thread avoids hidden state bugs. + +--- + +## Extending the Solution + +Now that you know **how to use OCR** with Aspose, you might want to: + +1. **Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then feed it to the same pipeline. +2. **Batch process a folder** – Loop through files in a directory, applying the same steps, and write results to a CSV. +3. **Integrate with a web service** – Expose the OCR logic via a Spring Boot `@RestController` that accepts multipart uploads. + +All of those scenarios reuse the same **ocr image preprocessing** configuration we built here. + +--- + +## Conclusion + +We’ve covered **how to use OCR** in Java with Aspose from start to finish: applying a license, creating the engine, turning on **auto deskew images**, enabling **auto language detection**, loading an image, and finally **extract text image** with a single `System.out.println`. The code is fully self‑contained, runs on any recent JDK, and demonstrates best practices for accuracy and performance. + +Give it a spin with your own pictures—maybe a scanned contract or a screenshot of a receipt. Tweak the preprocessing flags, experiment with different languages, and you’ll quickly see why Aspose’s OCR library is a solid choice for production‑grade text extraction. + +Got questions or want to share your results? Drop a comment below or ping me on GitHub. Happy coding! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## 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 Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/english/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..a0ac27606 --- /dev/null +++ b/ocr/english/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,318 @@ +--- +category: general +date: 2026-06-19 +description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: en +og_description: Improve OCR accuracy in Python by setting OCR language, loading an + image for OCR, and extracting text from image with a custom dictionary. +og_title: Improve OCR Accuracy in Python – Step‑by‑Step Guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Improve OCR Accuracy in Python – Complete Guide +url: /python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Improve OCR Accuracy in Python – Complete Guide + +Ever wondered how to **improve OCR accuracy** when the text you’re scanning contains weird symbols, product codes, or brand names? You’re not alone. In many projects the default engine just spits out gibberish, and that’s a real productivity killer. + +In this tutorial we’ll walk through a practical, end‑to‑end example that shows you how to **set OCR language**, **load image for OCR**, **perform OCR on image**, and finally **extract text from image** with a custom dictionary that boosts recognition rates. By the end you’ll have a ready‑to‑run script you can drop into any Python codebase. + +## What You’ll Walk Away With + +- A fully functional Python script that uses Aspose OCR to read a PNG file. +- The ability to **improve OCR accuracy** by configuring language and a custom word list. +- Clear explanations of why each setting matters, plus tips for handling edge cases like non‑Latin characters. +- A quick checklist for troubleshooting common OCR pitfalls. + +### Prerequisites + +- Python 3.8 or newer installed on your machine. +- `aspose-ocr` package (install via `pip install aspose-ocr`). +- A sample image (`technical_doc.png`) that contains the text you want to read. +- Basic familiarity with Python—nothing fancy required. + +> **Pro tip:** If you’re working in a virtual environment, activate it before installing the package. It keeps your dependencies tidy and avoids version clashes. + +--- + +## Step 1: Install and Import Aspose OCR + +First things first—let’s get the library into our environment and import the pieces we need. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +The `aspose.ocr` namespace gives you access to the `OcrEngine` class, which is the heart of the OCR process. Importing it here keeps the rest of the script clean and readable. + +--- + +## Step 2: Create an OCR Engine and **Set OCR Language** + +Why does the language matter? OCR engines rely on language‑specific models to recognize character shapes and word patterns. If you tell the engine you’re scanning English text, it will ignore Cyrillic glyphs and focus on the Latin alphabet, dramatically **improving OCR accuracy**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Note:** Aspose OCR supports over 50 languages. Swap `ocr.Language.English` for `ocr.Language.Spanish`, `ocr.Language.French`, etc., if your document isn’t English. + +--- + +## Step 3: Define a **Custom Dictionary** to Boost Accuracy + +Imagine you’re scanning invoices that contain the word “AsposeOCR” or product codes like “SKU12345”. The engine doesn’t know those terms, so it guesses incorrectly. Supplying a custom word list tells the engine, *“Hey, these strings are legit—don’t try to correct them.”* That’s a quick win for **improve OCR accuracy**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +You can load this list from a file or a database if you have hundreds of entries—just keep it in a Python list for simplicity. + +--- + +## Step 4: **Load Image for OCR** + +Now we need an image. The `Image.load` method accepts a path to any supported raster format (PNG, JPEG, BMP, etc.). If the file can’t be found, the engine throws an exception, so we’ll guard against that. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Why this step matters:** Loading the image correctly ensures the engine works with the exact pixel data you intend to analyze. Corrupted files or wrong paths are a common source of frustration. + +--- + +## Step 5: **Perform OCR on Image** and Extract Results + +With the engine configured and the image ready, the actual recognition is a single method call. The result object contains the raw text, confidence scores, and even layout information if you need it later. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +If you need to **extract text from image** line by line, you can split on newline characters: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Step 6: Verify the Output – Does It Really **Improve OCR Accuracy**? + +Let’s print the result and see if our custom dictionary made a difference. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Typical output for the sample image might look like: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Notice how the brand name, Greek character, and product code appear exactly as we defined them. Without the custom dictionary, the engine would have tried to “correct” them, often producing something like “Aspose OCR” or “SKU 1234”. + +--- + +## Common Pitfalls & How to Tackle Them + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | Wrong language set or low‑resolution image | Ensure `engine.language` matches the source language and use a high‑DPI scan (300 dpi or higher). | +| **Custom words ignored** | Dictionary not attached or typo in property name | Double‑check `engine.text_processing.custom_dictionary = …`. | +| **File not found** | Incorrect path or missing file permissions | Use `os.path.abspath()` to verify the absolute path; run script with proper permissions. | +| **Slow processing** | Large images or many pages | Pre‑process the image (crop, resize) or use `engine.recognize(image, max_threads=4)` to parallelize. | + +--- + +## Going Further: Advanced Tweaks for **Improve OCR Accuracy** + +1. **Pre‑processing** – Apply contrast enhancement or binarization with Pillow before feeding the image to Aspose OCR. +2. **Multiple Languages** – Set `engine.language = ocr.Language.English | ocr.Language.French` to enable bilingual recognition. +3. **Region‑Based OCR** – If you only need a specific area (e.g., a table), crop the image first to reduce noise. +4. **Confidence Filtering** – `result.confidence` gives a per‑character score; you can discard low‑confidence results programmatically. + +--- + +## Full Working Script + +Below is the complete, copy‑paste‑ready script that incorporates every step we discussed. Save it as `improve_ocr_accuracy.py` and run it from the command line. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Run it: + +```bash +python improve_ocr_accuracy.py +``` + +You should see the nicely formatted output we displayed earlier. + +--- + +## Conclusion + +We’ve just covered a straightforward way to **improve OCR accuracy** in Python by: + +1. **Setting the OCR language** to match your document. +2. **Loading the image correctly** so the engine sees the right pixels. +3. **Performing OCR on the image** with a single method call. +4. **Extracting text from the image** and confirming the result. +5. **Adding a custom dictionary** to lock in domain‑specific terms. + +That’s the entire workflow—from raw picture to clean, searchable text—wrapped up in a tidy, reusable script. + +If you’re ready for the next challenge, try experimenting with image pre‑processing (contrast, deskew) or switch to a multilingual setup using `ocr.Language.English | ocr.Language.German`. The same principles apply, and you’ll keep **improving OCR accuracy** across a broader set of documents. + +Got questions or a weird edge case? Drop a comment below, and happy coding! + +![improve OCR accuracy + + +## 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 – 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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/english/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..b84a4a986 --- /dev/null +++ b/ocr/english/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-19 +description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image efficiently. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: en +og_description: Perform OCR on image with Python and extract text from scanned files. + This guide walks you through loading images, deskewing, and recognizing text step‑by‑step. +og_title: Perform OCR on Image in Python – Full Text Extraction Guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Perform OCR on Image in Python – Full Text Extraction Guide +url: /python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Perform OCR on Image in Python – Full Text Extraction Guide + +Ever needed to **perform OCR on image** files but kept hitting a wall because the code looked cryptic? You're not the only one. Whether you're turning a pile of scanned receipts into searchable PDFs or pulling captions from a JPEG for a data‑science project, the ability to recognize text from JPEGs and other formats is a must‑have skill for any developer today. + +In this tutorial we'll walk through a complete, runnable example that shows you how to **detect text from image** files, **extract text from scanned image** documents, and even **load image for OCR** in just a handful of lines. By the end, you’ll have a solid, production‑ready snippet you can drop into your own projects—no missing imports, no vague “see docs” shortcuts. + +## What You’ll Build + +- A tiny Python script that creates an OCR engine, enables auto‑deskew, loads a JPEG (or any supported format), and prints the recognized text. +- Explanations of **why** each setting matters, not just **how** to type it. +- Tips for handling multi‑page PDFs, non‑English languages, and common pitfalls like blurry scans. + +### Prerequisites + +- Python 3.8+ installed (the example uses the `ocr` package available via `pip install ocr-lib` – replace with your actual library name). +- Basic familiarity with Python functions and virtual environments. +- An image file (JPEG, PNG, TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeholder. + +> **Pro tip:** If you’re on Windows, run your terminal as Administrator when installing the OCR library to avoid permission headaches. + +--- + +## Perform OCR on Image – Setup and Configuration + +The first thing you need is a clean OCR engine instance. Think of it as the brain behind the operation; without proper configuration, even the sharpest image will return gibberish. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters:** +Setting `engine.language` narrows the character set the OCR engine expects, dramatically boosting accuracy. If you skip this, the engine will try to guess, often misreading simple words. + +--- + +## Enable Automatic Deskew – Fix Tilted Scans + +Scanned pages are rarely perfectly flat. A slight tilt can throw off character segmentation, turning “Hello” into “H3llo”. The `auto_deskew` flag does the heavy lifting for you. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** If you know your images are already straight, disabling deskew can shave a few milliseconds off processing time—useful when handling thousands of pages in a batch job. + +--- + +## Load Image for OCR – Supporting JPEG, PNG, TIFF + +Now we actually **load image for OCR**. The `ocr.Image.load` method is flexible; it accepts a path to any supported raster format. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial:** The library reads the file into an internal bitmap, applying any necessary color space conversion. Skipping this and passing a raw byte stream would raise a `FileNotFoundError` or, worse, silently produce empty results. + +If you need to **recognize text from JPEG** files specifically, just ensure the file extension is `.jpeg` or `.jpg`. The same call works for PNG (`.png`) or TIFF (`.tif`) without modification. + +--- + +## Perform OCR on Image – Running the Engine + +With the engine primed and the image in memory, it’s time to **perform OCR on image** data. This single line does the heavy lifting: pre‑processing, segmentation, classification, and text assembly. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood?** +- The engine applies the deskew transformation (if enabled). +- It runs a neural network or Tesseract backend to identify characters. +- Finally, it stitches characters into words and lines, returning a rich `result` object. + +--- + +## Extract Text from Scanned Image – Output the Results + +The final step is to **extract text from scanned image** and display it. The `result.text` attribute contains the plain‑text representation. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Typical output looks like: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +If the OCR engine fails to find any characters, `result.text` will be an empty string. In that case, double‑check the image quality or consider adjusting the `engine.confidence_threshold` property (if your library supports it). + +--- + +## Handling Common Variations + +### Recognize Text from JPEG vs PNG + +Both formats are supported, but JPEG compression can introduce artifacts that confuse the engine. If you notice frequent mis‑recognitions, try converting the JPEG to PNG first: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detect Text from Image with Multiple Languages + +If your document mixes English and Spanish, set a multilingual mode: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +The engine will then consider both alphabets during recognition. + +### Extract Text from Scanned PDFs + +For PDFs, you need to rasterize each page into an image first. Libraries like `pdf2image` make this painless: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Full Working Example + +Below is the complete script you can copy‑paste into a `ocr_demo.py` file. It includes error handling and a small helper to measure execution time. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (assuming a clear scan): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Frequently Asked Questions + +**Q: Can I run this on a headless server?** +A: Absolutely. The library works without a GUI; just ensure the necessary native binaries (e.g., Tesseract) are installed on the server. + +**Q: What if the image is blurry?** +A: Consider adding a sharpening filter before `engine.recognize`. Many OCR libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s `cv2.GaussianBlur` in reverse. + +**Q: Does the script support batch processing?** +A: Yes. Wrap `perform_ocr` in a loop over a list of file paths, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/english/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..7f257e08d --- /dev/null +++ b/ocr/english/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Perform OCR on image using Aspose OCR Java. Learn how to load image for + OCR, use Aspose license, and extract text from image in minutes. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: en +og_description: Perform OCR on image with Aspose OCR Java. This guide shows how to + use aspose license, load image for OCR, and extract text from image efficiently. +og_title: Perform OCR on Image with Aspose OCR Java – Full Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide +url: /python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + +Ever needed to **perform OCR on image** files but weren’t sure which library would give you reliable results without a ton of configuration? You’re not alone. In many real‑world projects—think scanning passports, digitizing invoices, or pulling text from screenshots—the ability to quickly recognize text image data is a game‑changer. + +In this tutorial we’ll walk through a hands‑on example that shows exactly how to **perform OCR on image** using Aspose OCR for Java. We’ll cover everything from applying your Aspose license to loading the picture, running the engine, and finally **extract text from image** so you can use it downstream. No fluff, just a working solution you can copy‑paste. + +## What You’ll Walk Away With + +- A clear picture of how to **use Aspose license** in a Java project. +- The exact code needed to **load image for OCR** and let the engine auto‑detect languages. +- Step‑by‑step instructions to **recognize text image** content and **extract text from image** safely. +- Tips for handling common pitfalls (empty results, unsupported formats, and memory concerns). + +> **Prerequisites** – Java 8 or newer, Maven or Gradle for dependency management, and an Aspose OCR for Java license file (or you can run in evaluation mode). + +--- + +## How to Perform OCR on Image with Aspose OCR Java + +Below is the full, ready‑to‑run Java program that demonstrates the entire flow. Save it as `AsposeOcrDemo.java` and run it from your IDE or command line. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Expected Console Output + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +If you run the program without a license file, the first line will simply state that you’re in evaluation mode, but the OCR still works. + +--- + +## Set Up and Use Aspose License + +### Why a License Matters + +Running the library in evaluation mode is fine for quick tests, but it adds a watermark to the output and limits the number of pages you can process per run. Applying the **use aspose license** step removes these restrictions and signals to Aspose that you’re a paying customer. + +### How to Obtain and Apply It + +1. Purchase a license from the Aspose store. +2. Download the `Aspose.OCR.Java.lic` file. +3. Place it somewhere your application can read—commonly the `src/main/resources` folder. +4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any OCR work, as shown in the code above. + +> **Pro tip:** If you deploy to a server, use an absolute path or a class‑path resource loader to avoid `FileNotFoundException`. + +--- + +## Load Image for OCR Processing + +The line `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` is the heart of the **load image for OCR** step. Aspose OCR supports a wide range of formats: PNG, JPEG, BMP, TIFF, and even multi‑page PDFs (when combined with Aspose.Pdf). + +### Common Pitfalls + +| Issue | Symptom | Fix | +|-------|---------|-----| +| Wrong file path | `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent separators. | +| Unsupported format | `UnsupportedOperationException` | Convert the image to PNG or JPEG before loading. | +| Huge image ( > 10 MP) | Out‑of‑memory errors | Downscale the image using `java.awt.Image` before feeding it to Aspose. | + +--- + +## Extract Text from Image and Handle Results + +Once the OCR engine finishes, the `OcrResult` object contains the recognized string. This is where we **extract text from image** for further processing—saving to a database, feeding a search index, or feeding a downstream NLP pipeline. + +### Dealing with Multiple Languages + +Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt to detect languages on‑the‑fly. If you know the language in advance (e.g., all documents are Russian), you can replace `Language.Auto` with `Language.Russian` for a performance boost. + +### Post‑Processing Tips + +- **Trim whitespace**: `result.getText().trim()`. +- **Normalize line endings**: `result.getText().replace("\r\n", "\n")`. +- **Remove non‑printable characters**: use a regex like `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Recognize Text Image with Advanced Options (Optional) + +If you need finer control, Aspose OCR offers additional properties: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +These tweaks are handy when you’re dealing with scanned documents that suffer from skew or low contrast. + +--- + +## Full Working Example Recap + +Putting everything together, the final program does the following in order: + +1. **Perform OCR on image** – by creating an `OcrEngine`. +2. **Use Aspose license** – optional but recommended. +3. **Load image for OCR** – via `Image.load`. +4. **Set language detection** – `Language.Auto` to **recognize text image** automatically. +5. **Extract text from image** – print the result, handling empty responses gracefully. + +You can copy the code block above directly into a Maven project with this dependency: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Run `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` and watch the console display the recognized text. + +--- + +## Conclusion + +We’ve just shown you how to **perform OCR on image** files using Aspose OCR for Java, from applying a license to **loading the image for OCR**, **recognizing text image** content, and finally **extracting text from image** for downstream use. The approach is straightforward, works with multiple languages out of the box, and can be extended with advanced preprocessing options when needed. + +What’s next? Try feeding the OCR output into a search index, generate PDFs with the extracted text, or experiment with different image formats. The possibilities are endless, and with Aspose’s robust API you’ll spend more time building features than wrestling with OCR quirks. + +Got questions or run into an edge case? Drop a comment below—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. + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/french/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..5edf117d2 --- /dev/null +++ b/ocr/french/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Créer un PDF consultable à partir d’une image en utilisant l’OCR Python. + Apprenez à convertir l’OCR en PDF, extraire le texte d’une image et effectuer rapidement + l’OCR sur une image. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: fr +og_description: Créez un PDF consultable à partir d’une image avec Python OCR. Ce + guide montre comment convertir l’OCR en PDF, extraire le texte d’une image et effectuer + l’OCR sur une image. +og_title: Créer un PDF recherchable en Python – Guide complet de programmation +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Créer un PDF interrogeable en Python – Guide complet étape par étape +url: /fr/python-java/general/create-searchable-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 >}} + +# Créer un PDF interrogeable en Python – Guide complet étape par étape + +Vous avez déjà eu besoin de **créer un PDF interrogeable** à partir d'un reçu numérisé mais vous ne saviez pas par où commencer ? Vous n'êtes pas seul — de nombreux développeurs rencontrent le même obstacle lorsqu'ils essaient pour la première fois de transformer une image de texte en un PDF réellement recherchable. + +Dans ce tutoriel, nous allons parcourir une solution pratique qui vous permet de **perform OCR on image**, de transformer ce résultat OCR en **searchable PDF**, et même d'extraire le texte brut si vous en avez besoin pour un traitement ultérieur. Pas de superflu, juste un exemple fonctionnel que vous pouvez copier‑coller dans votre projet dès aujourd'hui. + +## Ce que vous allez apprendre + +- Comment configurer un moteur OCR léger en Python +- Les étapes exactes pour **convert OCR to PDF** et l'enregistrer comme document interrogeable +- Moyens d'**extract text from image** pour une analyse en aval +- Conseils pour gérer les pièges courants comme l'orientation de l'image et les gros fichiers +- Un script complet et exécutable que vous pouvez adapter à votre propre cas d'utilisation + +### Prérequis + +- Python 3.8+ installé sur votre machine +- Familiarité de base avec pip et les environnements virtuels (optionnel mais recommandé) +- Un fichier image (PNG, JPEG, etc.) contenant du texte clair et lisible par machine + +Si vous avez tout cela, plongeons‑nous dedans. + +## Étape 1 : Installer la bibliothèque requise + +Le fragment de code que vous avez vu plus tôt utilise un paquet fictif `ocr`, mais les mêmes idées s’appliquent aux bibliothèques réelles telles que **EasyOCR**, **pytesseract**, ou **pdfminer.six**. Pour ce guide, nous utiliserons **EasyOCR** car il est purement Python, prend en charge de nombreuses langues, et renvoie une méthode pratique de conversion PDF via un assistant auxiliaire. + +```bash +pip install easyocr pillow +``` + +> **Astuce :** Installez dans un environnement virtuel (`python -m venv venv && source venv/bin/activate`) pour garder vos dépendances propres. + +## Étape 2 : Initialiser le moteur OCR – Effectuer l'OCR sur l'image + +Maintenant que la bibliothèque est prête, nous créons un moteur OCR et lui indiquons de travailler avec du texte anglais. C’est le premier endroit où nous **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Pourquoi avons‑nous besoin d’un objet lecteur dédié ? EasyOCR pré‑charge les modèles de langue, donc réutiliser le même `reader` pour plusieurs images est bien plus efficace que de le réinitialiser à chaque fois. + +## Étape 3 : Charger l'image – Extraire le texte de l'image + +Apportons l'image en mémoire. Cette étape est celle où nous **extract text from image** plus tard, mais pour l’instant nous nous contentons de la charger. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Si votre image est à l’envers ou inclinée, envisagez d’utiliser les méthodes `rotate` ou `transpose` de Pillow avant de la transmettre au moteur OCR. Une vérification visuelle rapide peut vous faire gagner des heures de débogage plus tard. + +## Étape 4 : Exécuter le moteur OCR et capturer les résultats + +Voici le cœur du processus — envoyer l'image au moteur OCR et récupérer des données structurées. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Le drapeau `detail=1` nous fournit des boîtes englobantes, dont nous aurons besoin lorsque nous **convert OCR to PDF** plus tard. Si vous ne vous intéressez qu'aux chaînes brutes, définissez `detail=0`. + +## Étape 5 : Convertir le résultat OCR en PDF interrogeable – Convertir l'OCR en PDF + +EasyOCR ne fournit pas de générateur PDF direct, mais nous pouvons assembler le PDF nous‑mêmes en utilisant Pillow et la bibliothèque `reportlab`. Pour garder le tutoriel léger, nous utiliserons `fpdf2`, qui nous permet d’intégrer l’image originale et de superposer du texte invisible. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Qu’est‑ce qui vient de se passer ? Nous avons placé l’image numérisée comme couche visible, puis écrit les mots reconnus au-dessus en texte blanc qui se fond dans le fond blanc. Les outils de recherche lisent toujours la couche cachée, de sorte que le PDF devient **searchable** sans modifier l’apparence visuelle. + +## Étape 6 : Enregistrer les octets du PDF – Convertir l'image en PDF + +Si vous préférez manipuler le PDF en mémoire (par ex., l’envoyer via une API), vous pouvez capturer les octets au lieu d’écrire directement sur le disque. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Cette ligne illustre le flux de travail classique **convert image to PDF** : vous partez d’une image, exécutez l’OCR, superposez le texte, puis émettez finalement un flux PDF. + +## Étape 7 : Vérifier le résultat – Vérifications rapides + +Après avoir exécuté le script, ouvrez `receipt_searchable.pdf` dans n'importe quel lecteur PDF et essayez la boîte de recherche (Ctrl + F). Tapez un mot que vous savez présent dans le reçu — s’il saute à l’endroit correct, vous avez réussi à **create searchable pdf** ! + +Si la recherche échoue, revérifiez : + +1. Les scores de confiance de l'OCR (valeurs `conf`). Une faible confiance peut indiquer que l'image est floue. +2. Les coordonnées des boîtes englobantes — parfois EasyOCR les rapporte dans une orientation différente. +3. Que le lecteur PDF n'est pas réglé en mode « image‑only » (rare, mais certains lecteurs ont cette option). + +## Script complet fonctionnel + +En réunissant tous les éléments, voici le fichier Python complet, prêt à être exécuté : + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Enregistrez‑le sous le nom `searchable_pdf.py`, remplacez les espaces réservés `YOUR_DIRECTORY` par de vrais chemins, puis lancez : + +```bash +python searchable_pdf.py +``` + +Vous devriez voir un message de confirmation et un tout nouveau PDF interrogeable apparaître dans votre dossier. + +## Questions fréquentes & cas particuliers + +**Et si l'image est en couleur ?** +EasyOCR fonctionne avec les images en niveaux de gris et en couleur, mais convertir en niveaux de gris (`pil_image.convert("L")`) peut parfois améliorer la précision sur des scans bruyants. + +**Puis‑je gérer des PDF multipages ?** +Oui — bouclez sur chaque image de page, exécutez les étapes OCR, et ajoutez chaque page au même objet `FPDF`. N’oubliez pas de réinitialiser le curseur (`self.add_page()`) pour chaque nouvelle image. + +**Existe‑t‑il un moyen de garder la couche texte originale au lieu du texte blanc invisible ?** +Si vous avez besoin d’un vrai PDF « texte‑sous‑image » (par ex., pour l’accessibilité), envisagez d’utiliser `pdfminer` ou `pikepdf` pour intégrer une couche texte cachée avec les balises PDF appropriées. C’est plus avancé, mais le principe reste le même : image de fond + texte superposé. + +**Et si la confiance OCR est basse ?** +Vous pouvez filtrer les mots à faible confiance : + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Conclusion – Ce que nous avons accompli + +Nous avons commencé avec une simple image de reçu, **performed OCR on image**, extrait les chaînes reconnues, et enfin **create searchable pdf** qui se comporte comme tout document numérisé professionnellement. Le processus a couvert chaque mot‑clé secondaire—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, et **perform OCR on image**—vous offrant ainsi une boîte à outils réutilisable pour tout projet similaire. + +### Prochaines étapes + +- Expérimentez d'autres langues en passant leurs codes ISO à `easyocr.Reader(['en', 'es'])`. +- Remplacez EasyOCR par Tesseract si vous avez besoin d'une solution entièrement hors ligne ; le reste du pipeline reste identique. +- Ajoutez une visualisation de la confiance OCR (dessinez les boîtes englobantes sur l'image) pour déboguer les scans problématiques. + +Vous avez une variante à partager ? Laissez un commentaire, fork + +## 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/) +- [Convertir des images en PDF C# – Enregistrer le résultat OCR multipage](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Comment OCR une image – Effectuer l'OCR sur une image dans la reconnaissance d'images 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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/french/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..9bac7d2fe --- /dev/null +++ b/ocr/french/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-19 +description: Extrayez du texte à partir d'images en Python avec un moteur OCR simple. + Apprenez à convertir des images numérisées en texte, à reconnaître le texte à partir + de photos et à répertorier efficacement les fichiers image en Python. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: fr +og_description: Extraire du texte d'images en Python à l'aide d'un moteur OCR léger. + Ce guide vous montre comment convertir des images numérisées en texte, reconnaître + le texte à partir de photos et lister les fichiers image en Python en quelques étapes. +og_title: Extraire du texte d'images avec Python – Guide complet d'OCR par lots +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Extraire du texte d'images en Python – Guide complet d'OCR en lot +url: /fr/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraire du texte à partir d'images en Python – Guide complet d'OCR par lots + +Vous avez déjà eu besoin d'**extraire du texte à partir d'images** mais vous ne saviez pas par où commencer ? Vous n'êtes pas seul—les développeurs sont constamment confrontés au défi de transformer des PDF numérisés, des reçus photographiés ou des captures d'écran en texte consultable. Dans ce tutoriel, nous parcourrons un exemple complet, prêt à l'exécution, qui montre comment **convertir des images numérisées en texte**, reconnaître le texte à partir d'images, et même **list image files python**‑style. À la fin, vous disposerez d'un script réutilisable qui traite un dossier entier en une seule fois. + +Nous couvrirons tout ce dont vous avez besoin : les bibliothèques requises, pourquoi chaque étape est importante, la gestion des cas limites, et un peu de dépannage. Pas besoin de courir après la documentation externe ; le code ci‑dessous est autonome, et les explications répondent au « comment » *et* au « pourquoi ». Prenez votre IDE préféré, et c'est parti. + +--- + +## Ce que vous allez construire + +- Initialiser un moteur OCR (nous utiliserons le package `ocr` à titre d'illustration). +- Parcourir un répertoire et **list image files python**‑style, en filtrant PNG, JPG et TIFF. +- Exécuter une opération **batch OCR** sur toutes les images trouvées. +- Imprimer le texte extrait pour chaque fichier, clairement étiqueté. + +> **Astuce pro :** Si vous n'avez pas la bibliothèque `ocr` installée, vous pouvez la remplacer par `pytesseract` avec quelques modifications mineures — la logique principale reste la même. + +## Prérequis + +- Python 3.8+ (le script utilise les f‑strings et les annotations de type). +- Une bibliothèque OCR qui expose un `OcrEngine` avec `recognize_batch`. Pour ce guide, nous supposons un package fictif `ocr`, mais le modèle fonctionne avec de vraies bibliothèques. +- Un dossier contenant les fichiers image que vous souhaitez traiter (`.png`, `.jpg`, `.tif`). + +## Étape 1 – Installer & importer les modules requis + +Tout d'abord, assurez-vous que le package OCR est disponible. Si vous utilisez une vraie bibliothèque comme `pytesseract`, remplacez l'import en conséquence. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Pourquoi c'est important :** L'import de `os` nous fournit une gestion des chemins multiplateforme, tandis que `typing.List` aide à l'autocomplétion dans l'IDE et à la pérennité du code. + +## Étape 2 – **Extract Text from Images** : Initialiser le moteur OCR + +Créer le moteur est la première étape de tout travail OCR. Nous définissons également la langue en auto‑détection afin que le moteur puisse gérer des documents multilingues. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explication :** En encapsulant la création du moteur dans une fonction, nous gardons le code modulaire. Si vous devez plus tard ajuster le DPI ou le mode OCR, vous n'avez qu'à modifier cet unique endroit. + +## Étape 3 – **List Image Files Python** : Rassembler les fichiers d'un répertoire + +Nous devons maintenant localiser chaque image que nous voulons traiter. La compréhension de liste ci‑dessous reflète un modèle courant de “list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Gestion des cas limites :** La fonction ignore les sous‑dossiers (vous pouvez ajouter la récursion plus tard) et filtre automatiquement les fichiers cachés car ils ne se terminent généralement pas par les extensions prises en charge. + +## Étape 4 – **Convert Scanned Images to Text** : Exécuter le batch OCR + +La plupart des bibliothèques OCR offrent une méthode batch qui est bien plus rapide que le traitement image par image. Voici comment nous l'appelons. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Pourquoi le batch ?** Envoyer toutes les images d'un coup réduit la surcharge (par ex., charger le modèle OCR à plusieurs reprises) et permet souvent une meilleure utilisation du CPU/GPU. + +## Étape 5 – **Recognize Text from Pictures** : Afficher les résultats + +Enfin, nous parcourons les noms de fichiers associés et les résultats OCR, en imprimant un en‑tête propre pour chaque image. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Astuce :** `strip()` supprime les espaces blancs en début et fin de chaîne que l'OCR ajoute souvent. + +## Script complet – Assemblez le tout + +Voici le programme complet et exécutable. Enregistrez‑le sous le nom `batch_ocr.py` et lancez `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Sortie attendue + +En supposant que le dossier contienne `invoice1.png` et `receipt.jpg`, vous pourriez voir : + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Chaque bloc est clairement étiqueté, ce qui rend le traitement en aval (par ex., l'enregistrement dans une base de données) simple. + +## Gérer les problèmes courants + +| Problème | Pourquoi cela se produit | Solution rapide | +|----------|--------------------------|-----------------| +| **Aucun texte n'apparaît** | Langue OCR non détectée ou image à faible contraste. | Forcer une langue (`engine.language = ocr.Language.English`) ou prétraiter les images (augmenter le contraste). | +| **Erreur de mémoire sur de gros lots** | Le moteur tente de charger toutes les images d'un coup. | Diviser `image_files` en morceaux (`batch_size = 20`) et appeler `recognize_batch` de façon répétée. | +| **Format de fichier non pris en charge** | Vous avez ajouté un `.gif` ou `.bmp`. | Étendre le tuple `supported_exts` ou convertir les images en PNG/JPG au préalable. | +| **Corruption Unicode** | L'OCR renvoie des octets au lieu de chaînes. | S'assurer que la bibliothèque OCR renvoie du Unicode (`result.text.decode('utf‑8')` si nécessaire). | + +## Étendre le flux de travail + +Maintenant que vous pouvez **extraire du texte à partir d'images**, envisagez les étapes suivantes : + +- **Exportation vers CSV** – Écrire chaque nom de fichier et son texte extrait dans une feuille de calcul pour l'analyse. +- **Traitement parallèle** – Utiliser `concurrent.futures.ThreadPoolExecutor` pour gérer plusieurs lots simultanément. +- **Intégration avec un OCR cloud** – Remplacer le moteur local par Google Vision ou Azure OCR pour une meilleure précision sur des mises en page complexes. +- **Ajout de prétraitement d'image** – Des bibliothèques comme Pillow ou OpenCV peuvent redresser, débruiter ou binariser les images avant l'OCR, améliorant les résultats. + +Toutes ces idées utilisent naturellement les mêmes fonctions de base que nous avons créées, vous n'aurez donc pas besoin de repartir de zéro. + +## Conclusion + +Nous venons de parcourir une solution complète pour **extraire du texte à partir d'images** en Python, couvrant tout, de **list image files python** à **recognize text from pictures** et enfin **convert scanned images to text** dans un batch propre. Le script est délibérément simple tout en étant suffisamment flexible pour servir de base à des projets plus importants — que vous numérisiez des reçus, construisiez une archive consultable ou alimentiez un pipeline d'extraction de données. + +Essayez-le, ajustez les étapes de prétraitement, et voyez votre précision OCR s'améliorer. Si vous rencontrez des problèmes, consultez à nouveau le tableau « Gérer les problèmes courants » ; la plupart des soucis se résolvent avec un petit changement de configuration. + +Prêt pour le prochain défi ? Essayez d'ajouter une étape de conversion PDF‑vers‑image avec `pdf2image`, puis alimentez ces images directement dans le même pipeline. Le ciel est la limite lorsque vous combinez l'OCR avec le riche écosystème de Python. + +Bon codage, et que votre texte soit toujours lisible ! + +## 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 des fonctionnalités d'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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/french/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..71a5a11df --- /dev/null +++ b/ocr/french/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: extraire du texte d'images en utilisant Python OCR. Apprenez la détection + automatique de la langue, le traitement parallèle et la reconnaissance par lots + dans un tutoriel concis. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: fr +og_description: extraire du texte à partir d'images avec Python OCR. Ce guide montre + la détection automatique de la langue, le traitement parallèle et la reconnaissance + par lots dans un seul tutoriel. +og_title: extraire du texte d'images en Python – Guide complet d'OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Extraire du texte des images en Python – Guide complet d'OCR +url: /fr/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraire du texte à partir d'images en Python – Guide complet OCR + +Vous vous êtes déjà demandé comment **extraire du texte à partir d'images** sans taper manuellement chaque mot ? Vous n'êtes pas le seul. Que vous numérisiez d'anciens reçus, que vous construisiez une archive de documents consultable, ou que vous vous amusiez simplement avec des astuces d'IA sympas, la capacité d'extraire du texte à partir d'images est une compétence indispensable pour tout développeur Python aujourd'hui. + +Dans ce tutoriel, nous parcourrons un exemple complet, prêt à l’emploi, qui **extrait du texte à partir d'images** en utilisant un moteur OCR populaire. Nous aborderons la détection automatique de la langue, le traitement parallèle pour la vitesse, et la reconnaissance d'images en lot afin que vous puissiez gérer des dizaines de fichiers en quelques secondes. Ça ressemble à ce dont vous avez besoin ? Plongeons‑y. + +## Ce que vous apprendrez + +- Comment instancier le moteur OCR avec `ocr.OcrEngine`. +- Activer la **détection automatique de la langue** afin que le moteur choisisse la bonne langue tout seul. +- Configurer le **OCR en traitement parallèle** avec un pool de threads personnalisé. +- Exécuter la **reconnaissance d'images en lot** sur une liste de fichiers. +- Imprimer le texte reconnu pour chaque image, prêt à être sauvegardé ou indexé. + +Aucune documentation externe requise — tout ce dont vous avez besoin se trouve ici, et le code fonctionne immédiatement avec le package `ocr` (installez‑le via `pip install ocr`). + +## Prérequis + +1. Python 3.8 ou plus récent installé. +2. Le package `ocr` (`pip install ocr`). +3. Un dossier d'images PNG (ou JPG) que vous souhaitez traiter. +4. Une familiarité de base avec les fonctions et boucles Python. + +C’est tout — aucune dépendance lourde, aucune magie GPU, juste du Python pur. + +![exemple d'extraction de texte à partir d'images](https://example.com/ocr-demo.png "Capture d'écran montrant la sortie d'extraction de texte à partir d'images") + +*Texte alternatif : capture d'écran de démonstration d'extraction de texte à partir d'images* + +## Étape 1 – Configurer le moteur OCR (Mot‑clé principal en action) + +First thing’s first: create an OCR engine instance. Think of `ocr.OcrEngine()` as the brain behind the operation; it knows how to read characters, lines, and paragraphs. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Pourquoi avons‑nous besoin d’un moteur explicite ? Parce que l’**utilisation de ocr.OcrEngine** vous donne un contrôle fin sur les paramètres de langue, le threading, et plus encore. C’est la façon la plus flexible d’**extraire du texte à partir d'images** comparée aux aides en une ligne. + +## Étape 2 – Laisser le moteur détecter les langues automatiquement + +Most OCR libraries require you to tell them which language to look for. That’s fine for a single‑language project, but cumbersome for a mixed‑language batch. Luckily, the `ocr` package supports **automatic language detection**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Définir `engine.language` à `ocr.Language.Auto` indique au moteur de sentir chaque image et de choisir le modèle de langue approprié. Cette petite ligne vous fait gagner des heures de configuration manuelle lorsque vous traitez des documents internationaux. + +## Étape 3 – Accélérer le traitement avec le OCR en parallélisation + +If you have four or more CPU cores, why not use them? The engine can spin up a thread pool, letting multiple images be processed at the same time. This is where **parallel processing OCR** shines. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +N’hésitez pas à ajuster le nombre `4` en fonction de votre machine. Plus de threads → des exécutions de lot plus rapides, mais rappelez‑vous que chaque thread consomme de la mémoire, alors trouvez le juste milieu pour votre environnement. + +## Étape 4 – Rassembler les images que vous souhaitez traiter + +Now we need a list of file paths. You can build this list manually, read it from a CSV, or use `glob`. For clarity, we’ll hard‑code a short list: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Remplacez `YOUR_DIRECTORY` par le chemin réel sur votre système. Si vous avez des dizaines de fichiers, un simple `glob.glob("*.png")` fera le gros du travail. + +## Étape 5 – Exécuter la reconnaissance d'images en lot + +Here’s the heart of the tutorial: a single call that processes every image in `files` and returns a list of result objects. This is the **batch image recognition** feature that makes large‑scale OCR practical. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +En coulisses, le moteur répartit chaque fichier sur les quatre threads de travail que nous avons configurés précédemment, tout en détectant automatiquement la langue pour chaque image. La méthode renvoie une liste où chaque élément contient le texte reconnu et les métadonnées. + +## Étape 6 – Imprimer (ou stocker) le texte extrait + +Finally, we loop over the results and print the text. In a real project you’d probably write this to a database or a CSV file, but printing keeps the example simple. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Sortie attendue** (troncature pour la brièveté) : + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Chaque bloc montre le nom de fichier suivi de la chaîne dérivée de l’OCR. Si une image contient plusieurs langues, vous verrez apparaître les caractères appropriés grâce à l’étape précédente de **détection automatique de la langue**. + +## Astuces professionnelles & pièges courants + +- **La qualité de l'image compte** – les photos floues ou à faible contraste produiront du bruit. Pré‑traitez avec OpenCV (`cv2.threshold`, `cv2.resize`) si nécessaire. +- **Nombre de threads vs. I/O** – si vos images résident sur un lecteur réseau lent, plus de threads ne vous aidera pas. Surveillez l’utilisation du CPU avec `top` ou le **Gestionnaire des tâches**. +- **Gestion de l'Unicode** – `result.text` est une chaîne Unicode. Lors de l’écriture dans des fichiers, ouvrez‑les avec `encoding="utf‑8"` pour éviter les `UnicodeEncodeError`. +- **Utilisation de la mémoire** – les gros PDF peuvent consommer beaucoup de RAM. Si vous rencontrez un `MemoryError`, réduisez la taille du pool de threads ou traitez les images par petits lots. + +## Script complet fonctionnel + +Below is the complete, copy‑and‑paste‑ready script that incorporates every step we discussed. Save it as `batch_ocr.py` and run `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Exécutez‑le ainsi : + +```bash +python batch_ocr.py ./my_images 4 +``` + +Vous verrez un bloc de texte joliment formaté pour chaque image, prouvant que vous pouvez **extraire du texte à partir d'images** à grande échelle. + +## Et après ? + +Now that you’ve mastered the basics of **extract text from images** with Python, consider exploring: + +- **Post‑processing** : nettoyez la sortie OCR avec des expressions régulières ou des bibliothèques de traitement du langage naturel. +- **Conversion PDF** : alimentez les chaînes extraites dans un générateur de PDF pour des PDF consultables. +- **Services OCR cloud** : comparez les résultats `ocr` on‑prem avec Google Vision ou Azure OCR pour des cas limites de précision. +- **Interface GUI** : créez une petite application Flask ou FastAPI qui permet aux utilisateurs de télécharger des images et de voir instantanément le texte extrait. + +Each of these topics builds on the **Python OCR library** foundation you just set up, and they all benefit from the same **parallel processing OCR** tricks we used here. + +--- + +*Bon codage ! Si vous rencontrez des problèmes, laissez un commentaire ci‑dessous — je suis toujours disponible pour dépanner les bizarreries du OCR.* + +## Que devriez‑vous apprendre ensuite ? + +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. + +- [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/) +- [Extraire du texte d'images en utilisant l'opération OCR sur des dossiers](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/french/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/french/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..6de22ceea --- /dev/null +++ b/ocr/french/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-06-19 +description: Comment extraire un PDF avec OCR en Python – tutoriel étape par étape + couvrant l'extraction de texte d'un PDF, la reconnaissance de texte à partir d'une + image et un exemple d'OCR en Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: fr +og_description: Comment extraire un PDF avec OCR en Python. Apprenez à extraire le + texte d’un PDF, à reconnaître le texte d’une image, et découvrez un exemple complet + d’OCR en Python. +og_title: Comment extraire le texte d’un PDF avec OCR en Python – Tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Comment extraire le texte d’un PDF avec OCR en Python – Guide complet +url: /fr/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment extraire du texte PDF avec OCR en Python – Guide complet + +Vous vous êtes déjà demandé **comment extraire PDF** lorsque le fichier n’est qu’une image numérisée ? Vous n’êtes pas seul. Dans de nombreux projets réels—contrats, factures ou archives historiques—le PDF que vous recevez ne contient aucun texte sélectionnable. Bonne nouvelle : quelques lignes de Python peuvent transformer ces pages uniquement images en texte consultable et modifiable. + +Dans ce tutoriel, nous allons parcourir un **exemple OCR Python** pratique qui lit un PDF, rend sa première page sous forme d’image, puis **extrait le texte du PDF** à l’aide d’un moteur OCR. À la fin, vous saurez exactement comment **lire PDF avec OCR**, pourquoi chaque étape est importante, et comment adapter le code pour des documents multi‑pages ou d’autres langues. + +## Ce que vous allez apprendre + +- Installer et configurer une bibliothèque OCR fiable pour Python. +- Convertir les pages PDF en images adaptées à l’OCR. +- **Reconnaître le texte à partir d’une image** et récupérer des chaînes Unicode propres. +- Pièges courants (PDF basse résolution, pages tournées) et comment les éviter. +- Étendre le script pour gérer plusieurs pages ou un traitement par lots. + +**Prérequis** : Python 3.8+, pip, et une compréhension de base des environnements virtuels. Aucune expérience préalable en OCR requise—suivez simplement le guide. + +--- + +## ## Comment extraire du texte PDF avec OCR en Python + +Ce titre H2 contient notre mot‑clé principal exactement où les moteurs de recherche aiment le voir. Passons directement au code. + +### Étape 1 – Installer les paquets requis + +Tout d’abord, nous avons besoin d’un moteur OCR. L’exemple ci‑dessous utilise le populaire package **ocr** (un wrapper léger autour de Tesseract). Si vous préférez un autre backend, les concepts restent les mêmes. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Astuce :** Sous Linux, vous aurez également besoin du binaire Tesseract : `sudo apt-get install tesseract-ocr`. Les utilisateurs macOS peuvent l’obtenir via Homebrew : `brew install tesseract`. + +### Étape 2 – Initialiser le moteur OCR et définir la langue + +Nous lançons maintenant le moteur et lui indiquons de rechercher les caractères anglais. Vous pouvez remplacer `ocr.Language.English` par n’importe quel code de langue supporté. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Pourquoi c’est important :** Spécifier la langue améliore considérablement la précision car le moteur peut appliquer des dictionnaires et modèles de caractères propres à la langue. + +### Étape 3 – Charger une page PDF en tant qu’image + +L’OCR fonctionne sur des images raster, pas sur des objets PDF. L’aide‑mémoire `ocr.Image.from_pdf` rend la page choisie en bitmap. Ajustez `page_number` pour d’autres pages (indexation à partir de 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Cas particulier :** Si le PDF contient des graphiques vectoriels plutôt que des images numérisées, vous pourriez obtenir un rendu net. Pour des scans basse résolution, envisagez d’augmenter le DPI : `ocr.Image.from_pdf(..., dpi=300)`. + +### Étape 4 – Reconnaître le texte à partir de l’image rendue + +Voici le cœur de **l’exemple ocr python**. Le moteur traite le bitmap et renvoie un objet contenant la chaîne extraite. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +L’attribut `ocr_result.text` contient la sortie texte brute, en conservant les sauts de ligne lorsque c’est possible. + +### Étape 5 – Afficher ou stocker le texte extrait + +Enfin, nous affichons le résultat. Dans une vraie application, vous écririez probablement dans un fichier ou une base de données. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +L’exécution du script devrait afficher quelque chose comme : + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +C’est un flux de travail complet **extraction texte depuis pdf** utilisant l’OCR. + +--- + +## ## Reconnaître le texte à partir d’une image – Ajuster la précision + +Si vous ne vous intéressez qu’à **reconnaître le texte à partir d’une image** (par ex., un JPEG d’un reçu), vous pouvez ignorer l’étape de conversion PDF : + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Conseils pour de meilleurs résultats :** + +- **Pré‑traiter** l’image : convertir en niveaux de gris, appliquer un seuillage, ou redresser. Pillow rend cela simple. +- **Augmenter le DPI** lors du rendu PDF : une résolution plus élevée fournit plus de détails au moteur OCR. +- **Activer la configuration du moteur OCR** pour la segmentation de page (`ocr_engine.config = "--psm 6"` pour des blocs uniformes). + +--- + +## ## Lire PDF avec OCR – Gestion de plusieurs pages + +La plupart des contrats s’étendent sur plusieurs pages. Boucler sur chaque page est simple : + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Cette fonction **lit PDF avec OCR**, concatène la sortie et insère un marqueur de saut de page clair. Vous pouvez ensuite injecter `full_text` dans un index de recherche ou le stocker comme fichier `.txt`. + +--- + +## ## Problèmes courants et solutions + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Caractères brouillés, beaucoup de `?` | Mauvaise langue ou fichiers de données linguistiques manquants | Installer le bon pack de langue Tesseract (`tesseract-ocr-`) et définir `ocr_engine.language`. | +| Lignes manquantes ou mots tronqués | DPI trop faible (inférieur à 150) | Rendre le PDF à 300 DPI ou plus (`dpi=300`). | +| Texte tourné ou à l’envers | Page numérisée pas à l’endroit | Utiliser `ocr.Image.deskew(page_image)` avant la reconnaissance. | +| Traitement lent sur de gros PDFs | Traitement séquentiel des pages sur un seul thread | Paralleliser avec `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Étendre l’exemple OCR Python + +- **Exporter vers PDF/A** : après extraction, vous pouvez réintégrer le texte dans un PDF consultable à l’aide de `reportlab` ou `pypdf2`. +- **Détection de langue** : utilisez `langdetect` sur la sortie OCR pour changer dynamiquement `ocr_engine.language`. +- **Traitement par lots** : parcourez un répertoire avec `os.listdir` et appliquez `extract_all_pages` à chaque fichier. + +--- + +## ## Résultat attendu et vérification + +Lorsque vous exécutez le script sur un scan clair en anglais, vous devriez voir un bloc de texte propre avec une ponctuation correcte. Vérifiez en : + +1. Comparant quelques lignes avec l’image numérisée d’origine. +2. Exécutant un simple comptage de mots (`len(ocr_result.text.split())`) pour s’assurer que la sortie n’est pas vide. +3. Optionnellement, en passant le résultat dans un correcteur orthographique comme `pyspellchecker` pour repérer les erreurs d’OCR. + +--- + +## Conclusion + +Nous avons couvert **comment extraire PDF** lorsque l’analyse traditionnelle échoue, démontré un **exemple ocr python** complet, et expliqué comment **reconnaître le texte à partir d’une image** et **lire PDF avec OCR** pour des scénarios mono‑page et multi‑pages. Avec les extraits de code ci‑dessus, vous pouvez désormais transformer n’importe quel PDF numérisé en texte consultable et modifiable—plus besoin de retaper manuellement. + +Prochaines étapes ? Essayez de changer la langue en espagnol (`ocr.Language.Spanish`) ou expérimentez les techniques de pré‑traitement d’image pour augmenter la précision. Si vous construisez un système de gestion de documents, pensez à indexer le texte extrait avec Elasticsearch pour une recherche ultra‑rapide. + +Des questions ou un PDF capricieux ? Laissez un commentaire, et bon codage ! + +![Comment extraire PDF avec OCR en Python](image.png "Comment extraire PDF avec OCR en Python") + + +## 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/french/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..72293c233 --- /dev/null +++ b/ocr/french/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-19 +description: Apprenez à utiliser l’OCR en Java avec Aspose. Ce guide étape par étape + couvre le redressement automatique des images, la détection automatique de la langue + et l’extraction facile du texte d’une image. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: fr +og_description: 'Comment utiliser l''OCR en Java avec Aspose : un guide complet couvrant + le redressement automatique des images, la détection automatique de la langue et + l''extraction de texte à partir d''images.' +og_title: Comment utiliser l'OCR en Java avec Aspose – Guide complet +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Comment utiliser l’OCR en Java avec Aspose – Guide complet +url: /fr/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment utiliser l’OCR en Java avec Aspose – Guide complet + +Vous êtes-vous déjà demandé **comment utiliser l’OCR** dans un projet Java sans perdre patience à cause de la configuration ? Vous n’êtes pas seul. De nombreux développeurs se heurtent à un mur lorsqu’ils doivent **extraire du texte d’une image** rapidement, surtout lorsque les scans sources sont de travers ou rédigés dans une langue inconnue. + +Dans ce tutoriel, nous allons parcourir un exemple pratique qui montre exactement comment utiliser l’OCR avec Aspose, incluant **l’auto‑redressement des images**, **la détection automatique de la langue**, et le pipeline complet de **prétraitement d’image OCR**. À la fin, vous disposerez d’un extrait de code prêt à l’emploi qui affiche le texte reconnu dans la console, et vous comprendrez pourquoi chaque paramètre est important. + +> **Ce que vous obtiendrez :** un programme Java complet et exécutable, des explications ligne par ligne, des astuces pour gérer les cas limites, et des idées pour étendre la solution au traitement par lots ou aux PDF. + +--- + +## Prérequis + +- Java 17 (ou toute version récente du JDK) installé et configuré. +- Maven ou Gradle pour la gestion des dépendances (nous montrerons les coordonnées Maven). +- Un fichier de licence Aspose OCR for Java (`Aspose.OCR.Java.lic`). Si vous ne faites que tester, vous pouvez ignorer l’étape de licence, mais la version d’essai ajoutera un filigrane. +- Une image d’exemple (`your_image.png`) placée quelque part d’accessible au code. + +> **Astuce pro :** conservez vos images dans un dossier `resources` dédié et chargez‑les via le classpath ; cela évite les problèmes de chemins sur différents systèmes d’exploitation. + +--- + +## Étape 1 : Configurer le projet et ajouter la dépendance Aspose OCR + +Créez un nouveau projet Maven (ou utilisez celui existant) et ajoutez ce qui suit à votre `pom.xml` : + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Exécutez `mvn clean install` pour récupérer la bibliothèque. Si vous préférez Gradle, l’équivalent est : + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Vous avez maintenant les classes de **prétraitement d’image OCR** sur votre classpath. + +--- + +## Étape 2 : Appliquer votre licence Aspose OCR (Optionnel mais recommandé) + +Si vous possédez une licence, appliquez‑la dès le début de votre méthode `main`. Ignorer cette étape fonctionne, mais la version gratuite ajoute un filigrane « Demo » sur le résultat. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Pourquoi c’est important :** la version sous licence supprime les limites d’utilisation et désactive le filigrane, vous offrant des résultats propres et prêts pour la production. + +--- + +## Étape 3 : Créer l’instance du moteur OCR + +Le moteur est le cœur du processus. L’instancier vous donne accès à toutes les options de **prétraitement d’image OCR**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +À ce stade, le moteur est prêt, mais il utilisera les paramètres par défaut qui ne sont peut‑être pas optimaux pour les documents numérisés. Ajustons quelques‑uns. + +--- + +## Étape 4 : Activer l’auto‑redressement des images pour des scans plus propres + +Les scans inclinés sont un problème fréquent. Aspose propose une fonctionnalité **auto deskew images** qui redresse automatiquement l’image avant la reconnaissance. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Comment ça fonctionne :** l’algorithme analyse les angles de la ligne de base du texte et fait pivoter l’image vers l’orientation la plus probable. Cela améliore considérablement la précision pour les photos prises avec un téléphone. + +--- + +## Étape 5 : Activer la détection automatique de la langue + +Si vous ne connaissez pas la langue de l’image source, laissez le moteur la déterminer. C’est le paramètre **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Lorsque vous activez cela, Aspose analyse les glyphes et sélectionne le modèle linguistique le plus probable, supportant plus de 30 langues dès le départ. + +--- + +## Étape 6 : Charger l’image à reconnaître + +Vous pouvez charger une image depuis le disque, une URL, ou même un tableau d’octets. Pour la simplicité, nous lirons depuis un fichier local. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Conseil :** si vous traitez de grandes images, envisagez de les sous‑échantillonner d’abord avec `engine.getImagePreprocessing().setResizeFactor(0.5)` pour accélérer le traitement sans perdre trop de détails. + +--- + +## Étape 7 : Effectuer la reconnaissance OCR et extraire le texte de l’image + +Le moteur fait maintenant sa magie. La méthode `recognize` renvoie un objet `OcrResult` contenant le texte reconnu, les scores de confiance, et plus encore. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +La console affichera le texte brut extrait de l’image — c’est le résultat principal **extract text image** que nous voulions obtenir. + +--- + +## Exemple complet fonctionnel + +Voici la classe Java complète qui réunit tous les éléments. Copiez‑collez‑la dans `src/main/java/com/example/OcrDemo.java` et exécutez‑la. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Résultat attendu + +Si l’image contient la phrase « Hello World » sur un scan propre, vous verrez : + +``` +=== Recognized Text === +Hello World +``` + +Pour des documents plus complexes (par ex. des reçus multilingues), la sortie inclura des sauts de ligne et le code de langue détecté. + +--- + +## Pièges courants & Astuces pro + +| Problème | Pourquoi cela arrive | Solution | +|----------|----------------------|----------| +| **Caractères illisibles** | L’image est trop sombre ou bruyante. | Activez `engine.getImagePreprocessing().setBinarization(true)` ou ajustez le contraste manuellement. | +| **Mauvaise langue** | La détection automatique se trompe sur des pages multilingues. | Définissez `engine.setLanguage(Language.English)` (ou l’enum approprié) pour forcer une langue spécifique. | +| **Traitement lent** | Images très haute résolution. | Réduisez la taille avec `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Erreurs de mémoire** | Grand lot d’images chargé en même temps. | Traitez les images séquentiellement et appelez `engine.dispose()` après chaque exécution. | + +> **Rappel :** le moteur OCR est sûr pour les threads en lecture seule, mais créer une nouvelle instance par thread évite les bugs liés à un état caché. + +--- + +## Étendre la solution + +Maintenant que vous savez **comment utiliser l’OCR** avec Aspose, vous pourriez vouloir : + +1. **Traiter des PDF** – Convertir chaque page PDF en image (`PdfConverter`) puis la passer dans le même pipeline. +2. **Traitement par lots d’un dossier** – Parcourir les fichiers d’un répertoire, appliquer les mêmes étapes, et écrire les résultats dans un CSV. +3. **Intégrer à un service web** – Exposer la logique OCR via un `@RestController` Spring Boot qui accepte des téléchargements multipart. + +Tous ces scénarios réutilisent la même configuration de **prétraitement d’image OCR** que nous avons construite ici. + +--- + +## Conclusion + +Nous avons couvert **comment utiliser l’OCR** en Java avec Aspose du début à la fin : appliquer une licence, créer le moteur, activer **auto deskew images**, activer **auto language detection**, charger une image, et enfin **extract text image** avec un simple `System.out.println`. Le code est autonome, fonctionne avec n’importe quel JDK récent, et montre les meilleures pratiques pour la précision et les performances. + +Essayez-le avec vos propres images — peut‑être un contrat numérisé ou une capture d’écran de reçu. Ajustez les drapeaux de prétraitement, expérimentez avec différentes langues, et vous verrez rapidement pourquoi la bibliothèque OCR d’Aspose est un choix solide pour l’extraction de texte en production. + +Des questions ou envie de partager vos résultats ? Laissez un commentaire ci‑dessous ou contactez‑moi sur GitHub. Bon codage ! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## 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 d’autres fonctionnalités de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/french/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..cad2fa402 --- /dev/null +++ b/ocr/french/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,320 @@ +--- +category: general +date: 2026-06-19 +description: Améliorez la précision de l'OCR en Python avec Aspose OCR. Apprenez à + définir la langue de l'OCR, charger une image pour l'OCR et extraire le texte de + l'image à l'aide d'un dictionnaire personnalisé. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: fr +og_description: Améliorez la précision de l'OCR en Python en définissant la langue + de l'OCR, en chargeant une image pour l'OCR et en extrayant le texte de l'image + avec un dictionnaire personnalisé. +og_title: Améliorer la précision de l’OCR en Python – Guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Améliorer la précision de l’OCR en Python – Guide complet +url: /fr/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Améliorer la précision OCR en Python – Guide complet + +Vous êtes-vous déjà demandé comment **améliorer la précision OCR** lorsque le texte que vous numérisez contient des symboles étranges, des codes produit ou des noms de marque ? Vous n’êtes pas seul. Dans de nombreux projets, le moteur par défaut ne renvoie que du charabia, ce qui est un vrai frein à la productivité. + +Dans ce tutoriel, nous parcourrons un exemple pratique, de bout en bout, qui vous montre comment **définir la langue OCR**, **charger une image pour l’OCR**, **effectuer l’OCR sur l’image**, et enfin **extraire le texte de l’image** avec un dictionnaire personnalisé qui augmente les taux de reconnaissance. À la fin, vous disposerez d’un script prêt à l’emploi que vous pourrez intégrer à n’importe quel projet Python. + +## Ce que vous retirerez de ce tutoriel + +- Un script Python entièrement fonctionnel qui utilise Aspose OCR pour lire un fichier PNG. +- La capacité d’**améliorer la précision OCR** en configurant la langue et une liste de mots personnalisée. +- Des explications claires sur l’importance de chaque paramètre, ainsi que des astuces pour gérer les cas limites comme les caractères non latins. +- Une checklist rapide pour dépanner les problèmes OCR courants. + +### Prérequis + +- Python 3.8 ou une version plus récente installé sur votre machine. +- Le package `aspose-ocr` (installez‑le via `pip install aspose-ocr`). +- Une image d’exemple (`technical_doc.png`) contenant le texte que vous souhaitez lire. +- Une connaissance de base de Python — rien de spécial n’est requis. + +> **Astuce pro :** Si vous travaillez dans un environnement virtuel, activez‑le avant d’installer le package. Cela garde vos dépendances propres et évite les conflits de version. + +--- + +## Étape 1 : Installer et importer Aspose OCR + +Première chose à faire — installons la bibliothèque dans notre environnement et importons les éléments dont nous avons besoin. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +L’espace de noms `aspose.ocr` vous donne accès à la classe `OcrEngine`, qui est le cœur du processus OCR. L’importer ici rend le reste du script plus clair et lisible. + +--- + +## Étape 2 : Créer un moteur OCR et **définir la langue OCR** + +Pourquoi la langue est‑elle importante ? Les moteurs OCR s’appuient sur des modèles spécifiques à chaque langue pour reconnaître les formes de caractères et les modèles de mots. Si vous indiquez au moteur que vous numérisez du texte anglais, il ignorera les glyphes cyrilliques et se concentrera sur l’alphabet latin, améliorant ainsi de façon spectaculaire **la précision OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Remarque :** Aspose OCR prend en charge plus de 50 langues. Remplacez `ocr.Language.English` par `ocr.Language.Spanish`, `ocr.Language.French`, etc., si votre document n’est pas en anglais. + +--- + +## Étape 3 : Définir un **dictionnaire personnalisé** pour booster la précision + +Imaginez que vous numérisez des factures contenant le mot « AsposeOCR » ou des codes produit comme « SKU12345 ». Le moteur ne connaît pas ces termes et les devine incorrectement. Fournir une liste de mots personnalisée indique au moteur : *« Hey, ces chaînes sont légitimes — ne les corrigez pas. »* C’est un gain rapide pour **améliorer la précision OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Vous pouvez charger cette liste depuis un fichier ou une base de données si vous avez des centaines d’entrées — gardez‑la simplement dans une liste Python pour la simplicité. + +--- + +## Étape 4 : **Charger l’image pour l’OCR** + +Nous avons maintenant besoin d’une image. La méthode `Image.load` accepte le chemin vers n’importe quel format raster pris en charge (PNG, JPEG, BMP, etc.). Si le fichier est introuvable, le moteur lève une exception, nous allons donc nous prémunir contre cela. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Pourquoi cette étape est importante :** Charger correctement l’image garantit que le moteur travaille avec les pixels exacts que vous souhaitez analyser. Les fichiers corrompus ou les mauvais chemins sont une source fréquente de frustration. + +--- + +## Étape 5 : **Effectuer l’OCR sur l’image** et extraire les résultats + +Avec le moteur configuré et l’image prête, la reconnaissance proprement dite se résume à un appel de méthode. L’objet résultat contient le texte brut, les scores de confiance, et même les informations de mise en page si vous en avez besoin plus tard. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Si vous devez **extraire le texte de l’image** ligne par ligne, vous pouvez scinder sur les caractères de nouvelle ligne : + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Étape 6 : Vérifier la sortie – Cela **améliore‑t‑il réellement la précision OCR** ? + +Affichons le résultat et voyons si notre dictionnaire personnalisé a fait une différence. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Une sortie typique pour l’image d’exemple pourrait ressembler à : + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Remarquez comment le nom de la marque, le caractère grec et le code produit apparaissent exactement comme nous les avons définis. Sans le dictionnaire personnalisé, le moteur aurait tenté de les « corriger », produisant souvent quelque chose comme « Aspose OCR » ou « SKU 1234 ». + +--- + +## Pièges courants & comment les résoudre + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| **Caractères parasites** | Langue incorrecte ou image à basse résolution | Assurez‑vous que `engine.language` correspond à la langue source et utilisez une numérisation haute résolution (300 dpi ou plus). | +| **Mots personnalisés ignorés** | Dictionnaire non attaché ou faute de frappe dans le nom de la propriété | Revérifiez `engine.text_processing.custom_dictionary = …`. | +| **Fichier introuvable** | Chemin incorrect ou permissions manquantes | Utilisez `os.path.abspath()` pour vérifier le chemin absolu ; exécutez le script avec les permissions appropriées. | +| **Traitement lent** | Images volumineuses ou nombreuses pages | Pré‑traitez l’image (recadrage, redimensionnement) ou utilisez `engine.recognize(image, max_threads=4)` pour paralléliser. | + +--- + +## Aller plus loin : Ajustements avancés pour **améliorer la précision OCR** + +1. **Pré‑traitement** – Appliquez un renforcement du contraste ou une binarisation avec Pillow avant d’alimenter l’image à Aspose OCR. +2. **Multiples langues** – Définissez `engine.language = ocr.Language.English | ocr.Language.French` pour activer la reconnaissance bilingue. +3. **OCR basé sur une région** – Si vous ne avez besoin que d’une zone spécifique (par ex., un tableau), recadrez d’abord l’image pour réduire le bruit. +4. **Filtrage par confiance** – `result.confidence` fournit un score par caractère ; vous pouvez éliminer les résultats à faible confiance de façon programmatique. + +--- + +## Script complet fonctionnel + +Voici le script complet, prêt à copier‑coller, qui intègre chaque étape abordée. Enregistrez‑le sous le nom `improve_ocr_accuracy.py` et exécutez‑le depuis la ligne de commande. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Exécutez‑le : + +```bash +python improve_ocr_accuracy.py +``` + +Vous devriez voir la sortie formatée proprement que nous avons affichée précédemment. + +--- + +## Conclusion + +Nous venons de couvrir une méthode simple pour **améliorer la précision OCR** en Python en : + +1. **Définissant la langue OCR** correspondant à votre document. +2. **Chargeant correctement l’image** afin que le moteur voie les bons pixels. +3. **Effectuant l’OCR sur l’image** avec un appel de méthode unique. +4. **Extrait le texte de l’image** et en confirmant le résultat. +5. **Ajoutant un dictionnaire personnalisé** pour verrouiller les termes spécifiques à votre domaine. + +Voilà le flux complet — de l’image brute au texte propre et interrogeable—emballé dans un script réutilisable. + +Si vous êtes prêt pour le prochain défi, essayez le pré‑traitement d’image (contraste, redressement) ou passez à une configuration multilingue avec `ocr.Language.English | ocr.Language.German`. Les mêmes principes s’appliquent, et vous continuerez à **améliorer la précision OCR** sur un plus large éventail de documents. + +Des questions ou un cas particulier ? Laissez un commentaire ci‑dessous, et bon codage ! + +![improve OCR accuracy + + +## 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 – 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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/french/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..13dc15007 --- /dev/null +++ b/ocr/french/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,306 @@ +--- +category: general +date: 2026-06-19 +description: Effectuez la reconnaissance optique de caractères (OCR) sur une image + en utilisant la bibliothèque OCR de Python. Apprenez comment détecter le texte d’une + image, reconnaître le texte d’un JPEG et extraire le texte d’une image numérisée + efficacement. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: fr +og_description: Effectuez la reconnaissance optique de caractères (OCR) sur une image + avec Python et extrayez le texte des fichiers numérisés. Ce guide vous accompagne + pas à pas dans le chargement des images, la correction de l’inclinaison et la reconnaissance + du texte. +og_title: Effectuer l’OCR d’une image en Python – Guide complet d’extraction de texte +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Effectuer une OCR sur une image en Python – Guide complet d'extraction de texte +url: /fr/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Effectuer une OCR sur une image en Python – Guide complet d'extraction de texte + +Vous avez déjà eu besoin de **perform OCR on image** mais vous êtes tombé sur un mur parce que le code semblait cryptique ? Vous n'êtes pas seul. Que vous transformiez une pile de reçus numérisés en PDF consultables ou que vous extrayiez des légendes d'un JPEG pour un projet de data‑science, la capacité à reconnaître du texte à partir de JPEG et d'autres formats est une compétence indispensable pour tout développeur aujourd'hui. + +Dans ce tutoriel, nous parcourrons un exemple complet et exécutable qui vous montre comment **detect text from image**, **extract text from scanned image** et même **load image for OCR** en quelques lignes seulement. À la fin, vous disposerez d’un extrait de code solide, prêt pour la production, que vous pourrez intégrer directement dans vos projets — sans importations manquantes, sans raccourcis vagues du type « voir la documentation ». + +## Ce que vous allez créer + +- Un petit script Python qui crée un moteur OCR, active l’auto‑deskew, charge un JPEG (ou tout autre format supporté) et affiche le texte reconnu. +- Des explications sur **why** chaque paramètre est important, pas seulement **how** le taper. +- Des astuces pour gérer les PDF multi‑pages, les langues non‑anglais et les pièges courants comme les scans flous. + +### Prérequis + +- Python 3.8+ installé (l’exemple utilise le package `ocr` disponible via `pip install ocr-lib` – remplacez‑le par le nom réel de votre bibliothèque). +- Une connaissance de base des fonctions Python et des environnements virtuels. +- Un fichier image (JPEG, PNG, TIFF) que vous souhaitez traiter ; nous utiliserons `skewed_page.jpg` comme exemple. + +> **Pro tip :** Si vous êtes sous Windows, lancez votre terminal en tant qu’administrateur lors de l’installation de la bibliothèque OCR pour éviter les problèmes de permissions. + +--- + +## Perform OCR on Image – Configuration et mise en place + +La première chose dont vous avez besoin est une instance propre du moteur OCR. Pensez‑y comme le cerveau de l’opération ; sans une configuration correcte, même l’image la plus nette renverra du charabia. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters :** +Définir `engine.language` restreint l’ensemble de caractères attendu par le moteur OCR, ce qui augmente considérablement la précision. Si vous omettez cela, le moteur devinera, souvent en lisant mal des mots simples. + +--- + +## Enable Automatic Deskew – Corriger les scans inclinés + +Les pages numérisées ne sont rarement parfaitement plates. Une légère inclinaison peut perturber la segmentation des caractères, transformant « Hello » en « H3llo ». Le drapeau `auto_deskew` fait le gros du travail pour vous. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case :** Si vous savez que vos images sont déjà droites, désactiver le deskew peut économiser quelques millisecondes de temps de traitement — utile lorsqu’on traite des milliers de pages dans un job batch. + +--- + +## Load Image for OCR – Prise en charge de JPEG, PNG, TIFF + +Nous allons maintenant réellement **load image for OCR**. La méthode `ocr.Image.load` est flexible ; elle accepte un chemin vers n’importe quel format raster supporté. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial :** La bibliothèque lit le fichier dans un bitmap interne, appliquant les conversions d’espace couleur nécessaires. Ignorer cette étape et passer un flux d’octets brut déclencherait une `FileNotFoundError` ou, pire, produirait silencieusement des résultats vides. + +Si vous devez **recognize text from JPEG** spécifiquement, assurez‑vous simplement que l’extension du fichier est `.jpeg` ou `.jpg`. Le même appel fonctionne pour PNG (`.png`) ou TIFF (`.tif`) sans modification. + +--- + +## Perform OCR on Image – Exécution du moteur + +Avec le moteur prêt et l’image en mémoire, il est temps de **perform OCR on image**. Cette ligne unique fait tout le travail : pré‑traitement, segmentation, classification et assemblage du texte. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood ?** +- Le moteur applique la transformation de deskew (si activée). +- Il exécute un réseau neuronal ou le backend Tesseract pour identifier les caractères. +- Enfin, il assemble les caractères en mots et lignes, renvoyant un objet `result` riche. + +--- + +## Extract Text from Scanned Image – Afficher les résultats + +L’étape finale consiste à **extract text from scanned image** et à l’afficher. L’attribut `result.text` contient la représentation en texte brut. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Un résultat typique ressemble à : + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Si le moteur OCR ne trouve aucun caractère, `result.text` sera une chaîne vide. Dans ce cas, revérifiez la qualité de l’image ou envisagez d’ajuster la propriété `engine.confidence_threshold` (si votre bibliothèque le supporte). + +--- + +## Gestion des variations courantes + +### Recognize Text from JPEG vs PNG + +Les deux formats sont supportés, mais la compression JPEG peut introduire des artefacts qui perturbent le moteur. Si vous remarquez des erreurs fréquentes, essayez de convertir le JPEG en PNG d’abord : + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detect Text from Image with Multiple Languages + +Si votre document mêle anglais et espagnol, activez un mode multilingue : + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Le moteur prendra alors en compte les deux alphabets lors de la reconnaissance. + +### Extract Text from Scanned PDFs + +Pour les PDF, il faut d’abord rasteriser chaque page en image. Des bibliothèques comme `pdf2image` rendent cela très simple : + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Exemple complet fonctionnel + +Voici le script complet que vous pouvez copier‑coller dans un fichier `ocr_demo.py`. Il inclut la gestion des erreurs et un petit helper pour mesurer le temps d’exécution. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (en supposant un scan clair) : + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Questions fréquentes + +**Q : Puis‑je exécuter cela sur un serveur sans interface graphique ?** +R : Absolument. La bibliothèque fonctionne sans GUI ; assurez‑vous simplement que les binaires natifs nécessaires (par ex., Tesseract) sont installés sur le serveur. + +**Q : Et si l’image est floue ?** +R : Envisagez d’ajouter un filtre de netteté avant `engine.recognize`. De nombreuses bibliothèques OCR exposent `image_preprocessing.sharpen = True` ou vous pouvez utiliser `cv2.GaussianBlur` d’OpenCV en sens inverse. + +**Q : Le script supporte‑t‑il le traitement par lots ?** +R : Oui. Enveloppez `perform_ocr` dans une boucle sur une liste de chemins de fichiers, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/french/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..c6cf75f02 --- /dev/null +++ b/ocr/french/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-19 +description: Effectuez la reconnaissance optique de caractères (OCR) sur une image + avec Aspose OCR Java. Apprenez à charger une image pour l’OCR, à utiliser la licence + Aspose et à extraire le texte de l’image en quelques minutes. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: fr +og_description: Effectuez la reconnaissance optique de caractères (OCR) sur une image + avec Aspose OCR Java. Ce guide montre comment utiliser la licence Aspose, charger + une image pour l’OCR et extraire le texte de l’image efficacement. +og_title: Effectuer l'OCR sur une image avec Aspose OCR Java – Tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Effectuer la reconnaissance optique de caractères (OCR) sur une image avec + Aspose OCR Java – Guide complet étape par étape +url: /fr/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Effectuer la reconnaissance OCR sur une image avec Aspose OCR Java – Guide complet étape par étape + +Vous avez déjà eu besoin de **perform OCR on image** mais vous n'étiez pas sûr de la bibliothèque qui vous fournirait des résultats fiables sans une tonne de configuration ? Vous n'êtes pas seul. Dans de nombreux projets réels — pensez à la numérisation de passeports, à la digitalisation de factures ou à l'extraction de texte à partir de captures d'écran — la capacité de reconnaître rapidement les données textuelles d'une image est un véritable changement de jeu. + +Dans ce tutoriel, nous allons parcourir un exemple pratique qui montre exactement comment **perform OCR on image** en utilisant Aspose OCR pour Java. Nous couvrirons tout, de l'application de votre licence Aspose au chargement de l'image, en passant par l'exécution du moteur, jusqu'à **extract text from image** afin que vous puissiez l'utiliser en aval. Pas de superflu, juste une solution fonctionnelle que vous pouvez copier‑coller. + +## Ce que vous retirerez de ce tutoriel + +- Une vision claire de comment **use Aspose license** dans un projet Java. +- Le code exact nécessaire pour **load image for OCR** et laisser le moteur détecter automatiquement les langues. +- Des instructions étape par étape pour **recognize text image** et **extract text from image** en toute sécurité. +- Conseils pour gérer les pièges courants (résultats vides, formats non pris en charge et problèmes de mémoire). + +> **Prerequisites** – Java 8 ou plus récent, Maven ou Gradle pour la gestion des dépendances, et un fichier de licence Aspose OCR pour Java (ou vous pouvez fonctionner en mode d'évaluation). + +--- + +## Comment effectuer l'OCR sur une image avec Aspose OCR Java + +Voici le programme Java complet, prêt à être exécuté, qui démontre l'ensemble du flux. Enregistrez‑le sous le nom `AsposeOcrDemo.java` et exécutez‑le depuis votre IDE ou en ligne de commande. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Sortie console attendue + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Si vous exécutez le programme sans fichier de licence, la première ligne indiquera simplement que vous êtes en mode d'évaluation, mais l'OCR fonctionnera tout de même. + +--- + +## Configurer et utiliser la licence Aspose + +### Pourquoi une licence est importante + +Exécuter la bibliothèque en mode d'évaluation convient pour des tests rapides, mais cela ajoute un filigrane à la sortie et limite le nombre de pages que vous pouvez traiter par exécution. Appliquer l'étape **use aspose license** supprime ces restrictions et indique à Aspose que vous êtes un client payant. + +### Comment l'obtenir et l'appliquer + +1. Achetez une licence sur la boutique Aspose. +2. Téléchargez le fichier `Aspose.OCR.Java.lic`. +3. Placez‑le à un endroit où votre application peut le lire — généralement le dossier `src/main/resources`. +4. Appelez `new License().setLicense("Aspose.OCR.Java.lic");` avant toute opération OCR, comme indiqué dans le code ci‑dessus. + +> **Pro tip:** Si vous déployez sur un serveur, utilisez un chemin absolu ou un chargeur de ressources class‑path pour éviter `FileNotFoundException`. + +--- + +## Charger une image pour le traitement OCR + +La ligne `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` est le cœur de l'étape **load image for OCR**. Aspose OCR prend en charge un large éventail de formats : PNG, JPEG, BMP, TIFF, et même les PDF multi‑pages (lorsqu'ils sont combinés avec Aspose.Pdf). + +### Pièges courants + +| Problème | Symptôme | Solution | +|----------|----------|----------| +| Chemin de fichier incorrect | `FileNotFoundException` | Vérifiez le chemin ; utilisez `Paths.get(...)` pour des séparateurs indépendants du système d'exploitation. | +| Format non pris en charge | `UnsupportedOperationException` | Convertissez l'image en PNG ou JPEG avant de la charger. | +| Image volumineuse ( > 10 MP) | Out‑of‑memory errors | Réduisez l'image en utilisant `java.awt.Image` avant de la transmettre à Aspose. | + +--- + +## Extraire le texte d'une image et gérer les résultats + +Une fois le moteur OCR terminé, l'objet `OcrResult` contient la chaîne reconnue. C'est ici que nous **extract text from image** pour un traitement ultérieur — sauvegarde dans une base de données, alimentation d'un index de recherche, ou passage à un pipeline NLP en aval. + +### Gestion de plusieurs langues + +Comme nous avons configuré `engine.setLanguage(Language.Auto)`, Aspose tentera de détecter les langues à la volée. Si vous connaissez la langue à l'avance (par exemple, tous les documents sont en russe), vous pouvez remplacer `Language.Auto` par `Language.Russian` pour améliorer les performances. + +### Conseils de post‑traitement + +- **Supprimer les espaces** : `result.getText().trim()`. +- **Normaliser les fins de ligne** : `result.getText().replace("\r\n", "\n")`. +- **Supprimer les caractères non imprimables** : utilisez une expression régulière comme `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Reconnaître le texte d'une image avec des options avancées (facultatif) + +Si vous avez besoin d'un contrôle plus fin, Aspose OCR propose des propriétés supplémentaires : + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +--- + +## Récapitulatif de l'exemple complet fonctionnel + +En rassemblant tous les éléments, le programme final effectue les étapes suivantes dans l'ordre : + +1. **Perform OCR on image** – en créant un `OcrEngine`. +2. **Use Aspose license** – optionnel mais recommandé. +3. **Load image for OCR** – via `Image.load`. +4. **Set language detection** – `Language.Auto` pour **recognize text image** automatiquement. +5. **Extract text from image** – afficher le résultat, en gérant les réponses vides avec grâce. + +Vous pouvez copier le bloc de code ci‑dessus directement dans un projet Maven avec cette dépendance : + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Exécutez `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` et observez la console afficher le texte reconnu. + +--- + +## Conclusion + +Nous venons de vous montrer comment **perform OCR on image** des fichiers en utilisant Aspose OCR pour Java, depuis l'application d'une licence jusqu'à **loading the image for OCR**, **recognizing text image** et enfin **extracting text from image** pour une utilisation en aval. L'approche est simple, fonctionne avec plusieurs langues dès le départ, et peut être étendue avec des options de prétraitement avancées si nécessaire. + +Et après ? Essayez d'alimenter la sortie OCR dans un index de recherche, générez des PDF avec le texte extrait, ou expérimentez différents formats d'image. Les possibilités sont infinies, et avec l'API robuste d'Aspose vous passerez plus de temps à développer des fonctionnalités qu'à lutter contre les particularités de l'OCR. + +Des questions ou un cas particulier ? Laissez un commentaire ci‑dessous — 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 comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités supplémentaires de l'API et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Comment extraire du texte d'une image depuis une URL avec Aspose.OCR pour Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convertir une image en texte en Java avec Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extraire du texte d'une image Java avec le mode Détection de zones d'Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/german/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1c8c669f2 --- /dev/null +++ b/ocr/german/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-06-19 +description: Erstelle ein durchsuchbares PDF aus einem Bild mit Python‑OCR. Lerne, + OCR in ein PDF zu konvertieren, Text aus einem Bild zu extrahieren und OCR schnell + auf ein Bild anzuwenden. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: de +og_description: Erstelle ein durchsuchbares PDF aus einem Bild mit Python‑OCR. Dieser + Leitfaden zeigt, wie man OCR in ein PDF umwandelt, Text aus einem Bild extrahiert + und OCR auf ein Bild anwendet. +og_title: Erstelle durchsuchbare PDF in Python – Vollständige Programmieranleitung +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Durchsuchbare PDFs in Python erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-searchable-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 >}} + +# Erstelle durchsuchbare PDFs in Python – Vollständige Schritt‑für‑Schritt‑Anleitung + +Hast du schon einmal **durchsuchbare PDFs** aus einem gescannten Beleg erstellen wollen, wusstest aber nicht, wo du anfangen sollst? Du bist nicht allein – vielen Entwicklern stößt man an dieselbe Hürde, wenn sie versuchen, ein Bild von Text in ein PDF zu verwandeln, das man tatsächlich durchsuchen kann. + +In diesem Tutorial gehen wir eine praktische Lösung durch, mit der du **OCR auf Bild** ausführen, das OCR‑Ergebnis in ein **durchsuchbares PDF** umwandeln und sogar den Rohtext extrahieren kannst, falls du ihn für weitere Verarbeitung benötigst. Kein Schnickschnack, nur ein funktionierendes Beispiel, das du noch heute in dein Projekt kopieren‑und‑einfügen kannst. + +## Was du lernen wirst + +- Wie du eine leichte OCR‑Engine in Python einrichtest +- Die genauen Schritte, um **OCR in PDF zu konvertieren** und als durchsuchbares Dokument zu speichern +- Methoden, um **Text aus Bild zu extrahieren** für nachgelagerte Analysen +- Tipps zum Umgang mit häufigen Stolperfallen wie Bildorientierung und großen Dateien +- Ein vollständiges, ausführbares Skript, das du an deinen Anwendungsfall anpassen kannst + +### Voraussetzungen + +- Python 3.8+ auf deinem Rechner installiert +- Grundlegende Kenntnisse im Umgang mit pip und virtuellen Umgebungen (optional, aber empfohlen) +- Eine Bilddatei (PNG, JPEG usw.), die klaren, maschinenlesbaren Text enthält + +Wenn du das hast, legen wir los. + +## Schritt 1: Installiere die benötigte Bibliothek + +Der Code‑Ausschnitt, den du vorher gesehen hast, verwendet ein fiktives `ocr`‑Paket, aber dieselben Ideen gelten für reale Bibliotheken wie **EasyOCR**, **pytesseract** oder **pdfminer.six**. Für diese Anleitung nutzen wir **EasyOCR**, weil es reines Python ist, viele Sprachen unterstützt und eine praktische PDF‑Konvertierungsmethode über einen Hilfs‑Helper bereitstellt. + +```bash +pip install easyocr pillow +``` + +> **Profi‑Tipp:** Installiere innerhalb einer virtuellen Umgebung (`python -m venv venv && source venv/bin/activate`), um deine Abhängigkeiten sauber zu halten. + +## Schritt 2: Initialisiere die OCR‑Engine – OCR auf Bild ausführen + +Jetzt, wo die Bibliothek bereit ist, erstellen wir eine OCR‑Engine und geben ihr an, mit englischem Text zu arbeiten. Das ist der erste Ort, an dem wir **OCR auf Bild** ausführen. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Warum benötigen wir ein dediziertes Reader‑Objekt? EasyOCR lädt Sprachmodelle im Voraus, sodass die Wiederverwendung desselben `reader` für mehrere Bilder weitaus effizienter ist, als ihn jedes Mal neu zu initialisieren. + +## Schritt 3: Bild laden – Text aus Bild extrahieren + +Lassen wir das Bild in den Speicher laden. Dieser Schritt ist später der Ort, an dem wir **Text aus Bild extrahieren**, aber zunächst laden wir es nur. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Falls dein Bild verkehrt herum oder schief ist, solltest du Pillow‑Methoden wie `rotate` oder `transpose` verwenden, bevor du es an die OCR‑Engine übergibst. Ein kurzer visueller Check kann dir später Stunden an Fehlersuche ersparen. + +## Schritt 4: OCR‑Engine ausführen und Ergebnisse erfassen + +Hier kommt der Kern des Prozesses – das Bild an die OCR‑Engine senden und strukturierte Daten zurückbekommen. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Das Flag `detail=1` liefert uns Begrenzungsrahmen, die wir später benötigen, wenn wir **OCR in PDF konvertieren**. Wenn du nur an den rohen Zeichenketten interessiert bist, setze `detail=0`. + +## Schritt 5: OCR‑Ergebnis in ein durchsuchbares PDF konvertieren – OCR in PDF konvertieren + +EasyOCR bietet keinen direkten PDF‑Writer, aber wir können das PDF selbst zusammenstellen, indem wir Pillow und die Bibliothek `reportlab` verwenden. Um das Tutorial leichtgewichtig zu halten, nutzen wir `fpdf2`, das uns erlaubt, das Originalbild einzubetten und unsichtbaren Text darüber zu legen. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Was ist gerade passiert? Wir haben das gescannte Bild als sichtbare Ebene platziert und dann die erkannten Wörter darüber geschrieben, wobei wir weißen Text verwenden, der mit dem weißen Hintergrund verschmilzt. Suchwerkzeuge lesen trotzdem die verborgene Ebene, sodass das PDF **durchsuchbar** wird, ohne das visuelle Erscheinungsbild zu verändern. + +## Schritt 6: PDF‑Bytes speichern – Bild in PDF konvertieren + +Wenn du das PDF lieber im Speicher halten möchtest (z. B. zum Versand über eine API), kannst du die Bytes erfassen, anstatt direkt auf die Festplatte zu schreiben. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Diese Zeile demonstriert den klassischen **Bild‑zu‑PDF konvertieren**‑Workflow: Du startest mit einem Bild, führst OCR aus, überlagerst Text und erzeugst schließlich einen PDF‑Stream. + +## Schritt 7: Ergebnis prüfen – Schnell‑Checks + +Nachdem du das Skript ausgeführt hast, öffne `receipt_searchable.pdf` in einem beliebigen PDF‑Betrachter und teste das Suchfeld (Strg + F). Gib ein Wort ein, von dem du weißt, dass es im Beleg vorkommt – wenn es zur richtigen Stelle springt, hast du erfolgreich **durchsuchbare PDFs erstellt**! + +Falls die Suche fehlschlägt, prüfe: + +1. Die OCR‑Vertrauenswerte (`conf`‑Werte). Niedrige Werte können auf ein unscharfes Bild hinweisen. +2. Die Koordinaten der Begrenzungsrahmen – manchmal meldet EasyOCR sie in einer anderen Orientierung. +3. Ob der PDF‑Betrachter nicht im „nur‑Bild“-Modus ist (selten, aber manche Viewer haben diese Option). + +## Vollständiges funktionierendes Skript + +Alles zusammengefügt, hier die komplette, sofort ausführbare Python‑Datei: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Speichere sie als `searchable_pdf.py`, ersetze die Platzhalter `YOUR_DIRECTORY` durch echte Pfade und führe sie aus: + +```bash +python searchable_pdf.py +``` + +Du solltest eine Bestätigungsnachricht sehen und ein brandneues durchsuchbares PDF in deinem Ordner liegen haben. + +## Häufige Fragen & Sonderfälle + +**Was, wenn das Bild farbig ist?** +EasyOCR funktioniert sowohl mit Graustufen‑ als auch mit Farbbildern, aber das Konvertieren zu Graustufen (`pil_image.convert("L")`) kann die Genauigkeit bei verrauschten Scans manchmal verbessern. + +**Kann ich mehrseitige PDFs verarbeiten?** +Ja – iteriere über jedes Seitenbild, führe die OCR‑Schritte aus und füge jede Seite zum selben `FPDF`‑Objekt hinzu. Denk daran, den Cursor für jedes neue Bild zurückzusetzen (`self.add_page()`). + +**Gibt es eine Möglichkeit, die originale Textebene statt unsichtbarem weißem Text zu behalten?** +Wenn du ein echtes „Text‑unter‑Bild“‑PDF (z. B. für Barrierefreiheit) benötigst, erwäge `pdfminer` oder `pikepdf`, um eine versteckte Textebene mit korrekten PDF‑Tags einzubetten. Das ist fortgeschrittener, aber das Prinzip bleibt gleich: Hintergrundbild + überlagerter Text. + +**Was, wenn die OCR‑Vertrauenswerte niedrig sind?** +Du kannst Wörter mit geringer Vertrauenswürdigkeit herausfiltern: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Fazit – Was wir erreicht haben + +Wir begannen mit einem einfachen Bild eines Belegs, **OCR auf Bild** ausgeführt, die erkannten Zeichenketten extrahiert und schließlich **durchsuchbare PDFs erstellt**, die sich wie professionell gescannte Dokumente verhalten. Der Prozess deckte jedes sekundäre Schlüsselwort ab – **OCR in PDF konvertieren**, **Text aus Bild extrahieren**, **Bild in PDF konvertieren** und **OCR auf Bild ausführen** – sodass du jetzt ein wiederverwendbares Werkzeugset für jedes ähnliche Projekt hast. + +### Nächste Schritte + +- Experimentiere mit anderen Sprachen, indem du ihre ISO‑Codes an `easyocr.Reader(['en', 'es'])` übergibst. +- Tausche EasyOCR gegen Tesseract aus, wenn du eine vollständig offline‑Lösung brauchst; der Rest der Pipeline bleibt gleich. +- Füge eine Visualisierung der OCR‑Vertrauenswerte hinzu (Zeichne Begrenzungsrahmen ins Bild), um problematische Scans zu debuggen. + +Hast du eine eigene Variante, die du teilen möchtest? Hinterlasse einen Kommentar, forke das Repository. + +## Was solltest du 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 du weitere API‑Funktionen meistern und alternative Implementierungsansätze in deinen eigenen Projekten erkunden kannst. + +- [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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/german/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/german/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..555b8109c --- /dev/null +++ b/ocr/german/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-19 +description: Extrahiere Text aus Bildern in Python mit einer einfachen OCR‑Engine. + Lerne, wie man gescannte Bilder in Text umwandelt, Text aus Fotos erkennt und Bilddateien + in Python effizient auflistet. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: de +og_description: Extrahiere Text aus Bildern in Python mit einer leichten OCR-Engine. + Dieser Leitfaden zeigt dir, wie du gescannte Bilder in Text umwandelst, Text aus + Bildern erkennst und Bilddateien in Python auflistest – in wenigen Schritten. +og_title: Text aus Bildern in Python extrahieren – Vollständiger Batch‑OCR‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Text aus Bildern in Python extrahieren – Vollständiger Batch‑OCR‑Leitfaden +url: /de/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bildern in Python extrahieren – Vollständiger Batch‑OCR‑Leitfaden + +Haben Sie schon einmal **Text aus Bildern extrahieren** müssen, wussten aber nicht, wo Sie anfangen sollen? Sie sind nicht allein – Entwickler stehen ständig vor der Herausforderung, gescannte PDFs, fotografierte Quittungen oder Screenshots in durchsuchbaren Text zu verwandeln. In diesem Tutorial gehen wir Schritt für Schritt durch ein komplettes, sofort ausführbares Beispiel, das zeigt, wie man **gescannte Bilder in Text umwandelt**, Text aus Fotos erkennt und sogar **list image files python**‑artig auflistet. Am Ende haben Sie ein wiederverwendbares Skript, das einen ganzen Ordner in einem Durchgang verarbeitet. + +Wir behandeln alles, was Sie benötigen: erforderliche Bibliotheken, warum jeder Schritt wichtig ist, Edge‑Case‑Handling und ein wenig Fehlersuche. Keine Notwendigkeit, externe Dokumentationen zu durchforsten; der Code unten ist eigenständig, und die Erklärungen beantworten das „Wie“ *und* das „Warum“. Öffnen Sie Ihre Lieblings‑IDE und legen wir los. + +--- + +## Was Sie bauen werden + +- Einen OCR‑Engine initialisieren (wir verwenden das `ocr`‑Paket zur Veranschaulichung). +- Ein Verzeichnis scannen und **list image files python**‑artig auflisten, wobei PNG, JPG und TIFF gefiltert werden. +- Einen **Batch‑OCR**‑Durchlauf für alle gefundenen Bilder ausführen. +- Den extrahierten Text für jede Datei ausgeben, klar gekennzeichnet. + +> **Pro‑Tipp:** Wenn Sie die `ocr`‑Bibliothek nicht installiert haben, können Sie sie mit ein paar kleinen Änderungen durch `pytesseract` ersetzen – die Kernlogik bleibt gleich. + +--- + +## Voraussetzungen + +- Python 3.8+ (das Skript nutzt f‑Strings und Type Hints). +- Eine OCR‑Bibliothek, die ein `OcrEngine` mit `recognize_batch` bereitstellt. Für diesen Leitfaden gehen wir von einem fiktiven `ocr`‑Paket aus, aber das Muster funktioniert mit echten Bibliotheken. +- Ein Ordner, der die Bilddateien enthält, die Sie verarbeiten möchten (`.png`, `.jpg`, `.tif`). + +--- + +## Schritt 1 – Installieren & Importieren der benötigten Module + +Stellen Sie zunächst sicher, dass das OCR‑Paket verfügbar ist. Wenn Sie eine reale Bibliothek wie `pytesseract` verwenden, passen Sie den Import entsprechend an. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Warum das wichtig ist:** Der Import von `os` liefert plattformübergreifende Pfad‑Handling‑Funktionen, während `typing.List` IDE‑Autocomplete und Zukunftssicherheit unterstützt. + +--- + +## Schritt 2 – **Extract Text from Images**: OCR‑Engine initialisieren + +Die Erstellung der Engine ist der erste Schritt für jede OCR‑Arbeit. Wir setzen die Sprache auf Auto‑Detect, damit die Engine gemischte Sprachdokumente verarbeiten kann. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Erklärung:** Durch das Kapseln der Engine‑Erstellung in einer Funktion bleibt der Code modular. Wenn Sie später DPI oder OCR‑Modus anpassen müssen, ändern Sie nur diese eine Stelle. + +--- + +## Schritt 3 – **List Image Files Python**: Dateien aus einem Verzeichnis sammeln + +Jetzt müssen wir jedes Bild finden, das wir verarbeiten wollen. Die List‑Comprehension unten spiegelt ein übliches „list image files python“‑Muster wider. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge‑Case‑Handling:** Die Funktion ignoriert Unterordner (Sie können später Rekursion hinzufügen) und filtert versteckte Dateien automatisch heraus, weil diese typischerweise nicht mit den unterstützten Erweiterungen enden. + +--- + +## Schritt 4 – **Convert Scanned Images to Text**: Batch‑OCR ausführen + +Die meisten OCR‑Bibliotheken bieten eine Batch‑Methode, die weitaus schneller ist als die Verarbeitung einzelner Bilder. So rufen wir sie auf. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Warum Batch?** Das gleichzeitige Senden aller Bilder reduziert Overhead (z. B. wiederholtes Laden des OCR‑Modells) und führt häufig zu besserer CPU/GPU‑Auslastung. + +--- + +## Schritt 5 – **Recognize Text from Pictures**: Ergebnisse anzeigen + +Abschließend iterieren wir über die gepaarten Dateinamen und OCR‑Ergebnisse und geben für jedes Bild eine klare Überschrift aus. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tipp:** `strip()` entfernt führende bzw. nachfolgende Leerzeichen, die OCR häufig hinzufügt. + +--- + +## Vollständiges Skript – Alles zusammenführen + +Unten finden Sie das komplette, ausführbare Programm. Speichern Sie es als `batch_ocr.py` und führen Sie `python batch_ocr.py ` aus. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Erwartete Ausgabe + +Angenommen, der Ordner enthält `invoice1.png` und `receipt.jpg`, dann könnte die Ausgabe etwa so aussehen: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Jeder Block ist klar gekennzeichnet, sodass nachgelagerte Verarbeitung (z. B. Speichern in einer Datenbank) unkompliziert ist. + +--- + +## Häufige Stolperfallen behandeln + +| Problem | Warum es passiert | Schnelllösung | +|---------|-------------------|---------------| +| **Kein Text erscheint** | OCR‑Sprache nicht erkannt oder Bild hat zu geringen Kontrast. | Sprache erzwingen (`engine.language = ocr.Language.English`) oder Bilder vorverarbeiten (Kontrast erhöhen). | +| **Speicherfehler bei großen Batches** | Die Engine versucht, alle Bilder gleichzeitig zu laden. | `image_files` in Stücke aufteilen (`batch_size = 20`) und `recognize_batch` wiederholt aufrufen. | +| **Nicht unterstütztes Dateiformat** | Sie haben eine `.gif`‑ oder `.bmp`‑Datei hinzugefügt. | `supported_exts`‑Tuple erweitern oder Bilder vorher in PNG/JPG konvertieren. | +| **Unicode‑Verzerrung** | OCR gibt Bytes statt Strings zurück. | Sicherstellen, dass die OCR‑Bibliothek Unicode ausgibt (`result.text.decode('utf‑8')` falls nötig). | + +--- + +## Workflow erweitern + +Jetzt, wo Sie **Text aus Bildern extrahieren** können, denken Sie an folgende nächste Schritte: + +- **Export nach CSV** – Schreiben Sie jeden Dateinamen und den extrahierten Text in eine Tabelle für Analysen. +- **Parallelverarbeitung** – Nutzen Sie `concurrent.futures.ThreadPoolExecutor`, um mehrere Batches gleichzeitig zu bearbeiten. +- **Integration mit Cloud‑OCR** – Ersetzen Sie die lokale Engine durch Google Vision oder Azure OCR für höhere Genauigkeit bei komplexen Layouts. +- **Bildvorverarbeitung hinzufügen** – Bibliotheken wie Pillow oder OpenCV können Bilder entzerren, entrauschen oder schwellen, bevor sie OCR unterzogen werden, was die Ergebnisse verbessert. + +All diese Ideen bauen auf denselben Kernfunktionen auf, die wir erstellt haben, sodass Sie nicht von Grund auf neu beginnen müssen. + +--- + +## Fazit + +Wir haben gerade eine komplette Lösung zum **Extrahieren von Text aus Bildern** in Python durchgegangen, von **list image files python** über **recognize text from pictures** bis hin zu **convert scanned images to text** in einem sauberen Batch‑Verfahren. Das Skript ist bewusst einfach gehalten, aber flexibel genug, um als Grundlage für größere Projekte zu dienen – sei es beim Digitalisieren von Quittungen, beim Aufbau eines durchsuchbaren Archivs oder beim Betreiben einer Daten‑Extraktions‑Pipeline. + +Probieren Sie es aus, passen Sie die Vorverarbeitungsschritte an und beobachten Sie, wie Ihre OCR‑Genauigkeit steigt. Wenn Sie auf Probleme stoßen, werfen Sie einen Blick zurück in die Tabelle „Häufige Stolperfallen“; die meisten Probleme lassen sich mit einer kleinen Konfigurationsänderung beheben. + +Bereit für die nächste Herausforderung? Versuchen Sie, einen PDF‑zu‑Bild‑Konvertierungsschritt mit `pdf2image` hinzuzufügen und füttern Sie diese Bilder direkt in dieselbe Pipeline. Der Himmel ist die Grenze, wenn Sie OCR mit dem reichen Python‑Ökosystem kombinieren. + +Viel Spaß beim Coden und möge Ihr Text stets lesbar sein! + + +## Was Sie als Nächstes lernen sollten + + +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. + +- [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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/german/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..ca964d03b --- /dev/null +++ b/ocr/german/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-19 +description: Extrahiere Text aus Bildern mit Python‑OCR. Lerne automatische Spracherkennung, + Parallelverarbeitung und Stapelerkennung in einem prägnanten Tutorial. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: de +og_description: Text aus Bildern mit Python OCR extrahieren. Dieser Leitfaden zeigt + automatische Spracherkennung, Parallelverarbeitung und Batch‑Erkennung in einem + einzigen Tutorial. +og_title: Text aus Bildern in Python extrahieren – Vollständiger OCR-Leitfaden +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Text aus Bildern in Python extrahieren – Vollständiger OCR-Leitfaden +url: /de/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bildern in Python extrahieren – Vollständiger OCR-Leitfaden + +Haben Sie sich jemals gefragt, wie man **Text aus Bildern** extrahiert, ohne jedes Wort manuell einzutippen? Sie sind nicht allein. Egal, ob Sie alte Quittungen digitalisieren, ein durchsuchbares Dokumentenarchiv aufbauen oder einfach nur mit coolen KI‑Tricks experimentieren, die Fähigkeit, Text aus Bildern zu ziehen, ist heute eine unverzichtbare Fähigkeit für jeden Python‑Entwickler. + +In diesem Tutorial gehen wir ein komplettes, sofort ausführbares Beispiel durch, das **Text aus Bildern** mithilfe einer populären OCR‑Engine extrahiert. Wir behandeln automatische Spracherkennung, Parallelverarbeitung für Geschwindigkeit und Batch‑Bild­erkennung, sodass Sie Dutzende von Dateien in Sekunden verarbeiten können. Klingt nach dem, was Sie brauchen? Dann legen wir los. + +## Was Sie lernen werden + +- Wie man die OCR‑Engine mit `ocr.OcrEngine` instanziiert. +- Aktivierung der **automatischen Spracherkennung**, damit die Engine die richtige Sprache selbst auswählt. +- Konfiguration von **Parallel‑Processing‑OCR** mit einem benutzerdefinierten Thread‑Pool. +- Ausführen von **Batch‑Bild­erkennung** auf einer Dateiliste. +- Ausgabe des erkannten Textes für jedes Bild, bereit zum Speichern oder Indexieren. + +Keine externe Dokumentation nötig — alles, was Sie brauchen, finden Sie hier, und der Code funktioniert sofort mit dem `ocr`‑Paket (installieren Sie es via `pip install ocr`). + +## Voraussetzungen + +1. Python 3.8 oder neuer installiert. +2. Das `ocr`‑Paket (`pip install ocr`). +3. Ein Ordner mit PNG‑ (oder JPG‑) Bildern, die Sie verarbeiten möchten. +4. Grundlegende Kenntnisse von Python‑Funktionen und Schleifen. + +Das war’s — keine schweren Abhängigkeiten, keine GPU‑Magie, nur reines Python. + +![Beispiel für Textauszug aus Bildern](https://example.com/ocr-demo.png "Screenshot, der die Ausgabe des Textauszugs aus Bildern zeigt") + +*Alt‑Text: Demo‑Screenshot zum Extrahieren von Text aus Bildern* + +## Schritt 1 – OCR‑Engine einrichten (Primäres Schlüsselwort in Aktion) + +Zuerst: Erstellen Sie eine Instanz der OCR‑Engine. Denken Sie an `ocr.OcrEngine()` als das Gehirn hinter dem Vorgang; es weiß, wie man Zeichen, Zeilen und Absätze liest. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Warum benötigen wir eine explizite Engine? Weil die **ocr.OcrEngine‑Verwendung** Ihnen feinkörnige Kontrolle über Spracheinstellungen, Threading und mehr gibt. Sie ist der flexibelste Weg, **Text aus Bildern** zu extrahieren, verglichen mit Einzeiler‑Hilfsfunktionen. + +## Schritt 2 – Die Engine automatisch Sprachen erkennen lassen + +Die meisten OCR‑Bibliotheken verlangen, dass Sie ihnen mitteilen, welche Sprache sie suchen sollen. Das ist für ein einsprachiges Projekt in Ordnung, aber umständlich für einen gemischten Sprach‑Batch. Glücklicherweise unterstützt das `ocr`‑Paket **automatische Spracherkennung**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Durch das Setzen von `engine.language` auf `ocr.Language.Auto` wird die Engine jede Bilddatei analysieren und das passende Sprachmodell auswählen. Diese winzige Zeile spart Ihnen Stunden manueller Konfiguration, wenn Sie mit internationalen Dokumenten arbeiten. + +## Schritt 3 – Vorgänge mit Parallel‑Processing‑OCR beschleunigen + +Wenn Sie vier oder mehr CPU‑Kerne haben, warum diese nicht nutzen? Die Engine kann einen Thread‑Pool hochfahren, sodass mehrere Bilder gleichzeitig verarbeitet werden. Hier glänzt **Parallel‑Processing‑OCR**. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Passen Sie die Zahl `4` gern an Ihre Maschine an. Mehr Threads → schnellere Batch‑Durchläufe, aber denken Sie daran, dass jeder Thread Speicher verbraucht. Finden Sie also den optimalen Wert für Ihre Umgebung. + +## Schritt 4 – Sammeln Sie die zu verarbeitenden Bilder + +Jetzt benötigen wir eine Liste von Dateipfaden. Sie können diese Liste manuell erstellen, aus einer CSV einlesen oder `glob` verwenden. Zur Übersicht kodieren wir eine kurze Liste fest ein: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Ersetzen Sie `YOUR_DIRECTORY` durch den tatsächlichen Pfad auf Ihrem System. Haben Sie Dutzende von Dateien, erledigt ein kurzer Aufruf `glob.glob("*.png")` die schwere Arbeit. + +## Schritt 5 – Batch‑Bild­erkennung ausführen + +Hier ist das Herzstück des Tutorials: ein einzelner Aufruf, der jedes Bild in `files` verarbeitet und eine Liste von Ergebnis‑Objekten zurückgibt. Das ist die **Batch‑Bild­erkennung**‑Funktion, die OCR im großen Maßstab praktisch macht. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Im Hintergrund verteilt die Engine jede Datei auf die vier Worker‑Threads, die wir zuvor konfiguriert haben, und erkennt dabei automatisch die Sprache jedes Bildes. Die Methode liefert eine Liste, wobei jedes Element den erkannten Text und Metadaten enthält. + +## Schritt 6 – Den extrahierten Text ausgeben (oder speichern) + +Zum Schluss iterieren wir über die Ergebnisse und geben den Text aus. In einem echten Projekt würden Sie das wahrscheinlich in einer Datenbank oder einer CSV‑Datei speichern, aber das Ausgeben hält das Beispiel einfach. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Erwartete Ausgabe** (gekürzt zur Übersicht): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Jeder Block zeigt den Dateinamen gefolgt von der OCR‑abgeleiteten Zeichenkette. Enthält ein Bild mehrere Sprachen, erscheinen die entsprechenden Zeichen dank des vorherigen **automatischen Spracherkennungs**‑Schritts. + +## Pro‑Tipps & häufige Stolperfallen + +- **Bildqualität ist entscheidend** – unscharfe oder kontrastarme Bilder erzeugen Müll. Vorverarbeiten Sie bei Bedarf mit OpenCV (`cv2.threshold`, `cv2.resize`). +- **Thread‑Anzahl vs. I/O** – liegen Ihre Bilder auf einem langsamen Netzlaufwerk, helfen mehr Threads möglicherweise nicht. Beobachten Sie die CPU‑Auslastung mit `top` oder dem Task‑Manager. +- **Unicode‑Umgang** – `result.text` ist ein Unicode‑String. Öffnen Sie Dateien beim Schreiben mit `encoding="utf‑8"`, um `UnicodeEncodeError`s zu vermeiden. +- **Speichernutzung** – Große PDFs können viel RAM verbrauchen. Bei einem `MemoryError` reduzieren Sie die Thread‑Pool‑Größe oder verarbeiten Bilder in kleineren Stapeln. + +## Vollständiges funktionierendes Skript + +Unten finden Sie das komplette, copy‑and‑paste‑bereite Skript, das jeden besprochenen Schritt integriert. Speichern Sie es als `batch_ocr.py` und führen Sie `python batch_ocr.py` aus. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Führen Sie es so aus: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Sie sehen für jedes Bild einen schön formatierten Textblock, der beweist, dass Sie **Text aus Bildern** in großem Maßstab extrahieren können. + +## Was kommt als Nächstes? + +Jetzt, wo Sie die Grundlagen von **Text aus Bildern extrahieren** mit Python beherrschen, können Sie Folgendes erkunden: + +- **Post‑Processing**: OCR‑Ausgabe mit Regex oder Natural‑Language‑Libraries bereinigen. +- **PDF‑Konvertierung**: Die extrahierten Zeichenketten in einen PDF‑Generator einspeisen, um durchsuchbare PDFs zu erzeugen. +- **Cloud‑OCR‑Dienste**: On‑Premise‑`ocr`‑Ergebnisse mit Google Vision oder Azure OCR vergleichen, um Randfall‑Genauigkeit zu prüfen. +- **GUI‑Frontend**: Eine kleine Flask‑ oder FastAPI‑App bauen, die Nutzern das Hochladen von Bildern ermöglicht und den extrahierten Text sofort anzeigt. + +All diese Themen bauen auf dem **Python OCR‑Library**‑Fundament auf, das Sie gerade eingerichtet haben, und profitieren von denselben **Parallel‑Processing‑OCR**‑Tricks, die wir hier verwendet haben. + +--- + +*Viel Spaß beim Coden! Wenn Sie auf Probleme stoßen, hinterlassen Sie unten einen Kommentar – ich helfe gerne bei der Fehlersuche von OCR‑Eigenheiten.* + +## 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 zusätzliche API‑Funktionen meistern und alternative Implementierungsansätze in Ihren eigenen Projekten erkunden können. + +- [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/) +- [Text aus Bildern mithilfe von OCR‑Operationen in Ordnern extrahieren](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Text aus Bild – OCR‑Optimierung mit Aspose.OCR für .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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/german/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..b3c948dc6 --- /dev/null +++ b/ocr/german/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-19 +description: Wie man PDFs mit OCR in Python extrahiert – Schritt‑für‑Schritt‑Tutorial + zur Textextraktion aus PDFs, Texterkennung aus Bildern und ein OCR‑Python‑Beispiel. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: de +og_description: Wie man PDFs mit OCR in Python extrahiert. Lernen Sie, Text aus PDFs + zu extrahieren, Text aus Bildern zu erkennen, und sehen Sie ein komplettes OCR-Python-Beispiel. +og_title: Wie man PDF-Text mit OCR in Python extrahiert – Vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Wie man PDF‑Text mit OCR in Python extrahiert – Komplettanleitung +url: /de/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man PDF-Text mit OCR in Python – Vollständige Anleitung + +Haben Sie sich jemals gefragt, **wie man PDF**‑Inhalte extrahiert, wenn die Datei nur ein gescanntes Bild ist? Sie sind nicht allein. In vielen realen Projekten – denken Sie an Verträge, Rechnungen oder historische Archive – enthält das erhaltene PDF keinen auswählbaren Text. Die gute Nachricht? Ein paar Zeilen Python können diese rein bildbasierten Seiten in durchsuchbaren, editierbaren Text verwandeln. + +In diesem Tutorial führen wir Sie durch ein praktisches **OCR Python Beispiel**, das ein PDF einliest, die erste Seite als Bild rendert und dann **Text aus PDF** mithilfe einer OCR‑Engine extrahiert. Am Ende wissen Sie genau, wie man **PDF mit OCR liest**, warum jeder Schritt wichtig ist und wie Sie den Code für mehrseitige Dokumente oder verschiedene Sprachen anpassen können. + +## Was Sie lernen werden + +- Eine zuverlässige OCR‑Bibliothek für Python installieren und einrichten. +- PDF‑Seiten in für OCR geeignete Bilder konvertieren. +- **Text aus Bild erkennen** und saubere Unicode‑Zeichenketten abrufen. +- Häufige Stolperfallen (PDFs mit niedriger Auflösung, gedrehte Seiten) und wie man sie vermeidet. +- Das Skript erweitern, um mehrere Seiten oder Batch‑Verarbeitung zu unterstützen. + +**Voraussetzungen**: Python 3.8+, pip und ein grundlegendes Verständnis von virtuellen Umgebungen. Keine vorherige OCR‑Erfahrung erforderlich – einfach mitmachen. + +--- + +## ## Wie man PDF-Text mit OCR in Python extrahiert + +Dieser H2‑Header enthält unser Haupt‑Keyword genau dort, wo Suchmaschinen es lieben. Lassen Sie uns direkt in den Code eintauchen. + +### Schritt 1 – Erforderliche Pakete installieren + +Zuerst benötigen wir eine OCR‑Engine. Das untenstehende Beispiel verwendet das beliebte **ocr**‑Paket (ein dünner Wrapper um Tesseract). Wenn Sie ein anderes Backend bevorzugen, bleiben die Konzepte gleich. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro‑Tipp:** Unter Linux benötigen Sie außerdem das Tesseract‑Binary: `sudo apt-get install tesseract-ocr`. macOS‑Benutzer können es über Homebrew holen: `brew install tesseract`. + +### Schritt 2 – OCR‑Engine initialisieren und Sprache festlegen + +Jetzt starten wir die Engine und weisen sie an, nach englischen Zeichen zu suchen. Sie können `ocr.Language.English` durch jeden unterstützten Sprachcode ersetzen. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Warum das wichtig ist:** Die Angabe der Sprache verbessert die Genauigkeit erheblich, da die Engine sprachspezifische Wörterbücher und Zeichenmodelle anwenden kann. + +### Schritt 3 – PDF‑Seite als Bild laden + +OCR arbeitet mit Rasterbildern, nicht mit PDF‑Objekten. Der Helfer `ocr.Image.from_pdf` rendert die ausgewählte Seite in ein Bitmap. Passen Sie `page_number` für andere Seiten an (0‑basierte Indexierung). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Randfall:** Wenn das PDF Vektorgrafiken statt gescannter Bilder enthält, erhalten Sie möglicherweise ein scharfes Rendering. Bei niedrig aufgelösten Scans sollten Sie die DPI erhöhen: `ocr.Image.from_pdf(..., dpi=300)`. + +### Schritt 4 – Text aus dem gerenderten Bild erkennen + +Hier ist das Herzstück des **ocr python example**. Die Engine verarbeitet das Bitmap und gibt ein Objekt zurück, das die extrahierte Zeichenkette enthält. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Das Attribut `ocr_result.text` enthält die reine Textausgabe und bewahrt, wo möglich, Zeilenumbrüche. + +### Schritt 5 – Extrahierten Text ausgeben oder speichern + +Abschließend geben wir das Ergebnis aus. In einer realen Anwendung würden Sie es wahrscheinlich in eine Datei oder Datenbank schreiben. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Das Ausführen des Skripts sollte etwa Folgendes anzeigen: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Das ist ein vollständiger **extract text from pdf**‑Workflow mit OCR. + +--- + +## ## Text aus Bild erkennen – Genauigkeit optimieren + +Wenn Sie nur an **recognize text from image** interessiert sind (z. B. ein JPEG eines Belegs), können Sie den PDF‑Konvertierungsschritt überspringen: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tipps für bessere Ergebnisse:** + +- **Vorverarbeiten** des Bildes: in Graustufen konvertieren, Schwellenwert anwenden oder entzerren. Pillow macht das einfach. +- **DPI erhöhen** beim PDF‑Rendering: höhere Auflösung liefert der OCR‑Engine mehr Details. +- **OCR‑Engine‑Konfiguration aktivieren** für Seitensegmentierung (`ocr_engine.config = "--psm 6"` für einheitliche Blöcke). + +--- + +## ## PDF mit OCR lesen – Mehrere Seiten verarbeiten + +Die meisten Verträge erstrecken sich über mehrere Seiten. Das Durchlaufen jeder Seite ist unkompliziert: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Diese Funktion **reads PDF with OCR**, fügt die Ausgabe zusammen und fügt einen klaren Seitenumbruch‑Marker ein. Sie können `full_text` dann in einen Suchindex einspeisen oder als `.txt`‑Datei speichern. + +--- + +## ## Häufige Fallstricke und wie man sie behebt + +| Symptom | Wahrscheinliche Ursache | Lösung | +|---------|--------------------------|--------| +| Verzerrte Zeichen, viele `?` | Falsche Sprache oder fehlende Sprachdaten-Dateien | Installieren Sie das richtige Tesseract‑Sprachpaket (`tesseract-ocr-`) und setzen Sie `ocr_engine.language`. | +| Fehlende Zeilen oder abgeschnittene Wörter | Niedrige DPI (unter 150) | Rendern Sie das PDF mit 300 DPI oder höher (`dpi=300`). | +| Text ist gedreht oder verkehrt herum | Gescannte Seite nicht aufrecht | Verwenden Sie `ocr.Image.deskew(page_image)` vor der Erkennung. | +| Langsame Verarbeitung bei großen PDFs | Seiten werden sequenziell in einem einzelnen Thread verarbeitet | Parallelisieren Sie mit `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Das OCR‑Python‑Beispiel erweitern + +- **Export nach PDF/A**: Nach der Extraktion können Sie den Text mit `reportlab` oder `pypdf2` wieder in ein durchsuchbares PDF einbetten. +- **Spracherkennung**: Verwenden Sie `langdetect` auf dem OCR‑Output, um `ocr_engine.language` dynamisch zu wechseln. +- **Batch‑Verarbeitung**: Durchlaufen Sie ein Verzeichnis mit `os.listdir` und wenden Sie `extract_all_pages` auf jede Datei an. + +--- + +## ## Erwartete Ausgabe und Verifizierung + +Wenn Sie das Skript gegen einen klaren Scan in englischer Sprache ausführen, sollten Sie einen sauberen Textblock mit korrekter Interpunktion sehen. Überprüfen Sie dies durch: + +1. Einige Zeilen mit dem Original‑Scan vergleichen. +2. Eine einfache Wortzählung ausführen (`len(ocr_result.text.split())`), um sicherzustellen, dass die Ausgabe nicht leer ist. +3. Optional das Ergebnis in einen Rechtschreibprüfer wie `pyspellchecker` einspeisen, um OCR‑Fehler zu erkennen. + +--- + +## Fazit + +Wir haben **wie man PDF**‑Inhalte extrahiert, wenn herkömmliches Parsen scheitert, ein vollständiges **ocr python example** demonstriert und erklärt, wie man **recognize text from image** und **read PDF with OCR** sowohl für einseitige als auch mehrseitige Szenarien durchführt. Mit den obigen Code‑Snippets können Sie nun jedes gescannte PDF in durchsuchbaren, editierbaren Text verwandeln – kein manuelles Abtippen mehr. + +Nächste Schritte? Versuchen Sie, die Sprache zu Spanisch zu wechseln (`ocr.Language.Spanish`) oder experimentieren Sie mit Bild‑Vorverarbeitungstechniken, um die Genauigkeit zu erhöhen. Wenn Sie ein Dokumenten‑Management‑System bauen, denken Sie darüber nach, den extrahierten Text mit Elasticsearch für blitzschnelle Suche zu indexieren. + +Haben Sie Fragen oder stoßen Sie auf ein eigenartiges PDF? Hinterlassen Sie einen Kommentar und happy coding! + +![Wie man PDF mit OCR in Python extrahiert](image.png "Wie man PDF mit OCR in Python extrahiert") + +## Was Sie als Nächstes lernen sollten? + +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 mit Aspose OCR extrahieren – Schritt‑für‑Schritt‑Anleitung](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [PDF‑Text erkennen – OCR‑Operationen mit Aspose.OCR für Java](/ocr/english/java/ocr-operations/) +- [Bildtext in C# mit Sprachauswahl mithilfe von Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/german/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..8b501e765 --- /dev/null +++ b/ocr/german/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-19 +description: Erfahren Sie, wie Sie OCR in Java mit Aspose verwenden. Dieser Schritt‑für‑Schritt‑Leitfaden + behandelt das automatische Entzerren von Bildern, die automatische Spracherkennung + und das einfache Extrahieren von Text aus Bildern. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: de +og_description: 'Wie man OCR in Java mit Aspose verwendet: ein vollständiger Leitfaden, + der automatische Bildentzerrung, automatische Spracherkennung und das Extrahieren + von Text aus Bildern abdeckt.' +og_title: Wie man OCR in Java mit Aspose verwendet – Vollständige Anleitung +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Wie man OCR in Java mit Aspose verwendet – Komplettanleitung +url: /de/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man OCR in Java mit Aspose verwendet – Vollständiger Leitfaden + +Haben Sie sich schon einmal gefragt, **wie man OCR** in einem Java‑Projekt nutzt, ohne sich über die Konfiguration die Haare auszureißen? Sie sind nicht allein. Viele Entwickler stoßen an ihre Grenzen, wenn sie **Text aus Bild**‑Daten schnell extrahieren müssen, besonders wenn die Quell‑Scans schief sind oder in einer unbekannten Sprache vorliegen. + +In diesem Tutorial gehen wir Schritt für Schritt durch ein praktisches Beispiel, das genau zeigt, wie man OCR mit Aspose verwendet, inklusive **auto deskew images**, **auto language detection** und der kompletten **ocr image preprocessing**‑Pipeline. Am Ende haben Sie einen sofort ausführbaren Code‑Snippet, der den erkannten Text in der Konsole ausgibt, und Sie verstehen, warum jede Einstellung wichtig ist. + +> **Was Sie erhalten:** ein vollständiges, ausführbares Java‑Programm, Erklärungen zu jeder Zeile, Tipps zum Umgang mit Randfällen und Ideen, wie Sie die Lösung auf Batch‑Verarbeitung oder PDFs ausweiten können. + +--- + +## Voraussetzungen + +- Java 17 (oder ein aktuelles JDK) installiert und konfiguriert. +- Maven oder Gradle für das Dependency‑Management (wir zeigen die Maven‑Koordinaten). +- Eine Aspose OCR for Java Lizenzdatei (`Aspose.OCR.Java.lic`). Wenn Sie nur testen, können Sie den Lizenzschritt überspringen, aber die kostenlose Testversion fügt ein Wasserzeichen hinzu. +- Ein Beispielbild (`your_image.png`), das an einem für den Code zugänglichen Ort liegt. + +> **Pro‑Tipp:** Legen Sie Ihre Bilder in einem eigenen `resources`‑Ordner ab und laden Sie sie über den Klassenpfad; das vermeidet Pfad‑Probleme auf verschiedenen Betriebssystemen. + +--- + +## Schritt 1: Projekt einrichten und Aspose OCR‑Abhängigkeit hinzufügen + +Erstellen Sie ein neues Maven‑Projekt (oder verwenden Sie ein bestehendes) und fügen Sie das Folgende zu Ihrer `pom.xml` hinzu: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Führen Sie `mvn clean install` aus, um die Bibliothek zu holen. Wenn Sie Gradle bevorzugen, lautet das Äquivalent: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Jetzt stehen Ihnen die **ocr image preprocessing**‑Klassen auf dem Klassenpfad zur Verfügung. + +--- + +## Schritt 2: Aspose OCR‑Lizenz anwenden (optional, aber empfohlen) + +Wenn Sie eine Lizenz besitzen, wenden Sie sie gleich zu Beginn Ihrer `main`‑Methode an. Das Überspringen dieses Schrittes funktioniert, aber die kostenlose Version versieht die Ausgabe mit einem „Demo“‑Wasserzeichen. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Warum das wichtig ist:** Die lizenzierte Version entfernt Nutzungslimits und das Wasserzeichen, sodass Sie saubere, produktionsreife Ergebnisse erhalten. + +--- + +## Schritt 3: OCR‑Engine‑Instanz erstellen + +Die Engine ist das Herzstück des Prozesses. Durch das Instanziieren erhalten Sie Zugriff auf alle **ocr image preprocessing**‑Optionen. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +An diesem Punkt ist die Engine bereit, verwendet jedoch die Standardeinstellungen, die für gescannte Dokumente nicht optimal sein könnten. Lassen Sie uns ein paar Anpassungen vornehmen. + +--- + +## Schritt 4: Auto Deskew Images aktivieren für sauberere Scans + +Schief gescannte Bilder sind ein häufiges Problem. Aspose bietet die **auto deskew images**‑Funktion, die das Bild automatisch vor der Erkennung begradigt. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Wie es funktioniert:** Der Algorithmus analysiert die Winkel der Textgrundlinie und dreht das Bild in die wahrscheinlichste aufrechte Ausrichtung. Das verbessert die Genauigkeit bei Fotos, die mit dem Handy aufgenommen wurden, erheblich. + +--- + +## Schritt 5: Auto Language Detection einschalten + +Wenn Sie die Sprache des Quellbildes nicht kennen, lassen Sie die Engine sie ermitteln. Das ist die **auto language detection**‑Einstellung. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Wenn Sie das aktivieren, scannt Aspose die Glyphen und wählt das wahrscheinlichste Sprachmodell aus, das von Haus aus über 30 Sprachen unterstützt. + +--- + +## Schritt 6: Bild laden, das Sie erkennen möchten + +Sie können ein Bild von der Festplatte, einer URL oder sogar einem Byte‑Array laden. Der Einfachheit halber lesen wir aus einer lokalen Datei. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tipp:** Wenn Sie mit großen Bildern arbeiten, sollten Sie sie zuerst mit `engine.getImagePreprocessing().setResizeFactor(0.5)` verkleinern, um die Verarbeitung zu beschleunigen, ohne zu viel Detail zu verlieren. + +--- + +## Schritt 7: OCR‑Erkennung durchführen und Text extrahieren + +Jetzt wirkt die Engine ihre Magie. Die Methode `recognize` liefert ein `OcrResult`‑Objekt, das den erkannten Text, Vertrauenswerte und mehr enthält. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Die Konsole zeigt den aus dem Bild extrahierten Klartext – das ist das Kern‑Ergebnis **extract text image**, das wir erreichen wollten. + +--- + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie die komplette Java‑Klasse, die alles zusammenführt. Kopieren Sie sie nach `src/main/java/com/example/OcrDemo.java` und führen Sie sie aus. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Erwartete Ausgabe + +Enthält das Bild die Phrase „Hello World“ in einem sauberen Scan, sehen Sie: + +``` +=== Recognized Text === +Hello World +``` + +Bei komplexeren Dokumenten (z. B. mehrsprachige Belege) enthält die Ausgabe Zeilenumbrüche und den erkannten Sprachcode. + +--- + +## Häufige Stolperfallen & Pro‑Tipps + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| **Garbage‑Zeichen** | Bild ist zu dunkel oder verrauscht. | `engine.getImagePreprocessing().setBinarization(true)` aktivieren oder den Kontrast manuell anpassen. | +| **Falsche Sprache** | Auto‑Detection schlägt bei gemischten Sprachseiten fehl. | `engine.setLanguage(Language.English)` (oder das passende Enum) setzen, um eine bestimmte Sprache zu erzwingen. | +| **Langsame Verarbeitung** | Sehr hochauflösende Bilder. | Mit `engine.getImagePreprocessing().setResizeFactor(0.5)` herunterskalieren. | +| **Out‑of‑Memory‑Fehler** | Große Bild‑Batches gleichzeitig geladen. | Bilder sequenziell verarbeiten und nach jedem Durchlauf `engine.dispose()` aufrufen. | + +> **Denken Sie daran:** Die OCR‑Engine ist für reine Lese‑Operationen thread‑sicher, aber das Erzeugen einer neuen Instanz pro Thread vermeidet versteckte Zustands‑Bugs. + +--- + +## Lösung erweitern + +Jetzt, wo Sie **wie man OCR** mit Aspose verwendet, könnten Sie: + +1. **PDFs verarbeiten** – Jede PDF‑Seite in ein Bild (`PdfConverter`) umwandeln und dann dieselbe Pipeline nutzen. +2. **Ordner batch‑verarbeiten** – Durch Dateien in einem Verzeichnis iterieren, dieselben Schritte anwenden und Ergebnisse in eine CSV schreiben. +3. **In einen Web‑Service integrieren** – Die OCR‑Logik über einen Spring Boot `@RestController` bereitstellen, der Multipart‑Uploads akzeptiert. + +All diese Szenarien nutzen dieselbe **ocr image preprocessing**‑Konfiguration, die wir hier aufgebaut haben. + +--- + +## Fazit + +Wir haben **wie man OCR** in Java mit Aspose von Anfang bis Ende behandelt: Lizenz anwenden, Engine erstellen, **auto deskew images** aktivieren, **auto language detection** einschalten, ein Bild laden und schließlich **extract text image** mit einem einzigen `System.out.println` ausgeben. Der Code ist komplett eigenständig, läuft auf jedem aktuellen JDK und demonstriert bewährte Praktiken für Genauigkeit und Performance. + +Probieren Sie es mit Ihren eigenen Bildern aus – vielleicht ein gescannter Vertrag oder ein Screenshot eines Belegs. Passen Sie die Pre‑Processing‑Flags an, experimentieren Sie mit verschiedenen Sprachen, und Sie werden schnell sehen, warum Asposes OCR‑Bibliothek eine solide Wahl für produktionsreife Textextraktion ist. + +Fragen oder Ergebnisse zu teilen? Hinterlassen Sie einen Kommentar unten oder kontaktieren Sie mich auf GitHub. Viel Spaß beim Coden! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## 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 Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/german/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..43aee5d5e --- /dev/null +++ b/ocr/german/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Verbessern Sie die OCR‑Genauigkeit in Python mit Aspose OCR. Erfahren + Sie, wie Sie die OCR‑Sprache festlegen, ein Bild für die OCR laden und Text aus + dem Bild mit einem benutzerdefinierten Wörterbuch extrahieren. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: de +og_description: Verbessern Sie die OCR-Genauigkeit in Python, indem Sie die OCR-Sprache + festlegen, ein Bild für die OCR laden und Text aus dem Bild mit einem benutzerdefinierten + Wörterbuch extrahieren. +og_title: Verbessern Sie die OCR‑Genauigkeit in Python – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Verbessern Sie die OCR‑Genauigkeit in Python – Komplettanleitung +url: /de/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR-Genauigkeit in Python verbessern – Komplettanleitung + +Haben Sie sich jemals gefragt, wie Sie die **OCR-Genauigkeit** verbessern können, wenn der gescannte Text seltsame Symbole, Produktcodes oder Markennamen enthält? Sie sind nicht allein. In vielen Projekten liefert die Standard‑Engine nur Kauderwelsch, was ein echter Produktivitätskiller ist. + +In diesem Tutorial führen wir Sie durch ein praktisches End‑to‑End‑Beispiel, das zeigt, wie Sie **OCR‑Sprache festlegen**, **Bild für OCR laden**, **OCR auf Bild ausführen** und schließlich **Text aus Bild extrahieren** mit einem benutzerdefinierten Wörterbuch, das die Erkennungsraten steigert. Am Ende haben Sie ein einsatzbereites Skript, das Sie in jede Python‑Codebasis einbinden können. + +## Was Sie am Ende haben werden + +- Ein voll funktionsfähiges Python‑Skript, das Aspose OCR verwendet, um eine PNG‑Datei zu lesen. +- Die Möglichkeit, die **OCR‑Genauigkeit** zu verbessern, indem Sie Sprache und eine benutzerdefinierte Wortliste konfigurieren. +- Klare Erklärungen, warum jede Einstellung wichtig ist, plus Tipps zum Umgang mit Sonderfällen wie nicht‑lateinischen Zeichen. +- Eine schnelle Checkliste zur Fehlersuche bei gängigen OCR‑Problemen. + +### Voraussetzungen + +- Python 3.8 oder neuer auf Ihrem Rechner installiert. +- `aspose-ocr`‑Paket (Installation über `pip install aspose-ocr`). +- Ein Beispielbild (`technical_doc.png`), das den zu lesenden Text enthält. +- Grundlegende Kenntnisse in Python – nichts Besonderes erforderlich. + +> **Pro‑Tipp:** Wenn Sie in einer virtuellen Umgebung arbeiten, aktivieren Sie diese vor der Installation des Pakets. So bleiben Ihre Abhängigkeiten sauber und Versionskonflikte werden vermieden. + +--- + +## Schritt 1: Aspose OCR installieren und importieren + +Zuerst einmal – wir holen die Bibliothek in unsere Umgebung und importieren die benötigten Komponenten. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Der Namespace `aspose.ocr` gibt Ihnen Zugriff auf die Klasse `OcrEngine`, das Herzstück des OCR‑Prozesses. Durch das Importieren hier bleibt der Rest des Skripts übersichtlich und lesbar. + +--- + +## Schritt 2: Einen OCR‑Engine erstellen und **OCR‑Sprache festlegen** + +Warum ist die Sprache wichtig? OCR‑Engines nutzen sprachspezifische Modelle, um Zeichenformen und Wortmuster zu erkennen. Wenn Sie der Engine mitteilen, dass Sie englischen Text scannen, ignoriert sie kyrillische Glyphen und konzentriert sich auf das lateinische Alphabet, was die **OCR‑Genauigkeit** deutlich **verbessert**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Hinweis:** Aspose OCR unterstützt über 50 Sprachen. Ersetzen Sie `ocr.Language.English` durch `ocr.Language.Spanish`, `ocr.Language.French` usw., falls Ihr Dokument nicht Englisch ist. + +--- + +## Schritt 3: Ein **benutzerdefiniertes Wörterbuch** definieren, um die Genauigkeit zu steigern + +Stellen Sie sich vor, Sie scannen Rechnungen, die das Wort „AsposeOCR“ oder Produktcodes wie „SKU12345“ enthalten. Die Engine kennt diese Begriffe nicht und rät falsch. Durch das Bereitstellen einer eigenen Wortliste sagen Sie der Engine: *„Hey, diese Zeichenketten sind korrekt – versucht nicht, sie zu korrigieren.“* Das ist ein schneller Gewinn für **die Verbesserung der OCR‑Genauigkeit**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Sie können diese Liste aus einer Datei oder einer Datenbank laden, wenn Sie Hunderte von Einträgen haben – für die Einfachheit halten Sie sie einfach in einer Python‑Liste. + +--- + +## Schritt 4: **Bild für OCR laden** + +Jetzt benötigen wir ein Bild. Die Methode `Image.load` akzeptiert einen Pfad zu jedem unterstützten Rasterformat (PNG, JPEG, BMP usw.). Wenn die Datei nicht gefunden wird, wirft die Engine eine Ausnahme, daher prüfen wir das vorher. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Warum dieser Schritt wichtig ist:** Das korrekte Laden des Bildes stellt sicher, dass die Engine mit den genauen Pixeldaten arbeitet, die Sie analysieren möchten. Beschädigte Dateien oder falsche Pfade sind häufige Frustrationsquellen. + +--- + +## Schritt 5: **OCR auf Bild ausführen** und Ergebnisse extrahieren + +Mit der konfigurierten Engine und dem geladenen Bild erfolgt die eigentliche Erkennung mit einem einzigen Methodenaufruf. Das Ergebnisobjekt enthält den Rohtext, Konfidenzwerte und sogar Layout‑Informationen, falls Sie diese später benötigen. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Wenn Sie **Text aus Bild** zeilenweise extrahieren möchten, können Sie an Zeilenumbrüche splitten: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Schritt 6: Ausgabe überprüfen – Verbessert es wirklich die **OCR‑Genauigkeit**? + +Lassen Sie uns das Ergebnis ausgeben und prüfen, ob unser benutzerdefiniertes Wörterbuch einen Unterschied macht. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Typische Ausgabe für das Beispielbild könnte so aussehen: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Beachten Sie, wie der Markenname, das griechische Zeichen und der Produktcode exakt so erscheinen, wie wir sie definiert haben. Ohne das benutzerdefinierte Wörterbuch hätte die Engine versucht, sie zu „korrigieren“, was häufig zu „Aspose OCR“ oder „SKU 1234“ führte. + +--- + +## Häufige Fallstricke & wie man sie behebt + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| **Fehlerhafte Zeichen** | Falsche Sprache eingestellt oder Bild mit niedriger Auflösung | Stellen Sie sicher, dass `engine.language` der Quellsprache entspricht und verwenden Sie einen Scan mit hoher DPI (300 dpi oder höher). | +| **Benutzerdefinierte Wörter werden ignoriert** | Wörterbuch nicht zugewiesen oder Tippfehler im Eigenschaftsnamen | Überprüfen Sie `engine.text_processing.custom_dictionary = …`. | +| **Datei nicht gefunden** | Falscher Pfad oder fehlende Dateiberechtigungen | Verwenden Sie `os.path.abspath()`, um den absoluten Pfad zu prüfen; führen Sie das Skript mit den richtigen Berechtigungen aus. | +| **Langsame Verarbeitung** | Große Bilder oder viele Seiten | Bild vorverarbeiten (zuschneiden, skalieren) oder `engine.recognize(image, max_threads=4)` zur Parallelisierung nutzen. | + +--- + +## Weiterführend: Erweiterte Anpassungen zur **Verbesserung der OCR‑Genauigkeit** + +1. **Vorverarbeitung** – Vor dem Übergeben an Aspose OCR Kontrast erhöhen oder binarisieren mit Pillow. +2. **Mehrere Sprachen** – `engine.language = ocr.Language.English | ocr.Language.French` setzen, um zweisprachige Erkennung zu aktivieren. +3. **Region‑basierte OCR** – Wenn Sie nur einen bestimmten Bereich (z. B. eine Tabelle) benötigen, das Bild zuerst zuschneiden, um Rauschen zu reduzieren. +4. **Konfidenz‑Filterung** – `result.confidence` liefert einen Wert pro Zeichen; Sie können Ergebnisse mit niedriger Konfidenz programmgesteuert verwerfen. + +--- + +## Vollständiges funktionierendes Skript + +Unten finden Sie das komplette, sofort einsetzbare Skript, das jeden besprochenen Schritt enthält. Speichern Sie es als `improve_ocr_accuracy.py` und führen Sie es über die Kommandozeile aus. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Ausführen: + +```bash +python improve_ocr_accuracy.py +``` + +Sie sollten die zuvor gezeigte, sauber formatierte Ausgabe sehen. + +--- + +## Fazit + +Wir haben eine unkomplizierte Methode vorgestellt, um die **OCR‑Genauigkeit** in Python zu **verbessern** durch: + +1. **Festlegen der OCR‑Sprache**, passend zu Ihrem Dokument. +2. **Korrektes Laden des Bildes**, sodass die Engine die richtigen Pixel sieht. +3. **Ausführen von OCR auf dem Bild** mit einem einzigen Methodenaufruf. +4. **Extrahieren des Textes aus dem Bild** und Überprüfen des Ergebnisses. +5. **Hinzufügen eines benutzerdefinierten Wörterbuchs**, um domänenspezifische Begriffe zu sichern. + +Damit ist der gesamte Workflow – vom Rohbild zum bereinigten, durchsuchbaren Text – in einem übersichtlichen, wiederverwendbaren Skript zusammengefasst. + +Wenn Sie bereit für die nächste Herausforderung sind, experimentieren Sie mit Bildvorverarbeitung (Kontrast, Deskew) oder wechseln Sie zu einer mehrsprachigen Einrichtung mittels `ocr.Language.English | ocr.Language.German`. Die gleichen Prinzipien gelten und Sie werden die **OCR‑Genauigkeit** über ein breiteres Dokumentenset hinweg weiter **verbessern**. + +Haben Sie Fragen oder einen ungewöhnlichen Sonderfall? Hinterlassen Sie einen Kommentar unten, und happy coding! + +![improve OCR accuracy + + +## 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. + +- [Text aus Bild extrahieren – OCR-Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Textbild erkennen mit Aspose OCR für mehrere Sprachen](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Wie man den Schwellenwert in der OCR-Bilderkennung festlegt](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/german/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..7a631bc06 --- /dev/null +++ b/ocr/german/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Führen Sie OCR auf einem Bild mit der OCR‑Bibliothek von Python durch. + Lernen Sie, wie Sie Text aus einem Bild erkennen, Text aus JPEGs erkennen und Text + aus gescannten Bildern effizient extrahieren. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: de +og_description: Führen Sie OCR auf Bildern mit Python durch und extrahieren Sie Text + aus gescannten Dateien. Dieser Leitfaden führt Sie Schritt für Schritt durch das + Laden von Bildern, das Entzerren und die Texterkennung. +og_title: OCR auf Bild in Python durchführen – Vollständiger Leitfaden zur Textextraktion +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: OCR auf Bild in Python durchführen – Vollständiger Leitfaden zur Textextraktion +url: /de/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR auf Bild in Python durchführen – Vollständiger Leitfaden zur Textextraktion + +Haben Sie jemals **OCR auf Bild**‑Dateien durchführen müssen, sind aber an einer Wand gestoßen, weil der Code kryptisch aussah? Sie sind nicht allein. Egal, ob Sie einen Haufen gescannter Quittungen in durchsuchbare PDFs verwandeln oder Bildunterschriften aus einem JPEG für ein Data‑Science‑Projekt extrahieren – die Fähigkeit, Text aus JPEGs und anderen Formaten zu erkennen, ist heute eine unverzichtbare Fähigkeit für jeden Entwickler. + +In diesem Tutorial führen wir Sie durch ein komplettes, ausführbares Beispiel, das zeigt, wie Sie **Text aus Bild**‑Dateien **erkennen**, **Text aus gescanntem Bild**‑Dokumenten **extrahieren** und sogar **Bild für OCR laden** – und das in nur wenigen Zeilen Code. Am Ende haben Sie ein solides, produktionsreifes Snippet, das Sie in Ihre eigenen Projekte einbinden können – ohne fehlende Importe, ohne vage „siehe Dokumentation“-Abkürzungen. + +## Was Sie erstellen werden + +- Ein kleines Python‑Skript, das eine OCR‑Engine erstellt, Auto‑Deskew aktiviert, ein JPEG (oder ein beliebiges unterstütztes Format) lädt und den erkannten Text ausgibt. +- Erklärungen, **warum** jede Einstellung wichtig ist, nicht nur **wie** man sie eingibt. +- Tipps zum Umgang mit mehrseitigen PDFs, nicht‑englischen Sprachen und häufigen Stolperfallen wie unscharfen Scans. + +### Voraussetzungen + +- Python 3.8+ installiert (das Beispiel verwendet das `ocr`‑Paket, das über `pip install ocr-lib` verfügbar ist – ersetzen Sie es durch den tatsächlichen Bibliotheksnamen). +- Grundlegende Kenntnisse von Python‑Funktionen und virtuellen Umgebungen. +- Eine Bilddatei (JPEG, PNG, TIFF), die Sie verarbeiten möchten; wir verwenden `skewed_page.jpg` als Platzhalter. + +> **Pro‑Tipp:** Wenn Sie Windows verwenden, führen Sie Ihr Terminal als Administrator aus, wenn Sie die OCR‑Bibliothek installieren, um Berechtigungsprobleme zu vermeiden. + +--- + +## OCR auf Bild – Einrichtung und Konfiguration + +Das Erste, was Sie benötigen, ist eine saubere OCR‑Engine‑Instanz. Denken Sie daran wie an das Gehirn hinter dem Vorgang; ohne richtige Konfiguration liefert selbst das schärfste Bild Kauderwelsch. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Warum das wichtig ist:** +Durch das Setzen von `engine.language` wird der Zeichensatz, den die OCR‑Engine erwartet, eingegrenzt, was die Genauigkeit dramatisch erhöht. Wenn Sie das überspringen, versucht die Engine zu raten und missinterpretiert häufig einfache Wörter. + +--- + +## Automatisches Deskew aktivieren – Schiefe Scans korrigieren + +Gescannte Seiten sind selten perfekt flach. Eine leichte Neigung kann die Zeichensegmentierung durcheinanderbringen und aus „Hello“ ein „H3llo“ machen. Das Flag `auto_deskew` übernimmt die schwere Arbeit für Sie. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Randfall:** Wenn Sie wissen, dass Ihre Bilder bereits gerade sind, kann das Deaktivieren von Deskew ein paar Millisekunden Verarbeitungszeit sparen – nützlich, wenn Sie Tausende von Seiten in einem Batch‑Job verarbeiten. + +--- + +## Bild für OCR laden – Unterstützung für JPEG, PNG, TIFF + +Jetzt **laden wir das Bild für OCR**. Die Methode `ocr.Image.load` ist flexibel; sie akzeptiert einen Pfad zu jedem unterstützten Rasterformat. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Warum dieser Schritt entscheidend ist:** Die Bibliothek liest die Datei in ein internes Bitmap ein und führt ggf. notwendige Farbraumkonvertierungen durch. Wird dieser Schritt übersprungen und ein roher Byte‑Stream übergeben, führt das zu einem `FileNotFoundError` oder, schlimmer noch, zu stillen leeren Ergebnissen. + +Wenn Sie speziell **Text aus JPEG**‑Dateien erkennen möchten, stellen Sie sicher, dass die Dateierweiterung `.jpeg` oder `.jpg` lautet. Der gleiche Aufruf funktioniert für PNG (`.png`) oder TIFF (`.tif`) ohne Änderungen. + +--- + +## OCR auf Bild ausführen – Engine starten + +Mit der vorbereiteten Engine und dem Bild im Speicher ist es Zeit, **OCR auf Bild**‑Daten **auszuführen**. Diese eine Zeile erledigt das Schwergewicht: Vorverarbeitung, Segmentierung, Klassifizierung und Textzusammenstellung. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Was im Hintergrund passiert:** +- Die Engine wendet die Deskew‑Transformation an (falls aktiviert). +- Sie führt ein neuronales Netzwerk oder das Tesseract‑Backend aus, um Zeichen zu identifizieren. +- Abschließend fügt sie Zeichen zu Wörtern und Zeilen zusammen und gibt ein reichhaltiges `result`‑Objekt zurück. + +--- + +## Text aus gescanntem Bild extrahieren – Ergebnisse ausgeben + +Der letzte Schritt besteht darin, **Text aus gescanntem Bild** zu **extrahieren** und anzuzeigen. Das Attribut `result.text` enthält die reine Textdarstellung. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Typische Ausgabe sieht etwa so aus: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Findet die OCR‑Engine keine Zeichen, ist `result.text` ein leerer String. In diesem Fall prüfen Sie die Bildqualität erneut oder passen ggf. die Eigenschaft `engine.confidence_threshold` an (sofern Ihre Bibliothek das unterstützt). + +--- + +## Umgang mit gängigen Variationen + +### Text aus JPEG vs. PNG erkennen + +Beide Formate werden unterstützt, aber JPEG‑Kompression kann Artefakte einführen, die die Engine verwirren. Wenn Sie häufig Fehlinterpretationen bemerken, konvertieren Sie das JPEG zunächst zu PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Text aus Bild mit mehreren Sprachen erkennen + +Wenn Ihr Dokument Englisch und Spanisch mischt, aktivieren Sie einen mehrsprachigen Modus: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Die Engine berücksichtigt dann beide Alphabete bei der Erkennung. + +### Text aus gescannten PDFs extrahieren + +Für PDFs müssen Sie jede Seite zuerst in ein Bild rasterisieren. Bibliotheken wie `pdf2image` machen das unkompliziert: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das komplette Skript, das Sie in eine Datei namens `ocr_demo.py` kopieren können. Es enthält Fehlerbehandlung und einen kleinen Helfer, um die Ausführungszeit zu messen. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Erwartete Ausgabe** (bei einem klaren Scan): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Häufig gestellte Fragen + +**F: Kann ich das auf einem headless Server ausführen?** +A: Absolut. Die Bibliothek funktioniert ohne GUI; stellen Sie nur sicher, dass die notwendigen nativen Binaries (z. B. Tesseract) auf dem Server installiert sind. + +**F: Was, wenn das Bild unscharf ist?** +A: Erwägen Sie, vor `engine.recognize` einen Schärfungsfilter hinzuzufügen. Viele OCR‑Bibliotheken bieten `image_preprocessing.sharpen = True` oder Sie nutzen OpenCVs `cv2.GaussianBlur` in umgekehrter Richtung. + +**F: Unterstützt das Skript die Stapelverarbeitung?** +A: Ja. Wickeln Sie `perform_ocr` in eine Schleife über eine Liste von Dateipfaden ein, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/german/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..897dce965 --- /dev/null +++ b/ocr/german/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Führen Sie OCR auf einem Bild mit Aspose OCR Java durch. Erfahren Sie, + wie Sie ein Bild für OCR laden, die Aspose‑Lizenz verwenden und Text aus dem Bild + in wenigen Minuten extrahieren. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: de +og_description: Führen Sie OCR auf einem Bild mit Aspose OCR Java durch. Dieser Leitfaden + zeigt, wie man die Aspose‑Lizenz verwendet, ein Bild für OCR lädt und effizient + Text aus dem Bild extrahiert. +og_title: OCR auf Bild mit Aspose OCR Java durchführen – Vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: OCR auf Bild mit Aspose OCR Java durchführen – vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR auf Bild mit Aspose OCR Java – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie jemals **OCR auf Bild**‑Dateien durchführen müssen, waren sich aber nicht sicher, welche Bibliothek zuverlässige Ergebnisse ohne umfangreiche Konfiguration liefert? Sie sind nicht allein. In vielen realen Projekten – denken Sie an das Scannen von Pässen, die Digitalisierung von Rechnungen oder das Extrahieren von Text aus Screenshots – ist die Fähigkeit, Text in Bilddaten schnell zu erkennen, ein echter Wendepunkt. + +In diesem Tutorial führen wir Sie durch ein praktisches Beispiel, das genau zeigt, wie man **OCR auf Bild** mit Aspose OCR für Java durchführt. Wir behandeln alles, vom Anwenden Ihrer Aspose‑Lizenz über das Laden des Bildes, das Ausführen der Engine bis hin zum **Extrahieren von Text aus Bild**, damit Sie ihn weiterverwenden können. Kein Schnickschnack, nur eine funktionierende Lösung, die Sie kopieren‑und‑einfügen können. + +## Was Sie am Ende wissen werden + +- Ein klares Bild davon, wie man **Aspose‑Lizenz verwendet** in einem Java‑Projekt. +- Der genaue Code, der benötigt wird, um **Bild für OCR zu laden** und die Engine die Sprachen automatisch erkennen zu lassen. +- Schritt‑für‑Schritt‑Anleitungen, um **Text im Bild zu erkennen** und **Text aus Bild zu extrahieren** sicher. +- Tipps zum Umgang mit häufigen Fallstricken (leere Ergebnisse, nicht unterstützte Formate und Speicherprobleme). + +> **Voraussetzungen** – Java 8 oder neuer, Maven oder Gradle für das Abhängigkeitsmanagement und eine Aspose OCR für Java‑Lizenzdatei (oder Sie können im Evaluierungsmodus arbeiten). + +--- + +## Wie man OCR auf Bild mit Aspose OCR Java durchführt + +Unten finden Sie das vollständige, sofort ausführbare Java‑Programm, das den gesamten Ablauf demonstriert. Speichern Sie es als `AsposeOcrDemo.java` und führen Sie es aus Ihrer IDE oder über die Befehlszeile aus. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Erwartete Konsolenausgabe + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Wenn Sie das Programm ohne Lizenzdatei ausführen, wird die erste Zeile lediglich anzeigen, dass Sie im Evaluierungsmodus sind, aber die OCR funktioniert weiterhin. + +--- + +## Einrichtung und Verwendung der Aspose‑Lizenz + +### Warum eine Lizenz wichtig ist + +Die Bibliothek im Evaluierungsmodus zu betreiben ist für schnelle Tests in Ordnung, aber sie fügt dem Ergebnis ein Wasserzeichen hinzu und begrenzt die Anzahl der Seiten, die Sie pro Durchlauf verarbeiten können. Das Anwenden des **use aspose license**‑Schritts entfernt diese Einschränkungen und signalisiert Aspose, dass Sie ein zahlender Kunde sind. + +### Wie Sie sie erhalten und anwenden + +1. Kaufen Sie eine Lizenz im Aspose‑Store. +2. Laden Sie die Datei `Aspose.OCR.Java.lic` herunter. +3. Platzieren Sie sie an einem Ort, den Ihre Anwendung lesen kann – typischerweise im Ordner `src/main/resources`. +4. Rufen Sie `new License().setLicense("Aspose.OCR.Java.lic");` vor jeglicher OCR‑Arbeit auf, wie im obigen Code gezeigt. + +> **Pro‑Tipp:** Wenn Sie auf einem Server bereitstellen, verwenden Sie einen absoluten Pfad oder einen Klassenpfad‑Ressourcen‑Lader, um `FileNotFoundException` zu vermeiden. + +--- + +## Bild für OCR‑Verarbeitung laden + +Die Zeile `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` ist das Herzstück des **load image for OCR**‑Schritts. Aspose OCR unterstützt ein breites Spektrum an Formaten: PNG, JPEG, BMP, TIFF und sogar mehrseitige PDFs (in Kombination mit Aspose.Pdf). + +### Häufige Fallstricke + +| Problem | Symptom | Lösung | +|-------|---------|-----| +| Falscher Dateipfad | `FileNotFoundException` | Pfad überprüfen; `Paths.get(...)` für betriebssystemunabhängige Trennzeichen verwenden. | +| Nicht unterstütztes Format | `UnsupportedOperationException` | Bild vor dem Laden in PNG oder JPEG konvertieren. | +| Sehr großes Bild ( > 10 MP) | Out‑of‑memory‑Fehler | Bild mit `java.awt.Image` verkleinern, bevor es an Aspose übergeben wird. | + +--- + +## Text aus Bild extrahieren und Ergebnisse verarbeiten + +Sobald die OCR‑Engine fertig ist, enthält das Objekt `OcrResult` die erkannte Zeichenkette. Hier **extrahieren wir Text aus Bild** für die Weiterverarbeitung – Speicherung in einer Datenbank, Befüllung eines Suchindexes oder Weitergabe an eine nachgelagerte NLP‑Pipeline. + +### Umgang mit mehreren Sprachen + +Da wir `engine.setLanguage(Language.Auto)` gesetzt haben, versucht Aspose, die Sprachen automatisch zu erkennen. Wenn Sie die Sprache im Voraus kennen (z. B. alle Dokumente sind Russisch), können Sie `Language.Auto` durch `Language.Russian` ersetzen, um die Leistung zu steigern. + +### Tipps zur Nachbearbeitung + +- **Leerzeichen trimmen**: `result.getText().trim()`. +- **Zeilenenden normalisieren**: `result.getText().replace("\r\n", "\n")`. +- **Nicht‑druckbare Zeichen entfernen**: Verwenden Sie einen Regex wie `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Text im Bild erkennen mit erweiterten Optionen (optional) + +Wenn Sie feinere Kontrolle benötigen, bietet Aspose OCR zusätzliche Eigenschaften: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Diese Anpassungen sind praktisch, wenn Sie mit gescannten Dokumenten arbeiten, die unter Schräglage oder geringem Kontrast leiden. + +--- + +## Zusammenfassung des vollständigen funktionierenden Beispiels + +Wenn man alles zusammenfügt, führt das endgültige Programm Folgendes in dieser Reihenfolge aus: + +1. **OCR auf Bild durchführen** – durch Erstellen einer `OcrEngine`. +2. **Aspose‑Lizenz verwenden** – optional, aber empfohlen. +3. **Bild für OCR laden** – über `Image.load`. +4. **Spracherkennung einstellen** – `Language.Auto`, um **Text im Bild zu erkennen** automatisch. +5. **Text aus Bild extrahieren** – Ergebnis ausgeben und leere Antworten elegant handhaben. + +Sie können den obigen Codeblock direkt in ein Maven‑Projekt mit dieser Abhängigkeit einfügen: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Führen Sie `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` aus und beobachten Sie, wie die Konsole den erkannten Text anzeigt. + +--- + +## Fazit + +Wir haben Ihnen gerade gezeigt, wie man **OCR auf Bild**‑Dateien mit Aspose OCR für Java durchführt, von der Anwendung einer Lizenz über das **Laden des Bildes für OCR**, das **Erkennen von Text im Bild**‑Inhalt bis hin zum **Extrahieren von Text aus Bild** für die nachgelagerte Nutzung. Der Ansatz ist unkompliziert, funktioniert sofort mit mehreren Sprachen und kann bei Bedarf mit erweiterten Vorverarbeitungsoptionen erweitert werden. + +Was kommt als Nächstes? Versuchen Sie, die OCR‑Ausgabe in einen Suchindex zu speisen, PDFs mit dem extrahierten Text zu erzeugen oder mit verschiedenen Bildformaten zu experimentieren. Die Möglichkeiten sind endlos, und mit Asposes robustem API verbringen Sie mehr Zeit mit dem Aufbau von Funktionen als mit dem Kampf gegen OCR‑Eigenheiten. + +Haben Sie Fragen oder stoßen Sie auf einen Sonderfall? Hinterlassen Sie unten einen Kommentar – happy coding! + +## 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. + +- [Wie man Text aus Bild von URL mit Aspose.OCR für Java extrahiert](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Bild in Text in Java mit Aspose.OCR BufferedImage konvertieren](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Text aus Bild in Java mit Aspose.OCR Detect Areas Mode extrahieren](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/greek/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0615e55b5 --- /dev/null +++ b/ocr/greek/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-19 +description: Δημιουργήστε αναζητήσιμο PDF από μια εικόνα χρησιμοποιώντας Python OCR. + Μάθετε πώς να μετατρέπετε το OCR σε PDF, να εξάγετε κείμενο από εικόνα και να εκτελείτε + OCR σε εικόνα γρήγορα. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: el +og_description: Δημιουργήστε αναζητήσιμο PDF από μια εικόνα με Python OCR. Αυτός ο + οδηγός δείχνει πώς να μετατρέψετε OCR σε PDF, να εξάγετε κείμενο από εικόνα και + να εκτελέσετε OCR σε εικόνα. +og_title: Δημιουργία Αναζητήσιμου PDF σε Python – Πλήρης Οδηγός Προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Δημιουργία Αναζητήσιμου PDF σε Python – Πλήρης Οδηγός Βήμα‑βήμα +url: /el/python-java/general/create-searchable-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 σε Python – Πλήρης Οδηγός Βήμα‑βήμα + +Έχετε ποτέ χρειαστεί να **δημιουργήσετε αναζητήσιμο PDF** από μια σαρωμένη απόδειξη αλλά δεν ήξερες από πού να ξεκινήσεις; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν το ίδιο πρόβλημα όταν προσπαθούν για πρώτη φορά να μετατρέψουν μια εικόνα κειμένου σε PDF που μπορείτε πραγματικά να αναζητήσετε. + +Σε αυτό το tutorial θα περάσουμε βήμα-βήμα μια πρακτική λύση που σας επιτρέπει να **εφαρμόσετε OCR σε εικόνα**, να μετατρέψετε το αποτέλεσμα του OCR σε **αναζητήσιμο PDF**, και ακόμη να εξάγετε το ακατέργαστο κείμενο αν το χρειάζεστε για περαιτέρω επεξεργασία. Χωρίς περιττά, μόνο ένα λειτουργικό παράδειγμα που μπορείτε να αντιγράψετε‑επικολλήσετε στο πρόγραμμά σας σήμερα. + +## Τι Θα Μάθετε + +- Πώς να εγκαταστήσετε μια ελαφριά μηχανή OCR σε Python +- Τα ακριβή βήματα για **convert OCR to PDF** και αποθήκευση ως αναζητήσιμο έγγραφο +- Τρόπους για **extract text from image** για ανάλυση downstream +- Συμβουλές για αντιμετώπιση κοινών προβλημάτων όπως προσανατολισμός εικόνας και μεγάλα αρχεία +- Ένα πλήρες, εκτελέσιμο script που μπορείτε να προσαρμόσετε στη δική σας περίπτωση χρήσης + +### Προαπαιτούμενα + +- Python 3.8+ εγκατεστημένο στο μηχάνημά σας +- Βασική εξοικείωση με pip και εικονικά περιβάλλοντα (προαιρετικό αλλά συνιστάται) +- Ένα αρχείο εικόνας (PNG, JPEG, κ.λπ.) που περιέχει καθαρό, μηχανικά αναγνώσιμο κείμενο + +Αν τα έχετε αυτά, ας ξεκινήσουμε. + +## Βήμα 1: Εγκατάσταση της Απαιτούμενης Βιβλιοθήκης + +Το απόσπασμα κώδικα που είδατε νωρίτερα χρησιμοποιεί ένα φανταστικό πακέτο `ocr`, αλλά οι ίδιες ιδέες ισχύουν για πραγματικές βιβλιοθήκες όπως **EasyOCR**, **pytesseract**, ή **pdfminer.six**. Για αυτόν τον οδηγό θα χρησιμοποιήσουμε **EasyOCR** επειδή είναι καθαρά Python, υποστηρίζει πολλές γλώσσες, και επιστρέφει μια χρήσιμη μέθοδο μετατροπής PDF μέσω ενός βοηθητικού βοηθού. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Εγκαταστήστε μέσα σε ένα εικονικό περιβάλλον (`python -m venv venv && source venv/bin/activate`) για να διατηρήσετε τις εξαρτήσεις σας οργανωμένες. + +## Βήμα 2: Αρχικοποίηση της Μηχανής OCR – Perform OCR on Image + +Τώρα που η βιβλιοθήκη είναι έτοιμη, δημιουργούμε μια μηχανή OCR και της λέμε να δουλεύει με αγγλικό κείμενο. Αυτό είναι το πρώτο σημείο όπου **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Γιατί χρειάζεται ένα αφιερωμένο αντικείμενο reader; Το EasyOCR προφορτώνει τα μοντέλα γλώσσας, έτσι η επαναχρησιμοποίηση του ίδιου `reader` για πολλαπλές εικόνες είναι πολύ πιο αποδοτική από το να το επανεκκινείτε κάθε φορά. + +## Βήμα 3: Φόρτωση της Εικόνας – Extract Text from Image + +Ας φορτώσουμε την εικόνα στη μνήμη. Αυτό το βήμα είναι όπου αργότερα **extract text from image**, αλλά πρώτα την φορτώνουμε. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Αν η εικόνα σας είναι ανάποδα ή παραμορφωμένη, σκεφτείτε να χρησιμοποιήσετε τις μεθόδους `rotate` ή `transpose` του Pillow πριν τη δώσετε στη μηχανή OCR. Μια γρήγορη οπτική επιθεώρηση μπορεί να σας εξοικονομήσει ώρες εντοπισμού σφαλμάτων αργότερα. + +## Βήμα 4: Εκτέλεση της Μηχανής OCR και Συλλογή Αποτελεσμάτων + +Αυτή είναι η καρδιά της διαδικασίας—αποστολή της εικόνας στη μηχανή OCR και λήψη δομημένων δεδομένων. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Η σημαία `detail=1` μας δίνει τα πλαίσια περιγράμματος, τα οποία θα χρειαστούμε όταν αργότερα **convert OCR to PDF**. Αν σας ενδιαφέρουν μόνο οι ακατέργαστες συμβολοσειρές, ορίστε `detail=0`. + +## Βήμα 5: Μετατροπή του Αποτελέσματος OCR σε Αναζητήσιμο PDF – Convert OCR to PDF + +Το EasyOCR δεν παρέχει άμεσο γράφτη PDF, αλλά μπορούμε να δημιουργήσουμε το PDF μόνοι μας χρησιμοποιώντας το Pillow και τη βιβλιοθήκη `reportlab`. Για να κρατήσουμε το tutorial ελαφρύ, θα χρησιμοποιήσουμε το `fpdf2`, το οποίο μας επιτρέπει να ενσωματώσουμε την αρχική εικόνα και να επικάψουμε αόρατο κείμενο. + +```bash +pip install fpdf2 +``` +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Τι συνέβη μόλις; Τοποθετήσαμε την σαρωμένη εικόνα ως ορατό στρώμα, έπειτα γράψαμε τις αναγνωρισμένες λέξεις από πάνω χρησιμοποιώντας λευκό κείμενο που ενσωματώνεται στο λευκό φόντο. Τα εργαλεία αναζήτησης εξακολουθούν να διαβάζουν το κρυφό στρώμα, έτσι το PDF γίνεται **searchable** χωρίς να αλλάζει η οπτική εμφάνιση. + +## Βήμα 6: Αποθήκευση των Bytes του PDF – Convert Image to PDF + +Αν προτιμάτε να χειριστείτε το PDF στη μνήμη (π.χ., αποστέλλοντάς το μέσω API), μπορείτε να συλλάβετε τα bytes αντί να γράψετε απευθείας στο δίσκο. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Αυτή η γραμμή δείχνει τη κλασική ροή εργασίας **convert image to PDF**: ξεκινάτε με μια εικόνα, εκτελείτε OCR, επικάθετε κείμενο, και τελικά παράγετε ένα ρεύμα PDF. + +## Βήμα 7: Επαλήθευση του Αποτελέσματος – Γρήγοροι Έλεγχοι + +Αφού εκτελέσετε το script, ανοίξτε το `receipt_searchable.pdf` σε οποιονδήποτε προβολέα PDF και δοκιμάστε το πεδίο αναζήτησης (Ctrl + F). Πληκτρολογήστε μια λέξη που γνωρίζετε ότι εμφανίζεται στην απόδειξη—αν μεταβεί στη σωστή θέση, έχετε δημιουργήσει επιτυχώς **create searchable pdf**! + +Αν η αναζήτηση αποτύχει, ελέγξτε ξανά: + +1. Τα σκορ εμπιστοσύνης του OCR (`conf` values). Χαμηλή εμπιστοσύνη μπορεί να σημαίνει ότι η εικόνα είναι θολή. +2. Συντεταγμένες πλαισίων περιγράμματος—μερικές φορές το EasyOCR τις αναφέρει σε διαφορετικό προσανατολισμό. +3. Ότι ο προβολέας PDF δεν είναι σε λειτουργία «μόνο‑εικόνα» (σπάνια, αλλά ορισμένοι προβολείς έχουν αυτή την επιλογή). + +## Πλήρες Λειτουργικό Script + +Συνδυάζοντας όλα, εδώ είναι το πλήρες, έτοιμο‑για‑εκτέλεση αρχείο Python: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Αποθηκεύστε το ως `searchable_pdf.py`, αντικαταστήστε τα placeholders `YOUR_DIRECTORY` με πραγματικές διαδρομές, και εκτελέστε: + +```bash +python searchable_pdf.py +``` + +Θα πρέπει να δείτε ένα μήνυμα επιβεβαίωσης και ένα ολοκαίνουργιο αναζητήσιμο PDF στον φάκελό σας. + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +**Τι γίνεται αν η εικόνα είναι έγχρωμη;** +Το EasyOCR λειτουργεί τόσο με εικόνες σε κλίμακα του γκρι όσο και με έγχρωμες, αλλά η μετατροπή σε κλίμακα του γκρι (`pil_image.convert("L")`) μπορεί μερικές φορές να βελτιώσει την ακρίβεια σε θορυβώδεις σαρώσεις. + +**Μπορώ να χειριστώ PDF πολλαπλών σελίδων;** +Ναι—επανάληψη πάνω σε κάθε εικόνα σελίδας, εκτέλεση των βημάτων OCR, και προσθήκη κάθε σελίδας στο ίδιο αντικείμενο `FPDF`. Απλώς θυμηθείτε να επαναφέρετε τον κέρσορα (`self.add_page()`) για κάθε νέα εικόνα. + +**Υπάρχει τρόπος να διατηρήσετε το αρχικό στρώμα κειμένου αντί για αόρατο λευκό κείμενο;** +Αν χρειάζεστε ένα πραγματικό PDF «κείμενο‑κάτω‑από‑εικόνα» (π.χ., για προσβασιμότητα), σκεφτείτε να χρησιμοποιήσετε το `pdfminer` ή το `pikepdf` για να ενσωματώσετε ένα κρυφό στρώμα κειμένου με σωστές ετικέτες PDF. Είναι πιο προχωρημένο, αλλά η αρχή παραμένει η ίδια: εικόνα φόντου + επικάλυψη κειμένου. + +**Τι γίνεται αν η εμπιστοσύνη του OCR είναι χαμηλή;** +Μπορείτε να φιλτράρετε τις λέξεις χαμηλής εμπιστοσύνης: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Συμπέρασμα – Τι Καταφέραμε + +Ξεκινήσαμε με μια απλή εικόνα απόδειξης, **performed OCR on image**, εξάγαμε τις αναγνωρισμένες συμβολοσειρές, και τελικά **create searchable pdf** που συμπεριφέρεται όπως οποιοδήποτε επαγγελματικά σαρωμένο έγγραφο. Η διαδικασία κάλυψε όλες τις δευτερεύουσες λέξεις‑κλειδιά—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, και **perform OCR on image**—οπότε τώρα έχετε ένα επαναχρησιμοποιήσιμο κουτί εργαλείων για οποιοδήποτε παρόμοιο έργο. + +### Επόμενα Βήματα + +- Πειραματιστείτε με άλλες γλώσσες περνώντας τους κωδικούς ISO στο `easyocr.Reader(['en', 'es'])`. +- Αντικαταστήστε το EasyOCR με το Tesseract αν χρειάζεστε μια πλήρως offline λύση· το υπόλοιπο pipeline παραμένει το ίδιο. +- Προσθέστε οπτικοποίηση εμπιστοσύνης OCR (σχεδίαση πλαισίων περιγράμματος στην εικόνα) για εντοπισμό προβληματικών σαρώσεων. + +Έχετε μια παραλλαγή που θέλετε να μοιραστείτε; Αφήστε ένα σχόλιο, κάντε fork + +## Τι Θα Πρέπει Να Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετικές θεματικές που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε σε επιπλέον δυνατότητες 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/greek/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/greek/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..a22c82655 --- /dev/null +++ b/ocr/greek/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Εξάγετε κείμενο από εικόνες σε Python με μια απλή μηχανή OCR. Μάθετε + πώς να μετατρέπετε σαρωμένες εικόνες σε κείμενο, να αναγνωρίζετε κείμενο από φωτογραφίες + και να καταγράφετε αρχεία εικόνας σε Python αποδοτικά. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: el +og_description: Εξάγετε κείμενο από εικόνες σε Python χρησιμοποιώντας μια ελαφριά + μηχανή OCR. Αυτός ο οδηγός σας δείχνει πώς να μετατρέψετε σαρωμένες εικόνες σε κείμενο, + να αναγνωρίσετε κείμενο από φωτογραφίες και να καταγράψετε αρχεία εικόνας σε Python + σε λίγα βήματα. +og_title: Εξαγωγή κειμένου από εικόνες σε Python – Πλήρης οδηγός OCR σε παρτίδα +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Εξαγωγή κειμένου από εικόνες με Python – Οδηγός πλήρους OCR σε παρτίδες +url: /el/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εξαγωγή Κειμένου από Εικόνες σε Python – Οδηγός Πλήρους Batch OCR + +Κάποτε χρειάστηκε να **εξάγετε κείμενο από εικόνες** αλλά δεν ήξερες από πού να ξεκινήσεις; Δεν είσαι μόνος—οι προγραμματιστές αντιμετωπίζουν συνεχώς την πρόκληση του να μετατρέπουν σαρωμένα PDF, φωτογραφημένα αποδείξεις ή στιγμιότυπα οθόνης σε αναζητήσιμο κείμενο. Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πλήρες, έτοιμο‑για‑εκτέλεση παράδειγμα που δείχνει πώς να **μετατρέψετε σαρωμένες εικόνες σε κείμενο**, να αναγνωρίζετε κείμενο από φωτογραφίες, και ακόμη να **καταγράψετε αρχεία εικόνας python‑style**. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο script που επεξεργάζεται ολόκληρο φάκελο με μια κλήση. + +Θα καλύψουμε όλα όσα χρειάζεστε: απαιτούμενες βιβλιοθήκες, γιατί κάθε βήμα είναι σημαντικό, διαχείριση edge‑case, και λίγη αντιμετώπιση προβλημάτων. Δεν χρειάζεται να ψάχνετε σε εξωτερική τεκμηρίωση· ο κώδικας παρακάτω είναι αυτόνομος, και οι εξηγήσεις απαντούν στο “πώς” *και* στο “γιατί”. Πάρτε το αγαπημένο σας IDE και ας ξεκινήσουμε. + +--- + +## Τι Θα Δημιουργήσετε + +- Αρχικοποίηση μηχανής OCR (θα χρησιμοποιήσουμε το πακέτο `ocr` για παράδειγμα). +- Σάρωση ενός καταλόγου και **καταγραφή αρχείων εικόνας python‑style**, φιλτράροντας PNG, JPG και TIFF. +- Εκτέλεση λειτουργίας **batch OCR** σε όλες τις εικόνες που βρέθηκαν. +- Εκτύπωση του εξαγόμενου κειμένου για κάθε αρχείο, με σαφή ετικέτα. + +> **Pro tip:** Αν δεν έχετε εγκαταστήσει τη βιβλιοθήκη `ocr`, μπορείτε να την αντικαταστήσετε με `pytesseract` με μερικές μικρές αλλαγές—η βασική λογική παραμένει η ίδια. + +--- + +## Προαπαιτούμενα + +- Python 3.8+ (το script χρησιμοποιεί f‑strings και type hints). +- Μια βιβλιοθήκη OCR που εκθέτει ένα `OcrEngine` με `recognize_batch`. Για αυτόν τον οδηγό υποθέτουμε ένα φανταστικό πακέτο `ocr`, αλλά το μοτίβο λειτουργεί με πραγματικές βιβλιοθήκες. +- Ένας φάκελος που περιέχει αρχεία εικόνας που θέλετε να επεξεργαστείτε (`.png`, `.jpg`, `.tif`). + +--- + +## Βήμα 1 – Εγκατάσταση & Εισαγωγή Απαιτούμενων Μονάδων + +Πρώτα, βεβαιωθείτε ότι το πακέτο OCR είναι διαθέσιμο. Αν χρησιμοποιείτε πραγματική βιβλιοθήκη όπως `pytesseract`, αντικαταστήστε την εισαγωγή αναλόγως. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Why this matters:** Η εισαγωγή του `os` μας δίνει διαχείριση διαδρομών ανεξαρτήτως πλατφόρμας, ενώ το `typing.List` βοηθά στην αυτόματη συμπλήρωση του IDE και στην προετοιμασία για το μέλλον. + +--- + +## Βήμα 2 – **Extract Text from Images**: Αρχικοποίηση της Μηχανής OCR + +Η δημιουργία της μηχανής είναι το πρώτο βήμα για οποιαδήποτε εργασία OCR. Ορίζουμε επίσης τη γλώσσα σε auto‑detect ώστε η μηχανή να μπορεί να διαχειριστεί έγγραφα με πολλαπλές γλώσσες. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explanation:** Με το να ενσωματώνουμε τη δημιουργία της μηχανής σε μια συνάρτηση κρατάμε τον κώδικα modular. Αν αργότερα χρειαστεί να ρυθμίσετε DPI ή OCR mode, θα το κάνετε μόνο σε αυτό το σημείο. + +--- + +## Βήμα 3 – **List Image Files Python**: Συλλογή Αρχείων από Κατάλογο + +Τώρα πρέπει να εντοπίσουμε κάθε εικόνα που θέλουμε να επεξεργαστούμε. Η list comprehension παρακάτω αντικατοπτρίζει ένα κοινό μοτίβο “list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge case handling:** Η συνάρτηση αγνοεί υπο‑φακέλους (μπορείτε να προσθέσετε επανάληψη αργότερα) και φιλτράρει αυτόματα κρυφά αρχεία επειδή συνήθως δεν τελειώνουν με υποστηριζόμενες επεκτάσεις. + +--- + +## Βήμα 4 – **Convert Scanned Images to Text**: Εκτέλεση Batch OCR + +Οι περισσότερες βιβλιοθήκες OCR παρέχουν μέθοδο batch που είναι πολύ πιο γρήγορη από την επεξεργασία μιας εικόνας τη φορά. Δείτε πώς την καλούμε. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Why batch?** Η αποστολή όλων των εικόνων ταυτόχρονα μειώνει το overhead (π.χ. την επανειλημμένη φόρτωση του μοντέλου OCR) και συχνά προσφέρει καλύτερη αξιοποίηση CPU/GPU. + +--- + +## Βήμα 5 – **Recognize Text from Pictures**: Εμφάνιση Αποτελεσμάτων + +Τέλος, διατρέχουμε τα ζευγάρια ονομάτων αρχείων και αποτελεσμάτων OCR, εκτυπώνοντας μια καθαρή κεφαλίδα για κάθε εικόνα. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** Η `strip()` αφαιρεί κενά στην αρχή/τέλος που συχνά προσθέτει το OCR. + +--- + +## Πλήρες Script – Συνδυάστε Όλα Μαζί + +Παρακάτω είναι το πλήρες, εκτελέσιμο πρόγραμμα. Αποθηκεύστε το ως `batch_ocr.py` και τρέξτε `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Αναμενόμενη Έξοδος + +Αν ο φάκελος περιέχει `invoice1.png` και `receipt.jpg`, μπορεί να δείτε: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Κάθε μπλοκ είναι σαφώς επισημασμένο, κάνοντας την επεξεργασία downstream (π.χ. αποθήκευση σε βάση δεδομένων) απλή. + +--- + +## Διαχείριση Συνηθισμένων Προβλημάτων + +| Πρόβλημα | Γιατί Συμβαίνει | Γρήγορη Λύση | +|----------|----------------|--------------| +| **Δεν εμφανίζεται κείμενο** | Η γλώσσα OCR δεν εντοπίστηκε ή η εικόνα είναι πολύ χαμηλής αντίθεσης. | Εξαναγκάστε μια γλώσσα (`engine.language = ocr.Language.English`) ή προεπεξεργαστείτε τις εικόνες (αυξήστε την αντίθεση). | +| **Σφάλμα μνήμης σε μεγάλα batch** | Η μηχανή προσπαθεί να φορτώσει όλες τις εικόνες ταυτόχρονα. | Χωρίστε το `image_files` σε τμήματα (`batch_size = 20`) και καλέστε επανειλημμένα το `recognize_batch`. | +| **Μη υποστηριζόμενη μορφή αρχείου** | Προσθέσατε ένα `.gif` ή `.bmp`. | Επεκτείνετε το tuple `supported_exts` ή μετατρέψτε τις εικόνες σε PNG/JPG εκ των προτέρων. | +| **Κατάρρευση Unicode** | Το OCR επιστρέφει bytes αντί για strings. | Βεβαιωθείτε ότι η βιβλιοθήκη OCR επιστρέφει Unicode (`result.text.decode('utf‑8')` αν χρειάζεται). | + +--- + +## Επέκταση της Ροής Εργασίας + +Τώρα που μπορείτε να **εξάγετε κείμενο από εικόνες**, σκεφτείτε τα επόμενα βήματα: + +- **Εξαγωγή σε CSV** – Γράψτε κάθε όνομα αρχείου και το εξαγόμενο κείμενο σε ένα φύλλο εργασίας για αναλύσεις. +- **Παράλληλη επεξεργασία** – Χρησιμοποιήστε `concurrent.futures.ThreadPoolExecutor` για να διαχειριστείτε πολλαπλά batch ταυτόχρονα. +- **Ενσωμάτωση με cloud OCR** – Αντικαταστήστε τη τοπική μηχανή με Google Vision ή Azure OCR για μεγαλύτερη ακρίβεια σε σύνθετες διατάξεις. +- **Προσθήκη προεπεξεργασίας εικόνας** – Βιβλιοθήκες όπως Pillow ή OpenCV μπορούν να διορθώσουν κλίση, θόρυβο ή να εφαρμόσουν κατώφλι πριν το OCR, βελτιώνοντας τα αποτελέσματα. + +Όλες αυτές οι ιδέες χρησιμοποιούν τις ίδιες βασικές συναρτήσεις που δημιουργήσαμε, οπότε δεν χρειάζεται να ξεκινήσετε από το μηδέν. + +--- + +## Συμπέρασμα + +Διασχίσαμε μια πλήρη λύση για **εξαγωγή κειμένου από εικόνες** σε Python, καλύπτοντας τα πάντα από το **list image files python** έως το **recognize text from pictures** και τελικά το **convert scanned images to text** σε ένα οργανωμένο batch. Το script είναι σκόπιμα απλό αλλά αρκετά ευέλικτο ώστε να λειτουργήσει ως βάση για μεγαλύτερα έργα—είτε ψηφιοποιείτε αποδείξεις, χτίζετε ένα αναζητήσιμο αρχείο, ή τροφοδοτείτε μια γραμμή εξαγωγής δεδομένων. + +Δοκιμάστε το, προσαρμόστε τα βήματα προεπεξεργασίας, και παρακολουθήστε την ακρίβεια του OCR να ανεβαίνει. Αν αντιμετωπίσετε δυσκολίες, επιστρέψτε στον πίνακα “Διαχείριση Συνηθισμένων Προβλημάτων”· τα περισσότερα ζητήματα λύνουν με μια μικρή αλλαγή ρυθμίσεων. + +Έτοιμοι για την επόμενη πρόκληση; Προσθέστε ένα βήμα μετατροπής PDF‑σε‑εικόνα χρησιμοποιώντας `pdf2image`, και τροφοδοτήστε αυτές τις εικόνες απευθείας στην ίδια ροή. Ο ουρανός είναι το όριο όταν συνδυάζετε OCR με το πλούσιο οικοσύστημα της Python. + +Καλή προγραμματιστική, και εύχομαι το κείμενό σας να είναι πάντα ευανάγνωστο! + +## Τι Θα Μάθετε Στη Σειρά Επόμενη; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κυριαρχήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας έργα. + +- [Εξαγωγή Κειμένου από Εικόνα με Aspose OCR – Οδηγός Βήμα‑Βήμα](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Εξαγωγή Κειμένου από Εικόνες – Βασικά OCR με Aspose.OCR για Java](/ocr/english/java/ocr-basics/) +- [Πώς να εξάγετε κείμενο από εικόνα από URL χρησιμοποιώντας Aspose.OCR για Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/greek/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..fccb6ba64 --- /dev/null +++ b/ocr/greek/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-19 +description: Εξάγετε κείμενο από εικόνες χρησιμοποιώντας Python OCR. Μάθετε αυτόματη + ανίχνευση γλώσσας, παράλληλη επεξεργασία και αναγνώριση σε παρτίδες σε ένα σύντομο + σεμινάριο. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: el +og_description: Εξάγετε κείμενο από εικόνες με Python OCR. Αυτός ο οδηγός δείχνει + αυτόματη ανίχνευση γλώσσας, παράλληλη επεξεργασία και αναγνώριση δέσμης σε ένα ενιαίο + σεμινάριο. +og_title: Εξαγωγή κειμένου από εικόνες σε Python – Πλήρης Οδηγός OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Εξαγωγή κειμένου από εικόνες σε Python – Πλήρης Οδηγός OCR +url: /el/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# εξαγωγή κειμένου από εικόνες σε Python – Πλήρης Οδηγός OCR + +Έχετε αναρωτηθεί ποτέ πώς να **εξάγετε κείμενο από εικόνες** χωρίς να πληκτρολογείτε κάθε λέξη χειροκίνητα; Δεν είστε οι μόνοι. Είτε ψηφιοποιείτε παλιές αποδείξεις, είτε δημιουργείτε ένα αναζητήσιμο αρχείο εγγράφων, είτε απλώς πειραματίζεστε με εντυπωσιακές τεχνικές AI, η δυνατότητα εξαγωγής κειμένου από εικόνες είναι απαραίτητη για κάθε προγραμματιστή Python σήμερα. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πλήρες, έτοιμο‑να‑τρέξει παράδειγμα που **εξάγει κείμενο από εικόνες** χρησιμοποιώντας μια δημοφιλή μηχανή OCR. Θα καλύψουμε αυτόματη ανίχνευση γλώσσας, παράλληλη επεξεργασία για ταχύτητα και επεξεργασία παρτίδας εικόνων ώστε να μπορείτε να διαχειριστείτε δεκάδες αρχεία σε δευτερόλεπτα. Σαφές ότι είναι αυτό που χρειάζεστε; Ας βουτήξουμε. + +## Τι Θα Μάθετε + +- Πώς να δημιουργήσετε μια μηχανή OCR με `ocr.OcrEngine`. +- Ενεργοποίηση **αυτόματης ανίχνευσης γλώσσας** ώστε η μηχανή να επιλέγει τη σωστή γλώσσα από μόνη της. +- Διαμόρφωση **παράλληλης επεξεργασίας OCR** με προσαρμοσμένο thread pool. +- Εκτέλεση **επεξεργασίας παρτίδας εικόνων** σε λίστα αρχείων. +- Εκτύπωση του αναγνωρισμένου κειμένου για κάθε εικόνα, έτοιμο για αποθήκευση ή ευρετηρίαση. + +Καμία εξωτερική τεκμηρίωση δεν απαιτείται — όλα όσα χρειάζεστε είναι εδώ, και ο κώδικας λειτουργεί αμέσως με το πακέτο `ocr` (εγκαταστήστε το μέσω `pip install ocr`). + +## Προαπαιτούμενα + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +1. Python 3.8 ή νεότερη έκδοση εγκατεστημένη. +2. Το πακέτο `ocr` (`pip install ocr`). +3. Έναν φάκελο με εικόνες PNG (ή JPG) που θέλετε να επεξεργαστείτε. +4. Βασική εξοικείωση με συναρτήσεις και βρόχους της Python. + +Αυτό είναι όλο — χωρίς βαριές εξαρτήσεις, χωρίς μαγικά GPU, μόνο καθαρή Python. + +![extract text from images example](https://example.com/ocr-demo.png "Στιγμιότυπο που δείχνει το αποτέλεσμα εξαγωγής κειμένου από εικόνες") + +*Alt text: στιγμιότυπο επίδειξης εξαγωγής κειμένου από εικόνες* + +## Βήμα 1 – Ρύθμιση της Μηχανής OCR (Κύρια Λέξη‑Κλειδί σε Δράση) + +Πρώτο πράγμα: δημιουργήστε ένα αντικείμενο μηχανής OCR. Σκεφτείτε το `ocr.OcrEngine()` ως τον εγκέφαλο της λειτουργίας· ξέρει πώς να διαβάζει χαρακτήρες, γραμμές και παραγράφους. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Γιατί χρειάζεται μια ρητή μηχανή; Επειδή η **χρήση του ocr.OcrEngine** σας δίνει λεπτομερή έλεγχο πάνω στις ρυθμίσεις γλώσσας, threading και άλλα. Είναι ο πιο ευέλικτος τρόπος για **εξαγωγή κειμένου από εικόνες** σε σύγκριση με τις βοηθητικές συναρτήσεις μίας γραμμής. + +## Βήμα 2 – Αφήστε τη Μηχανή να Ανιχνεύει Αυτόματα τις Γλώσσες + +Οι περισσότερες βιβλιοθήκες OCR απαιτούν να τους πείτε ποια γλώσσα να ψάξουν. Αυτό είναι εντάξει για ένα έργο μίας γλώσσας, αλλά ενοχλητικό για παρτίδα με μικτές γλώσσες. Ευτυχώς, το πακέτο `ocr` υποστηρίζει **αυτόματη ανίχνευση γλώσσας**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Ορίζοντας `engine.language` σε `ocr.Language.Auto` λέτε στη μηχανή να «ανιχνεύει» κάθε εικόνα και να επιλέγει το κατάλληλο μοντέλο γλώσσας. Αυτή η μικρή γραμμή σας εξοικονομεί ώρες χειροκίνητης ρύθμισης όταν δουλεύετε με διεθνή έγγραφα. + +## Βήμα 3 – Επιταχύνετε με Παράλληλη Επεξεργασία OCR + +Αν έχετε τέσσερις ή περισσότερους πυρήνες CPU, γιατί να μην τους χρησιμοποιήσετε; Η μηχανή μπορεί να δημιουργήσει ένα thread pool, επιτρέποντας την ταυτόχρονη επεξεργασία πολλαπλών εικόνων. Εδώ η **παράλληλη επεξεργασία OCR** δείχνει την αξία της. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Απλώς προσαρμόστε τον αριθμό `4` ανάλογα με το σύστημά σας. Περισσότερα νήματα → ταχύτερες εκτελέσεις παρτίδας, αλλά θυμηθείτε ότι κάθε νήμα καταναλώνει μνήμη, οπότε βρείτε το «sweet spot» για το περιβάλλον σας. + +## Βήμα 4 – Συλλογή των Εικόνων που Θέλετε να Επεξεργαστείτε + +Τώρα χρειαζόμαστε μια λίστα διαδρομών αρχείων. Μπορείτε να τη δημιουργήσετε χειροκίνητα, να τη διαβάσετε από CSV ή να χρησιμοποιήσετε `glob`. Για σαφήνεια, θα κωδικοποιήσουμε μια σύντομη λίστα: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Αντικαταστήστε το `YOUR_DIRECTORY` με την πραγματική διαδρομή στο σύστημά σας. Αν έχετε δεκάδες αρχεία, ένα γρήγορο `glob.glob("*.png")` θα κάνει τη δουλειά. + +## Βήμα 5 – Εκτέλεση Επεξεργασίας Παρτίδας Εικόνων + +Αυτή είναι η καρδιά του tutorial: μία κλήση που επεξεργάζεται κάθε εικόνα στη λίστα `files` και επιστρέφει μια λίστα αντικειμένων αποτελεσμάτων. Αυτή είναι η λειτουργία **επεξεργασίας παρτίδας εικόνων** που κάνει το OCR σε μεγάλη κλίμακα πρακτικό. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Στο παρασκήνιο, η μηχανή διανέμει κάθε αρχείο στα τέσσερα νήματα εργασίας που ρυθμίσαμε νωρίτερα, ενώ αυτόματα ανιχνεύει τη γλώσσα για κάθε εικόνα. Η μέθοδος επιστρέφει μια λίστα όπου κάθε στοιχείο περιέχει το αναγνωρισμένο κείμενο και μεταδεδομένα. + +## Βήμα 6 – Εκτύπωση (ή Αποθήκευση) του Εξαγόμενου Κειμένου + +Τέλος, διατρέχουμε τα αποτελέσματα και εκτυπώνουμε το κείμενο. Σε πραγματικό έργο πιθανότατα θα γράψετε τα δεδομένα σε βάση ή CSV, αλλά η εκτύπωση κρατά το παράδειγμα απλό. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Αναμενόμενο αποτέλεσμα** (κομμένο για συντομία): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Κάθε μπλοκ δείχνει το όνομα αρχείου ακολουθούμενο από το κείμενο που προέκυψε από το OCR. Αν μια εικόνα περιέχει πολλαπλές γλώσσες, θα δείτε τους αντίστοιχους χαρακτήρες χάρη στο προηγούμενο βήμα **αυτόματης ανίχνευσης γλώσσας**. + +## Pro Tips & Συνηθισμένα Πιθανά Προβλήματα + +- **Η ποιότητα της εικόνας μετρά** – θολές ή χαμηλής αντίθεσης εικόνες θα δώσουν άσχημα αποτελέσματα. Προεπεξεργαστείτε με OpenCV (`cv2.threshold`, `cv2.resize`) αν χρειάζεται. +- **Αριθμός νημάτων vs. I/O** – Αν οι εικόνες βρίσκονται σε αργό δίκτυο, περισσότερα νήματα ίσως δεν βοηθήσουν. Παρακολουθήστε τη χρήση CPU με `top` ή `Task Manager`. +- **Διαχείριση Unicode** – Το `result.text` είναι συμβολοσειρά Unicode. Όταν γράφετε σε αρχεία, ανοίξτε τα με `encoding="utf‑8"` για να αποφύγετε `UnicodeEncodeError`. +- **Κατανάλωση μνήμης** – Μεγάλα PDF μπορούν να καταναλώσουν πολύ RAM. Αν αντιμετωπίσετε `MemoryError`, μειώστε το μέγεθος του thread pool ή επεξεργαστείτε τις εικόνες σε μικρότερα τμήματα. + +## Πλήρες Εργαζόμενο Script + +Ακολουθεί το πλήρες, έτοιμο‑για‑αντιγραφή script που ενσωματώνει όλα τα βήματα που συζητήσαμε. Αποθηκεύστε το ως `batch_ocr.py` και τρέξτε `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Τρέξτε το έτσι: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Θα δείτε ένα ωραία μορφοποιημένο μπλοκ κειμένου για κάθε εικόνα, αποδεικνύοντας ότι μπορείτε να **εξάγετε κείμενο από εικόνες** σε κλίμακα. + +## Τι Ακολουθεί; + +Τώρα που έχετε κατακτήσει τα βασικά της **εξαγωγής κειμένου από εικόνες** με Python, σκεφτείτε να εξερευνήσετε: + +- **Post‑processing**: καθαρίστε το αποτέλεσμα OCR με regex ή βιβλιοθήκες φυσικής γλώσσας. +- **Μετατροπή σε PDF**: τροφοδοτήστε τις εξαγόμενες συμβολοσειρές σε δημιουργό PDF για αναζητήσιμα PDFs. +- **Υπηρεσίες Cloud OCR**: συγκρίνετε τα αποτελέσματα του τοπικού `ocr` με Google Vision ή Azure OCR για ακραίες περιπτώσεις ακρίβειας. +- **GUI front‑end**: χτίστε μια μικρή εφαρμογή Flask ή FastAPI που επιτρέπει στους χρήστες να ανεβάζουν εικόνες και να βλέπουν αμέσως το εξαγόμενο κείμενο. + +Κάθε ένα από αυτά τα θέματα βασίζεται στο **Python OCR library** που μόλις στήσατε, και όλα ωφελούνται από τις ίδιες **παράλληλες επεξεργασίες OCR** που χρησιμοποιήσαμε εδώ. + +--- + +*Καλό κώδικα! Αν αντιμετωπίσετε δυσκολίες, αφήστε ένα σχόλιο παρακάτω — είμαι πάντα διαθέσιμος για troubleshooting OCR.* + + +## Τι Πρέπει να Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετικές θεματικές που επεκτείνουν τις τεχνικές του παρόντος οδηγού. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κυριαρχήσετε σε επιπλέον δυνατότητες 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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/greek/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..f3af1728e --- /dev/null +++ b/ocr/greek/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-06-19 +description: Πώς να εξάγετε PDF χρησιμοποιώντας OCR σε Python – βήμα‑βήμα tutorial + που καλύπτει την εξαγωγή κειμένου από PDF, την αναγνώριση κειμένου από εικόνα και + ένα παράδειγμα OCR σε Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: el +og_description: Πώς να εξάγετε PDF χρησιμοποιώντας OCR σε Python. Μάθετε πώς να εξάγετε + κείμενο από PDF, να αναγνωρίζετε κείμενο από εικόνα και δείτε ένα πλήρες παράδειγμα + OCR σε Python. +og_title: Πώς να εξάγετε κείμενο PDF με OCR στην Python – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Πώς να εξάγετε κείμενο PDF με OCR σε Python – Πλήρης οδηγός +url: /el/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να εξάγετε κείμενο PDF με OCR στην Python – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ **πώς να εξάγετε PDF** περιεχόμενο όταν το αρχείο είναι απλώς μια σαρωμένη εικόνα; Δεν είστε μόνοι. Σε πολλά πραγματικά έργα—συμβόλαια, τιμολόγια ή ιστορικά αρχεία—το PDF που λαμβάνετε δεν έχει επιλέξιμο κείμενο. Το καλό νέο; Μερικές γραμμές Python μπορούν να μετατρέψουν αυτές τις σελίδες μόνο με εικόνα σε αναζητήσιμο, επεξεργάσιμο κείμενο. + +Σε αυτό το tutorial θα περάσουμε από ένα πρακτικό **OCR Python example** που διαβάζει ένα PDF, αποδίδει την πρώτη του σελίδα ως εικόνα και στη συνέχεια **εξάγει κείμενο από PDF** χρησιμοποιώντας μια μηχανή OCR. Στο τέλος θα ξέρετε ακριβώς πώς να **διαβάσετε PDF με OCR**, γιατί κάθε βήμα είναι σημαντικό και πώς να προσαρμόσετε τον κώδικα για έγγραφα πολλαπλών σελίδων ή διαφορετικές γλώσσες. + +## Τι Θα Μάθετε + +- Εγκατάσταση και ρύθμιση μιας αξιόπιστης βιβλιοθήκης OCR για Python. +- Μετατροπή σελίδων PDF σε εικόνες κατάλληλες για OCR. +- **Αναγνώριση κειμένου από εικόνα** και λήψη καθαρών συμβολοσειρών Unicode. +- Συνηθισμένα προβλήματα (PDF χαμηλής ανάλυσης, περιστρεφόμενες σελίδες) και πώς να τα αποφύγετε. +- Επέκταση του script για διαχείριση πολλαπλών σελίδων ή μαζική επεξεργασία. + +**Προαπαιτούμενα**: Python 3.8+, pip, και βασική κατανόηση εικονικών περιβαλλόντων. Δεν απαιτείται προηγούμενη εμπειρία OCR—απλώς ακολουθήστε τα βήματα. + +--- + +## ## Πώς να εξάγετε κείμενο PDF με OCR στην Python + +Αυτή η επικεφαλίδα H2 περιέχει τη βασική μας λέξη‑κλειδί ακριβώς εκεί που τις αγαπούν οι μηχανές αναζήτησης. Ας βουτήξουμε κατευθείαν στον κώδικα. + +### Βήμα 1 – Εγκατάσταση των Απαιτούμενων Πακέτων + +Πρώτα, χρειαζόμαστε μια μηχανή OCR. Το παρακάτω παράδειγμα χρησιμοποιεί το δημοφιλές πακέτο **ocr** (μια ελαφριά επικάλυψη γύρω από το Tesseract). Αν προτιμάτε διαφορετικό backend, οι έννοιες παραμένουν οι ίδιες. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** Σε Linux, θα χρειαστείτε επίσης το εκτελέσιμο Tesseract: `sudo apt-get install tesseract-ocr`. Οι χρήστες macOS μπορούν να το εγκαταστήσουν μέσω Homebrew: `brew install tesseract`. + +### Βήμα 2 – Αρχικοποίηση της Μηχανής OCR και Ορισμός Γλώσσας + +Τώρα ξεκινάμε τη μηχανή και της λέμε να ψάξει για αγγλικούς χαρακτήρες. Μπορείτε να αντικαταστήσετε το `ocr.Language.English` με οποιονδήποτε υποστηριζόμενο κωδικό γλώσσας. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Γιατί είναι σημαντικό:** Η καθορισμένη γλώσσα βελτιώνει δραστικά την ακρίβεια, επειδή η μηχανή μπορεί να εφαρμόσει λεξικά και μοντέλα χαρακτήρων ειδικά για τη γλώσσα. + +### Βήμα 3 – Φόρτωση μιας Σελίδας PDF ως Εικόνα + +Το OCR λειτουργεί σε raster εικόνες, όχι σε αντικείμενα PDF. Η βοηθητική συνάρτηση `ocr.Image.from_pdf` αποδίδει την επιλεγμένη σελίδα σε bitmap. Προσαρμόστε το `page_number` για άλλες σελίδες (αρίθμηση από το 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** Αν το PDF περιέχει διανυσματικά γραφικά αντί για σαρωμένες εικόνες, μπορεί να λάβετε μια καθαρή απόδοση. Για σαρώσεις χαμηλής ανάλυσης, σκεφτείτε να αυξήσετε το DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Βήμα 4 – Αναγνώριση Κειμένου από την Αποδοθείσα Εικόνα + +Αυτή είναι η καρδιά του **ocr python example**. Η μηχανή επεξεργάζεται το bitmap και επιστρέφει ένα αντικείμενο που περιέχει την εξαγόμενη συμβολοσειρά. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Το χαρακτηριστικό `ocr_result.text` περιέχει το απλό‑κείμενο αποτέλεσμα, διατηρώντας τις αλλαγές γραμμής όπου είναι δυνατόν. + +### Βήμα 5 – Εκτύπωση ή Αποθήκευση του Εξαγόμενου Κειμένου + +Τέλος, εμφανίζουμε το αποτέλεσμα. Σε μια πραγματική εφαρμογή πιθανότατα θα γράψετε σε αρχείο ή βάση δεδομένων. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Η εκτέλεση του script θα πρέπει να εμφανίσει κάτι όπως: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Αυτό είναι ένα πλήρες workflow **extract text from pdf** χρησιμοποιώντας OCR. + +--- + +## ## Αναγνώριση Κειμένου από Εικόνα – Βελτιστοποίηση Ακρίβειας + +Αν σας ενδιαφέρει μόνο η **αναγνώριση κειμένου από εικόνα** (π.χ. ένα JPEG από απόδειξη), μπορείτε να παραλείψετε το βήμα μετατροπής PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Συμβουλές για καλύτερα αποτελέσματα:** + +- **Προ‑επεξεργασία** της εικόνας: μετατροπή σε γκρι, εφαρμογή κατωφλίου ή διόρθωση κλίσης. Η Pillow το κάνει εύκολα. +- **Αύξηση DPI** κατά την απόδοση PDF: υψηλότερη ανάλυση δίνει στη μηχανή OCR περισσότερες λεπτομέρειες. +- **Ενεργοποίηση ρυθμίσεων OCR** για τμηματοποίηση σελίδας (`ocr_engine.config = "--psm 6"` για ομοιόμορφα μπλοκ). + +--- + +## ## Διαβάστε PDF με OCR – Διαχείριση Πολλαπλών Σελίδων + +Τα περισσότερα συμβόλαια εκτείνονται σε πολλές σελίδες. Η επανάληψη πάνω σε κάθε σελίδα είναι απλή: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Αυτή η συνάρτηση **reads PDF with OCR**, ενώνει το αποτέλεσμα και προσθέτει έναν σαφή διαχωριστή σελίδας. Στη συνέχεια μπορείτε να τροφοδοτήσετε το `full_text` σε έναν δείκτη αναζήτησης ή να το αποθηκεύσετε ως αρχείο `.txt`. + +--- + +## ## Συνηθισμένα Προβλήματα και Πώς να Τα Διορθώσετε + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Κατεστραμμένοι χαρακτήρες, πολλά `?` | Λάθος γλώσσα ή έλλειψη αρχείων δεδομένων γλώσσας | Εγκαταστήστε το σωστό πακέτο γλώσσας Tesseract (`tesseract-ocr-`) και ορίστε `ocr_engine.language`. | +| Λείπουν γραμμές ή κομμένες λέξεις | Χαμηλό DPI (κάτω από 150) | Αποδώστε το PDF σε 300 DPI ή περισσότερο (`dpi=300`). | +| Το κείμενο είναι περιστρεφόμενο ή ανάποδο | Η σαρωμένη σελίδα δεν είναι ευθεία | Χρησιμοποιήστε `ocr.Image.deskew(page_image)` πριν την αναγνώριση. | +| Αργή επεξεργασία σε μεγάλα PDFs | Επεξεργασία σελίδων διαδοχικά σε ένα νήμα | Παράλληλη εκτέλεση με `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Επέκταση του OCR Python Example + +- **Εξαγωγή σε PDF/A**: Μετά την εξαγωγή, μπορείτε να ενσωματώσετε το κείμενο πίσω σε ένα αναζητήσιμο PDF χρησιμοποιώντας `reportlab` ή `pypdf2`. +- **Ανίχνευση γλώσσας**: Χρησιμοποιήστε `langdetect` στο αποτέλεσμα OCR για να αλλάζετε δυναμικά το `ocr_engine.language`. +- **Μαζική επεξεργασία**: Περιηγηθείτε σε έναν φάκελο με `os.listdir` και εφαρμόστε `extract_all_pages` σε κάθε αρχείο. + +--- + +## ## Αναμενόμενο Αποτέλεσμα και Επαλήθευση + +Όταν εκτελέσετε το script σε μια καθαρή σάρωση αγγλικής γλώσσας, θα πρέπει να δείτε ένα καθαρό μπλοκ κειμένου με σωστή στίξη. Επαληθεύστε: + +1. Συγκρίνοντας μερικές γραμμές με την αρχική σαρωμένη εικόνα. +2. Εκτελώντας έναν απλό υπολογισμό λέξεων (`len(ocr_result.text.split())`) για να βεβαιωθείτε ότι το αποτέλεσμα δεν είναι κενό. +3. Προαιρετικά, τροφοδοτώντας το αποτέλεσμα σε έναν ορθογραφικό ελεγκτή όπως `pyspellchecker` για να εντοπίσετε σφάλματα OCR. + +--- + +## Συμπέρασμα + +Καλύψαμε **πώς να εξάγετε PDF** περιεχόμενο όταν η παραδοσιακή ανάλυση αποτυγχάνει, παρουσιάσαμε ένα πλήρες **ocr python example**, και εξηγήσαμε πώς να **αναγνωρίσετε κείμενο από εικόνα** και να **διαβάσετε PDF με OCR** για σενάρια μονής ή πολλαπλών σελίδων. Με τα παραπάνω αποσπάσματα κώδικα μπορείτε τώρα να μετατρέψετε οποιοδήποτε σαρωμένο PDF σε αναζητήσιμο, επεξεργάσιμο κείμενο—χωρίς να χρειάζεται να πληκτρολογείτε χειροκίνητα. + +Τι θα κάνετε στη συνέχεια; Δοκιμάστε να αλλάξετε τη γλώσσα σε Ισπανικά (`ocr.Language.Spanish`) ή πειραματιστείτε με τεχνικές προ‑επεξεργασίας εικόνας για να αυξήσετε την ακρίβεια. Αν χτίζετε σύστημα διαχείρισης εγγράφων, σκεφτείτε να ευρετηριάσετε το εξαγόμενο κείμενο με Elasticsearch για αστραπιαία αναζήτηση. + +Έχετε ερωτήσεις ή αντιμετωπίζετε κάποιο ιδιότροπο PDF; Αφήστε ένα σχόλιο, και καλή προγραμματιστική δουλειά! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + + +## Τι Θα Μάθετε Στη Σειρά Επόμενη; + +Οι παρακάτω οδηγίες καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε επιπλέον δυνατότητες 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/greek/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..2ecaadd56 --- /dev/null +++ b/ocr/greek/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-06-19 +description: Μάθετε πώς να χρησιμοποιείτε OCR στη Java με την Aspose. Αυτός ο οδηγός + βήμα‑βήμα καλύπτει την αυτόματη διόρθωση κλίσης εικόνων, την αυτόματη ανίχνευση + γλώσσας και την εύκολη εξαγωγή κειμένου από εικόνα. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: el +og_description: 'Πώς να χρησιμοποιήσετε OCR σε Java με Aspose: ένας πλήρης οδηγός + που καλύπτει την αυτόματη διόρθωση κλίσης εικόνων, την αυτόματη ανίχνευση γλώσσας + και την εξαγωγή κειμένου από εικόνες.' +og_title: Πώς να χρησιμοποιήσετε OCR σε Java με το Aspose – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Πώς να χρησιμοποιήσετε OCR στη Java με το Aspose – Πλήρης οδηγός +url: /el/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Χρησιμοποιήσετε OCR σε Java με το Aspose – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ **πώς να χρησιμοποιήσετε OCR** σε ένα έργο Java χωρίς να τρελαίνεστε με τη διαμόρφωση; Δεν είστε μόνοι. Πολλοί προγραμματιστές συναντούν πρόβλημα όταν χρειάζεται να **εξάγουν κείμενο από εικόνα** γρήγορα, ειδικά όταν οι σάρωση είναι στραβές ή γραμμένες σε άγνωστη γλώσσα. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα ένα πρακτικό παράδειγμα που δείχνει ακριβώς πώς να χρησιμοποιήσετε OCR με το Aspose, συμπεριλαμβανομένων των **auto deskew images**, **auto language detection**, και ολόκληρης της **ocr image preprocessing** αλυσίδας. Στο τέλος θα έχετε ένα έτοιμο κομμάτι κώδικα που εκτυπώνει το αναγνωρισμένο κείμενο στην κονσόλα, και θα καταλάβετε γιατί κάθε ρύθμιση είναι σημαντική. + +> **Τι θα πάρετε:** ένα πλήρες, εκτελέσιμο πρόγραμμα Java, εξηγήσεις για κάθε γραμμή, συμβουλές για τη διαχείριση ειδικών περιπτώσεων, και ιδέες για την επέκταση της λύσης σε επεξεργασία παρτίδων ή PDFs. + +--- + +## Προαπαιτούμενα + +- Java 17 (ή οποιοδήποτε πρόσφατο JDK) εγκατεστημένο και διαμορφωμένο. +- Maven ή Gradle για διαχείριση εξαρτήσεων (θα δείξουμε τις συντεταγμένες Maven). +- Αρχείο άδειας Aspose OCR for Java (`Aspose.OCR.Java.lic`). Αν κάνετε μόνο δοκιμές, μπορείτε να παραλείψετε το βήμα της άδειας, αλλά η δωρεάν δοκιμή θα προσθέσει υδατογράφημα. +- Ένα δείγμα εικόνας (`your_image.png`) τοποθετημένο κάπου προσβάσιμο από τον κώδικα. + +> **Pro tip:** κρατήστε τις εικόνες σας σε έναν αφιερωμένο φάκελο `resources` και φορτώστε τις μέσω του classpath· αποφεύγει προβλήματα με διαδρομές σε διαφορετικά λειτουργικά συστήματα. + +## Βήμα 1: Ρύθμιση του Έργου και Προσθήκη της Εξάρτησης Aspose OCR + +Δημιουργήστε ένα νέο Maven project (ή χρησιμοποιήστε το υπάρχον) και προσθέστε τα παρακάτω στο `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Τρέξτε `mvn clean install` για να κατεβάσετε τη βιβλιοθήκη. Αν προτιμάτε Gradle, το ισοδύναμο είναι: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Τώρα έχετε τις κλάσεις **ocr image preprocessing** στο classpath σας. + +## Βήμα 2: Εφαρμογή της Άδειας Aspose OCR (Προαιρετικό αλλά Συνιστάται) + +Αν διαθέτετε άδεια, εφαρμόστε την αμέσως στην αρχή της μεθόδου `main`. Η παράλειψη αυτού του βήματος λειτουργεί, αλλά η δωρεάν έκδοση προσθέτει υδατογράφημα “Demo” στην έξοδο. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Γιατί είναι σημαντικό:** Η έκδοση με άδεια αφαιρεί τα όρια χρήσης και απενεργοποιεί το υδατογράφημα, παρέχοντάς σας καθαρά, έτοιμα για παραγωγή αποτελέσματα. + +## Βήμα 3: Δημιουργία του Αντικειμένου OCR Engine + +Η μηχανή είναι η καρδιά της διαδικασίας. Η δημιουργία της σας δίνει πρόσβαση σε όλες τις επιλογές **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Σε αυτό το σημείο η μηχανή είναι έτοιμη, αλλά θα χρησιμοποιήσει τις προεπιλεγμένες ρυθμίσεις που μπορεί να μην είναι βέλτιστες για σαρωμένα έγγραφα. Ας κάνουμε μερικές προσαρμογές. + +## Βήμα 4: Ενεργοποίηση του Auto Deskew Images για Καθαρές Σαρώσεις + +Οι στραβές σαρώσεις είναι ένα κοινό πρόβλημα. Το Aspose παρέχει τη λειτουργία **auto deskew images** που ευθυγραμμίζει αυτόματα την εικόνα πριν από την αναγνώριση. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Πώς λειτουργεί:** Ο αλγόριθμος αναλύει τις γωνίες της βάσης του κειμένου και περιστρέφει την εικόνα στην πιο πιθανή όρθια προσανατολισμό. Αυτό βελτιώνει δραστικά την ακρίβεια για φωτογραφίες που τραβήχτηκαν με το τηλέφωνο. + +## Βήμα 5: Ενεργοποίηση του Auto Language Detection + +Αν δεν γνωρίζετε τη γλώσσα της πηγαίας εικόνας, αφήστε τη μηχανή να το προσδιορίσει. Αυτή είναι η ρύθμιση **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Όταν την ενεργοποιήσετε, το Aspose εξετάζει τα γλύφια και επιλέγει το πιο πιθανό μοντέλο γλώσσας, υποστηρίζοντας πάνω από 30 γλώσσες έτοιμες για χρήση. + +## Βήμα 6: Φόρτωση της Εικόνας που Θέλετε να Αναγνωρίσετε + +Μπορείτε να φορτώσετε μια εικόνα από δίσκο, URL ή ακόμη και από byte array. Για απλότητα, θα διαβάσουμε από ένα τοπικό αρχείο. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Συμβουλή:** Αν δουλεύετε με μεγάλες εικόνες, σκεφτείτε να τις υποδειγματοποιήσετε πρώτα με `engine.getImagePreprocessing().setResizeFactor(0.5)` για να επιταχύνετε την επεξεργασία χωρίς μεγάλη απώλεια λεπτομέρειας. + +## Βήμα 7: Εκτέλεση OCR Αναγνώρισης και Εξαγωγή Κειμένου από Εικόνα + +Τώρα η μηχανή κάνει τη μαγεία της. Η μέθοδος `recognize` επιστρέφει ένα αντικείμενο `OcrResult` που περιέχει το αναγνωρισμένο κείμενο, βαθμολογίες εμπιστοσύνης και άλλα. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Η κονσόλα θα εμφανίσει το απλό κείμενο που εξήχθη από την εικόνα—αυτό είναι το κύριο αποτέλεσμα **extract text image** που θέλαμε να πετύχουμε. + +## Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω βρίσκεται η πλήρης κλάση Java που ενώνει όλα τα παραπάνω. Αντιγράψτε‑και‑επικολλήστε την στο `src/main/java/com/example/OcrDemo.java` και τρέξτε την. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Αναμενόμενη Έξοδος + +Αν η εικόνα περιέχει τη φράση “Hello World” σε καθαρή σάρωση, θα δείτε: + +``` +=== Recognized Text === +Hello World +``` + +Για πιο σύνθετα έγγραφα (π.χ. πολύγλωσσες αποδείξεις), η έξοδος θα περιλαμβάνει αλλαγές γραμμής και τον κωδικό της ανιχνευμένης γλώσσας. + +## Συχνά Προβλήματα & Pro Συμβουλές + +| Πρόβλημα | Γιατί Συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **Αχρείαστοι χαρακτήρες** | Η εικόνα είναι πολύ σκοτεινή ή θορυβώδης. | Ενεργοποιήστε `engine.getImagePreprocessing().setBinarization(true)` ή ρυθμίστε το contrast χειροκίνητα. | +| **Λάθος γλώσσα** | Η αυτόματη ανίχνευση αποτυγχάνει σε σελίδες με πολλαπλές γλώσσες. | Ορίστε `engine.setLanguage(Language.English)` (ή το κατάλληλο enum) για να επιβάλετε συγκεκριμένη γλώσσα. | +| **Αργή επεξεργασία** | Πολύ υψηλή ανάλυση εικόνων. | Μειώστε την ανάλυση με `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Σφάλματα έλλειψης μνήμης** | Μεγάλη δέσμη εικόνων φορτώνεται ταυτόχρονα. | Επεξεργαστείτε τις εικόνες διαδοχικά και καλέστε `engine.dispose()` μετά από κάθε εκτέλεση. | + +> **Θυμηθείτε:** Η μηχανή OCR είναι thread‑safe για λειτουργίες μόνο ανάγνωσης, αλλά η δημιουργία νέας παρουσίας ανά νήμα αποφεύγει κρυφά σφάλματα κατάστασης. + +## Επέκταση της Λύσης + +Τώρα που ξέρετε **πώς να χρησιμοποιήσετε OCR** με το Aspose, ίσως θέλετε να: + +1. **Επεξεργασία PDFs** – Μετατρέψτε κάθε σελίδα PDF σε εικόνα (`PdfConverter`) και τροφοδοτήστε την στην ίδια αλυσίδα. +2. **Επεξεργασία παρτίδας φακέλου** – Περιηγηθείτε στα αρχεία ενός καταλόγου, εφαρμόζοντας τα ίδια βήματα, και γράψτε τα αποτελέσματα σε CSV. +3. **Ενσωμάτωση με web service** – Εκθέστε τη λογική OCR μέσω ενός Spring Boot `@RestController` που δέχεται multipart uploads. + +Όλα αυτά τα σενάρια επαναχρησιμοποιούν την ίδια διαμόρφωση **ocr image preprocessing** που δημιουργήσαμε εδώ. + +## Συμπέρασμα + +Καλύψαμε **πώς να χρησιμοποιήσετε OCR** σε Java με το Aspose από την αρχή μέχρι το τέλος: εφαρμογή άδειας, δημιουργία μηχανής, ενεργοποίηση **auto deskew images**, ενεργοποίηση **auto language detection**, φόρτωση εικόνας, και τελικά **extract text image** με ένα μόνο `System.out.println`. Ο κώδικας είναι πλήρως αυτόνομος, τρέχει σε οποιοδήποτε πρόσφατο JDK και δείχνει τις βέλτιστες πρακτικές για ακρίβεια και απόδοση. + +Δοκιμάστε το με τις δικές σας εικόνες—ίσως μια σαρωμένη σύμβαση ή ένα στιγμιότυπο από απόδειξη. Ρυθμίστε τις σημαίες preprocessing, πειραματιστείτε με διαφορετικές γλώσσες, και θα δείτε γρήγορα γιατί η βιβλιοθήκη OCR του Aspose είναι μια αξιόπιστη επιλογή για παραγωγική εξαγωγή κειμένου. + +Έχετε ερωτήσεις ή θέλετε να μοιραστείτε τα αποτελέσματά σας; Αφήστε ένα σχόλιο παρακάτω ή στείλτε μου μήνυμα στο GitHub. Καλό κώδικα! + +--- + +![Παράδειγμα χρήσης OCR σε Java](/images/ocr-java-example.png "Πώς να χρησιμοποιήσετε OCR σε Java – Aspose demo screenshot") + +## Τι Θα Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική; + +Οι παρακάτω οδηγίες καλύπτουν στενά σχετικές θεματικές που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να OCR Κείμενο Εικόνας με Γλώσσα Χρησιμοποιώντας Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Εξαγωγή Κειμένου από Εικόνα Java με Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Πώς να Χρησιμοποιήσετε OCR - Προχωρημένες Τεχνικές με Aspose.OCR για Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/greek/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..72eeb0f72 --- /dev/null +++ b/ocr/greek/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-06-19 +description: Βελτιώστε την ακρίβεια OCR στην Python χρησιμοποιώντας το Aspose OCR. + Μάθετε πώς να ορίσετε τη γλώσσα OCR, να φορτώσετε εικόνα για OCR και να εξάγετε + κείμενο από την εικόνα με ένα προσαρμοσμένο λεξικό. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: el +og_description: Βελτιώστε την ακρίβεια OCR στην Python ορίζοντας τη γλώσσα OCR, φορτώνοντας + μια εικόνα για OCR και εξάγοντας κείμενο από την εικόνα με προσαρμοσμένο λεξικό. +og_title: Βελτιώστε την ακρίβεια OCR στην Python – Οδηγός βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Βελτιώστε την ακρίβεια OCR σε Python – Πλήρης οδηγός +url: /el/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Βελτιώστε την Ακρίβεια OCR σε Python – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ πώς να **βελτιώσετε την ακρίβεια OCR** όταν το κείμενο που σαρώνετε περιέχει παράξενα σύμβολα, κωδικούς προϊόντων ή ονόματα εμπορικών σημάτων; Δεν είστε μόνοι. Σε πολλά έργα η προεπιλεγμένη μηχανή παράγει ακατανόητο κείμενο, και αυτό είναι πραγματικός περιορισμός παραγωγικότητας. + +Σε αυτό το tutorial θα περάσουμε από ένα πρακτικό, ολοκληρωμένο παράδειγμα που σας δείχνει πώς να **ορίσετε τη γλώσσα OCR**, **φορτώσετε εικόνα για OCR**, **εκτελέσετε OCR στην εικόνα**, και τέλος **εξάγετε κείμενο από την εικόνα** με ένα προσαρμοσμένο λεξικό που αυξάνει τα ποσοστά αναγνώρισης. Στο τέλος θα έχετε ένα έτοιμο προς εκτέλεση script που μπορείτε να ενσωματώσετε σε οποιαδήποτε βάση κώδικα Python. + +## Τι Θα Αποκομίσετε + +- Ένα πλήρως λειτουργικό script Python που χρησιμοποιεί το Aspose OCR για ανάγνωση αρχείου PNG. +- Τη δυνατότητα να **βελτιώσετε την ακρίβεια OCR** διαμορφώνοντας τη γλώσσα και μια προσαρμοσμένη λίστα λέξεων. +- Σαφείς εξηγήσεις για το γιατί κάθε ρύθμιση είναι σημαντική, καθώς και συμβουλές για την αντιμετώπιση ειδικών περιπτώσεων όπως μη‑λατινικοί χαρακτήρες. +- Μια γρήγορη λίστα ελέγχου για την αντιμετώπιση κοινών προβλημάτων OCR. + +### Προαπαιτούμενα + +- Python 3.8 ή νεότερο εγκατεστημένο στο μηχάνημά σας. +- Πακέτο `aspose-ocr` (εγκατάσταση μέσω `pip install aspose-ocr`). +- Ένα δείγμα εικόνας (`technical_doc.png`) που περιέχει το κείμενο που θέλετε να διαβάσετε. +- Βασική εξοικείωση με την Python — δεν απαιτείται τίποτα περίπλοκο. + +> **Pro tip:** Εάν εργάζεστε σε εικονικό περιβάλλον, ενεργοποιήστε το πριν εγκαταστήσετε το πακέτο. Διατηρεί τις εξαρτήσεις σας οργανωμένες και αποτρέπει συγκρούσεις εκδόσεων. + +## Βήμα 1: Εγκατάσταση και Εισαγωγή του Aspose OCR + +Πρώτα απ' όλα—ας προσθέσουμε τη βιβλιοθήκη στο περιβάλλον μας και να εισάγουμε τα στοιχεία που χρειαζόμαστε. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Το namespace `aspose.ocr` σας δίνει πρόσβαση στην κλάση `OcrEngine`, η οποία αποτελεί την καρδιά της διαδικασίας OCR. Η εισαγωγή της εδώ διατηρεί το υπόλοιπο script καθαρό και ευανάγνωστο. + +## Βήμα 2: Δημιουργία Μηχανής OCR και **Ορισμός Γλώσσας OCR** + +Γιατί είναι σημαντική η γλώσσα; Οι μηχανές OCR βασίζονται σε μοντέλα ειδικά για κάθε γλώσσα ώστε να αναγνωρίζουν τα σχήματα των χαρακτήρων και τα πρότυπα λέξεων. Εάν πείτε στη μηχανή ότι σαρώνετε αγγλικό κείμενο, θα αγνοήσει τα κυριλλικά σύμβολα και θα εστιάσει στο λατινικό αλφάβητο, βελτιώνοντας δραστικά την **ακρίβεια OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Note:** Το Aspose OCR υποστηρίζει πάνω από 50 γλώσσες. Αντικαταστήστε το `ocr.Language.English` με `ocr.Language.Spanish`, `ocr.Language.French`, κ.λπ., εάν το έγγραφό σας δεν είναι αγγλικό. + +## Βήμα 3: Ορισμός **Προσαρμοσμένου Λεξικού** για Βελτίωση της Ακρίβειας + +Φανταστείτε ότι σαρώνετε τιμολόγια που περιέχουν τη λέξη “AsposeOCR” ή κωδικούς προϊόντων όπως “SKU12345”. Η μηχανή δεν γνωρίζει αυτούς τους όρους, οπότε κάνει λανθασμένες εικασίες. Η παροχή μιας προσαρμοσμένης λίστας λέξεων λέει στη μηχανή, *«Εντάξει, αυτές οι ακολουθίες είναι έγκυρες—μην προσπαθήσετε να τις διορθώσετε»*. Αυτό είναι ένα γρήγορο κέρδος για **βελτίωση της ακρίβειας OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Μπορείτε να φορτώσετε αυτή τη λίστα από αρχείο ή βάση δεδομένων εάν έχετε εκατοντάδες καταχωρήσεις—απλώς κρατήστε την σε μια λίστα Python για απλότητα. + +## Βήμα 4: **Φόρτωση Εικόνας για OCR** + +Τώρα χρειαζόμαστε μια εικόνα. Η μέθοδος `Image.load` δέχεται διαδρομή προς οποιαδήποτε υποστηριζόμενη μορφή raster (PNG, JPEG, BMP, κ.λπ.). Εάν το αρχείο δεν βρεθεί, η μηχανή ρίχνει εξαίρεση, οπότε θα το προστατεύσουμε. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Γιατί αυτό το βήμα είναι σημαντικό:** Η σωστή φόρτωση της εικόνας εξασφαλίζει ότι η μηχανή εργάζεται με τα ακριβή δεδομένα pixel που σκοπεύετε να αναλύσετε. Τα κατεστραμμένα αρχεία ή οι λανθασμένες διαδρομές είναι κοινή πηγή απογοήτευσης. + +## Βήμα 5: **Εκτέλεση OCR στην Εικόνα** και Εξαγωγή Αποτελεσμάτων + +Με τη μηχανή διαμορφωμένη και την εικόνα έτοιμη, η πραγματική αναγνώριση είναι μια κλήση μεθόδου. Το αντικείμενο αποτελέσματος περιέχει το ακατέργαστο κείμενο, τις βαθμολογίες εμπιστοσύνης και ακόμη πληροφορίες διάταξης εάν τις χρειαστείτε αργότερα. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Εάν χρειάζεστε να **εξάγετε κείμενο από την εικόνα** γραμμή προς γραμμή, μπορείτε να χωρίσετε με χαρακτήρες νέας γραμμής: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +## Βήμα 6: Επαλήθευση του Αποτελέσματος – Βελτιώνει Πραγματικά την **Ακρίβεια OCR**; + +Ας εκτυπώσουμε το αποτέλεσμα και να δούμε αν το προσαρμοσμένο λεξικό μας έκανε διαφορά. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Η τυπική έξοδος για το δείγμα εικόνας μπορεί να φαίνεται ως εξής: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Παρατηρήστε πώς το όνομα της μάρκας, ο ελληνικός χαρακτήρας και ο κωδικός προϊόντος εμφανίζονται ακριβώς όπως τα ορίσαμε. Χωρίς το προσαρμοσμένο λεξικό, η μηχανή θα προσπαθούσε να τα «διορθώσει», συχνά παράγοντας κάτι όπως “Aspose OCR” ή “SKU 1234”. + +## Συνηθισμένα Προβλήματα & Πώς να τα Αντιμετωπίσετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|-------|----------------|-----| +| **Χαρακτήρες σκουπίδας** | Λάθος γλώσσα ή εικόνα χαμηλής ανάλυσης | Βεβαιωθείτε ότι `engine.language` ταιριάζει με τη γλώσσα προέλευσης και χρησιμοποιήστε σάρωση υψηλής ανάλυσης (300 dpi ή περισσότερο). | +| **Παράβλεψη προσαρμοσμένων λέξεων** | Το λεξικό δεν έχει προσαρτηθεί ή υπάρχει τυπογραφικό λάθος στο όνομα ιδιότητας | Ελέγξτε ξανά `engine.text_processing.custom_dictionary = …`. | +| **Αρχείο δεν βρέθηκε** | Λάθος διαδρομή ή έλλειψη δικαιωμάτων αρχείου | Χρησιμοποιήστε `os.path.abspath()` για να επαληθεύσετε την απόλυτη διαδρομή· εκτελέστε το script με τα κατάλληλα δικαιώματα. | +| **Αργή επεξεργασία** | Μεγάλες εικόνες ή πολλές σελίδες | Προεπεξεργαστείτε την εικόνα (κόψιμο, αλλαγή μεγέθους) ή χρησιμοποιήστε `engine.recognize(image, max_threads=4)` για παράλληλη εκτέλεση. | + +## Προχωρώντας Περαιτέρω: Προηγμένες Ρυθμίσεις για **Βελτίωση της Ακρίβειας OCR** + +1. **Προεπεξεργασία** – Εφαρμόστε ενίσχυση αντίθεσης ή δυαδικοποίηση με το Pillow πριν περάσετε την εικόνα στο Aspose OCR. +2. **Πολλαπλές Γλώσσες** – Ορίστε `engine.language = ocr.Language.English | ocr.Language.French` για ενεργοποίηση διγλωσσίας. +3. **OCR βάσει Περιοχής** – Εάν χρειάζεστε μόνο μια συγκεκριμένη περιοχή (π.χ., έναν πίνακα), κόψτε πρώτα την εικόνα για να μειώσετε το θόρυβο. +4. **Φιλτράρισμα Εμπιστοσύνης** – `result.confidence` παρέχει βαθμολογία ανά χαρακτήρα· μπορείτε να απορρίψετε αποτελέσματα χαμηλής εμπιστοσύνης προγραμματιστικά. + +## Πλήρες Λειτουργικό Script + +Παρακάτω βρίσκεται το πλήρες, έτοιμο για αντιγραφή script που ενσωματώνει κάθε βήμα που συζητήσαμε. Αποθηκεύστε το ως `improve_ocr_accuracy.py` και εκτελέστε το από τη γραμμή εντολών. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Τρέξτε το: + +```bash +python improve_ocr_accuracy.py +``` + +Θα πρέπει να δείτε την ωραία μορφοποιημένη έξοδο που εμφανίσαμε νωρίτερα. + +## Συμπέρασμα + +Μόλις καλύψαμε έναν απλό τρόπο για **βελτίωση της ακρίβειας OCR** σε Python μέσω: + +1. **Ορισμός της γλώσσας OCR** ώστε να ταιριάζει με το έγγραφό σας. +2. **Σωστή φόρτωση της εικόνας** ώστε η μηχανή να βλέπει τα σωστά pixel. +3. **Εκτέλεση OCR στην εικόνα** με μία κλήση μεθόδου. +4. **Εξαγωγή κειμένου από την εικόνα** και επιβεβαίωση του αποτελέσματος. +5. **Προσθήκη προσαρμοσμένου λεξικού** για να κλειδώσετε όρους ειδικού τομέα. + +Αυτή είναι η πλήρης ροή εργασίας—από ακατέργαστη εικόνα σε καθαρό, αναζητήσιμο κείμενο—συσκευασμένη σε ένα τακτοποιημένο, επαναχρησιμοποιήσιμο script. + +Εάν είστε έτοιμοι για την επόμενη πρόκληση, δοκιμάστε πειραματισμό με προεπεξεργασία εικόνας (αντίθεση, διόρθωση κλίσης) ή μεταβείτε σε πολυγλωσσική ρύθμιση χρησιμοποιώντας `ocr.Language.English | ocr.Language.German`. Οι ίδιες αρχές ισχύουν, και θα συνεχίσετε να **βελτιώνετε την ακρίβεια OCR** σε ένα ευρύτερο σύνολο εγγράφων. + +Έχετε ερωτήσεις ή κάποιο περίεργο σενάριο; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +![improve OCR accuracy + + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή Κειμένου από Εικόνα – Βελτιστοποίηση OCR με Aspose.OCR για .NET](/ocr/english/net/ocr-optimization/) +- [αναγνώριση κειμένου εικόνας με Aspose OCR για πολλές γλώσσες](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Πώς να Ορίσετε Τιμή Κατωφλίου στην Αναγνώριση Εικόνας OCR](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/greek/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..e42d5a24d --- /dev/null +++ b/ocr/greek/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Εκτελέστε OCR σε εικόνα χρησιμοποιώντας τη βιβλιοθήκη OCR της Python. + Μάθετε πώς να εντοπίζετε κείμενο από εικόνα, να αναγνωρίζετε κείμενο από JPEG και + να εξάγετε κείμενο από σαρωμένη εικόνα αποδοτικά. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: el +og_description: Κάντε OCR σε εικόνα με Python και εξάγετε κείμενο από σαρωμένα αρχεία. + Αυτός ο οδηγός σας καθοδηγεί βήμα‑βήμα στη φόρτωση εικόνων, την αποκλίση και την + αναγνώριση κειμένου. +og_title: Εκτέλεση OCR σε εικόνα με Python – Οδηγός πλήρους εξαγωγής κειμένου +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Εκτέλεση OCR σε εικόνα με Python – Οδηγός πλήρους εξαγωγής κειμένου +url: /el/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εκτέλεση OCR σε Εικόνα με Python – Οδηγός Πλήρους Εξαγωγής Κειμένου + +Κάποτε χρειάστηκε να **εκτελέσετε OCR σε εικόνα** αλλά αντιμετωπίζατε δυσκολίες επειδή ο κώδικας φαινόταν κρυπτογραφημένος; Δεν είστε ο μόνος. Είτε μετατρέπετε μια στοίβα σαρωμένων αποδείξεων σε αναζητήσιμα PDF, είτε εξάγετε λεζάντες από ένα JPEG για ένα έργο επιστήμης δεδομένων, η ικανότητα να αναγνωρίζετε κείμενο από JPEG και άλλες μορφές είναι απαραίτητη δεξιότητα για κάθε προγραμματιστή σήμερα. + +Σε αυτό το tutorial θα περάσουμε από ένα πλήρες, εκτελέσιμο παράδειγμα που δείχνει πώς να **ανιχνεύσετε κείμενο από εικόνα**, **εξάγετε κείμενο από σαρωμένο έγγραφο** και ακόμη **φορτώσετε εικόνα για OCR** σε λίγες μόνο γραμμές κώδικα. Στο τέλος, θα έχετε ένα σταθερό, έτοιμο για παραγωγή snippet που μπορείτε να ενσωματώσετε στα δικά σας έργα — χωρίς ελλιπείς εισαγωγές, χωρίς ασαφείς συντομεύσεις «δείτε τα docs». + +## Τι Θα Δημιουργήσετε + +- Ένα μικρό script Python που δημιουργεί μια μηχανή OCR, ενεργοποιεί το auto‑deskew, φορτώνει ένα JPEG (ή οποιαδήποτε υποστηριζόμενη μορφή) και εκτυπώνει το αναγνωρισμένο κείμενο. +- Επεξηγήσεις του **γιατί** κάθε ρύθμιση είναι σημαντική, όχι μόνο του **πώς** να την γράψετε. +- Συμβουλές για διαχείριση πολυ‑σελίδων PDF, μη‑αγγλικών γλωσσών και κοινών παγίδων όπως θολές σάρωση. + +### Προαπαιτούμενα + +- Python 3.8+ εγκατεστημένο (το παράδειγμα χρησιμοποιεί το πακέτο `ocr` διαθέσιμο μέσω `pip install ocr-lib` – αντικαταστήστε το με το πραγματικό όνομα της βιβλιοθήκης σας). +- Βασική εξοικείωση με συναρτήσεις Python και εικονικά περιβάλλοντα. +- Ένα αρχείο εικόνας (JPEG, PNG, TIFF) που θέλετε να επεξεργαστείτε· θα χρησιμοποιήσουμε το `skewed_page.jpg` ως παράδειγμα. + +> **Pro tip:** Αν χρησιμοποιείτε Windows, εκτελέστε το τερματικό σας ως Administrator όταν εγκαθιστάτε τη βιβλιοθήκη OCR για να αποφύγετε προβλήματα δικαιωμάτων. + +--- + +## Εκτέλεση OCR σε Εικόνα – Ρύθμιση και Διαμόρφωση + +Το πρώτο που χρειάζεστε είναι μια καθαρή παρουσία μηχανής OCR. Σκεφτείτε το ως τον εγκέφαλο πίσω από τη λειτουργία· χωρίς σωστή διαμόρφωση, ακόμη και η πιο καθαρή εικόνα θα επιστρέψει ακατανόητο κείμενο. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Γιατί είναι σημαντικό:** +Η ρύθμιση `engine.language` περιορίζει το σύνολο χαρακτήρων που αναμένει η μηχανή OCR, αυξάνοντας δραματικά την ακρίβεια. Αν το παραλείψετε, η μηχανή θα προσπαθήσει να μαντέψει, συχνά διαβάζοντας λανθασμένα απλές λέξεις. + +--- + +## Ενεργοποίηση Αυτόματου Deskew – Διόρθωση Κεκλιμένων Σαρώσεων + +Οι σαρωμένες σελίδες σπάνια είναι τέλεια επίπεδες. Μία μικρή κλίση μπορεί να διαταράξει τη διαχωριστική διαδικασία χαρακτήρων, μετατρέποντας το “Hello” σε “H3llo”. Η σημαία `auto_deskew` κάνει το σκληρό έργο για εσάς. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Ακραία περίπτωση:** Αν γνωρίζετε ότι οι εικόνες σας είναι ήδη ευθείες, η απενεργοποίηση του deskew μπορεί να εξοικονομήσει μερικά χιλιοστά του δευτερολέπτου χρόνο επεξεργασίας — χρήσιμο όταν διαχειρίζεστε χιλιάδες σελίδες σε batch job. + +--- + +## Φόρτωση Εικόνας για OCR – Υποστήριξη JPEG, PNG, TIFF + +Τώρα φορτώνουμε πραγματικά **εικόνα για OCR**. Η μέθοδος `ocr.Image.load` είναι ευέλικτη· δέχεται διαδρομή προς οποιαδήποτε υποστηριζόμενη μορφή raster. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Γιατί αυτό το βήμα είναι κρίσιμο:** Η βιβλιοθήκη διαβάζει το αρχείο σε ένα εσωτερικό bitmap, εφαρμόζοντας τυχόν απαραίτητη μετατροπή χρωματικού χώρου. Η παράλειψη αυτού και η μετάδοση ενός ακατέργαστου ρεύματος bytes θα προκαλούσε `FileNotFoundError` ή, χειρότερα, θα παρήγαγε σιωπηλά κενά αποτελέσματα. + +Αν χρειάζεται να **αναγνωρίσετε κείμενο από JPEG** αρχεία συγκεκριμένα, απλώς βεβαιωθείτε ότι η επέκταση του αρχείου είναι `.jpeg` ή `.jpg`. Η ίδια κλήση λειτουργεί για PNG (`.png`) ή TIFF (`.tif`) χωρίς τροποποίηση. + +--- + +## Εκτέλεση OCR σε Εικόνα – Εκτέλεση της Μηχανής + +Με τη μηχανή έτοιμη και την εικόνα στη μνήμη, ήρθε η ώρα να **εκτελέσετε OCR σε εικόνα**. Αυτή η μοναδική γραμμή κάνει το σκληρό έργο: προεπεξεργασία, διαχωρισμό, ταξινόμηση και συναρμολόγηση κειμένου. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Τι συμβαίνει στο παρασκήνιο;** +- Η μηχανή εφαρμόζει τη μεταστροφή deskew (αν είναι ενεργοποιημένη). +- Εκτελεί ένα νευρωνικό δίκτυο ή backend Tesseract για την ταυτοποίηση χαρακτήρων. +- Τέλος, ενώνει τους χαρακτήρες σε λέξεις και γραμμές, επιστρέφοντας ένα πλούσιο αντικείμενο `result`. + +--- + +## Εξαγωγή Κειμένου από Σαρωμένη Εικόνα – Εμφάνιση Αποτελεσμάτων + +Το τελευταίο βήμα είναι να **εξάγετε κείμενο από σαρωμένη εικόνα** και να το εμφανίσετε. Το χαρακτηριστικό `result.text` περιέχει την αναπαράσταση plain‑text. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Τυπική έξοδος μοιάζει με: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Αν η μηχανή OCR δεν βρει κανέναν χαρακτήρα, το `result.text` θα είναι κενή συμβολοσειρά. Σε αυτήν την περίπτωση, ελέγξτε ξανά την ποιότητα της εικόνας ή σκεφτείτε να προσαρμόσετε την ιδιότητα `engine.confidence_threshold` (αν η βιβλιοθήκη σας το υποστηρίζει). + +--- + +## Διαχείριση Συνηθισμένων Παραλλαγών + +### Αναγνώριση Κειμένου από JPEG vs PNG + +Και οι δύο μορφές υποστηρίζονται, αλλά η συμπίεση JPEG μπορεί να εισάγει τεχνουργήματα που μπερδεύουν τη μηχανή. Αν παρατηρήσετε συχνές λανθασμένες αναγνώσεις, δοκιμάστε πρώτα να μετατρέψετε το JPEG σε PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Ανίχνευση Κειμένου από Εικόνα με Πολλαπλές Γλώσσες + +Αν το έγγραφό σας συνδυάζει Αγγλικά και Ισπανικά, ορίστε λειτουργία πολυγλωσσίας: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Η μηχανή θα λάβει υπόψη και τα δύο αλφάβητα κατά την αναγνώριση. + +### Εξαγωγή Κειμένου από Σαρωμένα PDFs + +Για PDFs, πρέπει πρώτα να rasterize κάθε σελίδα σε εικόνα. Βιβλιοθήκες όπως η `pdf2image` κάνουν αυτή τη διαδικασία απλή: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω βρίσκεται το πλήρες script που μπορείτε να αντιγράψετε‑επικολλήσετε σε ένα αρχείο `ocr_demo.py`. Περιλαμβάνει διαχείριση σφαλμάτων και έναν μικρό βοηθό για μέτρηση χρόνου εκτέλεσης. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Αναμενόμενη έξοδος** (υπόθεση καθαρού σκαναρίσματος): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Συχνές Ερωτήσεις + +**Ε: Μπορώ να τρέξω αυτό σε headless server;** +Α: Απόλυτα. Η βιβλιοθήκη λειτουργεί χωρίς GUI· απλώς βεβαιωθείτε ότι τα απαραίτητα εγγενή binaries (π.χ., Tesseract) είναι εγκατεστημένα στον server. + +**Ε: Τι γίνεται αν η εικόνα είναι θολή;** +Α: Σκεφτείτε να προσθέσετε φίλτρο sharpening πριν από το `engine.recognize`. Πολλές βιβλιοθήκες OCR εκθέτουν `image_preprocessing.sharpen = True` ή μπορείτε να χρησιμοποιήσετε το `cv2.GaussianBlur` του OpenCV αντίστροφα. + +**Ε: Υποστηρίζει το script επεξεργασία παρτίδας;** +Α: Ναι. Τυλίξτε το `perform_ocr` σε βρόχο πάνω σε μια λίστα διαδρομών αρχείων, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/greek/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..9de74fa97 --- /dev/null +++ b/ocr/greek/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-06-19 +description: Πραγματοποιήστε OCR σε εικόνα χρησιμοποιώντας το Aspose OCR Java. Μάθετε + πώς να φορτώνετε εικόνα για OCR, να χρησιμοποιείτε την άδεια Aspose και να εξάγετε + κείμενο από την εικόνα σε λίγα λεπτά. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: el +og_description: Εκτελέστε OCR σε εικόνα με το Aspose OCR Java. Αυτός ο οδηγός δείχνει + πώς να χρησιμοποιήσετε την άδεια Aspose, να φορτώσετε εικόνα για OCR και να εξάγετε + κείμενο από την εικόνα αποδοτικά. +og_title: Εκτελέστε OCR σε εικόνα με το Aspose OCR Java – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Εκτελέστε OCR σε εικόνα με το Aspose OCR Java – Πλήρης οδηγός βήμα‑προς‑βήμα +url: /el/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Διεκπεραίωση OCR σε Εικόνα με Aspose OCR Java – Πλήρης Οδηγός Βήμα‑βήμα + +Έχετε ποτέ χρειαστεί να **perform OCR on image** αρχεία αλλά δεν ήσασταν σίγουροι ποια βιβλιοθήκη θα σας δώσει αξιόπιστα αποτελέσματα χωρίς άφθονη διαμόρφωση; Δεν είστε μόνοι. Σε πολλά πραγματικά έργα—σκεφτείτε τη σάρωση διαβατηρίων, την ψηφιοποίηση τιμολογίων ή την εξαγωγή κειμένου από στιγμιότυπα—η δυνατότητα γρήγορης αναγνώρισης δεδομένων κειμένου σε εικόνα είναι καθοριστική. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα ένα πρακτικό παράδειγμα που δείχνει ακριβώς πώς να **perform OCR on image** χρησιμοποιώντας το Aspose OCR για Java. Θα καλύψουμε τα πάντα, από την εφαρμογή της άδειας Aspose μέχρι τη φόρτωση της εικόνας, την εκτέλεση της μηχανής και τελικά το **extract text from image** ώστε να το χρησιμοποιήσετε παρακάτω. Χωρίς περιττές πληροφορίες, μόνο μια λειτουργική λύση που μπορείτε να αντιγράψετε‑επικολλήσετε. + +## Τι Θα Αποκομίσετε + +- Μια σαφής εικόνα για το πώς να **use Aspose license** σε ένα έργο Java. +- Ο ακριβής κώδικας που χρειάζεται για **load image for OCR** και να αφήσει τη μηχανή να ανιχνεύσει αυτόματα τις γλώσσες. +- Οδηγίες βήμα‑βήμα για **recognize text image** περιεχόμενο και **extract text from image** με ασφάλεια. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων (κενά αποτελέσματα, μη υποστηριζόμενες μορφές και προβλήματα μνήμης). + +> **Prerequisites** – Java 8 ή νεότερη, Maven ή Gradle για διαχείριση εξαρτήσεων, και αρχείο άδειας Aspose OCR για Java (ή μπορείτε να τρέξετε σε λειτουργία αξιολόγησης). + +--- + +## Πώς να Διεκπεραιώσετε OCR σε Εικόνα με Aspose OCR Java + +Παρακάτω είναι το πλήρες, έτοιμο‑για‑εκτέλεση πρόγραμμα Java που δείχνει ολόκληρη τη ροή. Αποθηκεύστε το ως `AsposeOcrDemo.java` και τρέξτε το από το IDE ή τη γραμμή εντολών. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Αναμενόμενη Έξοδος Κονσόλας + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Αν τρέξετε το πρόγραμμα χωρίς αρχείο άδειας, η πρώτη γραμμή θα δηλώνει απλώς ότι βρίσκεστε σε λειτουργία αξιολόγησης, αλλά το OCR λειτουργεί κανονικά. + +--- + +## Ρύθμιση και Χρήση Άδειας Aspose + +### Γιατί είναι Σημαντική η Άδεια + +Η εκτέλεση της βιβλιοθήκης σε λειτουργία αξιολόγησης είναι εντάξει για γρήγορες δοκιμές, αλλά προσθέτει υδατογράφημα στην έξοδο και περιορίζει τον αριθμό των σελίδων που μπορείτε να επεξεργαστείτε ανά εκτέλεση. Η εφαρμογή του βήματος **use aspose license** αφαιρεί αυτούς τους περιορισμούς και ενημερώνει το Aspose ότι είστε πελάτης με πληρωμή. + +### Πώς να Αποκτήσετε και να Εφαρμόσετε την Άδεια + +1. Αγοράστε μια άδεια από το κατάστημα Aspose. +2. Κατεβάστε το αρχείο `Aspose.OCR.Java.lic`. +3. Τοποθετήστε το κάπου που η εφαρμογή σας μπορεί να το διαβάσει—συνήθως στο φάκελο `src/main/resources`. +4. Καλέστε `new License().setLicense("Aspose.OCR.Java.lic");` πριν από οποιαδήποτε εργασία OCR, όπως φαίνεται στον παραπάνω κώδικα. + +> **Pro tip:** Αν αναπτύξετε σε διακομιστή, χρησιμοποιήστε απόλυτη διαδρομή ή φορτωτή πόρων class‑path για να αποφύγετε το `FileNotFoundException`. + +--- + +## Φόρτωση Εικόνας για Επεξεργασία OCR + +Η γραμμή `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` είναι η καρδιά του βήματος **load image for OCR**. Το Aspose OCR υποστηρίζει μια ευρεία γκάμα μορφών: PNG, JPEG, BMP, TIFF, και ακόμη πολυ‑σελίδες PDF (όταν συνδυάζεται με το Aspose.Pdf). + +### Συνηθισμένα Προβλήματα + +| Πρόβλημα | Σύμπτωμα | Διόρθωση | +|----------|----------|----------| +| Λάθος διαδρομή αρχείου | `FileNotFoundException` | Ελέγξτε ξανά τη διαδρομή· χρησιμοποιήστε `Paths.get(...)` για διαχωριστές ανεξάρτητους από το OS. | +| Μη υποστηριζόμενη μορφή | `UnsupportedOperationException` | Μετατρέψτε την εικόνα σε PNG ή JPEG πριν τη φόρτωση. | +| Μεγάλη εικόνα ( > 10 MP) | Σφάλματα έλλειψης μνήμης | Μειώστε την ανάλυση της εικόνας χρησιμοποιώντας `java.awt.Image` πριν τη δώσετε στο Aspose. | + +--- + +## Εξαγωγή Κειμένου από Εικόνα και Διαχείριση Αποτελεσμάτων + +Μόλις ολοκληρωθεί η μηχανή OCR, το αντικείμενο `OcrResult` περιέχει το αναγνωρισμένο κείμενο. Εδώ είναι που **extract text from image** για περαιτέρω επεξεργασία—αποθήκευση σε βάση δεδομένων, τροφοδοσία ευρετηρίου αναζήτησης ή ενσωμάτωση σε pipeline NLP. + +### Διαχείριση Πολλαπλών Γλωσσών + +Επειδή ορίσαμε `engine.setLanguage(Language.Auto)`, το Aspose θα προσπαθήσει να εντοπίσει τις γλώσσες αυτόματα. Αν γνωρίζετε τη γλώσσα εκ των προτέρων (π.χ., όλα τα έγγραφα είναι Ρωσικά), μπορείτε να αντικαταστήσετε το `Language.Auto` με `Language.Russian` για βελτίωση απόδοσης. + +### Συμβουλές Μετα‑επεξεργασίας + +- **Αποκοπή κενών**: `result.getText().trim()`. +- **Κανονικοποίηση λήξεων γραμμής**: `result.getText().replace("\r\n", "\n")`. +- **Αφαίρεση μη‑εκτυπώσιμων χαρακτήρων**: χρησιμοποιήστε regex όπως `result.getText().replaceAll("[^\\p{Print}]", "")`. + +## Αναγνώριση Εικόνας Κειμένου με Προηγμένες Επιλογές (Προαιρετικό) + +Αν χρειάζεστε πιο λεπτομερή έλεγχο, το Aspose OCR προσφέρει επιπλέον ιδιότητες: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Αυτές οι ρυθμίσεις είναι χρήσιμες όταν εργάζεστε με σαρωμένα έγγραφα που έχουν παραμόρφωση ή χαμηλή αντίθεση. + +## Συνοπτική Παρουσίαση Πλήρους Παραδείγματος + +Συνδυάζοντας όλα, το τελικό πρόγραμμα εκτελεί τα εξής με τη σωστή σειρά: + +1. **Perform OCR on image** – δημιουργώντας ένα `OcrEngine`. +2. **Use Aspose license** – προαιρετικό αλλά συνιστάται. +3. **Load image for OCR** – μέσω `Image.load`. +4. **Set language detection** – `Language.Auto` για **recognize text image** αυτόματα. +5. **Extract text from image** – εκτύπωση του αποτελέσματος, με ευγενική διαχείριση κενών απαντήσεων. + +Μπορείτε να αντιγράψετε το παραπάνω μπλοκ κώδικα απευθείας σε ένα έργο Maven με αυτήν την εξάρτηση: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Τρέξτε `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` και παρακολουθήστε την κονσόλα να εμφανίζει το αναγνωρισμένο κείμενο. + +## Συμπέρασμα + +Μόλις σας δείξαμε πώς να **perform OCR on image** αρχεία χρησιμοποιώντας το Aspose OCR για Java, από την εφαρμογή άδειας μέχρι το **loading the image for OCR**, το **recognizing text image** περιεχόμενο, και τελικά το **extracting text from image** για περαιτέρω χρήση. Η προσέγγιση είναι απλή, λειτουργεί με πολλές γλώσσες αμέσως, και μπορεί να επεκταθεί με προχωρημένες επιλογές προεπεξεργασίας όταν χρειάζεται. + +Τι ακολουθεί; Δοκιμάστε να τροφοδοτήσετε το αποτέλεσμα OCR σε ευρετήριο αναζήτησης, να δημιουργήσετε PDF με το εξαγόμενο κείμενο, ή να πειραματιστείτε με διαφορετικές μορφές εικόνας. Οι δυνατότητες είναι ατελείωτες, και με το ισχυρό API του Aspose θα περάσετε περισσότερο χρόνο δημιουργώντας λειτουργίες παρά αντιμετωπίζοντας προβλήματα OCR. + +Έχετε ερωτήσεις ή αντιμετωπίζετε κάποιο σενάριο; Αφήστε ένα σχόλιο παρακάτω—καλή προγραμματιστική! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να εξάγετε κείμενο από εικόνα από URL χρησιμοποιώντας Aspose.OCR για Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Μετατροπή Εικόνας σε Κείμενο σε Java χρησιμοποιώντας Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Εξαγωγή Κειμένου από Εικόνα Java με Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e3e5b8ba8 --- /dev/null +++ b/ocr/hindi/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR का उपयोग करके छवि से खोज योग्य PDF बनाएं। OCR को PDF में बदलना, + छवि से टेक्स्ट निकालना, और छवि पर तेज़ी से OCR करना सीखें। +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: hi +og_description: Python OCR के साथ छवि से खोज योग्य PDF बनाएं। यह गाइड दिखाता है कि + OCR को PDF में कैसे बदलें, छवि से टेक्स्ट निकालें, और छवि पर OCR कैसे करें। +og_title: Python में सर्चेबल PDF बनाएं – पूर्ण प्रोग्रामिंग मार्गदर्शन +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Python में खोज योग्य PDF बनाएं – पूर्ण चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/create-searchable-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 बनाएं – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको कभी स्कैन किए गए रसीद से **searchable PDF** बनाने की ज़रूरत पड़ी, लेकिन शुरुआत नहीं पता थी? आप अकेले नहीं हैं—कई डेवलपर्स को वही समस्या आती है जब वे पहली बार टेक्स्ट की तस्वीर को ऐसे PDF में बदलने की कोशिश करते हैं जिसे आप वास्तव में खोज सकें। + +इस ट्यूटोरियल में हम एक व्यावहारिक समाधान पर चलेंगे जो आपको **perform OCR on image** करने, उस OCR परिणाम को **searchable PDF** में बदलने, और यदि आपको आगे की प्रोसेसिंग के लिए कच्चा टेक्स्ट चाहिए तो उसे निकालने की सुविधा देता है। कोई फालतू बात नहीं, सिर्फ एक कार्यशील उदाहरण जिसे आप आज ही अपने प्रोजेक्ट में कॉपी‑पेस्ट कर सकते हैं। + +## आप क्या सीखेंगे + +- Python में एक हल्का OCR इंजन सेट अप करना +- **convert OCR to PDF** करने के सटीक चरण और उसे खोज योग्य दस्तावेज़ के रूप में सहेजना +- डाउनस्ट्रीम विश्लेषण के लिए **extract text from image** करने के तरीके +- इमेज ओरिएंटेशन और बड़े फ़ाइलों जैसी सामान्य समस्याओं को संभालने के टिप्स +- एक पूर्ण, चलाने योग्य स्क्रिप्ट जिसे आप अपने उपयोग‑केस के अनुसार अनुकूलित कर सकते हैं + +### पूर्वापेक्षाएँ + +- आपके मशीन पर Python 3.8+ स्थापित हो +- pip और वर्चुअल एन्वायरनमेंट्स की बुनियादी जानकारी (वैकल्पिक लेकिन अनुशंसित) +- एक इमेज फ़ाइल (PNG, JPEG, आदि) जिसमें स्पष्ट, मशीन‑पठनीय टेक्स्ट हो + +यदि आपके पास ये सब है, तो चलिए शुरू करते हैं। + +## चरण 1: आवश्यक लाइब्रेरी स्थापित करें + +जो कोड स्निपेट आपने पहले देखा था वह एक काल्पनिक `ocr` पैकेज का उपयोग करता है, लेकिन वही विचार वास्तविक लाइब्रेरीज़ जैसे **EasyOCR**, **pytesseract**, या **pdfminer.six** पर भी लागू होते हैं। इस गाइड के लिए हम **EasyOCR** का उपयोग करेंगे क्योंकि यह पूरी तरह Python में लिखा है, कई भाषाओं को सपोर्ट करता है, और एक सहायक हेल्पर के माध्यम से उपयोगी PDF कन्वर्ज़न मेथड प्रदान करता है। + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** एक वर्चुअल एन्वायरनमेंट (`python -m venv venv && source venv/bin/activate`) के अंदर इंस्टॉल करें ताकि आपकी डिपेंडेंसीज़ साफ़ रहें। + +## चरण 2: OCR इंजन को इनिशियलाइज़ करें – इमेज पर OCR करें + +अब लाइब्रेरी तैयार है, हम एक OCR इंजन बनाते हैं और उसे अंग्रेज़ी टेक्स्ट के साथ काम करने के लिए बताते हैं। यही वह पहला स्थान है जहाँ हम **perform OCR on image** करते हैं। + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +हमें एक समर्पित रीडर ऑब्जेक्ट की आवश्यकता क्यों है? EasyOCR भाषा मॉडल्स को प्री‑लोड करता है, इसलिए कई इमेज के लिए वही `reader` पुनः उपयोग करना हर बार पुनः‑इनिशियलाइज़ करने की तुलना में बहुत अधिक कुशल होता है। + +## चरण 3: इमेज लोड करें – इमेज से टेक्स्ट निकालें + +आइए तस्वीर को मेमोरी में लाएँ। यह चरण वह है जहाँ हम बाद में **extract text from image** करेंगे, लेकिन अभी हम केवल इसे लोड करते हैं। + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +यदि आपकी इमेज उल्टी या तिरछी है, तो OCR इंजन को फ़ीड करने से पहले Pillow के `rotate` या `transpose` मेथड्स का उपयोग करने पर विचार करें। एक त्वरित विज़ुअल चेक बाद में कई घंटे की डिबगिंग बचा सकता है। + +## चरण 4: OCR इंजन चलाएँ और परिणाम कैप्चर करें + +यह प्रक्रिया का मुख्य भाग है—इमेज को OCR इंजन को भेजना और संरचित डेटा वापस प्राप्त करना। + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +`detail=1` फ़्लैग हमें बाउंडिंग बॉक्स देता है, जिसकी हमें बाद में **convert OCR to PDF** के समय आवश्यकता होगी। यदि आप केवल कच्ची स्ट्रिंग्स में रुचि रखते हैं, तो `detail=0` सेट करें। + +## चरण 5: OCR परिणाम को खोज योग्य PDF में बदलें – OCR को PDF में बदलें + +EasyOCR सीधे PDF राइटर प्रदान नहीं करता, लेकिन हम Pillow और `reportlab` लाइब्रेरी का उपयोग करके स्वयं PDF को जोड़ सकते हैं। ट्यूटोरियल को हल्का रखने के लिए, हम `fpdf2` का उपयोग करेंगे, जो मूल इमेज को एम्बेड करने और अदृश्य टेक्स्ट ओवरले करने की सुविधा देता है। + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +क्या हुआ? हमने स्कैन की गई इमेज को दृश्यमान लेयर के रूप में रखा, फिर पहचाने गए शब्दों को सफ़ेद टेक्स्ट के साथ ऊपर लिखा जो सफ़ेद बैकग्राउंड में मिल जाता है। सर्च टूल अभी भी छिपी हुई लेयर को पढ़ते हैं, इसलिए PDF **searchable** बन जाता है बिना दृश्य रूप बदलें। + +## चरण 6: PDF बाइट्स सहेजें – इमेज को PDF में बदलें + +यदि आप PDF को मेमोरी में संभालना पसंद करते हैं (जैसे API के माध्यम से भेजना), तो आप सीधे डिस्क पर लिखने के बजाय बाइट्स को कैप्चर कर सकते हैं। + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +यह लाइन क्लासिक **convert image to PDF** वर्कफ़्लो को दर्शाती है: आप इमेज से शुरू करते हैं, OCR चलाते हैं, टेक्स्ट ओवरले करते हैं, और अंत में एक PDF स्ट्रीम उत्पन्न करते हैं। + +## चरण 7: परिणाम सत्यापित करें – त्वरित जांच + +स्क्रिप्ट चलाने के बाद, `receipt_searchable.pdf` को किसी भी PDF व्यूअर में खोलें और सर्च बॉक्स (Ctrl + F) आज़माएँ। रसीद में मौजूद किसी शब्द को टाइप करें—यदि वह सही स्थान पर कूदता है, तो आपने सफलतापूर्वक **create searchable pdf** कर लिया है! + +यदि सर्च विफल हो, तो दोबारा जाँचें: + +1. OCR कॉन्फिडेंस स्कोर (`conf` वैल्यूज़)। कम कॉन्फिडेंस का मतलब हो सकता है कि इमेज धुंधली है। +2. बाउंडिंग बॉक्स कॉर्डिनेट्स—कभी‑कभी EasyOCR उन्हें अलग ओरिएंटेशन में रिपोर्ट करता है। +3. यह सुनिश्चित करें कि PDF व्यूअर “image‑only” मोड में नहीं है (दुर्लभ, लेकिन कुछ व्यूअर में यह विकल्प होता है)। + +## पूर्ण कार्यशील स्क्रिप्ट + +सब कुछ मिलाकर, यहाँ पूरी, तैयार‑चलाने‑योग्य Python फ़ाइल है: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +इसे `searchable_pdf.py` के रूप में सहेजें, `YOUR_DIRECTORY` प्लेसहोल्डर्स को वास्तविक पाथ्स से बदलें, और चलाएँ: + +```bash +python searchable_pdf.py +``` + +आपको एक पुष्टि संदेश दिखाई देगा और आपके फ़ोल्डर में एक नई खोज योग्य PDF बनकर रखी होगी। + +## सामान्य प्रश्न और किनारे के मामले + +**यदि इमेज रंगीन हो तो?** +EasyOCR ग्रेस्केल और कलर दोनों इमेज के साथ काम करता है, लेकिन ग्रेस्केल में बदलना (`pil_image.convert("L")`) कभी‑कभी शोरयुक्त स्कैन पर सटीकता बढ़ा सकता है। + +**क्या मैं मल्टी‑पेज PDF संभाल सकता हूँ?** +हां—प्रत्येक पेज इमेज पर लूप चलाएँ, OCR चरण चलाएँ, और प्रत्येक पेज को उसी `FPDF` ऑब्जेक्ट में जोड़ें। प्रत्येक नई इमेज के लिए कर्सर रीसेट करना याद रखें (`self.add_page()`)। + +**क्या मूल टेक्स्ट लेयर को अदृश्य सफ़ेद टेक्स्ट की बजाय रख सकते हैं?** +यदि आपको वास्तविक “text‑under‑image” PDF चाहिए (जैसे एक्सेसिबिलिटी के लिए), तो `pdfminer` या `pikepdf` का उपयोग करके proper PDF टैग्स के साथ एक छिपी हुई टेक्स्ट लेयर एम्बेड करने पर विचार करें। यह अधिक उन्नत है, लेकिन सिद्धांत वही रहता है: बैकग्राउंड इमेज + ओवरले टेक्स्ट। + +**यदि OCR कॉन्फिडेंस कम है तो?** +आप कम‑कॉन्फिडेंस वाले शब्दों को फ़िल्टर कर सकते हैं: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## समापन – हमने क्या हासिल किया + +हमने रसीद की एक साधारण इमेज से शुरू किया, **performed OCR on image**, पहचाने गए स्ट्रिंग्स निकाले, और अंत में **create searchable pdf** बनाया जो किसी भी प्रोफ़ेशनल स्कैन किए गए दस्तावेज़ की तरह व्यवहार करता है। प्रक्रिया ने हर द्वितीयक कीवर्ड को कवर किया—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, और **perform OCR on image**—इसलिए अब आपके पास किसी भी समान प्रोजेक्ट के लिए एक पुन: उपयोग योग्य टूलबॉक्स है। + +### आगे के कदम + +- अन्य भाषाओं के साथ प्रयोग करें, उनके ISO कोड को `easyocr.Reader(['en', 'es'])` में पास करके। +- यदि आपको पूरी तरह ऑफ़लाइन समाधान चाहिए तो EasyOCR को Tesseract से बदलें; बाकी पाइपलाइन समान रहती है। +- OCR कॉन्फिडेंस विज़ुअलाइज़ेशन जोड़ें (इमेज पर बाउंडिंग बॉक्स ड्रॉ करें) ताकि समस्या वाली स्कैन को डिबग किया जा सके। + +क्या आपके पास कोई नया तरीका है जिसे आप साझा करना चाहते हैं? टिप्पणी छोड़ें, fork + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/hindi/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/hindi/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..69ea16ebd --- /dev/null +++ b/ocr/hindi/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Python में एक सरल OCR इंजन के साथ छवियों से टेक्स्ट निकालें। सीखें कि + स्कैन की गई छवियों को टेक्स्ट में कैसे बदलें, तस्वीरों से टेक्स्ट को पहचानें, और + Python में इमेज फ़ाइलों को कुशलतापूर्वक सूचीबद्ध करें। +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: hi +og_description: Python में हल्के OCR इंजन का उपयोग करके छवियों से टेक्स्ट निकालें। + यह गाइड आपको दिखाता है कि स्कैन की गई छवियों को टेक्स्ट में कैसे बदलें, तस्वीरों + से टेक्स्ट कैसे पहचानें, और कुछ ही चरणों में Python में इमेज फ़ाइलों की सूची कैसे + बनाएं। +og_title: Python में छवियों से टेक्स्ट निकालें – पूर्ण बैच OCR गाइड +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Python में छवियों से टेक्स्ट निकालें – पूर्ण बैच OCR गाइड +url: /hi/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में इमेज से टेक्स्ट निकालें – पूर्ण बैच OCR गाइड + +क्या आपको कभी **इमेज से टेक्स्ट निकालना** पड़ा लेकिन शुरू करने का तरीका नहीं पता था? आप अकेले नहीं हैं—डेवलपर्स अक्सर स्कैन किए गए PDF, फ़ोटो में रसीदें, या स्क्रीनशॉट को सर्चेबल टेक्स्ट में बदलने की चुनौती का सामना करते हैं। इस ट्यूटोरियल में हम एक पूरी, तैयार‑चलाने‑योग्य उदाहरण के माध्यम से दिखाएंगे कि **स्कैन की गई इमेज को टेक्स्ट में कैसे बदलें**, तस्वीरों से टेक्स्ट कैसे पहचानें, और यहाँ तक कि **list image files python**‑स्टाइल में फ़ाइलों की सूची बनाएं। अंत तक आपके पास एक पुन: उपयोग योग्य स्क्रिप्ट होगी जो एक ही बार में पूरे फ़ोल्डर को प्रोसेस कर सके। + +हम वह सब कवर करेंगे जिसकी आपको ज़रूरत है: आवश्यक लाइब्रेरीज़, प्रत्येक चरण का महत्व, एज‑केस हैंडलिंग, और थोड़ा ट्रबलशूटिंग। बाहरी दस्तावेज़ों का पीछा करने की ज़रूरत नहीं; नीचे दिया गया कोड सेल्फ‑कंटेन्ड है, और व्याख्याएँ “कैसे” *और* “क्यों” दोनों का उत्तर देती हैं। अपना पसंदीदा IDE खोलें, और चलिए शुरू करते हैं। + +--- + +## What You’ll Build + +- OCR इंजन को इनिशियलाइज़ करें (उदाहरण के लिए हम `ocr` पैकेज का उपयोग करेंगे)। +- एक डायरेक्टरी स्कैन करें और **list image files python**‑स्टाइल में PNG, JPG, और TIFF फ़ाइलों को फ़िल्टर करके सूची बनाएं। +- सभी मिली तस्वीरों पर **batch OCR** ऑपरेशन चलाएँ। +- प्रत्येक फ़ाइल के लिए निकाला गया टेक्स्ट साफ़‑साफ़ लेबल के साथ प्रिंट करें। + +> **Pro tip:** यदि आपके पास `ocr` लाइब्रेरी नहीं है, तो आप कुछ छोटे बदलावों के साथ इसे `pytesseract` से बदल सकते हैं—कोर लॉजिक वही रहता है। + +--- + +## Prerequisites + +- Python 3.8+ (स्क्रिप्ट f‑strings और type hints का उपयोग करता है)। +- एक OCR लाइब्रेरी जो `OcrEngine` के साथ `recognize_batch` एक्सपोज़ करती हो। इस गाइड में हम एक काल्पनिक `ocr` पैकेज मान रहे हैं, लेकिन पैटर्न वास्तविक लाइब्रेरीज़ पर भी लागू होता है। +- एक फ़ोल्डर जिसमें वे इमेज फ़ाइलें हों जिन्हें आप प्रोसेस करना चाहते हैं (`.png`, `.jpg`, `.tif`)। + +--- + +## Step 1 – Install & Import Required Modules + +पहले, सुनिश्चित करें कि OCR पैकेज उपलब्ध है। यदि आप `pytesseract` जैसी वास्तविक लाइब्रेरी इस्तेमाल कर रहे हैं, तो इम्पोर्ट को उसी अनुसार बदलें। + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Why this matters:** `os` को इम्पोर्ट करने से हमें क्रॉस‑प्लेटफ़ॉर्म पाथ हैंडलिंग मिलती है, जबकि `typing.List` IDE ऑटोकम्प्लीट और भविष्य‑प्रूफ़िंग में मदद करता है। + +--- + +## Step 2 – **Extract Text from Images**: Initialize the OCR Engine + +इंजन बनाना किसी भी OCR काम की पहली कदम है। हम भाषा को ऑटो‑डिटेक्ट पर सेट करते हैं ताकि इंजन मिश्रित‑भाषा दस्तावेज़ों को संभाल सके। + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explanation:** इंजन निर्माण को एक फ़ंक्शन में एन्कैप्सुलेट करने से कोड मॉड्यूलर रहता है। अगर बाद में आपको DPI या OCR मोड बदलना पड़े, तो आप केवल इस एक जगह को एडिट करेंगे। + +--- + +## Step 3 – **List Image Files Python**: Gather Files from a Directory + +अब हमें हर तस्वीर को लोकेट करना है जिसे हम प्रोसेस करना चाहते हैं। नीचे दिया गया लिस्ट कॉम्प्रिहेंशन एक सामान्य “list image files python” पैटर्न को दर्शाता है। + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge case handling:** फ़ंक्शन सब‑फ़ोल्डर को इग्नोर करता है (बाद में आप रीकर्शन जोड़ सकते हैं) और हिडन फ़ाइलों को स्वचालित रूप से फ़िल्टर कर देता है क्योंकि वे आमतौर पर सपोर्टेड एक्सटेंशन से समाप्त नहीं होतीं। + +--- + +## Step 4 – **Convert Scanned Images to Text**: Run Batch OCR + +ज्यादातर OCR लाइब्रेरीज़ एक बैच मेथड प्रदान करती हैं जो एक‑एक इमेज प्रोसेस करने से कहीं तेज़ होती है। यहाँ हम इसे कॉल कर रहे हैं। + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Why batch?** सभी इमेज को एक साथ भेजने से ओवरहेड कम होता है (जैसे OCR मॉडल को बार‑बार लोड करना) और अक्सर बेहतर CPU/GPU उपयोग मिलता है। + +--- + +## Step 5 – **Recognize Text from Pictures**: Display the Results + +अंत में, हम फ़ाइल नामों और OCR परिणामों की जोड़ी पर इटररेट करते हैं, और प्रत्येक इमेज के लिए एक साफ़ हेडर प्रिंट करते हैं। + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** `strip()` OCR द्वारा अक्सर जोड़े गए लीडिंग/ट्रेलिंग व्हाइटस्पेस को हटाता है। + +--- + +## Full Script – Put It All Together + +नीचे पूरा, चलाने योग्य प्रोग्राम दिया गया है। इसे `batch_ocr.py` के रूप में सेव करें और `python batch_ocr.py ` चलाएँ। + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Expected Output + +मान लीजिए फ़ोल्डर में `invoice1.png` और `receipt.jpg` हैं, तो आप कुछ इस तरह देख सकते हैं: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +प्रत्येक ब्लॉक स्पष्ट रूप से लेबल किया गया है, जिससे डाउनस्ट्रीम प्रोसेसिंग (जैसे डेटाबेस में सेव करना) आसान हो जाता है। + +--- + +## Handling Common Pitfalls + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **No text appears** | OCR भाषा डिटेक्ट नहीं हुई या इमेज बहुत लो‑कॉन्ट्रास्ट है। | भाषा को फ़ोर्स करें (`engine.language = ocr.Language.English`) या इमेज को प्री‑प्रोसेस करें (कॉन्ट्रास्ट बढ़ाएँ)। | +| **Memory error on large batches** | इंजन सभी इमेज एक साथ लोड करने की कोशिश करता है। | `image_files` को चंक्स में बाँटें (`batch_size = 20`) और `recognize_batch` को बार‑बार कॉल करें। | +| **Unsupported file format** | आपने `.gif` या `.bmp` जोड़ दिया। | `supported_exts` ट्यूपल को एक्सटेंड करें या इमेज को पहले PNG/JPG में कन्वर्ट करें। | +| **Unicode garbling** | OCR बाइट्स रिटर्न करता है न कि स्ट्रिंग। | सुनिश्चित करें कि OCR लाइब्रेरी Unicode आउटपुट दे (`result.text.decode('utf‑8')` अगर ज़रूरी हो)। | + +--- + +## Extending the Workflow + +अब जब आप **extract text from images** कर सकते हैं, तो इन अगले कदमों पर विचार करें: + +- **Export to CSV** – प्रत्येक फ़ाइलनाम और उसके निकाले गए टेक्स्ट को स्प्रेडशीट में लिखें ताकि एनालिटिक्स आसान हो। +- **Parallel processing** – `concurrent.futures.ThreadPoolExecutor` का उपयोग करके कई बैच एक साथ हैंडल करें। +- **Integrate with cloud OCR** – स्थानीय इंजन को Google Vision या Azure OCR से बदलें ताकि जटिल लेआउट पर अधिक सटीकता मिले। +- **Add image preprocessing** – Pillow या OpenCV जैसी लाइब्रेरीज़ से इमेज को डेस्क्यू, डीनॉइज़, या थ्रेशहोल्ड करें, जिससे OCR परिणाम बेहतर हों। + +इन सभी आइडियाज़ में हमने जो कोर फ़ंक्शन बनाए हैं, वही उपयोग होते हैं, इसलिए आपको स्क्रैच से शुरू नहीं करना पड़ेगा। + +--- + +## Conclusion + +हमने अभी-अभी Python में **extract text from images** के लिए एक पूर्ण समाधान पर चर्चा की, जिसमें **list image files python** से लेकर **recognize text from pictures** तक और अंत में **convert scanned images to text** बैच में शामिल है। स्क्रिप्ट जानबूझकर सरल रखी गई है, फिर भी बड़ी प्रोजेक्ट्स के लिए पर्याप्त लचीली है—चाहे आप रसीदें डिजिटाइज़ कर रहे हों, सर्चेबल आर्काइव बना रहे हों, या डेटा‑एक्सट्रैक्शन पाइपलाइन चला रहे हों। + +इसे चलाएँ, प्री‑प्रोसेसिंग स्टेप्स को ट्यून करें, और अपनी OCR सटीकता को बढ़ते देखें। अगर कोई समस्या आती है, तो “Handling Common Pitfalls” तालिका को दोबारा देखें; अधिकांश मुद्दे छोटे कॉन्फ़िगरेशन बदलावों से हल हो जाते हैं। + +अगली चुनौती के लिए तैयार हैं? `pdf2image` का उपयोग करके PDF‑to‑image कन्वर्ज़न स्टेप जोड़ें, फिर उन इमेज को उसी पाइपलाइन में फीड करें। OCR को Python के समृद्ध इकोसिस्टम के साथ मिलाकर संभावनाएँ अनंत हैं। + +Happy coding, and may your text be ever legible! + +## 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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/hindi/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..b8c74a62b --- /dev/null +++ b/ocr/hindi/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR का उपयोग करके छवियों से टेक्स्ट निकालें। स्वचालित भाषा पहचान, + समानांतर प्रोसेसिंग और बैच पहचान को एक संक्षिप्त ट्यूटोरियल में सीखें। +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: hi +og_description: Python OCR के साथ छवियों से टेक्स्ट निकालें। यह गाइड स्वचालित भाषा + पहचान, समानांतर प्रोसेसिंग और बैच मान्यता को एक ही ट्यूटोरियल में दिखाता है। +og_title: Python में छवियों से टेक्स्ट निकालें – पूर्ण OCR गाइड +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python में छवियों से टेक्स्ट निकालें – पूर्ण OCR गाइड +url: /hi/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेज़ से टेक्स्ट निकालें Python में – पूर्ण OCR गाइड + +क्या आपने कभी सोचा है कि **इमेज़ से टेक्स्ट निकालना** बिना हर शब्द को मैन्युअली टाइप किए कैसे संभव है? आप अकेले नहीं हैं। चाहे आप पुराने रसीदों को डिजिटल बना रहे हों, सर्चेबल डॉक्यूमेंट आर्काइव बना रहे हों, या बस कूल AI ट्रिक्स के साथ खेल रहे हों, तस्वीरों से टेक्स्ट निकालने की क्षमता आज के किसी भी Python डेवलपर के लिए आवश्यक कौशल है। + +इस ट्यूटोरियल में हम एक पूर्ण, तैयार‑चलाने‑योग्य उदाहरण के माध्यम से **इमेज़ से टेक्स्ट निकालने** की प्रक्रिया को देखेंगे, जिसमें एक लोकप्रिय OCR इंजन का उपयोग किया गया है। हम ऑटोमैटिक लैंग्वेज डिटेक्शन, स्पीड के लिए पैरालेल प्रोसेसिंग, और बैच इमेज़ रेकग्निशन को कवर करेंगे ताकि आप सेकंड में दर्जनों फ़ाइलों को संभाल सकें। क्या यह वही है जिसकी आपको ज़रूरत है? चलिए शुरू करते हैं। + +## आप क्या सीखेंगे + +- `ocr.OcrEngine` के साथ OCR इंजन को इंस्टैंशिएट करना। +- **ऑटोमैटिक लैंग्वेज डिटेक्शन** को सक्षम करना ताकि इंजन खुद ही सही भाषा चुन ले। +- कस्टम थ्रेड पूल के साथ **पैरालेल प्रोसेसिंग OCR** को कॉन्फ़िगर करना। +- फ़ाइलों की सूची पर **बैच इमेज़ रेकग्निशन** चलाना। +- प्रत्येक इमेज़ के लिए पहचाने गए टेक्स्ट को प्रिंट करना, जिसे आप सेव या इंडेक्स कर सकते हैं। + +कोई बाहरी डॉक्यूमेंटेशन आवश्यक नहीं—आपको जो चाहिए वह सब यहाँ है, और कोड `ocr` पैकेज के साथ बॉक्स से बाहर काम करता है (`pip install ocr` के ज़रिए इंस्टॉल करें)। + +## आवश्यकताएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास है: + +1. Python 3.8 या उससे नया संस्करण। +2. `ocr` पैकेज (`pip install ocr`)। +3. प्रोसेस करने के लिए PNG (या JPG) इमेज़ की एक फ़ोल्डर। +4. Python फ़ंक्शन और लूप्स की बेसिक समझ। + +बस इतना ही—कोई भारी डिपेंडेंसी नहीं, कोई GPU मैजिक नहीं, सिर्फ सादा Python। + +![इमेज़ से टेक्स्ट निकालने का उदाहरण](https://example.com/ocr-demo.png "इमेज़ से टेक्स्ट निकालने के आउटपुट का स्क्रीनशॉट") + +*Alt text: इमेज़ से टेक्स्ट निकालने का डेमो स्क्रीनशॉट* + +## चरण 1 – OCR इंजन सेट अप करें (प्राथमिक कीवर्ड इन एक्शन) + +सबसे पहले: एक OCR इंजन इंस्टेंस बनाएं। `ocr.OcrEngine()` को ऑपरेशन के दिमाग़ की तरह समझें; यह कैरेक्टर्स, लाइन्स, और पैराग्राफ़ पढ़ना जानता है। + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +इंजिन को स्पष्ट रूप से क्यों चाहिए? क्योंकि **ocr.OcrEngine उपयोग** आपको भाषा सेटिंग्स, थ्रेडिंग, और बहुत कुछ पर फाइन‑ग्रेन कंट्रोल देता है। यह एक‑लाइनर हेल्पर्स की तुलना में **इमेज़ से टेक्स्ट निकालने** का सबसे लचीला तरीका है। + +## चरण 2 – इंजन को ऑटोमैटिक भाषा पहचान करने दें + +ज्यादातर OCR लाइब्रेरीज़ को यह बताना पड़ता है कि किस भाषा की तलाश करनी है। यह एक‑भाषा प्रोजेक्ट के लिए ठीक है, लेकिन मिश्रित‑भाषा बैच के लिए झंझट भरा हो सकता है। सौभाग्य से, `ocr` पैकेज **ऑटोमैटिक भाषा पहचान** को सपोर्ट करता है। + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +`engine.language` को `ocr.Language.Auto` सेट करने से इंजन प्रत्येक इमेज़ को sniff करके उपयुक्त भाषा मॉडल चुन लेता है। यह छोटा सा लाइन अंतर्राष्ट्रीय डॉक्यूमेंट्स के साथ काम करते समय घंटों की मैन्युअल कॉन्फ़िगरेशन बचा देता है। + +## चरण 3 – पैरालेल प्रोसेसिंग OCR से गति बढ़ाएँ + +यदि आपके पास चार या अधिक CPU कोर हैं, तो उनका उपयोग क्यों न करें? इंजन एक थ्रेड पूल बना सकता है, जिससे कई इमेज़ एक साथ प्रोसेस हो सकें। यही वह जगह है जहाँ **पैरालेल प्रोसेसिंग OCR** चमकता है। + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +अपने मशीन के अनुसार संख्या `4` को समायोजित कर सकते हैं। अधिक थ्रेड → तेज़ बैच रन, लेकिन याद रखें कि प्रत्येक थ्रेड मेमोरी खपत करता है, इसलिए अपने वातावरण के लिए एक संतुलित संख्या चुनें। + +## चरण 4 – प्रोसेस करने के लिए इमेज़ एकत्र करें + +अब हमें फ़ाइल पाथ्स की एक सूची चाहिए। आप यह सूची मैन्युअली बना सकते हैं, CSV से पढ़ सकते हैं, या `glob` का उपयोग कर सकते हैं। स्पष्टता के लिए, हम एक छोटी सूची हार्ड‑कोड करेंगे: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +`YOUR_DIRECTORY` को अपने सिस्टम पर वास्तविक पाथ से बदलें। यदि आपके पास दर्जनों फ़ाइलें हैं, तो `glob.glob("*.png")` जल्दी से काम संभाल लेगा। + +## चरण 5 – बैच इमेज़ रेकग्निशन चलाएँ + +यह ट्यूटोरियल का दिल है: एक ही कॉल जो `files` में हर इमेज़ को प्रोसेस करता है और परिणाम ऑब्जेक्ट्स की सूची लौटाता है। यह **बैच इमेज़ रेकग्निशन** फीचर है जो बड़े‑पैमाने पर OCR को प्रैक्टिकल बनाता है। + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +पर्दे के पीछे, इंजन प्रत्येक फ़ाइल को पहले कॉन्फ़िगर किए गए चार वर्कर थ्रेड्स में वितरित करता है, साथ ही प्रत्येक चित्र के लिए ऑटो‑डिटेक्टेड भाषा भी। मेथड एक सूची लौटाता है जहाँ प्रत्येक एलिमेंट में पहचाना गया टेक्स्ट और मेटाडेटा होता है। + +## चरण 6 – निकाले गए टेक्स्ट को प्रिंट (या स्टोर) करें + +अंत में, हम परिणामों पर लूप चलाते हैं और टेक्स्ट प्रिंट करते हैं। वास्तविक प्रोजेक्ट में आप इसे डेटाबेस या CSV फ़ाइल में लिखेंगे, लेकिन प्रिंट करने से उदाहरण सरल रहता है। + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**अपेक्षित आउटपुट** (संक्षिप्त रूप में): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +हर ब्लॉक फ़ाइलनाम के बाद OCR‑डेराइव्ड स्ट्रिंग दिखाता है। यदि इमेज़ में कई भाषाएँ हैं, तो आप पहले के **ऑटोमैटिक भाषा पहचान** चरण के कारण उपयुक्त कैरेक्टर्स देखेंगे। + +## प्रो टिप्स एवं सामान्य गलतियाँ + +- **इमेज़ की क्वालिटी महत्वपूर्ण है** – धुंधली या लो‑कॉन्ट्रास्ट तस्वीरें गड़बड़ आउटपुट देंगी। आवश्यकता पड़ने पर OpenCV (`cv2.threshold`, `cv2.resize`) से प्री‑प्रोसेस करें। +- **थ्रेड काउंट बनाम I/O** – यदि आपकी इमेज़ स्लो नेटवर्क ड्राइव पर हैं, तो अधिक थ्रेड मदद नहीं करेंगे। `top` या `Task Manager` से CPU उपयोग पर नजर रखें। +- **Unicode हैंडलिंग** – `result.text` एक Unicode स्ट्रिंग है। फ़ाइलों में लिखते समय `encoding="utf‑8"` के साथ खोलें ताकि `UnicodeEncodeError` न आए। +- **मेमोरी उपयोग** – बड़े PDFs बहुत RAM ले सकते हैं। यदि `MemoryError` मिले, तो थ्रेड पूल साइज घटाएँ या इमेज़ को छोटे चंक्स में प्रोसेस करें। + +## पूर्ण कार्यशील स्क्रिप्ट + +नीचे पूरी, कॉपी‑एंड‑पेस्ट‑रेडी स्क्रिप्ट है जिसमें हमने चर्चा किए सभी चरण शामिल हैं। इसे `batch_ocr.py` के रूप में सेव करें और `python batch_ocr.py` चलाएँ। + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +ऐसे चलाएँ: + +```bash +python batch_ocr.py ./my_images 4 +``` + +आप प्रत्येक इमेज़ के लिए एक सुंदर फ़ॉर्मेटेड टेक्स्ट ब्लॉक देखेंगे, जिससे साबित होगा कि आप **इमेज़ से टेक्स्ट निकाल सकते** हैं बड़े पैमाने पर। + +## आगे क्या? + +अब जब आपने Python के साथ **इमेज़ से टेक्स्ट निकालने** की बुनियादें समझ ली हैं, तो आप निम्नलिखित चीज़ों को एक्सप्लोर कर सकते हैं: + +- **पोस्ट‑प्रोसेसिंग**: OCR आउटपुट को रेगएक्स या नेचुरल‑लैंग्वेज लाइब्रेरीज़ से साफ़ करें। +- **PDF कन्वर्ज़न**: निकाले गए स्ट्रिंग्स को एक PDF जेनरेटर में फीड करें ताकि सर्चेबल PDFs बन सकें। +- **क्लाउड OCR सर्विसेज**: ऑन‑प्रेम `ocr` परिणामों की तुलना Google Vision या Azure OCR से करें ताकि एज‑केस सटीकता मिल सके। +- **GUI फ्रंट‑एंड**: एक छोटा Flask या FastAPI ऐप बनाएं जो यूज़र्स को इमेज़ अपलोड करने और तुरंत निकाला गया टेक्स्ट देखने की सुविधा दे। + +इन सभी टॉपिक्स का आधार वही **Python OCR लाइब्रेरी** है जिसे आपने अभी सेट किया है, और सभी को वही **पैरालेल प्रोसेसिंग 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 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/hindi/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/hindi/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..ea0f97085 --- /dev/null +++ b/ocr/hindi/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-06-19 +description: Python में OCR का उपयोग करके PDF कैसे निकालें – चरण‑दर‑चरण ट्यूटोरियल + जिसमें PDF से टेक्स्ट निकालना, छवि से टेक्स्ट पहचानना, और एक OCR Python उदाहरण शामिल + है। +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: hi +og_description: Python में OCR का उपयोग करके PDF कैसे निकालें। PDF से टेक्स्ट निकालना, + इमेज से टेक्स्ट पहचानना सीखें, और एक पूर्ण OCR Python उदाहरण देखें। +og_title: Python में OCR के साथ PDF टेक्स्ट कैसे निकालें – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Python में OCR के साथ PDF टेक्स्ट कैसे निकालें – पूर्ण गाइड +url: /hi/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में OCR के साथ PDF टेक्स्ट निकालने का तरीका – पूर्ण गाइड + +क्या आप कभी सोचते थे कि **PDF से टेक्स्ट कैसे निकालें** जब फ़ाइल केवल स्कैन की गई छवि हो? आप अकेले नहीं हैं। कई वास्तविक‑दुनिया प्रोजेक्ट्स—जैसे अनुबंध, चालान, या ऐतिहासिक अभिलेख—में प्राप्त PDF में चयन योग्य टेक्स्ट नहीं होता। अच्छी खबर? कुछ ही पंक्तियों के Python कोड से उन केवल‑छवि पृष्ठों को खोज योग्य, संपादन योग्य टेक्स्ट में बदला जा सकता है। + +इस ट्यूटोरियल में हम एक व्यावहारिक **OCR Python example** के माध्यम से चलेंगे जो PDF पढ़ता है, उसकी पहली पेज को इमेज के रूप में रेंडर करता है, और फिर OCR इंजन का उपयोग करके **extracts text from PDF** करता है। अंत तक आप बिल्कुल जानेंगे कि **read PDF with OCR** कैसे किया जाता है, प्रत्येक चरण क्यों महत्वपूर्ण है, और कोड को मल्टी‑पेज डॉक्यूमेंट या विभिन्न भाषाओं के लिए कैसे अनुकूलित किया जाए। + +## आप क्या सीखेंगे + +- Python के लिए एक भरोसेमंद OCR लाइब्रेरी को इंस्टॉल और सेट अप करें। +- OCR के अनुकूल PDF पेजों को इमेज में बदलें। +- **Recognize text from image** और साफ़ Unicode स्ट्रिंग्स प्राप्त करें। +- सामान्य समस्याएँ (कम‑रिज़ॉल्यूशन PDFs, घुमा हुआ पेज) और उन्हें कैसे टालें। +- स्क्रिप्ट को कई पेजों या बैच प्रोसेसिंग को संभालने के लिए विस्तारित करें। + +**Prerequisites**: Python 3.8+, pip, और वर्चुअल एनवायरनमेंट्स की बुनियादी समझ। पहले से OCR का अनुभव आवश्यक नहीं—बस साथ चलें। + +--- + +## ## Python में OCR के साथ PDF टेक्स्ट निकालना + +यह H2 हेडर हमारे मुख्य कीवर्ड को ठीक वहीं रखता है जहाँ सर्च इंजन इसे देखना पसंद करते हैं। चलिए सीधे कोड में डुबकी लगाते हैं। + +### चरण 1 – आवश्यक पैकेज स्थापित करें + +First, we need an OCR engine. The example below uses the popular **ocr** package (a thin wrapper around Tesseract). If you prefer a different backend, the concepts stay the same. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** On Linux, you’ll also need the Tesseract binary: `sudo apt-get install tesseract-ocr`. macOS users can grab it via Homebrew: `brew install tesseract`. + +### चरण 2 – OCR इंजन को इनिशियलाइज़ करें और भाषा सेट करें + +Now we spin up the engine and tell it to look for English characters. You can swap `ocr.Language.English` for any supported language code. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Why this matters:** Specifying the language dramatically improves accuracy because the engine can apply language‑specific dictionaries and character models. + +### चरण 3 – PDF पेज को इमेज के रूप में लोड करें + +OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based indexing). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** If the PDF contains vector graphics rather than scanned images, you might get a crisp rendering. For low‑resolution scans, consider increasing the DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### चरण 4 – रेंडर की गई इमेज से टेक्स्ट पहचानें + +Here’s the heart of the **ocr python example**. The engine processes the bitmap and returns an object containing the extracted string. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +The `ocr_result.text` attribute holds the plain‑text output, preserving line breaks where possible. + +### चरण 5 – निकाले गए टेक्स्ट को प्रिंट या स्टोर करें + +Finally, we output the result. In a real application you’d probably write to a file or a database. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Running the script should display something like: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +That’s a complete **extract text from pdf** workflow using OCR. + +--- + +## ## इमेज से टेक्स्ट पहचानें – सटीकता सुधारना + +If you’re only interested in **recognize text from image** (say, a JPEG of a receipt), you can skip the PDF conversion step: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips for better results:** + +- **Pre‑process** the image: convert to grayscale, apply thresholding, or deskew. Pillow makes this easy. +- **Increase DPI** during PDF rendering: higher resolution gives the OCR engine more detail. +- **Enable OCR engine’s config** for page segmentation (`ocr_engine.config = "--psm 6"` for uniform blocks). + +## ## OCR के साथ PDF पढ़ें – कई पेजों को संभालना + +Most contracts span several pages. Looping over each page is straightforward: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +This function **reads PDF with OCR**, concatenates the output, and inserts a clear page break marker. You can then feed `full_text` into a search index or store it as a `.txt` file. + +## ## सामान्य समस्याएँ और उनके समाधान + +| लक्षण | संभावित कारण | समाधान | +|---------|--------------|-----| +| गड़बड़ अक्षर, बहुत सारे `?` | गलत भाषा या भाषा डेटा फ़ाइलें अनुपलब्ध | सही Tesseract भाषा पैक (`tesseract-ocr-`) इंस्टॉल करें और `ocr_engine.language` सेट करें। | +| लाइनें गायब या शब्द कटे हुए | निम्न DPI (150 से कम) | PDF को 300 DPI या उससे अधिक पर रेंडर करें (`dpi=300`). | +| टेक्स्ट घुमा हुआ या उल्टा | स्कैन किया गया पेज सीधा नहीं है | पहचान से पहले `ocr.Image.deskew(page_image)` का उपयोग करें। | +| बड़े PDFs पर धीमी प्रोसेसिंग | पेजों को एकल थ्रेड पर क्रमिक रूप से प्रोसेस करना | `concurrent.futures.ThreadPoolExecutor` के साथ समानांतर प्रोसेसिंग करें। | + +## ## OCR Python उदाहरण का विस्तार + +- **Export to PDF/A**: After extraction, you can embed the text back into a searchable PDF using `reportlab` or `pypdf2`। +- **Language detection**: Use `langdetect` on the OCR output to switch `ocr_engine.language` dynamically। +- **Batch processing**: Walk a directory with `os.listdir` and apply `extract_all_pages` to every file। + +## ## अपेक्षित आउटपुट और सत्यापन + +When you run the script against a clear, English‑language scan, you should see a clean block of text with proper punctuation. Verify by: + +1. Comparing a few lines to the original scanned image. +2. Running a simple word count (`len(ocr_result.text.split())`) to ensure the output isn’t empty. +3. Optionally, feeding the result into a spell‑checker like `pyspellchecker` to spot OCR errors। + +## निष्कर्ष + +We’ve covered **how to extract PDF** content when traditional parsing fails, demonstrated a full **ocr python example**, and explained how to **recognize text from image** and **read PDF with OCR** for both single‑page and multi‑page scenarios. With the code snippets above you can now turn any scanned PDF into searchable, editable text—no more manual re‑typing। + +Next steps? Try swapping the language to Spanish (`ocr.Language.Spanish`) or experiment with image pre‑processing techniques to boost accuracy. If you’re building a document‑management system, consider indexing the extracted text with Elasticsearch for lightning‑fast search। + +Got questions or run into a quirky PDF? Drop a comment, and happy coding! + +![Python में OCR का उपयोग करके PDF निकालने का तरीका](image.png "Python में OCR का उपयोग करके PDF निकालने का तरीका") + +## आगे आप क्या सीखें + +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. + +- [Aspose OCR के साथ इमेज से टेक्स्ट निकालें – चरण‑दर‑चरण गाइड](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [PDF टेक्स्ट पहचानें – Aspose.OCR for Java के साथ OCR ऑपरेशन्स](/ocr/english/java/ocr-operations/) +- [C# में इमेज टेक्स्ट निकालें भाषा चयन के साथ Aspose.OCR का उपयोग करके](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/hindi/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..f2198ba01 --- /dev/null +++ b/ocr/hindi/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-06-19 +description: Aspose के साथ जावा में OCR का उपयोग करना सीखें। यह चरण‑दर‑चरण गाइड ऑटो‑डेस्क्यू + इमेजेज, ऑटो भाषा पहचान, और आसानी से टेक्स्ट इमेज निकालने को कवर करता है। +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: hi +og_description: 'Aspose के साथ जावा में OCR का उपयोग कैसे करें: ऑटो‑डेस्क्यू इमेजेज, + ऑटो‑भाषा पहचान, और तस्वीरों से टेक्स्ट निकालने की पूरी मार्गदर्शिका।' +og_title: Aspose के साथ जावा में OCR का उपयोग कैसे करें – पूर्ण गाइड +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Aspose के साथ जावा में OCR का उपयोग कैसे करें – पूर्ण गाइड +url: /hi/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# जावा में Aspose के साथ OCR का उपयोग कैसे करें – पूर्ण गाइड + +क्या आपने कभी सोचा है **how to use OCR** को जावा प्रोजेक्ट में बिना कॉन्फ़िगरेशन की झंझट के इस्तेमाल करने के बारे में? आप अकेले नहीं हैं। कई डेवलपर्स को जल्दी से **extract text image** डेटा निकालने की जरूरत पड़ने पर रुकावट आती है, खासकर जब स्रोत स्कैन तिरछे हों या अज्ञात भाषा में लिखे हों। + +इस ट्यूटोरियल में हम एक व्यावहारिक उदाहरण के माध्यम से चलेंगे जो आपको बिल्कुल दिखाएगा कि Aspose के साथ OCR का उपयोग कैसे करें, जिसमें **auto deskew images**, **auto language detection**, और पूरा **ocr image preprocessing** पाइपलाइन शामिल है। अंत तक आपके पास एक तैयार‑से‑चलाने वाला स्निपेट होगा जो पहचाने गए टेक्स्ट को कंसोल पर प्रिंट करेगा, और आप समझेंगे कि प्रत्येक सेटिंग क्यों महत्वपूर्ण है। + +> **What you’ll get:** एक पूर्ण, चलाने योग्य जावा प्रोग्राम, प्रत्येक पंक्ति की व्याख्याएँ, एज केस को संभालने के टिप्स, और समाधान को बैच प्रोसेसिंग या PDFs में विस्तारित करने के विचार। + +--- + +## आवश्यकताएँ + +- Java 17 (या कोई भी नवीनतम JDK) स्थापित और कॉन्फ़िगर किया हुआ। +- डिपेंडेंसी मैनेजमेंट के लिए Maven या Gradle (हम Maven कोऑर्डिनेट्स दिखाएंगे)। +- Aspose OCR for Java लाइसेंस फ़ाइल (`Aspose.OCR.Java.lic`)। यदि आप केवल परीक्षण कर रहे हैं, तो आप लाइसेंस चरण को छोड़ सकते हैं, लेकिन फ्री ट्रायल में वॉटरमार्क जुड़ जाएगा। +- एक सैंपल इमेज (`your_image.png`) जो कोड के लिए सुलभ स्थान पर रखी हो। + +> **Pro tip:** अपनी इमेजेज़ को एक समर्पित `resources` फ़ोल्डर में रखें और उन्हें क्लासपाथ के माध्यम से लोड करें; यह विभिन्न OS पर पाथ‑संबंधी समस्याओं से बचाता है। + +## चरण 1: प्रोजेक्ट सेट अप करें और Aspose OCR डिपेंडेंसी जोड़ें + +एक नया Maven प्रोजेक्ट बनाएं (या अपना मौजूदा उपयोग करें) और अपने `pom.xml` में निम्नलिखित जोड़ें: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn clean install` चलाकर लाइब्रेरी प्राप्त करें। यदि आप Gradle पसंद करते हैं, तो समकक्ष यह है: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +अब आपके क्लासपाथ पर **ocr image preprocessing** क्लासेज़ उपलब्ध हैं। + +## चरण 2: अपना Aspose OCR लाइसेंस लागू करें (वैकल्पिक लेकिन अनुशंसित) + +यदि आपके पास लाइसेंस है, तो इसे अपने `main` मेथड की शुरुआत में लागू करें। इस चरण को छोड़ना काम करता है, लेकिन फ्री संस्करण आउटपुट पर “Demo” वॉटरमार्क जोड़ता है। + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Why this matters:** लाइसेंस्ड संस्करण उपयोग सीमा हटाता है और वॉटरमार्क को निष्क्रिय करता है, जिससे आपको साफ़, प्रोडक्शन‑रेडी परिणाम मिलते हैं। + +## चरण 3: OCR इंजन इंस्टेंस बनाएं + +इंजन प्रक्रिया का हृदय है। इसे इंस्टैंसिएट करने से आपको सभी **ocr image preprocessing** विकल्पों तक पहुँच मिलती है। + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +इस चरण पर इंजन तैयार है, लेकिन यह डिफ़ॉल्ट सेटिंग्स का उपयोग करेगा जो स्कैन किए गए दस्तावेज़ों के लिए अनुकूल नहीं हो सकतीं। चलिए कुछ सेटिंग्स को समायोजित करते हैं। + +## चरण 4: साफ़ स्कैन के लिए Auto Deskew Images सक्षम करें + +झुके हुए स्कैन एक सामान्य समस्या हैं। Aspose एक **auto deskew images** फीचर प्रदान करता है जो पहचान से पहले स्वचालित रूप से चित्र को सीधा कर देता है। + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **How it works:** एल्गोरिदम टेक्स्ट बेसलाइन एंगल्स का विश्लेषण करता है और सबसे संभावित सीधी दिशा में इमेज को घुमाता है। यह फोन से ली गई फ़ोटो की सटीकता को काफी बढ़ाता है। + +## चरण 5: Auto Language Detection को चालू करें + +यदि आप स्रोत इमेज की भाषा नहीं जानते, तो इंजन को इसे पता लगाने दें। यह **auto language detection** सेटिंग है। + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +जब आप इसे सक्षम करते हैं, तो Aspose ग्लिफ़्स को स्कैन करता है और सबसे संभावित भाषा मॉडल चुनता है, जो बॉक्स से बाहर 30 से अधिक भाषाओं का समर्थन करता है। + +## चरण 6: वह इमेज लोड करें जिसे आप पहचानना चाहते हैं + +आप इमेज को डिस्क, URL, या यहां तक कि बाइट एरे से लोड कर सकते हैं। सरलता के लिए, हम स्थानीय फ़ाइल से पढ़ेंगे। + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** यदि आप बड़े इमेजेज़ से निपट रहे हैं, तो उन्हें पहले `engine.getImagePreprocessing().setResizeFactor(0.5)` से डाउन‑सैंपल करने पर विचार करें ताकि प्रोसेसिंग तेज़ हो और बहुत अधिक विवरण न खोएँ। + +## चरण 7: OCR पहचान करें और Text Image निकालें + +अब इंजन अपना जादू करता है। `recognize` मेथड एक `OcrResult` ऑब्जेक्ट लौटाता है जिसमें पहचाना गया टेक्स्ट, कॉन्फिडेंस स्कोर, और अधिक शामिल होते हैं। + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +कंसोल में चित्र से निकाला गया साधारण टेक्स्ट प्रदर्शित होगा—यह वह मुख्य **extract text image** परिणाम है जिसे हम हासिल करना चाहते थे। + +## पूर्ण कार्यशील उदाहरण + +नीचे वह पूर्ण जावा क्लास है जो सब कुछ जोड़ता है। इसे `src/main/java/com/example/OcrDemo.java` में कॉपी‑पेस्ट करें और चलाएँ। + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### अपेक्षित आउटपुट + +यदि इमेज में साफ़ स्कैन पर वाक्य “Hello World” है, तो आप देखेंगे: + +``` +=== Recognized Text === +Hello World +``` + +अधिक जटिल दस्तावेज़ों (जैसे, बहुभाषी रसीदें) के लिए, आउटपुट में लाइन ब्रेक और पता लगी भाषा कोड शामिल होगा। + +## सामान्य समस्याएँ और प्रो टिप्स + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | इमेज बहुत डार्क या शोरयुक्त है। | `engine.getImagePreprocessing().setBinarization(true)` सक्षम करें या मैन्युअली कंट्रास्ट समायोजित करें। | +| **Wrong language** | मिश्रित‑भाषा पृष्ठों पर ऑटो डिटेक्शन गलत काम करता है। | `engine.setLanguage(Language.English)` सेट करें (या उपयुक्त enum) ताकि एक विशिष्ट भाषा को बाध्य किया जा सके। | +| **Slow processing** | बहुत हाई‑रिज़ॉल्यूशन इमेजेज़। | `engine.getImagePreprocessing().setResizeFactor(0.5)` के साथ डाउनस्केल करें। | +| **Out‑of‑memory errors** | एक साथ बड़ी संख्या में इमेजेज़ लोड हो रही हैं। | इमेजेज़ को क्रमिक रूप से प्रोसेस करें और प्रत्येक रन के बाद `engine.dispose()` कॉल करें। | + +> **Remember:** OCR इंजन रीड‑ओनली ऑपरेशन्स के लिए थ्रेड‑सेफ़ है, लेकिन प्रत्येक थ्रेड के लिए नया इंस्टेंस बनाना छिपी हुई स्टेट बग्स से बचाता है। + +## समाधान का विस्तार + +अब जब आप Aspose के साथ **how to use OCR** जानते हैं, आप चाहेंगे कि: + +1. PDF प्रोसेस करें – प्रत्येक PDF पेज को इमेज (`PdfConverter`) में बदलें और फिर उसे उसी पाइपलाइन में फीड करें। +2. फ़ोल्डर को बैच प्रोसेस करें – डायरेक्टरी में फ़ाइलों पर लूप चलाएँ, समान चरण लागू करें, और परिणाम CSV में लिखें। +3. वेब सर्विस के साथ इंटीग्रेट करें – OCR लॉजिक को Spring Boot `@RestController` के माध्यम से एक्सपोज़ करें जो मल्टीपार्ट अपलोड को स्वीकार करता है। + +इन सभी परिदृश्यों में वही **ocr image preprocessing** कॉन्फ़िगरेशन पुनः उपयोग किया जाता है जो हमने यहाँ बनाया था। + +## निष्कर्ष + +हमने जावा में Aspose के साथ **how to use OCR** को शुरू से अंत तक कवर किया: लाइसेंस लागू करना, इंजन बनाना, **auto deskew images** चालू करना, **auto language detection** सक्षम करना, इमेज लोड करना, और अंत में एकल `System.out.println` के साथ **extract text image** करना। कोड पूरी तरह से स्व-निर्भर है, किसी भी नवीनतम JDK पर चलता है, और सटीकता व प्रदर्शन के लिए सर्वोत्तम प्रैक्टिस दिखाता है। + +इसे अपनी तस्वीरों के साथ आज़माएँ—शायद कोई स्कैन किया हुआ कॉन्ट्रैक्ट या रसीद की स्क्रीनशॉट। प्री‑प्रोसेसिंग फ्लैग्स को समायोजित करें, विभिन्न भाषाओं के साथ प्रयोग करें, और आप जल्दी ही देखेंगे कि Aspose की OCR लाइब्रेरी प्रोडक्शन‑ग्रेड टेक्स्ट एक्सट्रैक्शन के लिए एक ठोस विकल्प क्यों है। + +कोई प्रश्न हैं या अपने परिणाम साझा करना चाहते हैं? नीचे टिप्पणी छोड़ें या GitHub पर मुझे ping करें। कोडिंग का आनंद लें! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन दृष्टिकोणों का अन्वेषण करने में मदद करेंगे। + +- [Aspose.OCR का उपयोग करके भाषा के साथ इमेज टेक्स्ट OCR कैसे करें](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR डिटेक्ट एरिया मोड के साथ जावा में इमेज से टेक्स्ट निकालें](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [OCR का उपयोग कैसे करें - जावा के लिए Aspose.OCR के साथ उन्नत तकनीकें](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/hindi/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..71ec59488 --- /dev/null +++ b/ocr/hindi/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,318 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR का उपयोग करके Python में OCR की सटीकता सुधारें। जानें कि OCR + भाषा कैसे सेट करें, OCR के लिए छवि कैसे लोड करें, और कस्टम शब्दकोश के साथ छवि से + टेक्स्ट कैसे निकालें। +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: hi +og_description: Python में OCR भाषा सेट करके, OCR के लिए छवि लोड करके, और कस्टम शब्दकोश + के साथ छवि से टेक्स्ट निकालकर OCR की सटीकता सुधारें। +og_title: Python में OCR की सटीकता सुधारें – चरण-दर-चरण मार्गदर्शिका +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Python में OCR की सटीकता बढ़ाएँ – संपूर्ण मार्गदर्शिका +url: /hi/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में OCR की सटीकता बढ़ाएँ – पूर्ण गाइड + +क्या आपने कभी सोचा है कि **OCR की सटीकता** कैसे **बेहतर** की जाए जब स्कैन किया गया टेक्स्ट अजीब प्रतीक, प्रोडक्ट कोड या ब्रांड नामों से भरा हो? आप अकेले नहीं हैं। कई प्रोजेक्ट्स में डिफ़ॉल्ट इंजन बस बकवास आउटपुट देता है, और यह उत्पादकता को गंभीर रूप से प्रभावित करता है। + +इस ट्यूटोरियल में हम एक व्यावहारिक, एंड‑टू‑एंड उदाहरण के माध्यम से दिखाएँगे कि कैसे **OCR भाषा सेट करें**, **इमेज को OCR के लिए लोड करें**, **इमेज पर OCR चलाएँ**, और अंत में **इमेज से टेक्स्ट निकालें** एक कस्टम डिक्शनरी के साथ जो पहचान दर को बढ़ाता है। अंत तक आपके पास एक तैयार‑स्क्रिप्ट होगा जिसे आप किसी भी Python कोडबेस में डाल सकते हैं। + +## आप क्या सीखेंगे + +- एक पूरी तरह कार्यशील Python स्क्रिप्ट जो Aspose OCR का उपयोग करके PNG फ़ाइल पढ़ती है। +- भाषा और कस्टम शब्द सूची को कॉन्फ़िगर करके **OCR की सटीकता बढ़ाने** की क्षमता। +- प्रत्येक सेटिंग क्यों महत्वपूर्ण है, इसका स्पष्ट विवरण, साथ ही गैर‑लैटिन अक्षरों जैसे एज केस को संभालने के टिप्स। +- सामान्य OCR समस्याओं के लिए एक त्वरित चेकलिस्ट। + +### आवश्यकताएँ + +- आपके मशीन पर Python 3.8 या उससे नया इंस्टॉल हो। +- `aspose-ocr` पैकेज (इंस्टॉल करने के लिए `pip install aspose-ocr`)। +- एक सैंपल इमेज (`technical_doc.png`) जिसमें वह टेक्स्ट हो जिसे आप पढ़ना चाहते हैं। +- Python की बुनियादी समझ—कोई विशेष चीज़ नहीं चाहिए। + +> **Pro tip:** यदि आप वर्चुअल एनवायरनमेंट में काम कर रहे हैं, तो पैकेज इंस्टॉल करने से पहले उसे एक्टिवेट करें। इससे डिपेंडेंसीज़ साफ़ रहती हैं और वर्ज़न कॉन्फ्लिक्ट से बचा जा सकता है। + +--- + +## चरण 1: Aspose OCR को इंस्टॉल और इम्पोर्ट करें + +सबसे पहले—लाइब्रेरी को अपने एनवायरनमेंट में जोड़ें और आवश्यक क्लासेस को इम्पोर्ट करें। + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr` नेमस्पेस आपको `OcrEngine` क्लास तक पहुँच देता है, जो OCR प्रक्रिया का दिल है। इसे यहाँ इम्पोर्ट करने से बाकी स्क्रिप्ट साफ़ और पढ़ने योग्य रहती है। + +--- + +## चरण 2: OCR इंजन बनाएं और **OCR भाषा सेट करें** + +भाषा क्यों महत्वपूर्ण है? OCR इंजन भाषा‑विशिष्ट मॉडल पर निर्भर करते हैं जो अक्षर रूप और शब्द पैटर्न को पहचानते हैं। यदि आप इंजन को बताते हैं कि आप अंग्रेज़ी टेक्स्ट स्कैन कर रहे हैं, तो वह सिलैरिक ग्लिफ़ को अनदेखा कर लैटिन अल्फाबेट पर फोकस करेगा, जिससे **OCR की सटीकता** में उल्लेखनीय सुधार होगा। + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Note:** Aspose OCR 50 से अधिक भाषाओं को सपोर्ट करता है। यदि आपका दस्तावेज़ अंग्रेज़ी नहीं है, तो `ocr.Language.English` को `ocr.Language.Spanish`, `ocr.Language.French` आदि से बदलें। + +--- + +## चरण 3: **कस्टम डिक्शनरी** परिभाषित करें ताकि सटीकता बढ़े + +कल्पना करें कि आप इनवॉइस स्कैन कर रहे हैं जिनमें “AsposeOCR” या “SKU12345” जैसे शब्द होते हैं। इंजन इन शब्दों को नहीं जानता, इसलिए वह गलत अनुमान लगाता है। एक कस्टम शब्द सूची प्रदान करने से इंजन को बताया जाता है, *“ये स्ट्रिंग्स वैध हैं—इन्हें सुधारने की कोशिश मत करो।”* यह **OCR की सटीकता बढ़ाने** का एक त्वरित तरीका है। + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +आप इस सूची को फ़ाइल या डेटाबेस से लोड कर सकते हैं यदि आपके पास सैकड़ों एंट्रीज़ हों—सादगी के लिए इसे Python लिस्ट में रखें। + +--- + +## चरण 4: **OCR के लिए इमेज लोड करें** + +अब हमें एक इमेज चाहिए। `Image.load` मेथड किसी भी सपोर्टेड रास्टर फ़ॉर्मेट (PNG, JPEG, BMP, आदि) का पाथ लेता है। यदि फ़ाइल नहीं मिलती, तो इंजन एक्सेप्शन फेंकेगा, इसलिए हम इस केस को हैंडल करेंगे। + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Why this step matters:** इमेज को सही तरीके से लोड करने से इंजन को वही पिक्सेल डेटा मिलता है जिसे आप विश्लेषण करना चाहते हैं। करप्ट फ़ाइलें या गलत पाथ अक्सर निराशा का कारण बनते हैं। + +--- + +## चरण 5: **इमेज पर OCR चलाएँ** और परिणाम निकालें + +इंजन कॉन्फ़िगर हो गया और इमेज तैयार है, अब वास्तविक पहचान सिर्फ एक मेथड कॉल है। रिज़ल्ट ऑब्जेक्ट में रॉ टेक्स्ट, कॉन्फिडेंस स्कोर, और यदि आवश्यक हो तो लेआउट जानकारी भी होती है। + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +यदि आपको **इमेज से टेक्स्ट निकालना** लाइन‑बाय‑लाइन चाहिए, तो आप न्यूलाइन कैरेक्टर पर स्प्लिट कर सकते हैं: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## चरण 6: आउटपुट वेरिफ़ाई करें – क्या यह वास्तव में **OCR की सटीकता** बढ़ाता है? + +आइए परिणाम प्रिंट करें और देखें कि हमारी कस्टम डिक्शनरी ने अंतर किया या नहीं। + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +सैंपल इमेज के लिए सामान्य आउटपुट कुछ इस प्रकार हो सकता है: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +ध्यान दें कि ब्रांड नाम, ग्रीक अक्षर, और प्रोडक्ट कोड ठीक वैसे ही दिख रहे हैं जैसा हमने परिभाषित किया था। कस्टम डिक्शनरी के बिना, इंजन इन्हें “Aspose OCR” या “SKU 1234” जैसी चीज़ों में “सुधार” करने की कोशिश करता। + +--- + +## सामान्य समस्याएँ और उनके समाधान + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | गलत भाषा सेट या कम‑रिज़ॉल्यूशन इमेज | सुनिश्चित करें `engine.language` स्रोत भाषा से मेल खाता हो और हाई‑DPI स्कैन (300 dpi या अधिक) उपयोग करें। | +| **Custom words ignored** | डिक्शनरी नहीं जुड़ी या प्रॉपर्टी नाम में टाइपो | `engine.text_processing.custom_dictionary = …` को दोबारा जांचें। | +| **File not found** | गलत पाथ या फ़ाइल परमिशन नहीं है | `os.path.abspath()` से एब्सोल्यूट पाथ वेरिफ़ाई करें; स्क्रिप्ट को उचित परमिशन के साथ चलाएँ। | +| **Slow processing** | बड़ी इमेज या कई पेज | इमेज को प्री‑प्रोसेस (क्रॉप, रिसाइज़) करें या `engine.recognize(image, max_threads=4)` से पैराललाइज़ करें। | + +--- + +## आगे बढ़ें: **OCR की सटीकता** बढ़ाने के उन्नत ट्यूनिंग + +1. **प्री‑प्रोसेसिंग** – Aspose OCR को फीड करने से पहले Pillow के साथ कंट्रास्ट एन्हांसमेंट या बिनैराइज़ेशन लागू करें। +2. **मल्टीपल लैंग्वेजेज** – `engine.language = ocr.Language.English | ocr.Language.French` सेट करके द्विभाषी पहचान सक्षम करें। +3. **रीजन‑बेस्ड OCR** – यदि आपको केवल किसी विशेष एरिया (जैसे टेबल) की जरूरत है, तो इमेज को पहले क्रॉप करें ताकि शोर कम हो। +4. **कॉन्फिडेंस फ़िल्टरिंग** – `result.confidence` प्रति‑कैरेक्टर स्कोर देता है; आप प्रोग्रामेटिकली लो‑कॉन्फिडेंस रिज़ल्ट को डिस्कार्ड कर सकते हैं। + +--- + +## पूर्ण कार्यशील स्क्रिप्ट + +नीचे वह पूरी, कॉपी‑पेस्ट‑रेडी स्क्रिप्ट है जिसमें हमने चर्चा किए सभी चरण शामिल हैं। इसे `improve_ocr_accuracy.py` के रूप में सेव करें और कमांड लाइन से चलाएँ। + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +चलाएँ: + +```bash +python improve_ocr_accuracy.py +``` + +आपको वही फॉर्मेटेड आउटपुट दिखेगा जैसा हमने पहले प्रदर्शित किया था। + +--- + +## निष्कर्ष + +हमने Python में **OCR की सटीकता** बढ़ाने का एक सरल तरीका कवर किया: + +1. **OCR भाषा** को आपके दस्तावेज़ से मेल खाने के लिए सेट करना। +2. **इमेज को सही तरीके से लोड** करना ताकि इंजन सही पिक्सेल देखे। +3. **इमेज पर OCR** एक ही मेथड कॉल से चलाना। +4. **इमेज से टेक्स्ट निकालना** और परिणाम की पुष्टि करना। +5. **कस्टम डिक्शनरी** जोड़ना ताकि डोमेन‑स्पेसिफिक टर्म्स लॉक हो सकें। + +यह पूरा वर्कफ़्लो—कच्ची तस्वीर से साफ़, सर्चेबल टेक्स्ट तक—एक साफ़, पुन: उपयोग योग्य स्क्रिप्ट में समेटा गया है। + +यदि आप अगली चुनौती के लिए तैयार हैं, तो इमेज प्री‑प्रोसेसिंग (कंट्रास्ट, डेस्क्यू) के साथ प्रयोग करें या `ocr.Language.English | ocr.Language.German` जैसी मल्टी‑लैंग्वेज सेटअप अपनाएँ। वही सिद्धांत लागू होते हैं, और आप विभिन्न दस्तावेज़ों में **OCR की सटीकता** लगातार बढ़ाते रहेंगे। + +कोई सवाल या अजीब एज केस है? नीचे कमेंट करें, और हैप्पी कोडिंग! + +![improve OCR accuracy + + +## आगे क्या सीखें? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और स्टेप‑बाय‑स्टेप व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स को मास्टर कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/hindi/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..901b6de93 --- /dev/null +++ b/ocr/hindi/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-19 +description: Python की OCR लाइब्रेरी का उपयोग करके छवि पर OCR करें। सीखें कि छवि से + टेक्स्ट कैसे पहचानें, JPEG से टेक्स्ट कैसे डिटेक्ट करें, और स्कैन की गई छवि से टेक्स्ट + को प्रभावी ढंग से निकालें। +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: hi +og_description: Python के साथ छवि पर OCR करें और स्कैन की गई फ़ाइलों से टेक्स्ट निकालें। + यह गाइड आपको चरण‑दर‑चरण छवियों को लोड करने, डेस्क्यूइंग करने और टेक्स्ट को पहचानने + के माध्यम से ले जाता है। +og_title: Python में इमेज पर OCR करें – पूर्ण टेक्स्ट एक्सट्रैक्शन गाइड +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Python में इमेज पर OCR करें – पूर्ण टेक्स्ट एक्सट्रैक्शन गाइड +url: /hi/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में इमेज पर OCR करें – पूर्ण टेक्स्ट एक्सट्रैक्शन गाइड + +क्या आपको कभी **perform OCR on image** फ़ाइलों को प्रोसेस करना पड़ा लेकिन कोड जटिल लगने के कारण रुकावट आई? आप अकेले नहीं हैं। चाहे आप स्कैन किए हुए रसीदों के ढेर को सर्चेबल PDFs में बदल रहे हों या डेटा‑साइंस प्रोजेक्ट के लिए JPEG से कैप्शन निकाल रहे हों, JPEGs और अन्य फ़ॉर्मैट्स से टेक्स्ट पहचानने की क्षमता आज के किसी भी डेवलपर के लिए अनिवार्य कौशल है। + +इस ट्यूटोरियल में हम एक पूर्ण, चलाने योग्य उदाहरण के माध्यम से दिखाएंगे कि आप कैसे **detect text from image** फ़ाइलों, **extract text from scanned image** दस्तावेज़ों को पहचानें, और यहाँ तक कि **load image for OCR** कुछ ही लाइनों में करें। अंत तक, आपके पास एक ठोस, प्रोडक्शन‑रेडी स्निपेट होगा जिसे आप अपने प्रोजेक्ट्स में जोड़ सकते हैं—कोई गायब इम्पोर्ट नहीं, कोई अस्पष्ट “see docs” शॉर्टकट नहीं। + +## आप क्या बनाएँगे + +- एक छोटा Python स्क्रिप्ट जो OCR इंजन बनाता है, auto‑deskew सक्षम करता है, JPEG (या कोई भी समर्थित फ़ॉर्मैट) लोड करता है, और पहचाने गए टेक्स्ट को प्रिंट करता है। +- **why** प्रत्येक सेटिंग के महत्व की व्याख्या, न कि केवल **how** टाइप करने की। +- मल्टी‑पेज PDFs, गैर‑अंग्रेज़ी भाषाओं, और ब्लरी स्कैन जैसी सामान्य समस्याओं को संभालने के टिप्स। + +### आवश्यकताएँ + +- Python 3.8+ स्थापित हो (उदाहरण में `ocr` पैकेज का उपयोग किया गया है जो `pip install ocr-lib` के माध्यम से उपलब्ध है – इसे अपने वास्तविक लाइब्रेरी नाम से बदलें)। +- Python फ़ंक्शन्स और वर्चुअल एनवायरनमेंट्स की बुनियादी परिचितता। +- एक इमेज फ़ाइल (JPEG, PNG, TIFF) जिसे आप प्रोसेस करना चाहते हैं; हम `skewed_page.jpg` को प्लेसहोल्डर के रूप में उपयोग करेंगे। + +> **Pro tip:** यदि आप Windows पर हैं, तो OCR लाइब्रेरी इंस्टॉल करते समय टर्मिनल को Administrator के रूप में चलाएँ ताकि परमिशन समस्याओं से बचा जा सके। + +## इमेज पर OCR करें – सेटअप और कॉन्फ़िगरेशन + +सबसे पहले आपको एक साफ़ OCR इंजन इंस्टेंस चाहिए। इसे ऑपरेशन के पीछे दिमाग समझें; उचित कॉन्फ़िगरेशन के बिना, सबसे तेज़ इमेज भी बेतुके परिणाम देगी। + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters:** +`engine.language` सेट करने से OCR इंजन द्वारा अपेक्षित कैरेक्टर सेट सीमित हो जाता है, जिससे सटीकता में उल्लेखनीय वृद्धि होती है। यदि आप इसे छोड़ देते हैं, तो इंजन अनुमान लगाने की कोशिश करेगा, अक्सर सरल शब्दों को गलत पढ़ेगा। + +## ऑटोमैटिक डेस्क्यू सक्षम करें – टिल्टेड स्कैन को ठीक करें + +स्कैन किए हुए पेज़ कभी भी पूरी तरह सपाट नहीं होते। एक हल्का टिल्ट कैरेक्टर सेगमेंटेशन को बिगाड़ सकता है, “Hello” को “H3llo” बना देता है। `auto_deskew` फ़्लैग आपके लिए यह काम करता है। + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** यदि आप जानते हैं कि आपकी इमेज पहले से ही सीधी है, तो deskew को डिसेबल करने से प्रोसेसिंग टाइम में कुछ मिलीसेकंड बच सकते हैं—हजारों पेज़ को बैच जॉब में हैंडल करते समय उपयोगी। + +## OCR के लिए इमेज लोड करें – JPEG, PNG, TIFF को सपोर्ट करना + +अब हम वास्तव में **load image for OCR** करते हैं। `ocr.Image.load` मेथड लचीला है; यह किसी भी समर्थित रास्टर फ़ॉर्मैट का पाथ स्वीकार करता है। + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial:** लाइब्रेरी फ़ाइल को एक आंतरिक बिटमैप में पढ़ती है, आवश्यक रंग स्थान परिवर्तन लागू करती है। इसे स्किप करके रॉ बाइट स्ट्रीम पास करने से `FileNotFoundError` उठेगा या, बदतर, चुपचाप खाली परिणाम देगा। + +यदि आपको विशेष रूप से **recognize text from JPEG** फ़ाइलों की आवश्यकता है, तो बस फ़ाइल एक्सटेंशन `.jpeg` या `.jpg` रखें। वही कॉल PNG (`.png`) या TIFF (`.tif`) के लिए भी बिना बदलाव के काम करता है। + +## इमेज पर OCR करें – इंजन चलाना + +इंजन तैयार और इमेज मेमोरी में होने के साथ, अब **perform OCR on image** डेटा का समय है। यह एकल लाइन सभी भारी काम करती है: प्री‑प्रोसेसिंग, सेगमेंटेशन, क्लासिफिकेशन, और टेक्स्ट असेंबली। + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood?** +- यदि सक्षम हो तो इंजन deskew ट्रांसफ़ॉर्मेशन लागू करता है। +- यह कैरेक्टर्स पहचानने के लिए न्यूरल नेटवर्क या Tesseract बैकएंड चलाता है। +- अंत में, यह कैरेक्टर्स को शब्दों और लाइनों में जोड़ता है, एक समृद्ध `result` ऑब्जेक्ट लौटाता है। + +## स्कैन की गई इमेज से टेक्स्ट निकालें – परिणाम आउटपुट करें + +अंतिम कदम है **extract text from scanned image** करना और उसे प्रदर्शित करना। `result.text` एट्रिब्यूट में प्लेन‑टेक्स्ट प्रतिनिधित्व होता है। + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +सामान्य आउटपुट इस प्रकार दिखता है: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +यदि OCR इंजन कोई कैरेक्टर नहीं ढूँढ पाता, तो `result.text` एक खाली स्ट्रिंग होगी। ऐसे में, इमेज की क्वालिटी दोबारा जांचें या `engine.confidence_threshold` प्रॉपर्टी को समायोजित करने पर विचार करें (यदि आपकी लाइब्रेरी इसे सपोर्ट करती है)। + +## सामान्य विविधताओं को संभालना + +### JPEG बनाम PNG से टेक्स्ट पहचानना + +दोनों फ़ॉर्मैट सपोर्टेड हैं, लेकिन JPEG कम्प्रेशन आर्टिफैक्ट्स पैदा कर सकता है जो इंजन को भ्रमित कर देते हैं। यदि आप अक्सर गलत पहचान देखते हैं, तो पहले JPEG को PNG में कन्वर्ट करने की कोशिश करें: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### कई भाषाओं वाले इमेज से टेक्स्ट डिटेक्ट करना + +यदि आपका दस्तावेज़ अंग्रेज़ी और स्पेनिश दोनों को मिलाता है, तो मल्टी‑लैंग्वेज मोड सेट करें: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +इंजन तब पहचान के दौरान दोनों अल्फ़ाबेट्स को ध्यान में रखेगा। + +### स्कैन किए हुए PDFs से टेक्स्ट निकालना + +PDFs के लिए, आपको पहले प्रत्येक पेज़ को इमेज में रास्टराइज़ करना होगा। `pdf2image` जैसी लाइब्रेरीज़ इसे आसान बनाती हैं: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +## पूरा कार्यशील उदाहरण + +नीचे पूरा स्क्रिप्ट है जिसे आप `ocr_demo.py` फ़ाइल में कॉपी‑पेस्ट कर सकते हैं। इसमें एरर हैंडलिंग और एग्जीक्यूशन टाइम मापने के लिए एक छोटा हेल्पर शामिल है। + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (मान लेते हैं कि स्कैन स्पष्ट है): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +## अक्सर पूछे जाने वाले प्रश्न + +**Q: क्या मैं इसे हेडलेस सर्वर पर चला सकता हूँ?** +A: बिल्कुल। लाइब्रेरी GUI के बिना काम करती है; बस सुनिश्चित करें कि आवश्यक नेटिव बाइनरीज़ (जैसे, Tesseract) सर्वर पर इंस्टॉल हों। + +**Q: अगर इमेज ब्लरी है तो क्या करें?** +A: `engine.recognize` से पहले शार्पनिंग फ़िल्टर जोड़ने पर विचार करें। कई OCR लाइब्रेरीज़ `image_preprocessing.sharpen = True` एक्सपोज़ करती हैं या आप OpenCV के `cv2.GaussianBlur` को रिवर्स में उपयोग कर सकते हैं। + +**Q: क्या स्क्रिप्ट बैच प्रोसेसिंग सपोर्ट करती है?** +A: हाँ। `perform_ocr` को फ़ाइल पाथ की सूची पर लूप में रैप करें, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/hindi/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..060274a12 --- /dev/null +++ b/ocr/hindi/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR Java का उपयोग करके छवि पर OCR करें। सीखें कि OCR के लिए छवि + कैसे लोड करें, Aspose लाइसेंस का उपयोग करें, और कुछ ही मिनटों में छवि से टेक्स्ट + निकालें। +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: hi +og_description: Aspose OCR Java के साथ छवि पर OCR करें। यह गाइड दिखाता है कि Aspose + लाइसेंस कैसे उपयोग करें, OCR के लिए छवि लोड करें, और छवि से प्रभावी ढंग से टेक्स्ट + निकालें। +og_title: Aspose OCR Java के साथ इमेज पर OCR करें – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Aspose OCR Java के साथ इमेज पर OCR करें – पूर्ण चरण-दर-चरण मार्गदर्शिका +url: /hi/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Java के साथ इमेज पर OCR करें – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको कभी **इमेज पर OCR करना** फ़ाइलों पर OCR करना पड़ा लेकिन आप सुनिश्चित नहीं थे कि कौन‑सी लाइब्रेरी बिना अधिक कॉन्फ़िगरेशन के भरोसेमंद परिणाम देगी? आप अकेले नहीं हैं। कई वास्तविक‑दुनिया प्रोजेक्ट्स में—जैसे पासपोर्ट स्कैन करना, इनवॉइस को डिजिटल बनाना, या स्क्रीनशॉट से टेक्स्ट निकालना—टेक्स्ट इमेज डेटा को जल्दी पहचानने की क्षमता एक गेम‑चेंजर है। + +इस ट्यूटोरियल में हम एक व्यावहारिक उदाहरण के माध्यम से दिखाएंगे कि Aspose OCR for Java का उपयोग करके **इमेज पर OCR करना** कैसे किया जाता है। हम सब कुछ कवर करेंगे—आपका Aspose लाइसेंस लागू करने से लेकर चित्र लोड करने, इंजन चलाने, और अंत में **इमेज से टेक्स्ट निकालना** ताकि आप इसे आगे उपयोग कर सकें। कोई फालतू नहीं, सिर्फ एक कार्यशील समाधान जिसे आप कॉपी‑पेस्ट कर सकते हैं। + +## आप क्या सीखेंगे + +- Java प्रोजेक्ट में **use Aspose license** कैसे किया जाता है, इसका स्पष्ट चित्र। +- **load image for OCR** करने के लिए आवश्यक सटीक कोड और इंजन को ऑटो‑डिटेक्ट लैंग्वेजेज़ देने देना। +- **recognize text image** सामग्री और **extract text from image** को सुरक्षित रूप से करने के चरण‑दर‑चरण निर्देश। +- सामान्य समस्याओं (खाली परिणाम, असमर्थित फॉर्मेट, और मेमोरी समस्याओं) को संभालने के टिप्स। + +> **Prerequisites** – Java 8 या उससे नया, निर्भरता प्रबंधन के लिए Maven या Gradle, और Aspose OCR for Java लाइसेंस फ़ाइल (या आप मूल्यांकन मोड में चला सकते हैं)। + +--- + +## Aspose OCR Java के साथ इमेज पर OCR कैसे करें + +नीचे पूरा, तैयार‑चलाने योग्य Java प्रोग्राम है जो पूरे फ्लो को दर्शाता है। इसे `AsposeOcrDemo.java` के रूप में सहेजें और अपने IDE या कमांड लाइन से चलाएँ। + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### अपेक्षित कंसोल आउटपुट + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +यदि आप प्रोग्राम को बिना लाइसेंस फ़ाइल के चलाते हैं, तो पहली पंक्ति सिर्फ यह बताएगी कि आप मूल्यांकन मोड में हैं, लेकिन OCR फिर भी काम करेगा। + +--- + +## Aspose लाइसेंस सेट अप और उपयोग करें + +### लाइसेंस क्यों महत्वपूर्ण है + +लाइब्रेरी को मूल्यांकन मोड में चलाना त्वरित परीक्षणों के लिए ठीक है, लेकिन यह आउटपुट में वॉटरमार्क जोड़ता है और प्रति रन आप जितने पेज प्रोसेस कर सकते हैं उसकी संख्या सीमित करता है। **use aspose license** चरण लागू करने से ये प्रतिबंध हटते हैं और Aspose को संकेत मिलता है कि आप एक भुगतान करने वाले ग्राहक हैं। + +### लाइसेंस कैसे प्राप्त करें और लागू करें + +1. Aspose स्टोर से लाइसेंस खरीदें। +2. `Aspose.OCR.Java.lic` फ़ाइल डाउनलोड करें। +3. इसे ऐसी जगह रखें जहाँ आपका एप्लिकेशन पढ़ सके—आमतौर पर `src/main/resources` फ़ोल्डर। +4. किसी भी OCR कार्य से पहले, ऊपर दिखाए गए कोड की तरह `new License().setLicense("Aspose.OCR.Java.lic");` कॉल करें। + +> **Pro tip:** यदि आप सर्वर पर डिप्लॉय कर रहे हैं, तो `FileNotFoundException` से बचने के लिए एक एब्सॉल्यूट पाथ या क्लास‑पाथ रिसोर्स लोडर का उपयोग करें। + +--- + +## OCR प्रोसेसिंग के लिए इमेज लोड करें + +`Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` लाइन **load image for OCR** चरण का मुख्य भाग है। Aspose OCR कई फॉर्मेट्स को सपोर्ट करता है: PNG, JPEG, BMP, TIFF, और यहाँ तक कि मल्टी‑पेज PDFs (जब Aspose.Pdf के साथ मिलाया जाए)। + +### सामान्य समस्याएँ + +| Issue | Symptom | Fix | +|-------|---------|-----| +| Wrong file path | `FileNotFoundException` | पाथ को दोबारा जांचें; OS‑स्वतंत्र सेपरेटर के लिए `Paths.get(...)` उपयोग करें। | +| Unsupported format | `UnsupportedOperationException` | इमेज को लोड करने से पहले PNG या JPEG में बदलें। | +| Huge image ( > 10 MP) | Out‑of‑memory errors | इमेज को `java.awt.Image` से डाउनस्केल करें फिर Aspose को दें। | + +--- + +## इमेज से टेक्स्ट निकालें और परिणाम संभालें + +जब OCR इंजन समाप्त हो जाता है, तो `OcrResult` ऑब्जेक्ट में पहचाना गया स्ट्रिंग होता है। यहाँ हम आगे की प्रोसेसिंग के लिए **extract text from image** करते हैं—डेटाबेस में सहेजना, सर्च इंडेक्स में फीड करना, या डाउनस्ट्रीम NLP पाइपलाइन में देना। + +### कई भाषाओं से निपटना + +चूँकि हमने `engine.setLanguage(Language.Auto)` सेट किया है, Aspose रन‑टाइम पर भाषाओं का पता लगाने की कोशिश करेगा। यदि आप पहले से भाषा जानते हैं (जैसे सभी दस्तावेज़ रूसी हैं), तो आप `Language.Auto` को `Language.Russian` से बदल सकते हैं जिससे प्रदर्शन में सुधार होगा। + +### पोस्ट‑प्रोसेसिंग टिप्स + +- **Trim whitespace**: `result.getText().trim()`। +- **Normalize line endings**: `result.getText().replace("\r\n", "\n")`। +- **Remove non‑printable characters**: `result.getText().replaceAll("[^\\p{Print}]", "")` जैसा रेगेक्स उपयोग करें। + +--- + +## उन्नत विकल्पों के साथ टेक्स्ट इमेज को पहचानें (वैकल्पिक) + +यदि आपको अधिक सूक्ष्म नियंत्रण चाहिए, तो Aspose OCR अतिरिक्त प्रॉपर्टीज़ प्रदान करता है: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +ये समायोजन उपयोगी होते हैं जब आप स्कैन किए गए दस्तावेज़ों से निपट रहे हों जो स्क्यू या कम कॉन्ट्रास्ट से पीड़ित हों। + +--- + +## पूर्ण कार्यशील उदाहरण का सारांश + +सब कुछ मिलाकर, अंतिम प्रोग्राम क्रम में निम्न कार्य करता है: + +1. **Perform OCR on image** – `OcrEngine` बनाकर। +2. **Use Aspose license** – वैकल्पिक लेकिन अनुशंसित। +3. **Load image for OCR** – `Image.load` के माध्यम से। +4. **Set language detection** – `Language.Auto` से **recognize text image** स्वचालित रूप से। +5. **Extract text from image** – परिणाम प्रिंट करें, खाली प्रतिक्रियाओं को सुगमता से संभालें। + +आप ऊपर दिया गया कोड ब्लॉक सीधे इस डिपेंडेंसी के साथ एक Maven प्रोजेक्ट में कॉपी कर सकते हैं: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` चलाएँ और कंसोल में पहचाना गया टेक्स्ट देखें। + +--- + +## निष्कर्ष + +हमने अभी आपको दिखाया है कि Aspose OCR for Java का उपयोग करके **perform OCR on image** फ़ाइलों को कैसे किया जाता है, लाइसेंस लागू करने से लेकर **loading the image for OCR**, **recognizing text image** सामग्री, और अंत में **extracting text from image** को डाउनस्ट्रीम उपयोग के लिए कैसे निकाला जाता है। यह तरीका सीधा है, कई भाषाओं के साथ बॉक्स से बाहर काम करता है, और आवश्यकता पड़ने पर उन्नत प्री‑प्रोसेसिंग विकल्पों के साथ विस्तारित किया जा सकता है। + +अगला क्या? OCR आउटपुट को सर्च इंडेक्स में फीड करें, निकाले गए टेक्स्ट के साथ PDFs बनाएं, या विभिन्न इमेज फॉर्मेट्स के साथ प्रयोग करें। संभावनाएँ अनंत हैं, और Aspose की मजबूत API के साथ आप OCR की जटिलताओं से लड़ने की बजाय फीचर बनाने में अधिक समय बिताएंगे। + +कोई सवाल है या किसी एज़ केस का सामना किया? नीचे टिप्पणी छोड़ें—हैप्पी कोडिंग! + +## अब आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [Aspose.OCR for Java का उपयोग करके URL से इमेज से टेक्स्ट निकालना कैसे करें](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Aspose.OCR BufferedImage का उपयोग करके Java में इमेज को टेक्स्ट में बदलना](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Aspose.OCR Detect Areas Mode के साथ Java में इमेज से टेक्स्ट निकालना](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..5d608d97a --- /dev/null +++ b/ocr/hongkong/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Python OCR 從影像建立可搜尋的 PDF。學習將 OCR 轉換為 PDF、從影像擷取文字,並快速執行影像 OCR。 +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: zh-hant +og_description: 使用 Python OCR 從圖像建立可搜尋的 PDF。本指南說明如何將 OCR 轉換為 PDF、從圖像擷取文字,以及對圖像執行 OCR。 +og_title: 在 Python 中建立可搜尋 PDF – 完整程式教學 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: 使用 Python 建立可搜尋 PDF – 完整逐步指南 +url: /zh-hant/python-java/general/create-searchable-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 – 完整步驟指南 + +有沒有曾經需要從掃描的收據**建立可搜尋的 PDF**,卻不知從何開始?你並不孤單——許多開發者在首次嘗試將文字圖片轉換成可搜尋的 PDF 時,都會碰到同樣的障礙。 + +在本教學中,我們將逐步說明一個實用解決方案,讓你**對圖像執行 OCR**,將 OCR 結果轉換為**可搜尋的 PDF**,甚至在需要時提取原始文字以供後續處理。內容直截了當,只提供一個可直接複製貼上到專案中的可運作範例。 + +## 你將學會 + +- 如何在 Python 中設置輕量級的 OCR 引擎 +- 將 **OCR 轉換為 PDF** 並儲存為可搜尋文件的完整步驟 +- 如何 **從圖像提取文字** 以進行後續分析 +- 處理常見問題(如圖像方向與大型檔案)的技巧 +- 一個完整、可執行的腳本,讓你可依需求自行調整 + +### 前置條件 + +- 在機器上已安裝 Python 3.8+ +- 對 pip 與虛擬環境有基本認識(非必須,但建議使用) +- 一個包含清晰、機器可讀文字的圖像檔案(PNG、JPEG 等) + +如果你已具備以上條件,讓我們開始吧。 + +## 步驟 1:安裝必要的函式庫 + +The code snippet you saw earlier uses a fictional `ocr` package, but the same ideas apply to real‑world libraries such as **EasyOCR**, **pytesseract**, or **pdfminer.six**. For this guide we’ll use **EasyOCR** because it’s pure Python, supports many languages, and returns a handy PDF conversion method via an auxiliary helper. + +```bash +pip install easyocr pillow +``` + +> **小技巧:** 在虛擬環境中安裝 (`python -m venv venv && source venv/bin/activate`) 以保持相依套件整潔。 + +## 步驟 2:初始化 OCR 引擎 – 對圖像執行 OCR + +Now that the library is ready, we create an OCR engine and tell it to work with English text. This is the first place where we **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Why do we need a dedicated reader object? EasyOCR pre‑loads language models, so re‑using the same `reader` for multiple images is far more efficient than re‑initializing it each time. + +## 步驟 3:載入圖像 – 從圖像提取文字 + +Let’s bring the picture into memory. This step is where we **extract text from image** later, but first we just load it. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +If your image is upside‑down or skewed, consider using Pillow’s `rotate` or `transpose` methods before feeding it to the OCR engine. A quick visual check can save you hours of debugging later. + +## 步驟 4:執行 OCR 引擎並取得結果 + +Here’s the core of the process—sending the image to the OCR engine and getting back structured data. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +The `detail=1` flag gives us bounding boxes, which we’ll need when we later **convert OCR to PDF**. If you only care about raw strings, set `detail=0`. + +## 步驟 5:將 OCR 結果轉換為可搜尋的 PDF – OCR 轉 PDF + +EasyOCR doesn’t provide a direct PDF writer, but we can stitch together the PDF ourselves using Pillow and the `reportlab` library. To keep the tutorial lightweight, we’ll use `fpdf2`, which lets us embed the original image and overlay invisible text. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +What just happened? We placed the scanned image as the visible layer, then wrote the recognized words on top using white text that blends into the white background. Search tools still read the hidden layer, so the PDF becomes **searchable** without altering the visual appearance. + +## 步驟 6:儲存 PDF 位元組 – 圖像轉 PDF + +If you prefer to handle the PDF in memory (e.g., sending it over an API), you can capture the bytes instead of writing directly to disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +That line demonstrates the classic **convert image to PDF** workflow: you start with an image, run OCR, overlay text, and finally emit a PDF stream. + +## 步驟 7:驗證結果 – 快速檢查 + +After you run the script, open `receipt_searchable.pdf` in any PDF viewer and try the search box (Ctrl + F). Type a word you know appears in the receipt—if it jumps to the right spot, you’ve successfully **create searchable pdf**! + +If the search fails, double‑check: + +1. OCR 信心分數(`conf` 值)。低信心可能表示圖像模糊。 +2. 邊界框座標——有時 EasyOCR 會以不同方向回報。 +3. PDF 檢視器未設定為「僅圖像」模式(雖少見,但部分檢視器有此選項)。 + +## 完整可執行腳本 + +Putting everything together, here’s the complete, ready‑to‑run Python file: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Save this as `searchable_pdf.py`, replace the `YOUR_DIRECTORY` placeholders with real paths, and run: + +```bash +python searchable_pdf.py +``` + +You should see a confirmation message and a brand‑new searchable PDF sitting in your folder. + +## 常見問題與邊緣情況 + +**如果圖像是彩色的呢?** +EasyOCR 同時支援灰階與彩色圖像,但將圖像轉為灰階(`pil_image.convert("L")`)有時能提升噪點掃描的辨識準確度。 + +**我可以處理多頁 PDF 嗎?** +可以——對每一頁圖像迴圈,執行 OCR 步驟,並將每頁加入同一個 `FPDF` 物件。只需記得對每張新圖像呼叫 `self.add_page()` 以重設游標。 + +**有沒有方法保留原始文字層,而不是使用不可見的白色文字?** +如果需要真正的「文字在圖像下」PDF(例如為了無障礙需求),可考慮使用 `pdfminer` 或 `pikepdf` 來嵌入帶有正確 PDF 標籤的隱藏文字層。這較為進階,但原理相同:背景圖像 + 覆蓋文字。 + +**如果 OCR 信心太低怎麼辦?** +You can filter out low‑confidence words: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## 總結 – 我們完成了什麼 + +We started with a simple image of a receipt, **performed OCR on image**, extracted the recognized strings, and finally **create searchable pdf** that behaves like any professionally scanned document. The process covered every secondary keyword—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, and **perform OCR on image**—so you now have a reusable toolbox for any similar project. + +### 往後的步驟 + +- 嘗試傳入其他語言的 ISO 代碼至 `easyocr.Reader(['en', 'es'])` 以支援多語言。 +- 若需要完全離線的解決方案,可改用 Tesseract 取代 EasyOCR;其餘流程保持不變。 +- 加入 OCR 信心可視化(在圖像上繪製邊界框)以除錯有問題的掃描。 + +Got a twist you’d like to share? Drop a comment, fork + +## 接下來該學什麼? + +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. + +- [使用 Aspose OCR 從圖像提取文字 – 步驟指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [將圖像轉為 PDF(C#) – 儲存多頁 OCR 結果](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [如何 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/hongkong/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/hongkong/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..61dfe69e4 --- /dev/null +++ b/ocr/hongkong/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-19 +description: 使用簡易 OCR 引擎在 Python 中從圖像提取文字。了解如何將掃描圖像轉換為文字、從圖片辨識文字,以及高效地使用 Python 列出圖像檔案。 +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: zh-hant +og_description: 使用輕量級 OCR 引擎於 Python 中提取圖像文字。本指南將示範如何將掃描圖像轉換為文字、從圖片辨識文字,並在簡單步驟中列出 + Python 圖像檔案。 +og_title: 使用 Python 從圖像提取文字 – 完整批次 OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: 使用 Python 從圖片提取文字 – 完整批次 OCR 指南 +url: /zh-hant/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從圖像中提取文字(Python) – 完整批次 OCR 指南 + +是否曾經需要 **從圖像中提取文字**,卻不知從何開始?你並不孤單——開發者常常面臨將掃描的 PDF、拍攝的收據或螢幕截圖轉換為可搜尋文字的挑戰。在本教學中,我們將逐步示範一個完整、可直接執行的範例,說明如何 **將掃描圖像轉換為文字**、從圖片中辨識文字,甚至以 **list image files python** 風格列出圖像檔案。完成後,你將擁有一個可重複使用的腳本,一次處理整個資料夾。 + +我們會涵蓋所有必備內容:所需函式庫、每一步的重要性、邊緣案例處理,以及一些除錯技巧。無需追尋外部文件;以下程式碼是完整自足的,說明同時回答「如何」*以及*「為什麼」。打開你最喜愛的 IDE,讓我們馬上開始吧。 + +--- + +## 你將建立的內容 + +- 初始化 OCR 引擎(本教學示範使用 `ocr` 套件)。 +- 掃描目錄並以 **list image files python** 風格列出圖像檔案,過濾 PNG、JPG 與 TIFF。 +- 對所有找到的圖片執行 **batch OCR** 作業。 +- 列印每個檔案的提取文字,並清楚標示。 + +> **專業提示:** 若尚未安裝 `ocr` 套件,你可以改用 `pytesseract`,只需做少量修改——核心邏輯保持不變。 + +--- + +## 前置條件 + +- Python 3.8+(腳本使用 f‑strings 與型別提示)。 +- 具備提供 `OcrEngine` 並支援 `recognize_batch` 的 OCR 套件。本教學假設使用虛構的 `ocr` 套件,但此模式同樣適用於真實套件。 +- 一個包含欲處理圖像檔案的資料夾(`.png`、`.jpg`、`.tif`)。 + +--- + +## 第一步 – 安裝與匯入必要模組 + +首先,確保 OCR 套件已安裝。若使用真實的套件如 `pytesseract`,請相應替換匯入語句。 + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **為什麼這很重要:** 匯入 `os` 可提供跨平台的路徑處理,而 `typing.List` 有助於 IDE 自動完成與未來相容性。 + +--- + +## 第二步 – **Extract Text from Images**:初始化 OCR 引擎 + +建立引擎是任何 OCR 工作的第一步。我們同時將語言設定為自動偵測,讓引擎能處理混合語言的文件。 + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **說明:** 透過將引擎建立封裝於函式中,使程式碼保持模組化。若日後需要調整 DPI 或 OCR 模式,只需修改此處即可。 + +--- + +## 第三步 – **List Image Files Python**:從目錄收集檔案 + +現在我們需要找出所有要處理的圖片。以下的列表推導式映射了常見的 “list image files python” 範式。 + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **邊緣案例處理:** 此函式會忽略子資料夾(日後可加入遞迴),並自動過濾隱藏檔,因為它們通常不會以支援的副檔名結尾。 + +--- + +## 第四步 – **Convert Scanned Images to Text**:執行批次 OCR + +大多數 OCR 套件提供批次方法,速度遠快於一次處理單張圖像。以下示範如何呼叫它。 + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **為什麼使用批次?** 一次傳送所有圖像可減少開銷(例如重複載入 OCR 模型),且通常能更有效利用 CPU/GPU。 + +--- + +## 第五步 – **Recognize Text from Pictures**:顯示結果 + +最後,我們遍歷檔名與 OCR 結果的配對,為每張圖像印出整潔的標題。 + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **提示:** `strip()` 會移除 OCR 常加入的前後空白字元。 + +--- + +## 完整腳本 – 整合所有步驟 + +以下為完整、可執行的程式。將其儲存為 `batch_ocr.py`,然後執行 `python batch_ocr.py `。 + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### 預期輸出 + +假設資料夾內有 `invoice1.png` 與 `receipt.jpg`,可能會看到以下輸出: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +每個區塊都有清楚的標籤,使後續處理(例如儲存至資料庫)變得簡單。 + +--- + +## 處理常見問題 + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **沒有文字顯示** | OCR 語言未偵測到或影像對比度過低。 | 強制指定語言 (`engine.language = ocr.Language.English`) 或預先處理影像(提升對比度)。 | +| **大批次記憶體錯誤** | 引擎嘗試一次載入所有影像。 | 將 `image_files` 分割成多個區塊(`batch_size = 20`),並重複呼叫 `recognize_batch`。 | +| **不支援的檔案格式** | 你加入了 `.gif` 或 `.bmp`。 | 擴充 `supported_exts` 元組或事先將影像轉為 PNG/JPG。 | +| **Unicode 亂碼** | OCR 回傳位元組而非字串。 | 確保 OCR 套件輸出 Unicode(如有需要使用 `result.text.decode('utf‑8')`)。 | + +--- + +## 擴充工作流程 + +既然你已能 **extract text from images**,可以考慮以下後續步驟: + +- **Export to CSV** – 將每個檔名與其提取文字寫入試算表,以供分析。 +- **Parallel processing** – 使用 `concurrent.futures.ThreadPoolExecutor` 同時處理多個批次。 +- **Integrate with cloud OCR** – 將本地引擎替換為 Google Vision 或 Azure OCR,以在複雜版面上獲得更高準確度。 +- **Add image preprocessing** – 如 Pillow 或 OpenCV 等函式庫可在 OCR 前進行去斜、去噪或二值化,提升結果。 + +所有這些想法皆使用我們已建立的核心函式,無需從頭開始。 + +--- + +## 結論 + +我們剛剛完整示範了在 Python 中 **extract text from images** 的解決方案,涵蓋從 **list image files python**、**recognize text from pictures** 到最終的 **convert scanned images to text**,全部以整潔的批次方式完成。此腳本刻意保持簡潔,同時具備彈性,可作為更大型專案的基礎——無論是數位化收據、建構可搜尋的檔案庫,或是驅動資料抽取管線。 + +試著執行它,調整前處理步驟,觀察 OCR 準確度提升。若遇到問題,請回顧「處理常見問題」表格;大多數問題只需微調設定即可解決。 + +準備好接受下一個挑戰了嗎?試著加入使用 `pdf2image` 的 PDF 轉圖像步驟,然後將這些圖像直接輸入同樣的管線。結合 OCR 與 Python 豐富的生態系統,無所不能。 + +祝編程愉快,願你的文字永遠清晰可讀! + +## 接下來該學什麼? + +以下教學涵蓋與本指南密切相關的主題,建立在所示技巧之上。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [使用 Aspose OCR 從圖像提取文字 – 步驟指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [提取文字圖像 – Aspose.OCR for Java 基礎](/ocr/english/java/ocr-basics/) +- [如何使用 Aspose.OCR for Java 從 URL 提取圖像文字](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/hongkong/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..580e7236f --- /dev/null +++ b/ocr/hongkong/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Python OCR 從圖片提取文字。於簡潔教學中學習自動語言偵測、平行處理與批次辨識。 +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: zh-hant +og_description: 使用 Python OCR 從圖像中提取文字。本指南在單一教學中展示自動語言偵測、平行處理與批次辨識。 +og_title: 使用 Python 從圖像提取文字 – 完整 OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 在 Python 中從圖片提取文字 – 完整 OCR 指南 +url: /zh-hant/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從圖片中擷取文字 – 完整 OCR 教學 + +有沒有想過 **從圖片中擷取文字** 而不必手動輸入每個字?你並不是唯一有這個需求的人。無論是要數位化舊收據、建立可搜尋的文件庫,或只是想玩玩 AI 小技巧,從圖片中抽取文字都是現今 Python 開發者必備的技能。 + +在本教學中,我們將一步步示範一個完整、可直接執行的範例,使用熱門的 OCR 引擎 **擷取圖片文字**。內容涵蓋自動語言偵測、平行處理加速,以及批次影像辨識,讓你能在數秒內處理數十個檔案。聽起來正是你需要的嗎?讓我們開始吧。 + +## 你將學到什麼 + +- 如何使用 `ocr.OcrEngine` 建立 OCR 引擎實例。 +- 啟用 **自動語言偵測**,讓引擎自行選擇正確語言。 +- 以自訂執行緒池設定 **平行處理 OCR**。 +- 在檔案清單上執行 **批次影像辨識**。 +- 印出每張圖片的辨識文字,方便儲存或建立索引。 + +不需要額外文件說明——所有必要資訊都在此,且程式碼可直接使用 `ocr` 套件(透過 `pip install ocr` 安裝)即跑通。 + +## 前置條件 + +在開始之前,請確保你已具備: + +1. Python 3.8 或更新版本。 +2. `ocr` 套件(`pip install ocr`)。 +3. 一個放有 PNG(或 JPG)圖片的資料夾。 +4. 基本的 Python 函式與迴圈概念。 + +就這樣——沒有繁重的相依套件,亦不需要 GPU,只要純 Python。 + +![從圖片中擷取文字範例](https://example.com/ocr-demo.png "螢幕截圖顯示從圖片中擷取文字的輸出") + +*Alt text: 從圖片中擷取文字示範螢幕截圖* + +## 第一步 – 設定 OCR 引擎 (Primary Keyword in Action) + +首先,建立一個 OCR 引擎實例。把 `ocr.OcrEngine()` 想成整個流程的「大腦」;它負責辨識字元、行與段落。 + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +為什麼需要顯式建立引擎?因為 **ocr.OcrEngine 的使用方式** 能讓你細部控制語言設定、執行緒等,是相較於單行輔助函式最彈性的 **從圖片中擷取文字** 方法。 + +## 第二步 – 讓引擎自動偵測語言 + +大多數 OCR 函式庫都需要你手動指定語言。對單一語言的專案還好,但面對混合語言的批次時就相當麻煩。幸好,`ocr` 套件支援 **自動語言偵測**。 + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +將 `engine.language` 設為 `ocr.Language.Auto` 後,引擎會自行嗅探每張圖片並挑選適當的語言模型。這一行程式碼能為你省下處理國際文件時的數小時手動設定時間。 + +## 第三步 – 使用平行處理加速 OCR + +如果你的電腦有四核心以上的 CPU,何不善加利用?引擎可以啟動執行緒池,讓多張圖片同時被處理。這正是 **平行處理 OCR** 發揮威力的地方。 + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +依照你的機器自行調整 `4` 的數值。執行緒越多 → 批次執行越快,但每條執行緒都會佔用記憶體,請找出最適合你環境的平衡點。 + +## 第四步 – 收集要處理的圖片 + +接下來需要一個檔案路徑清單。你可以手動寫入、從 CSV 讀取,或使用 `glob`。為了說明,我們直接硬寫一小段清單: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +把 `YOUR_DIRECTORY` 替換成你實際的路徑。如果有數十個檔案,只要 `glob.glob("*.png")` 就能快速抓取。 + +## 第五步 – 執行批次影像辨識 + +以下程式碼是本教學的核心:一次呼叫即可處理 `files` 中的所有圖片,並回傳結果物件清單。這就是讓大規模 OCR 成為可能的 **批次影像辨識** 功能。 + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +在背後,引擎會把每個檔案分配給先前設定的四個工作執行緒,同時自動偵測每張圖片的語言。回傳的清單中,每個元素都包含辨識出的文字與相關中繼資料。 + +## 第六步 – 印出(或儲存)擷取的文字 + +最後,我們遍歷結果並印出文字。實務上你可能會把它寫入資料庫或 CSV 檔,但為了簡化示範,我們直接印出。 + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**預期輸出**(為簡潔起見已截斷): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +每個區塊會先顯示檔名,接著是 OCR 產生的字串。若圖片包含多種語言,感謝前面的 **自動語言偵測** 步驟,對應的字元會正確顯示。 + +## 專業小技巧與常見陷阱 + +- **影像品質很重要** – 模糊或低對比的照片會產生雜訊。必要時可使用 OpenCV(`cv2.threshold`、`cv2.resize`)前處理。 +- **執行緒數 vs. I/O** – 若圖片儲存在慢速網路磁碟,增加執行緒未必有效。可使用 `top` 或 `Task Manager` 觀察 CPU 使用率。 +- **Unicode 處理** – `result.text` 為 Unicode 字串。寫檔時請以 `encoding="utf‑8"` 開啟,以免拋出 `UnicodeEncodeError`。 +- **記憶體使用** – 大型 PDF 可能佔用大量 RAM。若遭遇 `MemoryError`,請縮減執行緒池大小或分批處理圖片。 + +## 完整可執行腳本 + +以下是完整、可直接複製貼上的腳本,已整合上述所有步驟。將它存為 `batch_ocr.py`,然後執行 `python batch_ocr.py`。 + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +執行方式如下: + +```bash +python batch_ocr.py ./my_images 4 +``` + +執行後,你會看到每張圖片對應的格式化文字區塊,證明你已能 **從圖片中擷取文字**,且規模化處理。 + +## 接下來可以做什麼? + +既然已掌握使用 Python **從圖片中擷取文字** 的基礎,以下方向值得一試: + +- **後處理**:使用正規表達式或自然語言處理套件清理 OCR 輸出。 +- **PDF 轉換**:將擷取的字串輸入 PDF 產生器,製作可搜尋的 PDF。 +- **雲端 OCR 服務**:將本地 `ocr` 結果與 Google Vision、Azure OCR 等服務比較,提升邊緣案例的準確度。 +- **GUI 前端**:打造小型 Flask 或 FastAPI 應用,讓使用者上傳圖片即時看到擷取結果。 + +以上主題皆以本次建立的 **Python OCR 套件** 為基礎,且同樣受惠於 **平行處理 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 for .NET 進行 OCR 最佳化](/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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/hongkong/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..39bce3b89 --- /dev/null +++ b/ocr/hongkong/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-19 +description: 如何在 Python 中使用 OCR 提取 PDF – 步驟教學,涵蓋從 PDF 抽取文字、從圖像辨識文字,以及 OCR Python 範例。 +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: zh-hant +og_description: 如何使用 Python 進行 OCR 從 PDF 中提取文字。學習從 PDF 提取文字、從圖像辨識文字,並查看完整的 OCR Python + 範例。 +og_title: 如何在 Python 中使用 OCR 提取 PDF 文字 – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: 如何在 Python 中使用 OCR 提取 PDF 文字 – 完整指南 +url: /zh-hant/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Python OCR 提取 PDF 文字 – 完整指南 + +有沒有想過 **如何在 PDF 只是一張掃描圖像時** 取得其中的內容?你並不孤單。在許多實務專案中——例如合約、發票或歷史檔案——收到的 PDF 往往沒有可選取的文字。好消息是,只要幾行 Python 程式碼,就能把只有圖像的頁面轉換成可搜尋、可編輯的文字。 + +在本教學中,我們將一步步示範一個實用的 **OCR Python 範例**,讀取 PDF、將第一頁渲染成圖像,然後使用 OCR 引擎 **從 PDF 中提取文字**。完成後,你將清楚知道如何 **使用 OCR 讀取 PDF**、每個步驟的意義,以及如何將程式碼延伸至多頁文件或不同語言。 + +## 你將學到 + +- 安裝與設定可靠的 Python OCR 套件。 +- 將 PDF 頁面轉換為適合 OCR 的圖像。 +- **從圖像辨識文字** 並取得乾淨的 Unicode 字串。 +- 常見陷阱(低解析度 PDF、旋轉頁面)以及避免方法。 +- 擴充腳本以處理多頁或批次作業。 + +**先備條件**:Python 3.8+、pip,以及基本的虛擬環境概念。不需要先前的 OCR 經驗——只要跟著做即可。 + +--- + +## ## How to Extract PDF Text with OCR in Python + +這個 H2 標題正好包含主要關鍵字,搜尋引擎會很喜歡。讓我們直接進入程式碼。 + +### Step 1 – Install the Required Packages + +First, we need an OCR engine. The example below uses the popular **ocr** package (a thin wrapper around Tesseract). If you prefer a different backend, the concepts stay the same. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** On Linux, you’ll also need the Tesseract binary: `sudo apt-get install tesseract-ocr`. macOS users can grab it via Homebrew: `brew install tesseract`. + +### Step 2 – Initialize the OCR Engine and Set Language + +Now we spin up the engine and tell it to look for English characters. You can swap `ocr.Language.English` for any supported language code. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Why this matters:** Specifying the language dramatically improves accuracy because the engine can apply language‑specific dictionaries and character models. + +### Step 3 – Load a PDF Page as an Image + +OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based indexing). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** If the PDF contains vector graphics rather than scanned images, you might get a crisp rendering. For low‑resolution scans, consider increasing the DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Step 4 – Recognize Text from the Rendered Image + +Here’s the heart of the **ocr python example**. The engine processes the bitmap and returns an object containing the extracted string. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +The `ocr_result.text` attribute holds the plain‑text output, preserving line breaks where possible. + +### Step 5 – Print or Store the Extracted Text + +Finally, we output the result. In a real application you’d probably write to a file or a database. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Running the script should display something like: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +That’s a complete **extract text from pdf** workflow using OCR. + +--- + +## ## Recognize Text from Image – Tweaking Accuracy + +If you’re only interested in **recognize text from image** (say, a JPEG of a receipt), you can skip the PDF conversion step: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips for better results:** + +- **Pre‑process** the image: convert to grayscale, apply thresholding, or deskew. Pillow makes this easy. +- **Increase DPI** during PDF rendering: higher resolution gives the OCR engine more detail. +- **Enable OCR engine’s config** for page segmentation (`ocr_engine.config = "--psm 6"` for uniform blocks). + +--- + +## ## Read PDF with OCR – Handling Multiple Pages + +Most contracts span several pages. Looping over each page is straightforward: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +This function **reads PDF with OCR**, concatenates the output, and inserts a clear page break marker. You can then feed `full_text` into a search index or store it as a `.txt` file. + +--- + +## ## Common Pitfalls and How to Fix Them + +| 症狀 | 可能原因 | 解決方法 | +|---------|--------------|-----| +| 文字雜亂、出現大量 `?` | 語言設定錯誤或缺少語言資料檔 | 安裝正確的 Tesseract 語言套件(`tesseract-ocr-`)並設定 `ocr_engine.language`。 | +| 缺少行或字被截斷 | DPI 太低(低於 150) | 以 300 DPI 或更高解析度渲染 PDF(`dpi=300`)。 | +| 文字旋轉或倒置 | 掃描頁面未正立 | 在辨識前使用 `ocr.Image.deskew(page_image)` 進行去斜。 | +| 大型 PDF 處理緩慢 | 單執行緒逐頁處理 | 使用 `concurrent.futures.ThreadPoolExecutor` 進行平行化。 | + +--- + +## ## Extending the OCR Python Example + +- **Export to PDF/A**: After extraction, you can embed the text back into a searchable PDF using `reportlab` or `pypdf2`. +- **Language detection**: Use `langdetect` on the OCR output to switch `ocr_engine.language` dynamically. +- **Batch processing**: Walk a directory with `os.listdir` and apply `extract_all_pages` to every file. + +--- + +## ## Expected Output and Verification + +When you run the script against a clear, English‑language scan, you should see a clean block of text with proper punctuation. Verify by: + +1. Comparing a few lines to the original scanned image. +2. Running a simple word count (`len(ocr_result.text.split())`) to ensure the output isn’t empty. +3. Optionally, feeding the result into a spell‑checker like `pyspellchecker` to spot OCR errors. + +--- + +## Conclusion + +We’ve covered **how to extract PDF** content when traditional parsing fails, demonstrated a full **ocr python example**, and explained how to **recognize text from image** and **read PDF with OCR** for both single‑page and multi‑page scenarios. With the code snippets above you can now turn any scanned PDF into searchable, editable text—no more manual re‑typing. + +Next steps? Try swapping the language to Spanish (`ocr.Language.Spanish`) or experiment with image pre‑processing techniques to boost accuracy. If you’re building a document‑management system, consider indexing the extracted text with Elasticsearch for lightning‑fast search. + +Got questions or run into a quirky PDF? Drop a comment, and happy coding! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + +## 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/hongkong/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..650a3a2b6 --- /dev/null +++ b/ocr/hongkong/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-06-19 +description: 學習如何在 Java 中使用 Aspose 的 OCR。本分步指南涵蓋自動校正傾斜圖像、自動語言偵測,以及輕鬆提取圖像文字。 +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: zh-hant +og_description: 如何在 Java 中使用 Aspose 進行 OCR:完整教學,涵蓋自動校正傾斜影像、自動語言偵測,以及從圖片中提取文字。 +og_title: 如何在 Java 中使用 Aspose 進行 OCR – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: 使用 Aspose 在 Java 中的 OCR 完整指南 +url: /zh-hant/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Java 中使用 Aspose OCR – 完整指南 + +有沒有想過在 Java 專案中 **如何使用 OCR**,卻不想因為設定而抓狂?你並不是唯一的開發者。許多開發者在需要快速 **提取圖像文字** 時會卡住,尤其是來源掃描圖像歪斜或使用未知語言時。 + +在本教學中,我們將逐步示範一個實作範例,完整說明如何使用 Aspose 的 OCR,包括 **auto deskew images**、**auto language detection** 以及完整的 **ocr image preprocessing** 流程。完成後,你將擁有一段可直接執行的程式碼,能將辨識出的文字輸出到主控台,並了解每個設定為何重要。 + +> **你將獲得:** 完整、可執行的 Java 程式、每行程式碼的說明、處理邊緣案例的技巧,以及將解決方案擴展至批次處理或 PDF 的想法。 + +--- + +## 前置條件 + +- 已安裝並設定 Java 17(或任何較新的 JDK)。 +- 用於相依管理的 Maven 或 Gradle(我們將示範 Maven 坐標)。 +- Aspose OCR for Java 授權檔 (`Aspose.OCR.Java.lic`)。如果只是測試,可以跳過授權步驟,但免費試用版會加上浮水印。 +- 一張範例圖像 (`your_image.png`),放置在程式碼可存取的位置。 + +> **專業提示:** 將圖像放在專屬的 `resources` 資料夾,並透過 classpath 載入;可避免在不同作業系統上因路徑問題產生的麻煩。 + +## 步驟 1:設定專案並加入 Aspose OCR 相依性 + +建立一個新的 Maven 專案(或使用現有的),並在 `pom.xml` 中加入以下內容: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +執行 `mvn clean install` 以下載套件。若偏好 Gradle,等價指令如下: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +現在你的 classpath 上已經有 **ocr image preprocessing** 類別了。 + +## 步驟 2:套用 Aspose OCR 授權(可選但建議) + +如果你擁有授權,請在 `main` 方法的開頭套用。跳過此步驟亦可執行,但免費版會在輸出上加上「Demo」浮水印。 + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +**為什麼這很重要:** 授權版會移除使用限制並關閉浮水印,讓你得到乾淨、可直接投入生產的結果。 + +## 步驟 3:建立 OCR 引擎實例 + +引擎是此流程的核心。實例化它即可取得所有 **ocr image preprocessing** 選項。 + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +此時引擎已就緒,但會使用預設設定,對掃描文件可能不是最佳化。我們來微調幾項設定。 + +## 步驟 4:啟用 Auto Deskew Images 以取得較乾淨的掃描圖像 + +傾斜的掃描圖像是常見的痛點。Aspose 提供 **auto deskew images** 功能,會在辨識前自動校正圖像。 + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +**運作原理:** 演算法會分析文字基線的角度,將圖像旋轉至最可能的正立方向。這能大幅提升手機拍攝照片的辨識準確度。 + +## 步驟 5:啟用 Auto Language Detection + +如果你不清楚來源圖像的語言,讓引擎自行判斷。這就是 **auto language detection** 設定。 + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +啟用後,Aspose 會掃描字形並選擇最可能的語言模型,內建支援超過 30 種語言。 + +## 步驟 6:載入欲辨識的圖像 + +你可以從磁碟、URL,甚至是位元組陣列載入圖像。為簡化說明,我們將從本機檔案讀取。 + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +**提示:** 若處理大型圖像,可先使用 `engine.getImagePreprocessing().setResizeFactor(0.5)` 進行降採樣,以加快處理速度且不會失去太多細節。 + +## 步驟 7:執行 OCR 辨識並提取文字圖像 + +現在引擎開始發揮魔法。`recognize` 方法會回傳一個 `OcrResult` 物件,內含辨識出的文字、信心分數等資訊。 + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +主控台會顯示從圖片中提取的純文字——這就是我們要達成的核心 **extract text image** 結果。 + +## 完整範例程式 + +以下是完整的 Java 類別,將所有步驟串接起來。請將其複製貼上至 `src/main/java/com/example/OcrDemo.java`,然後執行。 + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### 預期輸出 + +若圖像在乾淨的掃描中包含「Hello World」字樣,將會看到: + +``` +=== Recognized Text === +Hello World +``` + +對於較複雜的文件(例如多語言收據),輸出會包含換行以及偵測到的語言代碼。 + +## 常見陷阱與專業提示 + +| 問題 | 發生原因 | 解決方法 | +|------|----------|----------| +| **雜訊字元** | 圖像過暗或雜訊過多。 | 啟用 `engine.getImagePreprocessing().setBinarization(true)` 或手動調整對比度。 | +| **語言錯誤** | 自動偵測在混合語言頁面上失敗。 | 設定 `engine.setLanguage(Language.English)`(或相應的列舉值)以強制使用特定語言。 | +| **處理緩慢** | 影像解析度過高。 | 使用 `engine.getImagePreprocessing().setResizeFactor(0.5)` 進行降解析度。 | +| **記憶體不足錯誤** | 一次載入大量圖像。 | 逐一處理圖像,並在每次執行後呼叫 `engine.dispose()`。 | + +**請記住:** OCR 引擎對唯讀操作是執行緒安全的,但每個執行緒建立新實例可避免隱藏的狀態錯誤。 + +## 擴充解決方案 + +既然你已了解 **如何使用 OCR** 搭配 Aspose,接下來可能想要: + +1. **處理 PDF** – 將每個 PDF 頁面轉換為圖像(`PdfConverter`),再送入相同的流程。 +2. **批次處理資料夾** – 迭代目錄中的檔案,套用相同步驟,並將結果寫入 CSV。 +3. **整合至 Web 服務** – 透過 Spring Boot `@RestController` 暴露 OCR 邏輯,接受 multipart 上傳。 + +上述所有情境皆可重複使用我們在此建立的 **ocr image preprocessing** 設定。 + +## 結論 + +我們已完整說明了在 Java 中 **如何使用 OCR** 搭配 Aspose,從套用授權、建立引擎、啟用 **auto deskew images**、開啟 **auto language detection**、載入圖像,到最後以單一 `System.out.println` 進行 **extract text image**。此程式碼完全自包含,可在任何近期的 JDK 上執行,並展示了準確度與效能的最佳實踐。 + +試著使用自己的圖片執行看看——例如掃描的合約或收據截圖。微調前處理旗標、測試不同語言,你會很快發現 Aspose 的 OCR 函式庫是生產等級文字提取的可靠選擇。 + +有任何問題或想分享成果嗎?在下方留言或在 GitHub 上私訊我。祝開發愉快! + +--- + +![如何在 Java 中使用 OCR 範例](/images/ocr-java-example.png "如何在 Java 中使用 OCR – Aspose 示範截圖") + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,並以此為基礎延伸。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [使用 Aspose.OCR 依語言 OCR 圖像文字](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [使用 Aspose.OCR 偵測區域模式從圖像提取文字(Java)](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [使用 OCR - Aspose.OCR for Java 進階技巧](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/hongkong/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..c85de4776 --- /dev/null +++ b/ocr/hongkong/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Aspose OCR 在 Python 中提升 OCR 準確度。了解如何設定 OCR 語言、載入影像進行 OCR,並使用自訂字典從影像中擷取文字。 +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: zh-hant +og_description: 透過設定 OCR 語言、載入影像進行 OCR,並使用自訂字典從影像中擷取文字,以提升 Python 的 OCR 準確度。 +og_title: 提升 Python OCR 準確度 – 步驟指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: 提升 Python 中的 OCR 準確度 – 完整指南 +url: /zh-hant/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中提升 OCR 準確度 – 完整指南 + +有沒有想過在掃描的文字中夾雜奇怪符號、產品代碼或品牌名稱時,**提升 OCR 準確度**?你並不孤單。許多專案中,預設引擎只會輸出亂碼,這真的是生產力的大殺手。 + +在本教學中,我們將一步步示範一個實務的端到端範例,教你如何 **設定 OCR 語言**、**載入影像以進行 OCR**、**對影像執行 OCR**,以及最後 **從影像中擷取文字**,並使用自訂字典提升辨識率。完成後,你將得到一個可直接放入任何 Python 程式碼庫的即用腳本。 + +## 你將學到什麼 + +- 一個完整的 Python 腳本,使用 Aspose OCR 讀取 PNG 檔案。 +- 透過設定語言與自訂詞彙表 **提升 OCR 準確度** 的能力。 +- 為何每個設定重要的清晰說明,並提供處理非拉丁字元等邊緣案例的技巧。 +- 常見 OCR 問題的快速檢查清單。 + +### 前置條件 + +- 已在機器上安裝 Python 3.8 或更新版本。 +- `aspose-ocr` 套件(使用 `pip install aspose-ocr` 安裝)。 +- 一張範例影像(`technical_doc.png`),內含你想讀取的文字。 +- 具備基本的 Python 語法認識——不需要任何高階技巧。 + +> **專業小技巧:** 若你在虛擬環境中工作,請先啟動該環境再安裝套件。這樣可以保持相依性整潔,避免版本衝突。 + +--- + +## 步驟 1:安裝並匯入 Aspose OCR + +首先,將函式庫安裝到環境中,並匯入所需的類別。 + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr` 命名空間讓你可以存取 `OcrEngine` 類別,這是 OCR 流程的核心。於此處匯入,可讓腳本其餘部分保持簡潔易讀。 + +--- + +## 步驟 2:建立 OCR 引擎並 **設定 OCR 語言** + +為何語言這麼重要?OCR 引擎依賴語言特定的模型來辨識字形與詞彙模式。若告訴引擎你正在掃描英文文字,它會忽略西里爾字母,專注於拉丁字母,從而顯著 **提升 OCR 準確度**。 + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **注意:** Aspose OCR 支援超過 50 種語言。若文件不是英文,可將 `ocr.Language.English` 替換為 `ocr.Language.Spanish`、`ocr.Language.French` 等。 + +--- + +## 步驟 3:定義 **自訂字典** 以提升準確度 + +想像你在掃描的發票中出現「AsposeOCR」或類似「SKU12345」的產品代碼。引擎不認識這些詞彙,會自行猜測並產生錯誤。提供自訂詞彙表即可告訴引擎:*「這些字串是正確的,別去更正它們。」* 這是 **提升 OCR 準確度** 的快速方法。 + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +若有上百筆條目,可從檔案或資料庫載入,只要先以 Python list 形式保存即可,保持簡單。 + +--- + +## 步驟 4:**載入影像以進行 OCR** + +現在需要一張影像。`Image.load` 方法接受任意支援的點陣圖格式(PNG、JPEG、BMP 等)的路徑。若找不到檔案,會拋出例外,我們會先做好防護。 + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **此步驟重要原因:** 正確載入影像可確保引擎使用你預期的像素資料進行分析。檔案損毀或路徑錯誤是常見的挫折來源。 + +--- + +## 步驟 5:**對影像執行 OCR** 並擷取結果 + +引擎設定完成、影像也已備妥,辨識只需要一次方法呼叫。結果物件包含原始文字、信心分數,甚至版面資訊(若日後需要)。 + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +若想 **逐行擷取影像文字**,只要以換行字元分割即可: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## 步驟 6:驗證輸出 – 真正 **提升 OCR 準確度** 嗎? + +印出結果,觀察自訂字典是否產生了差異。 + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +對於範例影像,典型輸出可能如下: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +可以看到品牌名稱、希臘字元與產品代碼都如我們所定義的那樣正確呈現。若未使用自訂字典,引擎可能會把它們「更正」成「Aspose OCR」或「SKU 1234」之類的錯誤文字。 + +--- + +## 常見陷阱與解決方式 + +| 問題 | 為何會發生 | 解決方法 | +|------|------------|----------| +| **雜訊字元** | 語言設定錯誤或解析度過低的影像 | 確認 `engine.language` 與來源語言相符,並使用高 DPI 掃描(300 dpi 以上)。 | +| **自訂詞彙被忽略** | 字典未正確附加或屬性名稱拼寫錯誤 | 再次檢查 `engine.text_processing.custom_dictionary = …`。 | +| **找不到檔案** | 路徑錯誤或缺乏檔案存取權限 | 使用 `os.path.abspath()` 確認絕對路徑;以適當權限執行腳本。 | +| **處理速度慢** | 影像過大或頁數過多 | 先行裁切、縮放影像,或使用 `engine.recognize(image, max_threads=4)` 進行平行化。 | + +--- + +## 更進一步:進階調校以 **提升 OCR 準確度** + +1. **前處理** – 使用 Pillow 進行對比度增強或二值化,再交給 Aspose OCR。 +2. **多語言支援** – 設定 `engine.language = ocr.Language.English | ocr.Language.French` 以啟用雙語辨識。 +3. **區域式 OCR** – 若只需特定區塊(例如表格),先裁切影像以降低雜訊。 +4. **信心過濾** – `result.confidence` 提供每個字元的分數,可自行過濾低信心結果。 + +--- + +## 完整可執行腳本 + +以下是完整、可直接複製貼上的腳本,涵蓋我們討論的每一步。將其存為 `improve_ocr_accuracy.py`,然後在命令列執行。 + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +執行方式: + +```bash +python improve_ocr_accuracy.py +``` + +執行後,你應該會看到先前示範的整齊輸出。 + +--- + +## 結論 + +我們剛剛示範了在 Python 中 **提升 OCR 準確度** 的簡易方法,步驟如下: + +1. **設定 OCR 語言** 以符合文件語言。 +2. **正確載入影像**,讓引擎看到正確的像素。 +3. **對影像執行 OCR**,只需一次方法呼叫。 +4. **擷取影像文字**,並驗證結果。 +5. **加入自訂字典**,鎖定領域專屬詞彙。 + +以上即完成從原始圖片到乾淨、可搜尋文字的完整工作流程,且腳本可重複使用。若想挑戰更高階的任務,可嘗試影像前處理(對比度、去斜)或使用 `ocr.Language.English | ocr.Language.German` 進行多語言辨識。相同原則仍然適用,讓你持續 **提升 OCR 準確度**,處理更廣泛的文件。 + +有任何問題或特殊案例想討論?歡迎在下方留言,祝編程愉快! + +![improve OCR accuracy + + +## 接下來該學什麼? + +以下教學與本指南緊密相關,能進一步深化你所學的技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能,或在專案中探索其他實作方式。 + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/hongkong/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..b881a0a2f --- /dev/null +++ b/ocr/hongkong/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Python 的 OCR 函式庫對圖像執行文字辨識。學習如何從圖像中偵測文字、從 JPEG 辨識文字,以及高效地從掃描圖像中提取文字。 +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: zh-hant +og_description: 使用 Python 對圖像執行 OCR,並從掃描檔案中提取文字。本指南將一步步帶領您載入圖像、校正傾斜,並辨識文字。 +og_title: 在 Python 中對圖像執行 OCR – 完整文字擷取指南 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: 在 Python 中對圖像執行 OCR – 完整文字提取指南 +url: /zh-hant/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中對圖像執行 OCR – 完整文字提取指南 + +是否曾經需要 **對圖像執行 OCR**,卻因為程式碼看起來晦澀而卡住?你並非唯一遇到這種情況的人。無論是將一堆掃描收據轉成可搜尋的 PDF,或是從 JPEG 中擷取說明文字用於資料科學專案,能夠辨識 JPEG 及其他格式的文字是當今開發者必備的技能。 + +在本教學中,我們將逐步示範一個完整、可直接執行的範例,說明如何 **從圖像偵測文字**、**從掃描圖像中提取文字**,甚至 **載入圖像以進行 OCR**,只需幾行程式碼。完成後,你將擁有一段穩定、可直接投入生產環境的程式碼片段,無需額外匯入,也不會出現「請參考文件」的模糊說明。 + +## 您將構建的內容 + +- 一個小型的 Python 腳本,建立 OCR 引擎、啟用自動去斜、載入 JPEG(或任何支援的格式),並印出辨識出的文字。 +- 說明 **為何** 每個設定重要,而不只是 **如何** 輸入。 +- 處理多頁 PDF、非英語語系,以及模糊掃描等常見問題的技巧。 + +### 前置條件 + +- 已安裝 Python 3.8+(範例使用可透過 `pip install ocr-lib` 安裝的 `ocr` 套件——請依實際使用的函式庫名稱替換)。 +- 具備基本的 Python 函式與虛擬環境概念。 +- 一張想要處理的圖像檔(JPEG、PNG、TIFF),此處以 `skewed_page.jpg` 作為範例檔名。 + +> **專業小技巧:** 若你使用 Windows,安裝 OCR 函式庫時請以系統管理員身分執行終端機,以免遭遇權限問題。 + +--- + +## Perform OCR on Image – Setup and Configuration + +首先,你需要一個乾淨的 OCR 引擎實例。它就像是整個流程的「大腦」;若未正確設定,即使是最清晰的圖像也會產生亂碼。 + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**為何這很重要:** +設定 `engine.language` 可縮小 OCR 引擎預期的字符集,顯著提升辨識準確度。若省略此步驟,引擎會自行猜測,常會誤讀簡單的單詞。 + +--- + +## Enable Automatic Deskew – Fix Tilted Scans + +掃描的頁面很少能完美平整。輕微的傾斜會影響字符分割,導致「Hello」變成「H3llo」。`auto_deskew` 旗標會自動為你完成這項工作。 + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**邊緣情況:** 若你確定圖像已經是直的,關閉去斜功能可節省數毫秒的處理時間——在大量批次作業時特別有用。 + +--- + +## Load Image for OCR – Supporting JPEG, PNG, TIFF + +現在我們實際 **載入圖像以進行 OCR**。`ocr.Image.load` 方法相當彈性,接受任意支援的點陣圖檔案路徑。 + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **為何此步驟關鍵:** 函式庫會將檔案讀入內部位圖,並在必要時執行色彩空間轉換。若跳過此步驟直接傳入原始位元串,會拋出 `FileNotFoundError`,甚至在不發出錯誤的情況下產生空結果。 + +如果你特別想 **從 JPEG 檔案辨識文字**,只要確保檔案副檔名為 `.jpeg` 或 `.jpg`。相同的呼叫方式同樣適用於 PNG(`.png`)或 TIFF(`.tif`),不需額外修改。 + +--- + +## Perform OCR on Image – Running the Engine + +引擎已就緒且圖像已載入記憶體,接下來就可以 **對圖像執行 OCR**。以下單行程式碼即完成前處理、分割、分類與文字組合等全部工作。 + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**底層發生了什麼?** +- 若已啟用去斜,會先套用去斜變換。 +- 透過神經網路或 Tesseract 後端辨識字符。 +- 最後將字符拼接成單詞與行,回傳一個豐富的 `result` 物件。 + +--- + +## Extract Text from Scanned Image – Output the Results + +最後一步是 **從掃描圖像中提取文字** 並顯示。`result.text` 屬性即為純文字內容。 + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +典型的輸出範例如下: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +若 OCR 引擎找不到任何字符,`result.text` 會是空字串。此時請檢查圖像品質,或考慮調整 `engine.confidence_threshold`(若你的函式庫支援此屬性)。 + +--- + +## Handling Common Variations + +### Recognize Text from JPEG vs PNG + +兩種格式皆受支援,但 JPEG 壓縮可能產生干擾,引擎容易誤判。若發現誤辨率頻繁,可先將 JPEG 轉為 PNG 再處理: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detect Text from Image with Multiple Languages + +若文件同時包含英文與西班牙文,請啟用多語言模式: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +引擎將同時考慮兩種字母表進行辨識。 + +### Extract Text from Scanned PDFs + +對於 PDF,需要先將每頁光柵化為圖像。`pdf2image` 等函式庫可輕鬆完成此步驟: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Full Working Example + +以下是完整腳本,可直接複製貼上至 `ocr_demo.py` 檔案。內含錯誤處理與簡易計時輔助函式。 + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**預期輸出**(以清晰掃描為例): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Frequently Asked Questions + +**Q: 可以在無頭(headless)伺服器上執行嗎?** +A: 完全可以。此函式庫不依賴 GUI,只要確保伺服器上已安裝必要的原生二進位檔(例如 Tesseract),即可正常運作。 + +**Q: 若圖像模糊該怎麼辦?** +A: 考慮在 `engine.recognize` 前加入銳化濾鏡。許多 OCR 函式庫提供 `image_preprocessing.sharpen = True`,或可使用 OpenCV 的 `cv2.GaussianBlur` 反向操作。 + +**Q: 這個腳本支援批次處理嗎?** +A: 支援。只要將 `perform_ocr` 包在遍歷檔案路徑清單的迴圈中即可, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/hongkong/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..e9ba02ec2 --- /dev/null +++ b/ocr/hongkong/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-06-19 +description: 使用 Aspose OCR Java 執行影像 OCR。學習如何載入影像進行 OCR、使用 Aspose 授權,並在數分鐘內從影像中提取文字。 +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: zh-hant +og_description: 使用 Aspose OCR Java 進行圖像文字辨識。本指南說明如何使用 Aspose 授權、載入圖像進行 OCR,並有效地從圖像中提取文字。 +og_title: 使用 Aspose OCR Java 進行圖像文字辨識 – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: 使用 Aspose OCR Java 進行圖像 OCR – 完整逐步指南 +url: /zh-hant/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在圖像上執行 OCR(使用 Aspose OCR Java) – 完整步驟指南 + +有沒有曾經需要**在圖像上執行 OCR**但不確定哪個函式庫能在不需要大量設定的情況下提供可靠的結果?你並不孤單。在許多實務專案中——例如掃描護照、數位化發票,或從螢幕截圖中提取文字——快速辨識圖像文字資料的能力是個改變遊戲規則的關鍵。 + +在本教學中,我們將示範一個實作範例,完整說明如何使用 Aspose OCR for Java **在圖像上執行 OCR**。我們會涵蓋從套用 Aspose 授權、載入圖片、執行引擎,到最後 **從圖像中提取文字** 供後續使用的全部步驟。沒有冗餘說明,直接給你可即時複製貼上的可運作解決方案。 + +## 您將學會的內容 + +- 清楚了解如何在 Java 專案中 **使用 Aspose 授權**。 +- 完整程式碼示範 **載入圖像以進行 OCR**,並讓引擎自動偵測語言。 +- 步驟式說明如何安全地 **辨識圖像文字** 以及 **從圖像中提取文字**。 +- 處理常見問題的技巧(結果為空、格式不支援、記憶體限制)。 + +> **先備條件** – Java 8 或更新版本、Maven 或 Gradle 進行相依管理,以及 Aspose OCR for Java 授權檔(或以評估模式執行)。 + +--- + +## 如何使用 Aspose OCR Java 在圖像上執行 OCR + +以下是完整、可直接執行的 Java 程式碼,示範整個流程。將它儲存為 `AsposeOcrDemo.java`,然後在 IDE 或命令列執行。 + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### 預期的主控台輸出 + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +如果在未放置授權檔的情況下執行程式,第一行只會顯示您正處於評估模式,但 OCR 仍會正常運作。 + +--- + +## 設定與使用 Aspose 授權 + +### 為什麼授權很重要 + +以評估模式執行函式庫雖然適合快速測試,但會在輸出上加上浮水印,且每次執行可處理的頁數會受限。套用 **使用 Aspose 授權** 的步驟即可移除這些限制,並向 Aspose 表明您是付費客戶。 + +### 取得與套用授權的步驟 + +1. 從 Aspose 商店購買授權。 +2. 下載 `Aspose.OCR.Java.lic` 檔案。 +3. 將檔案放置於應用程式可讀取的位置——通常是 `src/main/resources` 資料夾。 +4. 在任何 OCR 操作之前呼叫 `new License().setLicense("Aspose.OCR.Java.lic");`,如上方程式碼所示。 + +> **專業小技巧**:若部署至伺服器,請使用絕對路徑或 class‑path 資源載入器,以避免 `FileNotFoundException`。 + +--- + +## 載入圖像以進行 OCR 處理 + +`Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` 這一行即是 **載入圖像以進行 OCR** 的核心。Aspose OCR 支援多種格式:PNG、JPEG、BMP、TIFF,甚至在結合 Aspose.Pdf 時可處理多頁 PDF。 + +### 常見陷阱 + +| 問題 | 症狀 | 解決方式 | +|------|------|----------| +| 檔案路徑錯誤 | `FileNotFoundException` | 再次確認路徑;使用 `Paths.get(...)` 取得與作業系統無關的分隔符。 | +| 不支援的格式 | `UnsupportedOperationException` | 在載入前先將圖像轉為 PNG 或 JPEG。 | +| 圖像過大(> 10 MP) | 記憶體不足錯誤 | 使用 `java.awt.Image` 先縮小圖像,再交給 Aspose 處理。 | + +--- + +## 從圖像中提取文字並處理結果 + +OCR 引擎完成後,`OcrResult` 物件會包含辨識出的字串。這就是我們 **從圖像中提取文字**,以便進一步處理——存入資料庫、建立搜尋索引,或送入下游的 NLP 流程。 + +### 處理多語言情況 + +因為我們設定了 `engine.setLanguage(Language.Auto)`,Aspose 會即時偵測語言。如果事先知道文件語言(例如全部為俄文),可將 `Language.Auto` 改為 `Language.Russian`,提升效能。 + +### 後處理小技巧 + +- **去除前後空白**:`result.getText().trim()`。 +- **正規化換行符**:`result.getText().replace("\r\n", "\n")`。 +- **移除不可列印字元**:使用正規表達式 `result.getText().replaceAll("[^\\p{Print}]", "")`。 + +--- + +## 使用進階選項辨識圖像文字(可選) + +若需要更細緻的控制,Aspose OCR 提供額外屬性可調整: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +這些調整在處理有傾斜或對比度低的掃描文件時特別有用。 + +--- + +## 完整範例回顧 + +將所有步驟整合後,最終程式會依序執行: + +1. **在圖像上執行 OCR** – 建立 `OcrEngine`。 +2. **使用 Aspose 授權** – 雖非必須,但強烈建議。 +3. **載入圖像以進行 OCR** – 透過 `Image.load`。 +4. **設定語言偵測** – `Language.Auto` 讓 **辨識圖像文字** 自動完成。 +5. **從圖像中提取文字** – 輸出結果,並優雅處理空回應。 + +您可以直接將上述程式碼貼入 Maven 專案,並加入以下相依性: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +執行 `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"`,即可在主控台看到辨識出的文字。 + +--- + +## 結論 + +我們已示範如何使用 Aspose OCR for Java **在圖像上執行 OCR**,從套用授權、**載入圖像以進行 OCR**、**辨識圖像文字**,到最後 **從圖像中提取文字** 供下游使用。此方法簡潔、支援多語言,且可依需求加入進階前處理選項。 + +接下來可以嘗試將 OCR 輸出送入搜尋索引、產生帶文字的 PDF,或測試不同圖像格式。可能性無窮,憑藉 Aspose 穩定的 API,您將花更多時間開發功能,而不是與 OCR 雜事糾纏。 + +有任何問題或遇到特殊情況,歡迎在下方留言——祝開發順利! + +## 接下來您可以學習什麼? + +以下教學與本指南緊密相關,能進一步深化您對 API 的掌握,並探索在專案中實作的其他方式。每篇資源皆提供完整可執行的程式碼範例與步驟說明。 + +- [如何使用 Aspose.OCR for Java 從 URL 提取圖像文字](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [使用 Aspose.OCR BufferedImage 在 Java 中將圖像轉為文字](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [使用 Aspose.OCR 偵測區域模式在 Java 中提取圖像文字](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3f45441ad --- /dev/null +++ b/ocr/hungarian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Készíts kereshető PDF-et egy képből Python OCR segítségével. Tanuld meg, + hogyan konvertálj OCR-t PDF-be, hogyan nyerj ki szöveget a képből, és hogyan végezz + gyors OCR-t a képen. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: hu +og_description: Készíts kereshető PDF-et egy képből Python OCR-rel. Ez az útmutató + bemutatja, hogyan konvertáljuk az OCR-t PDF-be, hogyan nyerjünk ki szöveget a képből, + és hogyan hajtsunk végre OCR-t a képen. +og_title: Kereshető PDF létrehozása Pythonban – Teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Kereshető PDF létrehozása Pythonban – Teljes lépésről‑lépésre útmutató +url: /hu/python-java/general/create-searchable-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 >}} + +# Kereshető PDF létrehozása Pythonban – Teljes lépés‑ről‑lépésre útmutató + +Valaha szükséged volt **kereshető PDF** létrehozására egy beolvasott nyugtából, de nem tudtad, hol kezdj? Nem vagy egyedül – sok fejlesztő ugyanazzal a problémával szembesül, amikor először próbálja a szövegképet kereshető PDF‑vé alakítani. + +Ebben a tutorialban egy gyakorlati megoldáson vezetünk végig, amely lehetővé teszi, hogy **perform OCR on image**, az OCR‑eredményt **searchable PDF**‑vé alakítsd, és akár a nyers szöveget is kinyerd, ha további feldolgozásra van szükséged. Nincs felesleges részlet, csak egy működő példa, amelyet ma be‑másolhatsz a projektedbe. + +## What You’ll Learn + +- Hogyan állíts be egy könnyűsúlyú OCR‑motort Pythonban +- A pontos lépések a **convert OCR to PDF** elvégzéséhez és a kereshető dokumentum mentéséhez +- Módszerek a **extract text from image** végrehajtására downstream elemzéshez +- Tippek a gyakori buktatók, például a kép orientációja és nagy fájlok kezelése kapcsán +- Egy teljes, futtatható szkript, amelyet saját felhasználási esetedhez adaptálhatsz + +### Prerequisites + +- Python 3.8+ telepítve a gépeden +- Alapvető ismeretek a pip‑ről és a virtuális környezetekről (opcionális, de ajánlott) +- Egy képfájl (PNG, JPEG, stb.), amely tiszta, gép‑olvasható szöveget tartalmaz + +Ha ezek megvannak, vágjunk bele. + +## Step 1: Install the Required Library + +A korábban látott kódrészlet egy fiktív `ocr` csomagot használ, de ugyanazok az elvek alkalmazhatók valós könyvtárakra, mint a **EasyOCR**, **pytesseract**, vagy **pdfminer.six**. Ehhez a útmutatóhoz a **EasyOCR**‑t használjuk, mert tisztán Python‑alapú, sok nyelvet támogat, és egy kényelmes PDF‑konverziós metódust biztosít egy segédosztályon keresztül. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Telepítsd egy virtuális környezetben (`python -m venv venv && source venv/bin/activate`), hogy a függőségek rendezettek maradjanak. + +## Step 2: Initialize the OCR Engine – Perform OCR on Image + +Most, hogy a könyvtár készen áll, létrehozzuk az OCR‑motort, és megadjuk, hogy angol szöveggel dolgozzon. Ez az első hely, ahol **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Miért van szükség egy dedikált reader objektumra? Az EasyOCR előre betölti a nyelvi modelleket, így ugyanazt a `reader`‑t több képhez újra‑használni sokkal hatékonyabb, mint minden alkalommal újra inicializálni. + +## Step 3: Load the Image – Extract Text from Image + +Töltsük be a képet a memóriába. Ebben a lépésben később **extract text from image**‑t végzünk, de először csak betöltjük. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Ha a képed fejjel lefelé vagy ferde, fontold meg a Pillow `rotate` vagy `transpose` metódusainak használatát, mielőtt az OCR‑motorhoz adnád. Egy gyors vizuális ellenőrzés órákat takaríthat meg a hibakeresésben. + +## Step 4: Run the OCR Engine and Capture Results + +Itt van a folyamat központja – a kép elküldése az OCR‑motorba és a strukturált adatok visszakapása. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +A `detail=1` flag bounding box‑okat ad vissza, amelyekre később szükség lesz a **convert OCR to PDF** során. Ha csak a nyers karakterláncok érdekelnek, állítsd `detail=0`‑ra. + +## Step 5: Convert OCR Result to a Searchable PDF – Convert OCR to PDF + +Az EasyOCR nem biztosít közvetlen PDF‑író funkciót, de saját magunk összeállíthatjuk a PDF‑et a Pillow és a `reportlab` könyvtár segítségével. A tutorial könnyűsúlyú maradása érdekében a `fpdf2`‑t használjuk, amely lehetővé teszi az eredeti kép beágyazását és láthatatlan szöveg réteg felülírását. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Mi történt? A beolvasott képet látható rétegként helyeztük el, majd a felismert szavakat fehér szöveggel írtuk felül, amely beleolvad a fehér háttérbe. A keresőeszközök továbbra is olvassák a rejtett réteget, így a PDF **searchable** marad anélkül, hogy a vizuális megjelenés megváltozna. + +## Step 6: Save the PDF Bytes – Convert Image to PDF + +Ha inkább memóriában kezeled a PDF‑et (például API‑n keresztül küldöd), a lemezre írás helyett a bájtokat is elkapod. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Ez a sor bemutatja a klasszikus **convert image to PDF** munkafolyamatot: kiindulsz egy képből, futtatod az OCR‑t, felülírod a szöveget, és végül egy PDF‑streamet adsz ki. + +## Step 7: Verify the Result – Quick Checks + +A szkript futtatása után nyisd meg a `receipt_searchable.pdf`‑t bármely PDF‑olvasóban, és próbáld ki a keresőmezőt (Ctrl + F). Írj be egy szót, amely biztosan szerepel a nyugtán – ha a megfelelő helyre ugrik, sikeresen **create searchable pdf**‑t hoztál létre! + +Ha a keresés nem működik, ellenőrizd a következőket: + +1. Az OCR‑bizalmi pontszámok (`conf` értékek). Alacsony bizalom azt jelentheti, hogy a kép elmosódott. +2. A bounding box koordináták – néha az EasyOCR más orientációban adja vissza őket. +3. Hogy a PDF‑olvasó nincs „csak kép” módra állítva (ritka, de előfordul). + +## Full Working Script + +Mindent összegezve, itt a teljes, azonnal futtatható Python‑fájl: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Mentsd el `searchable_pdf.py`‑ként, cseréld ki a `YOUR_DIRECTORY` helyőrzőket valós útvonalakra, és futtasd: + +```bash +python searchable_pdf.py +``` + +Egy megerősítő üzenetet kell látnod, valamint egy vadonatúj kereshető PDF‑et a mappádban. + +## Common Questions & Edge Cases + +**Mi van, ha a kép színes?** +Az EasyOCR mind szürkeárnyalatos, mind színes képekkel működik, de a szürkeárnyalatosra (`pil_image.convert("L")`) konvertálás néha javíthatja a pontosságot zajos beolvasásoknál. + +**Kezelhetek többoldalas PDF‑eket?** +Igen – iterálj minden oldal képe fölött, futtasd le az OCR‑lépéseket, és minden oldalt fűzd hozzá ugyanahhoz az `FPDF` objektumhoz. Ne felejtsd el a kurzort resetelni (`self.add_page()`) minden új kép előtt. + +**Létezik mód arra, hogy az eredeti szövegréteget tartsam meg a látható fehér szöveg helyett?** +Ha valódi „text‑under‑image” PDF‑re van szükséged (pl. akadálymentesség miatt), használj `pdfminer`‑t vagy `pikepdf`‑t, hogy egy rejtett szövegréteget ágyazz be megfelelő PDF‑címkékkel. Ez haladóbb, de az elv ugyanaz: háttérkép + szövegréteg. + +**Mi van, ha az OCR‑bizalom alacsony?** +Kiszűrheted az alacsony bizalmi szavakat: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Wrap‑Up – What We Achieved + +Egy egyszerű nyugta‑képpel indultunk, **performed OCR on image**, kinyertük a felismert karakterláncokat, és végül **create searchable pdf**‑t hoztunk létre, amely úgy viselkedik, mint egy professzionálisan beolvasott dokumentum. A folyamat lefedte az összes másodlagos kulcsszót – **convert OCR to PDF**, **extract text from image**, **convert image to PDF**, és **perform OCR on image** – így most már van egy újrahasználható eszköztárad bármilyen hasonló projekthez. + +### Next Steps + +- Kísérletezz más nyelvekkel az `easyocr.Reader(['en', 'es'])`‑hez ISO kódok megadásával. +- Cseréld le az EasyOCR‑t Tesseract‑ra, ha teljesen offline megoldásra van szükséged; a pipeline többi része változatlan marad. +- Adj hozzá OCR‑bizalmi vizualizációt (rajzolj bounding box‑okat a képre) a problémás beolvasások hibakereséséhez. + +Van egy trükk, amit meg szeretnél osztani? Írj kommentet, forkold + +## What Should You Learn Next? + +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ódpéldákat tartalmaz 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/hungarian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..602b4da1f --- /dev/null +++ b/ocr/hungarian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Képek szövegének kinyerése Pythonban egy egyszerű OCR motorral. Tanulja + meg, hogyan konvertálja a beolvasott képeket szöveggé, hogyan ismerje fel a képeken + lévő szöveget, és hogyan listázza hatékonyan a képfájlokat Pythonban. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: hu +og_description: Szöveg kinyerése képekből Pythonban egy könnyű OCR motorral. Ez az + útmutató megmutatja, hogyan konvertálhatod a beolvasott képeket szöveggé, hogyan + ismerheted fel a szöveget a képekről, és hogyan listázhatod a képfájlokat Pythonban + néhány lépésben. +og_title: Szöveg kinyerése képekből Pythonban – Teljes kötegelt OCR útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Képek szövegének kinyerése Pythonban – Teljes kötegelt OCR útmutató +url: /hu/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Képek szövegének kinyerése Pythonban – Teljes kötegelt OCR útmutató + +Valaha is szükséged volt **képek szövegének kinyerésére**, de nem tudtad, hol kezdjed? Nem vagy egyedül – a fejlesztők folyamatosan szembesülnek a beolvasott PDF‑ek, fényképezett számlák vagy képernyőképek kereshető szöveggé alakításának kihívásával. Ebben az útmutatóban egy teljes, azonnal futtatható példán keresztül mutatjuk be, hogyan **konvertálhatod a beolvasott képeket szöveggé**, hogyan ismerheted fel a szöveget a képekről, és még **list image files python**‑stílusban is felsorolhatod a képfájlokat. A végére egy újrahasználható szkriptet kapsz, amely egy egész mappát egy lépésben feldolgoz. + +Mindent lefedünk, amire szükséged lehet: a szükséges könyvtárakat, hogy miért fontos minden egyes lépés, a szélsőséges esetek kezelését, és egy kis hibakeresést. Nincs szükség külső dokumentációk keresgélésére; az alábbi kód önmagában áll, és a magyarázatok a “hogyan” *és* a “miért” kérdésekre válaszolnak. Vedd elő a kedvenc IDE‑det, és kezdjünk bele. + +--- + +## Mit fogsz építeni + +- Inicializálod az OCR‑motort (az illusztrációhoz a `ocr` csomagot használjuk). +- Beolvasod egy könyvtár tartalmát és **list image files python**‑stílusban felsorolod a képfájlokat, szűrve a PNG, JPG és TIFF formátumokat. +- **Kötegelt OCR** műveletet futtatsz az összes megtalált képen. +- Kiírod az egyes fájlokhoz kinyert szöveget, egyértelműen címkézve. + +> **Pro tipp:** Ha nincs telepítve a `ocr` könyvtár, helyettesítheted `pytesseract`‑tel néhány kisebb módosítással – a fő logika változatlan marad. + +--- + +## Előfeltételek + +- Python 3.8+ (a szkript f‑stringeket és típusjelöléseket használ). +- Egy OCR könyvtár, amely egy `OcrEngine`‑t biztosít a `recognize_batch` metódussal. Ebben az útmutatóban egy fiktív `ocr` csomagot feltételezünk, de a minta valódi könyvtárakkal is működik. +- Egy mappa, amely a feldolgozni kívánt képfájlokat tartalmazza (`.png`, `.jpg`, `.tif`). + +--- + +## 1. lépés – A szükséges modulok telepítése és importálása + +Először győződj meg róla, hogy az OCR csomag elérhető. Ha valós könyvtárat, például `pytesseract`‑et használsz, cseréld le az importot ennek megfelelően. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Miért fontos:** Az `os` importálása platformfüggetlen útvonalkezelést biztosít, míg a `typing.List` segíti az IDE‑k automatikus kiegészítését és a jövőbiztosságot. + +--- + +## 2. lépés – **Extract Text from Images**: Az OCR‑motor inicializálása + +A motor létrehozása az első lépés minden OCR feladat felé. Emellett a nyelvet automatikus felismerésre állítjuk, hogy a motor kevert nyelvű dokumentumokkal is tudjon dolgozni. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Magyarázat:** A motor létrehozását egy függvénybe szervezve a kód moduláris marad. Ha később DPI‑t vagy OCR‑módot kell módosítanod, csak ezen a helyen kell változtatnod. + +--- + +## 3. lépés – **List Image Files Python**: Fájlok összegyűjtése egy könyvtárból + +Most meg kell találnunk minden képet, amelyet feldolgozni szeretnénk. Az alábbi listakomprehenszió egy gyakori “list image files python” mintát tükröz. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Szélsőséges esetek kezelése:** A függvény figyelmen kívül hagyja az alkönyvtárakat (később hozzáadhatsz rekurziót) és automatikusan kiszűri a rejtett fájlokat, mivel azok általában nem végződnek a támogatott kiterjesztésekkel. + +--- + +## 4. lépés – **Convert Scanned Images to Text**: Kötegelt OCR futtatása + +A legtöbb OCR könyvtár biztosít egy kötegelt metódust, amely sokkal gyorsabb, mint egyesével feldolgozni a képeket. Így hívjuk meg. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Miért kötegelt?** Az összes kép egyszerre történő elküldése csökkenti a terhelést (pl. a OCR modell többszöri betöltése) és gyakran jobb CPU/GPU kihasználtságot eredményez. + +--- + +## 5. lépés – **Recognize Text from Pictures**: Az eredmények megjelenítése + +Végül végigiterálunk a párosított fájlneveken és OCR‑eredményeken, és minden képhez tiszta fejlécet nyomtatunk. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tipp:** A `strip()` eltávolítja a vezető/utólagos szóközöket, amelyeket az OCR gyakran hozzáad. + +--- + +## Teljes szkript – Összeállítás egyben + +Az alábbiakban a teljes, futtatható program található. Mentsd el `batch_ocr.py` néven, és futtasd `python batch_ocr.py ` paranccsal. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Várható kimenet + +Tegyük fel, hogy a mappa tartalmazza az `invoice1.png` és a `receipt.jpg` fájlokat, akkor a következőhöz hasonló kimenetet láthatsz: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Minden blokk egyértelműen fel van címkézve, ami megkönnyíti a további feldolgozást (pl. adatbázisba mentés). + +--- + +## Gyakori hibák kezelése + +| Probléma | Miért fordul elő | Gyors megoldás | +|----------|------------------|----------------| +| **Nem jelenik meg szöveg** | Az OCR nyelv nem lett felismert, vagy a kép túl alacsony kontrasztú. | Kényszerítsd a nyelvet (`engine.language = ocr.Language.English`) vagy előfeldolgozd a képeket (növeld a kontrasztot). | +| **Memóriahiba nagy kötegeknél** | A motor egyszerre próbál betölteni minden képet. | Oszd fel a `image_files` listát darabokra (`batch_size = 20`), és hívd meg többször a `recognize_batch`‑et. | +| **Nem támogatott fájlformátum** | `.gif` vagy `.bmp` fájlt adtál hozzá. | Bővítsd a `supported_exts` tuple‑t, vagy konvertáld a képeket PNG/JPG formátumba előre. | +| **Unicode torzulás** | Az OCR bájtokat ad vissza szöveg helyett. | Győződj meg róla, hogy az OCR könyvtár Unicode‑t ad vissza (`result.text.decode('utf‑8')` szükség esetén). | + +--- + +## A munkafolyamat bővítése + +Most, hogy **képek szövegének kinyerését** megvalósítottad, gondolj ezekre a következő lépésekre: + +- **Export CSV‑be** – Írd ki minden fájlnevet és a kinyert szöveget egy táblázatba elemzési célokra. +- **Párhuzamos feldolgozás** – Használd a `concurrent.futures.ThreadPoolExecutor`‑t több köteg egyidejű kezeléséhez. +- **Integráció felhő‑OCR‑vel** – Cseréld le a helyi motort Google Vision vagy Azure OCR megoldásra a komplex elrendezések jobb pontossága érdekében. +- **Képelőfeldolgozás hozzáadása** – A Pillow vagy OpenCV könyvtárak segítségével kiegyenesítheted, zajtalaníthatod vagy küszöbölheted a képeket OCR előtt, ezáltal javítva az eredményeket. + +Mindezek az ötletek természetesen ugyanazokat a magfunkciókat használják, amelyeket felépítettünk, így nem kell a nulláról kezdened. + +--- + +## Összegzés + +Áttekintettük a **képek szövegének kinyerését** Pythonban, lefedve mindent a **list image files python**‑ról a **recognize text from pictures**‑ig, végül a **convert scanned images to text**‑ig egy rendezett kötegben. A szkript szándékosan egyszerű, mégis elég rugalmas ahhoz, hogy alapot nyújtson nagyobb projektekhez – legyen szó számlák digitalizálásáról, kereshető archívum építéséről vagy adatkinyerő csővezetékek üzemeltetéséről. + +Próbáld ki, finomítsd az előfeldolgozási lépéseket, és figyeld, ahogy az OCR pontossága javul. Ha problémába ütközöl, nézd meg újra a “Gyakori hibák kezelése” táblázatot; a legtöbb gondot egy apró konfigurációs változtatás oldja meg. + +Készen állsz a következő kihívásra? Próbálj meg egy PDF‑kép konverziós lépést hozzáadni a `pdf2image` használatával, majd ezeket a képeket közvetlenül a meglévő csővezetékbe táplálni. A lehetőségek határtalanok, ha az OCR‑t a Python gazdag ökoszisztémájával kombinálod. + +Boldog kódolást, és legyen a szöveged mindig olvasható! + +## Mit érdemes még megtanulnod? + +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ódpéldákat tartalmaz 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. + +- [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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/hungarian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..59186ef3d --- /dev/null +++ b/ocr/hungarian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: Képek szövegének kinyerése Python OCR segítségével. Ismerje meg az automatikus + nyelvfelismerést, a párhuzamos feldolgozást és a kötegelt felismerést egy tömör + útmutatóban. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: hu +og_description: Képekből szöveg kinyerése Python OCR-rel. Ez az útmutató bemutatja + az automatikus nyelvfelismerést, a párhuzamos feldolgozást és a kötegelt felismerést + egyetlen oktatóanyagban. +og_title: Képekből szöveg kinyerése Pythonban – Teljes OCR útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Szöveg kinyerése képekből Pythonban – Teljes OCR útmutató +url: /hu/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# szöveg kinyerése képekből Pythonban – Teljes OCR útmutató + +Valaha is elgondolkodtál, hogyan **szöveget nyerhetsz ki képekből** anélkül, hogy kézzel be kellene gépelned minden szót? Nem vagy egyedül. Akár régi nyugtákat digitalizálsz, kereshető dokumentumarchívumot építesz, vagy csak menő AI trükkökkel játszol, a képekből szöveg kinyerésének képessége ma már elengedhetetlen készség minden Python fejlesztő számára. + +Ebben a tutorialban egy teljes, azonnal futtatható példán keresztül mutatjuk be, hogyan **szöveget nyerhetsz ki képekből** egy népszerű OCR motor segítségével. Kitérünk az automatikus nyelvfelismerésre, a párhuzamos feldolgozásra a sebesség növelése érdekében, valamint a csoportos képfelismerésre, hogy tucatnyi fájlt másodpercek alatt tudj kezelni. Pontosan erre van szükséged? Merüljünk el benne. + +## Mit fogsz megtanulni + +- Hogyan hozhatsz létre OCR motor példányt a `ocr.OcrEngine` segítségével. +- Az **automatikus nyelvfelismerés** engedélyezése, hogy a motor önmagától kiválassza a megfelelő nyelvet. +- A **párhuzamos feldolgozású OCR** beállítása egy egyedi szálkészlettel. +- A **csoportos képfelismerés** futtatása fájlok listáján. +- A felismert szöveg kiírása minden képre, készen áll a mentésre vagy indexelésre. + +Nincs szükség külső dokumentációra – minden, amire szükséged van, itt van, és a kód azonnal működik az `ocr` csomaggal (telepítsd a `pip install ocr` paranccsal). + +## Előfeltételek + +1. Python 3.8 vagy újabb telepítve. +2. `ocr` csomag (`pip install ocr`). +3. Egy mappa PNG (vagy JPG) képekkel, amelyeket feldolgozni szeretnél. +4. Alapvető ismeretek a Python függvényekkel és ciklusokkal kapcsolatban. + +Ennyi – nincsenek nehéz függőségek, nincs GPU varázslat, csak tiszta Python. + +![szöveg kinyerése képekből példa](https://example.com/ocr-demo.png "Képernyőkép, amely a képekből kinyert szöveg kimenetét mutatja") + +*Alt szöveg: képekből szöveg kinyerése demó képernyőkép* + +## 1. lépés – Az OCR motor beállítása (Elsődleges kulcsszó akcióban) + +Először is: hozz létre egy OCR motor példányt. Tekintsd a `ocr.OcrEngine()`-t a művelet agyának; ismeri a karakterek, sorok és bekezdések olvasását. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Miért van szükségünk egy explicit motorra? Mert a **ocr.OcrEngine használata** finomhangolt vezérlést biztosít a nyelvi beállítások, a szálkezelés és egyéb funkciók felett. Ez a legflexibilisebb mód a **szöveg kinyerésére képekből**, összehasonlítva az egyvonalas segédeszközökkel. + +## 2. lépés – Engedjük, hogy a motor automatikusan felismerje a nyelveket + +A legtöbb OCR könyvtár megköveteli, hogy megadd, melyik nyelvet keresse. Ez egynyelvű projektnél rendben van, de egy vegyes nyelvű batch esetén nehézkes. Szerencsére az `ocr` csomag támogatja az **automatikus nyelvfelismerést**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Az `engine.language` beállítása `ocr.Language.Auto`-ra azt mondja a motornak, hogy minden képet átvizsgáljon, és a megfelelő nyelvi modellt válassza. Ez az apró sor órákat takarít meg a manuális konfigurációból, ha nemzetközi dokumentumokkal dolgozol. + +## 3. lépés – Gyorsítsuk fel a párhuzamos feldolgozású OCR-rel + +Ha négy vagy több CPU magod van, miért ne használnád őket? A motor képes szálkészletet indítani, így egyszerre több képet is feldolgozhatsz. Itt jön képbe a **párhuzamos feldolgozású OCR**. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Nyugodtan állítsd be a `4` számot a gépednek megfelelően. Több szál → gyorsabb batch futtatás, de ne feledd, hogy minden szál memóriát fogyaszt, ezért találd meg a megfelelő egyensúlyt a környezetedben. + +## 4. lépés – Gyűjtsd össze a feldolgozni kívánt képeket + +Most egy fájlútvonalak listájára van szükségünk. Kézzel is összeállíthatod, beolvashatod CSV‑ből, vagy használhatod a `glob`‑ot. Átláthatóság kedvéért egy rövid listát kódolunk be: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Cseréld le a `YOUR_DIRECTORY`‑t a rendszereden lévő tényleges útvonalra. Ha tucatnyi fájlod van, egy gyors `glob.glob("*.png")` elvégzi a nehéz munkát. + +## 5. lépés – Csoportos képfelismerés futtatása + +Itt van a tutorial szíve: egyetlen hívás, amely minden képet a `files` listában feldolgoz, és egy eredményobjektumok listáját adja vissza. Ez a **csoportos képfelismerés** funkció teszi a nagy léptékű OCR‑t gyakorlati szintre. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +A háttérben a motor minden fájlt eloszt a korábban beállított négy munkás szál között, miközben automatikusan felismeri az egyes képek nyelvét. A metódus egy listát ad vissza, ahol minden elem a felismert szöveget és a metaadatokat tartalmazza. + +## 6. lépés – A kinyert szöveg kiírása (vagy tárolása) + +Végül végigiterálunk az eredményeken, és kiírjuk a szöveget. Egy valódi projektben valószínűleg adatbázisba vagy CSV‑fájlba írnád, de a kiírás egyszerűvé teszi a példát. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Várható kimenet** (rövidítve a tömörség kedvéért): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Minden blokk a fájlnevet mutatja, majd az OCR‑ből származó karakterláncot. Ha egy kép több nyelvet tartalmaz, a megfelelő karakterek megjelennek az előző **automatikus nyelvfelismerés** lépésnek köszönhetően. + +## Profi tippek és gyakori buktatók + +- **A kép minősége számít** – a homályos vagy alacsony kontrasztú képek szemét eredményt adnak. Szükség esetén előfeldolgozd OpenCV‑vel (`cv2.threshold`, `cv2.resize`). +- **Szálak száma vs. I/O** – ha a képek lassú hálózati meghajtón vannak, a több szál nem segíthet. Figyeld a CPU használatot `top` vagy `Task Manager`‑rel. +- **Unicode kezelés** – a `result.text` egy Unicode karakterlánc. Fájlok írásakor nyisd meg őket `encoding="utf-8"` beállítással, hogy elkerüld a `UnicodeEncodeError`‑eket. +- **Memóriahasználat** – nagy PDF‑ek sok RAM‑ot fogyaszthatnak. Ha `MemoryError`-t kapsz, csökkentsd a szálkészlet méretét vagy dolgozd fel a képeket kisebb darabokban. + +## Teljes működő szkript + +Az alábbiakban megtalálod a teljes, másolás‑beillesztésre kész szkriptet, amely tartalmazza a megbeszélt összes lépést. Mentsd el `batch_ocr.py` néven, majd futtasd `python batch_ocr.py` paranccsal. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Futtasd így: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Minden képre egy szépen formázott szövegrészletet látsz, ami bizonyítja, hogy **szöveget nyerhetsz ki képekből** nagy léptékben. + +## Mi következik? + +Most, hogy elsajátítottad a **szöveg kinyerését képekből** Pythonban, érdemes tovább mélyedni: + +- **Utófeldolgozás**: tisztítsd meg az OCR kimenetet regex‑szel vagy természetes nyelvi könyvtárakkal. +- **PDF konverzió**: a kinyert szövegeket egy PDF generátorba táplálva kereshető PDF‑eket hozhatsz létre. +- **Felhő OCR szolgáltatások**: hasonlítsd össze az on‑prem `ocr` eredményeket a Google Vision vagy Azure OCR megoldásaival a szélsőséges pontosság érdekében. +- **GUI front‑end**: építs egy kis Flask vagy FastAPI alkalmazást, amely lehetővé teszi a felhasználók számára a képek feltöltését és a kinyert szöveg azonnali megtekintését. + +Mindezek a témák a **Python OCR könyvtár** alapjára épülnek, és mindegyik profitál a **párhuzamos feldolgozású OCR** trükkökből, amelyeket itt bemutattunk. + +--- + +*Boldog kódolást! Ha elakadsz, írj egy megjegyzést lent – mindig szívesen segítek az OCR‑buktatók megoldásában.* + +## Mit tanulj meg legközelebb? + +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és‑ről‑lépésre magyarázatokkal, hogy további API funkciókat saját projektjeidben is könnyedén alkalmazhass. + +- [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épből – OCR optimalizálás Aspose.OCR‑rel .NET‑hez](/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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/hungarian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..2d15a3463 --- /dev/null +++ b/ocr/hungarian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-06-19 +description: Hogyan lehet PDF-et kinyerni OCR-rel Pythonban – lépésről lépésre útmutató, + amely lefedi a PDF‑ből szöveg kinyerését, a képről szöveg felismerését, valamint + egy OCR Python példát. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: hu +og_description: Hogyan lehet PDF-et kinyerni OCR-rel Pythonban. Tanulja meg, hogyan + nyerjen ki szöveget PDF-ből, hogyan ismerje fel a szöveget képről, és tekintse meg + a teljes OCR Python példát. +og_title: Hogyan vonjunk ki PDF‑szöveget OCR-rel Pythonban – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Hogyan lehet PDF szöveget OCR-rel kinyerni Pythonban – Teljes útmutató +url: /hu/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan lehet PDF szöveget kinyerni OCR-rel Pythonban – Teljes útmutató + +Gondolkodtál már azon, **hogyan lehet PDF‑et kinyerni**, ha a fájl csak egy beolvasott kép? Nem vagy egyedül. Sok valós projektben – legyen szó szerződésekről, számlákról vagy történelmi archívumokról – a kapott PDF nem tartalmaz választható szöveget. A jó hír? Néhány Python sorral ezeket a csak képet tartalmazó oldalakat kereshető, szerkeszthető szöveggé alakíthatod. + +Ebben a tutorialban egy gyakorlati **OCR Python példát** mutatunk be, amely beolvas egy PDF‑et, megjeleníti az első oldalát képként, majd **kivonja a szöveget a PDF‑ből** egy OCR motor segítségével. A végére pontosan tudni fogod, hogyan **olvass PDF‑et OCR‑rel**, miért fontos minden lépés, és hogyan módosíthatod a kódot többoldalas dokumentumokhoz vagy más nyelvekhez. + +## Mit fogsz megtanulni + +- Megbízható OCR könyvtár telepítése és beállítása Pythonhoz. +- PDF oldalak képekké konvertálása OCR‑ra alkalmas formátumba. +- **Szöveg felismerése képről** és tiszta Unicode karakterláncok visszaadása. +- Gyakori buktatók (alacsony felbontású PDF‑ek, elfordított oldalak) és azok elkerülése. +- A szkript kiterjesztése több oldal vagy kötegelt feldolgozás kezelésére. + +**Előfeltételek**: Python 3.8+, pip, és alapvető ismeretek a virtuális környezetekről. Korábbi OCR tapasztalat nem szükséges – csak kövesd a lépéseket. + +--- + +## ## Hogyan lehet PDF szöveget kinyerni OCR-rel Pythonban + +Ez a H2 fejléc tartalmazza a fő kulcsszót pontosan ott, ahol a keresőmotorok szeretik látni. Merüljünk el a kódban. + +### 1. lépés – A szükséges csomagok telepítése + +Először is szükségünk van egy OCR motorra. Az alábbi példa a népszerű **ocr** csomagot használja (egy könnyű wrapper a Tesseract köré). Ha másik backendet részesítesz előnyben, a koncepciók ugyanazok maradnak. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tipp:** Linuxon a Tesseract binárisra is szükséged lesz: `sudo apt-get install tesseract-ocr`. macOS felhasználók a Homebrew‑en keresztül telepíthetik: `brew install tesseract`. + +### 2. lépés – Az OCR motor inicializálása és a nyelv beállítása + +Most elindítjuk a motort, és megmondjuk, hogy angol karaktereket keressen. A `ocr.Language.English` helyett bármely támogatott nyelvkódot használhatsz. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Miért fontos:** A nyelv megadása drámaian javítja a pontosságot, mivel a motor nyelvspecifikus szótárakat és karaktermodelleket alkalmaz. + +### 3. lépés – PDF oldal betöltése képként + +Az OCR raster képeken működik, nem PDF objektumokon. Az `ocr.Image.from_pdf` segédfüggvény a kiválasztott oldalt bitmapre rendereli. Más oldalakhoz állítsd a `page_number` értékét (0‑alapú indexelés). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Különleges eset:** Ha a PDF vektoros grafikát tartalmaz a beolvasott képek helyett, tiszta renderelést kaphatsz. Alacsony felbontású beolvasásoknál fontold meg a DPI növelését: `ocr.Image.from_pdf(..., dpi=300)`. + +### 4. lépés – Szöveg felismerése a renderelt képen + +Itt van a **ocr python példa** szíve. A motor feldolgozza a bitmapet, és egy objektumot ad vissza, amely a kinyert karakterláncot tartalmazza. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Az `ocr_result.text` attribútum a sima szöveges kimenetet tartalmazza, ahol lehetséges, megőrizve a sortöréseket. + +### 5. lépés – A kinyert szöveg kiírása vagy mentése + +Végül kiírjuk az eredményt. Egy valódi alkalmazásban valószínűleg fájlba vagy adatbázisba írnád. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +A szkript futtatása valami ilyesmit kell, hogy megjelenítsen: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Ez egy komplett **extract text from pdf** munkafolyamat OCR‑rel. + +--- + +## ## Szöveg felismerése képről – A pontosság finomhangolása + +Ha csak a **recognize text from image** érdekel (például egy nyugta JPEG‑je), kihagyhatod a PDF konverziós lépést: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tippek a jobb eredményhez:** + +- **Előfeldolgozás**: konvertáld szürkeárnyalatosra, alkalmazz küszöbölést vagy kiegyenesítést. A Pillow ezt egyszerűvé teszi. +- **DPI növelése** PDF rendereléskor: a magasabb felbontás több részletet ad az OCR motor számára. +- **OCR motor konfigurációjának engedélyezése** oldal szegmentáláshoz (`ocr_engine.config = "--psm 6"` egységes blokkokhoz). + +--- + +## ## PDF olvasása OCR‑rel – Több oldal kezelése + +A legtöbb szerződés több oldalas. Az egyes oldalak ciklusba helyezése egyszerű: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Ez a függvény **reads PDF with OCR**, összefűzi a kimenetet, és egy egyértelmű oldaltörés jelzőt szúr be. Ezután a `full_text` felhasználható keresőindexbe vagy `.txt` fájlként tárolható. + +--- + +## ## Gyakori buktatók és megoldások + +| Tünet | Valószínű ok | Megoldás | +|---------|--------------|-----| +| Elcsúszott karakterek, sok `?` | Rossz nyelv vagy hiányzó nyelvi adatfájlok | Telepítsd a megfelelő Tesseract nyelvi csomagot (`tesseract-ocr-`) és állítsd be az `ocr_engine.language`‑t. | +| Hiányzó sorok vagy levágott szavak | Alacsony DPI (150 alatti) | Rendereld a PDF‑et 300 DPI vagy magasabb értéken (`dpi=300`). | +| A szöveg elfordítva vagy fejjel lefelé | A beolvasott oldal nem álló helyzetben | Használd az `ocr.Image.deskew(page_image)`‑t a felismerés előtt. | +| Lassú feldolgozás nagy PDF‑eken | Oldalak soros feldolgozása egyetlen szálon | Párhuzamosítsd a `concurrent.futures.ThreadPoolExecutor`‑rel. | + +--- + +## ## Az OCR Python példa kibővítése + +- **Exportálás PDF/A‑ba**: Kinyerés után a szöveget visszaágyazhatod egy kereshető PDF‑be a `reportlab` vagy `pypdf2` segítségével. +- **Nyelvfelismerés**: Használd a `langdetect`‑et az OCR kimeneten, hogy dinamikusan váltsd a `ocr_engine.language`‑t. +- **Kötegelt feldolgozás**: Járj végig egy könyvtárat az `os.listdir`‑el, és alkalmazd az `extract_all_pages`‑t minden fájlra. + +--- + +## ## Várt kimenet és ellenőrzés + +Amikor a szkriptet egy tiszta, angol nyelvű beolvasáson futtatod, egy tiszta szövegrészt kell látnod megfelelő írásjelekkel. Ellenőrizd a következőkkel: + +1. Hasonlíts néhány sort az eredeti beolvasott képpel. +2. Futtass egy egyszerű szószámlálást (`len(ocr_result.text.split())`), hogy megbizonyosodj róla, hogy a kimenet nem üres. +3. Opcionálisan add át az eredményt egy helyesírás-ellenőrzőnek, például a `pyspellchecker`‑nek, hogy megtaláld az OCR hibákat. + +--- + +## Következtetés + +Áttekintettük, **hogyan lehet PDF‑et kinyerni**, amikor a hagyományos elemzés kudarcot vall, bemutattuk a teljes **ocr python példát**, és elmagyaráztuk, hogyan **recognize text from image** és **read PDF with OCR** egy‑ és többoldalas esetekben. A fenti kódrészletekkel most már bármely beolvasott PDF‑et kereshető, szerkeszthető szöveggé alakíthatsz – többé nincs szükség kézi újraírásra. + +Mi a következő lépés? Próbáld ki a nyelvet spanyolra (`ocr.Language.Spanish`) vagy kísérletezz képelőfeldolgozási technikákkal a pontosság növelése érdekében. Ha dokumentumkezelő rendszert építesz, gondold meg a kinyert szöveg indexelését Elasticsearch‑szel a villámgyors kereséshez. + +Van kérdésed vagy furcsa PDF‑ed? Írj kommentet, és jó kódolást! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + + +## Mit érdemes legközelebb 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 teljes, 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 módok 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/hungarian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..f4e85bbba --- /dev/null +++ b/ocr/hungarian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-06-19 +description: Tanulja meg, hogyan használja az OCR-t Java-ban az Aspose-szal. Ez a + lépésről‑lépésre útmutató lefedi az automatikus képek kiegyenesítését, az automatikus + nyelvfelismerést, és a szöveg könnyű kinyerését a képből. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: hu +og_description: 'Hogyan használjuk az OCR-t Java-ban az Aspose segítségével: egy teljes + útmutató, amely lefedi az automatikus képhajlítást, az automatikus nyelvfelismerést + és a szöveg kinyerését a képekből.' +og_title: Hogyan használjuk az OCR-t Java-ban az Aspose-szal – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Hogyan használjunk OCR-t Java-ban az Aspose segítségével – Teljes útmutató +url: /hu/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan használjuk az OCR-t Java-ban az Aspose-szal – Teljes útmutató + +Gondolkodtál már azon, **hogyan használjuk az OCR-t** egy Java projektben anélkül, hogy a konfiguráció miatt a hajadba nyúlnál? Nem vagy egyedül. Sok fejlesztő akad el, amikor gyorsan kell **extract text image** adatot kinyerni, különösen ha a forrás szkennelések ferdeek vagy ismeretlen nyelven íródtak. + +Ebben az útmutatóban egy gyakorlati példán keresztül mutatjuk be, hogyan kell pontosan használni az OCR-t az Aspose-szal, beleértve a **auto deskew images**, a **auto language detection** és a teljes **ocr image preprocessing** folyamatot. A végére egy kész‑futtatható kódrészletet kapsz, amely kiírja a felismert szöveget a konzolra, és megérted, miért fontos minden beállítás. + +> **Mit kapsz:** egy teljes, futtatható Java programot, minden sor magyarázatát, tippeket a szélsőséges esetek kezelésére, és ötleteket a megoldás kiterjesztésére kötegelt feldolgozásra vagy PDF-ekre. + +--- + +## Előfeltételek + +- Java 17 (vagy bármely friss JDK) telepítve és konfigurálva. +- Maven vagy Gradle a függőségkezeléshez (megmutatjuk a Maven koordinátákat). +- Egy Aspose OCR for Java licencfájl (`Aspose.OCR.Java.lic`). Ha csak tesztelsz, kihagyhatod a licenc lépést, de az ingyenes próba vízjelet helyez a kimenetre. +- Egy minta kép (`your_image.png`) valahol elérhető a kód számára. + +> **Pro tipp:** tartsd a képeket egy dedikált `resources` mappában, és töltsd be az osztályútvonalon keresztül; ez elkerüli az útvonal‑kapcsolódó fejfájásokat különböző operációs rendszereken. + +## 1. lépés: A projekt beállítása és az Aspose OCR függőség hozzáadása + +Hozz létre egy új Maven projektet (vagy használd a meglévőt), és add hozzá a következőt a `pom.xml`-hez: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Futtasd a `mvn clean install` parancsot a könyvtár letöltéséhez. Ha a Gradle-t részesíted előnyben, az ekvivalens: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Most már a **ocr image preprocessing** osztályok a classpath-eden vannak. + +## 2. lépés: Az Aspose OCR licenc alkalmazása (opcionális, de ajánlott) + +Ha van licenced, alkalmazd azt a `main` metódusod elején. Ennek a lépésnek a kihagyása működik, de az ingyenes verzió „Demo” vízjelet helyez a kimenetre. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Miért fontos:** A licencelt verzió eltávolítja a használati korlátokat és kikapcsolja a vízjelet, tiszta, termelés‑kész eredményeket biztosítva. + +## 3. lépés: OCR motor példány létrehozása + +A motor a folyamat szíve. Példányosítva hozzáférést kapsz az összes **ocr image preprocessing** beállításhoz. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Ekkor a motor készen áll, de alapértelmezett beállításokat használ, amelyek nem biztos, hogy optimálisak a beolvasott dokumentumokhoz. Finomítsunk néhányat. + +## 4. lépés: Auto Deskew Images engedélyezése a tisztább szkennelésekhez + +A ferde szkennelések gyakori problémát jelentenek. Az Aspose egy **auto deskew images** funkciót kínál, amely automatikusan kiegyenesíti a képet a felismerés előtt. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Hogyan működik:** Az algoritmus elemzi a szöveg alapvonalának szögeit, és elforgatja a képet a legvalószínűbb függőleges orientációra. Ez drámaian javítja a pontosságot a telefonról készült fényképek esetén. + +## 5. lépés: Auto Language Detection bekapcsolása + +Ha nem ismered a forráskép nyelvét, hagyd, hogy a motor kitalálja. Ez a **auto language detection** beállítás. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Ha bekapcsolod, az Aspose átvizsgálja a glifeket és kiválasztja a legvalószínűbb nyelvi modellt, több mint 30 nyelvet támogatva alapból. + +## 6. lépés: A felismertetni kívánt kép betöltése + +Betölthetsz egy képet lemezről, URL-ről vagy akár bájt tömbből. Egyszerűség kedvéért egy helyi fájlból olvasunk. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tipp:** Ha nagy képekkel dolgozol, fontold meg először a lecsökkentésüket a `engine.getImagePreprocessing().setResizeFactor(0.5)` segítségével, hogy felgyorsítsd a feldolgozást anélkül, hogy sok részletet veszítenél. + +## 7. lépés: OCR felismerés végrehajtása és Text Image kinyerése + +Most a motor varázsol. A `recognize` metódus egy `OcrResult` objektumot ad vissza, amely a felismert szöveget, a bizalmi pontszámokat és egyebeket tartalmazza. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +A konzol megjeleníti a képből kinyert egyszerű szöveget – ez a fő **extract text image** eredmény, amit el akartunk érni. + +## Teljes működő példa + +Az alábbiakban a teljes Java osztály látható, amely mindent összekapcsol. Másold be a `src/main/java/com/example/OcrDemo.java` fájlba, és futtasd. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Várható kimenet + +Ha a kép egy tiszta szkennelésen a “Hello World” kifejezést tartalmazza, a következőt fogod látni: + +``` +=== Recognized Text === +Hello World +``` + +Bonyolultabb dokumentumok esetén (pl. többnyelvű nyugták) a kimenet sortöréseket és a felismert nyelvkódot is tartalmazni fogja. + +## Gyakori buktatók és pro tippek + +| Probléma | Miért fordul elő | Megoldás | +|----------|------------------|----------| +| **Hibás karakterek** | A kép túl sötét vagy zajos. | Engedélyezd a `engine.getImagePreprocessing().setBinarization(true)` beállítást, vagy állítsd manuálisan a kontrasztot. | +| **Rossz nyelv** | Az automatikus felismerés hibásan működik vegyes nyelvű oldalakon. | Állítsd be a `engine.setLanguage(Language.English)` (vagy a megfelelő enum) értéket, hogy kényszeríts egy adott nyelvet. | +| **Lassú feldolgozás** | Nagyon nagy felbontású képek. | Lecsökkentés a `engine.getImagePreprocessing().setResizeFactor(0.5)` használatával. | +| **Memória‑hiány hibák** | Nagy mennyiségű kép egyszerre betöltve. | Feldolgozd a képeket sorban, és minden futtatás után hívd meg a `engine.dispose()` metódust. | + +> **Ne feledd:** Az OCR motor szál‑biztos csak olvasási műveletekhez, de új példány létrehozása szálanként elkerüli a rejtett állapot hibákat. + +## A megoldás bővítése + +Most, hogy tudod, **hogyan használjuk az OCR-t** az Aspose-szal, lehet, hogy szeretnéd: + +1. **PDF-ek feldolgozása** – Konvertáld minden PDF oldalt képpé (`PdfConverter`), majd add át ugyanabba a folyamatba. +2. **Könyvtár kötegelt feldolgozása** – Iterálj a könyvtárban lévő fájlokon, alkalmazd ugyanazokat a lépéseket, és írd az eredményeket CSV‑be. +3. **Webszolgáltatással való integráció** – Tedd elérhetővé az OCR logikát egy Spring Boot `@RestController` segítségével, amely multipart feltöltéseket fogad. + +Ezek a forgatókönyvek mind ugyanazt a **ocr image preprocessing** konfigurációt használják, amelyet itt építettünk. + +## Összegzés + +Áttekintettük, **hogyan használjuk az OCR-t** Java-ban az Aspose-szal a kezdetektől a végéig: licenc alkalmazása, motor létrehozása, **auto deskew images** bekapcsolása, **auto language detection** engedélyezése, kép betöltése, és végül **extract text image** egyetlen `System.out.println` hívással. A kód teljesen önálló, bármely friss JDK-n fut, és bemutatja a pontosság és teljesítmény legjobb gyakorlatait. + +Próbáld ki a saját képeiddel – legyen az egy beolvasott szerződés vagy egy nyugta képernyőképe. Finomítsd a preprocessing zászlókat, kísérletezz különböző nyelvekkel, és hamar meglátod, miért egy stabil választás az Aspose OCR könyvtára a termelési szintű szövegkinyeréshez. + +Van kérdésed vagy szeretnéd megosztani az eredményeidet? Hagyj egy megjegyzést alább, vagy jelezz a GitHub-on. Boldog kódolást! + +![Hogyan használjuk az OCR-t Java példában](/images/ocr-java-example.png "Hogyan használjuk az OCR-t Java – Aspose demo képernyőkép") + + +## Mit érdemes még 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ódrészleteket tartalmaz 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. + +- [Hogyan OCR-eljünk képszöveget nyelvvel az Aspose.OCR használatával](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Szöveg kinyerése képből Java-val az Aspose.OCR Detect Areas Mode használatával](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Hogyan használjuk az OCR-t – Fejlett technikák az Aspose.OCR for Java-val](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/hungarian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..bd5e87fc1 --- /dev/null +++ b/ocr/hungarian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Javítsa az OCR pontosságát Pythonban az Aspose OCR használatával. Tanulja + meg, hogyan állíthatja be az OCR nyelvet, hogyan tölthet be képet az OCR-hez, és + hogyan nyerhet ki szöveget a képből egy egyedi szótárral. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: hu +og_description: Növelje az OCR pontosságát Pythonban az OCR nyelv beállításával, egy + kép betöltésével az OCR-hez, és a szöveg kinyerésével a képből egy egyéni szótár + segítségével. +og_title: Az OCR pontosságának javítása Pythonban – Lépésről lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: OCR pontosságának javítása Pythonban – Teljes útmutató +url: /hu/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR pontosság javítása Pythonban – Teljes útmutató + +Gondolkodtál már azon, hogyan **javítható az OCR pontossága**, ha a beolvasott szövegben furcsa szimbólumok, termékkódok vagy márkanevek szerepelnek? Nem vagy egyedül. Sok projektben az alapértelmezett motor csak érthetetlen szöveget ad vissza, ami komoly termelékenységcsökkenést okoz. + +Ebben a tutorialban egy gyakorlati, vég‑től‑végig példán keresztül mutatjuk be, hogyan **állítsd be az OCR nyelvet**, **tölts be képet az OCR-hez**, **végezd el az OCR-t a képen**, és végül **nyerd ki a szöveget a képből** egy egyedi szótár segítségével, amely növeli a felismerési arányt. A végére egy kész, futtatható szkriptet kapsz, amelyet bármely Python kódbázisba beilleszthetsz. + +## Mit fogsz megtanulni + +- Egy teljesen működő Python szkript, amely az Aspose OCR-t használja PNG fájl beolvasására. +- A **OCR pontosság javítása** nyelv és egyedi szószótár konfigurálásával. +- Egyértelmű magyarázatok arra, hogy miért fontos minden beállítás, valamint tippek a speciális esetek, például nem latin karakterek kezelésére. +- Gyors ellenőrzőlista a gyakori OCR hibák hibaelhárításához. + +### Előfeltételek + +- Python 3.8 vagy újabb telepítve a gépeden. +- `aspose-ocr` csomag (telepítés: `pip install aspose-ocr`). +- Egy minta kép (`technical_doc.png`), amely a beolvasni kívánt szöveget tartalmazza. +- Alapvető Python ismeretek – semmi különös nem szükséges. + +> **Pro tipp:** Ha virtuális környezetben dolgozol, aktiváld azt a csomag telepítése előtt. Így a függőségek rendezettek maradnak, és elkerülheted a verzióütközéseket. + +--- + +## 1. lépés: Aspose OCR telepítése és importálása + +Először is, hozzuk be a könyvtárat a környezetünkbe, és importáljuk a szükséges elemeket. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Az `aspose.ocr` névtér hozzáférést biztosít az `OcrEngine` osztályhoz, amely az OCR folyamat szíve. Ennek importálása itt tisztábbá és olvashatóbbá teszi a további kódot. + +--- + +## 2. lépés: OCR motor létrehozása és **OCR nyelv beállítása** + +Miért fontos a nyelv? Az OCR motorok nyelvspecifikus modelleket használnak a karakteralakok és szóminták felismeréséhez. Ha azt mondod a motornak, hogy angol szöveget olvas be, akkor figyelmen kívül hagyja a cirill betűket, és a latin ábécére koncentrál, ami drámaian **javítja az OCR pontosságát**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Megjegyzés:** Az Aspose OCR több mint 50 nyelvet támogat. Cseréld ki az `ocr.Language.English`-t `ocr.Language.Spanish`, `ocr.Language.French` stb.-re, ha a dokumentumod nem angol. + +--- + +## 3. lépés: **Egyedi szótár** definiálása a pontosság növeléséhez + +Képzeld el, hogy számlákat olvasol be, amelyekben a „AsposeOCR” vagy a „SKU12345” kifejezések szerepelnek. A motor nem ismeri ezeket a szavakat, ezért helytelenül tippel. Egy egyedi szószótár megadása azt mondja a motornak: *„Ezek a karakterláncok legitimek – ne próbáld meg kijavítani őket.”* Ez egy gyors nyeremény a **OCR pontosság javítása** szempontjából. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +A listát betöltheted egy fájlból vagy adatbázisból, ha több száz bejegyzésed van – egyszerűség kedvéért tartsd Python listában. + +--- + +## 4. lépés: **Kép betöltése OCR-hez** + +Most szükségünk van egy képre. Az `Image.load` metódus bármely támogatott raszteres formátum (PNG, JPEG, BMP stb.) útvonalát elfogadja. Ha a fájl nem található, a motor kivételt dob, ezért ellenőrizzük ezt. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Miért fontos ez a lépés:** A kép helyes betöltése biztosítja, hogy a motor a pontos pixeladatokkal dolgozzon, amelyeket elemezni szeretnél. Sérült fájlok vagy rossz útvonalak gyakori frusztrációforrások. + +--- + +## 5. lépés: **OCR végrehajtása a képen** és az eredmények kinyerése + +Miután a motor be van állítva és a kép készen áll, a tényleges felismerés egyetlen metódushívás. Az eredményobjektum tartalmazza a nyers szöveget, a biztonsági pontszámokat, sőt akár az elrendezési információkat is, ha később szükséged van rájuk. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Ha **szöveget szeretnél kinyerni a képből** soronként, egyszerűen oszd fel a szöveget újsor karakterek mentén: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## 6. lépés: Az eredmény ellenőrzése – Valóban **javítja-e az OCR pontosságát**? + +Nyomtassuk ki az eredményt, és nézzük meg, hogy az egyedi szótár hozott-e változást. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +A minta kép tipikus kimenete így nézhet ki: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Figyeld meg, hogy a márkanév, a görög karakter és a termékkód pontosan úgy jelenik meg, ahogy definiáltuk. Egyedi szótár nélkül a motor megpróbálná „kijavítani” őket, gyakran olyasmit eredményezve, mint „Aspose OCR” vagy „SKU 1234”. + +--- + +## Gyakori hibák és megoldások + +| Probléma | Miért fordul elő | Megoldás | +|----------|------------------|----------| +| **Szemetelés karakterek** | Rossz nyelv beállítása vagy alacsony felbontású kép | Győződj meg róla, hogy `engine.language` egyezik a forrásnyelvvel, és használj magas DPI‑s beolvasást (300 dpi vagy magasabb). | +| **Egyedi szavak figyelmen kívül hagyva** | A szótár nincs csatolva, vagy elírás a tulajdonnévben | Ellenőrizd duplán, hogy `engine.text_processing.custom_dictionary = …`. | +| **Fájl nem található** | Hibás útvonal vagy hiányzó fájlengedélyek | Használd az `os.path.abspath()`-t az abszolút útvonal ellenőrzéséhez; futtasd a szkriptet megfelelő jogosultságokkal. | +| **Lassú feldolgozás** | Nagy képek vagy sok oldal | Előfeldolgozd a képet (vágás, átméretezés) vagy használd a `engine.recognize(image, max_threads=4)`-et a párhuzamosításra. | + +--- + +## További lépések: Haladó finomhangolás a **OCR pontosság javítása** érdekében + +1. **Előfeldolgozás** – Alkalmazz kontrasztnövelést vagy binarizálást a Pillow‑al, mielőtt a képet az Aspose OCR-nek adnád. +2. **Több nyelv** – Állítsd be `engine.language = ocr.Language.English | ocr.Language.French`-et a kétnyelvű felismeréshez. +3. **Terület‑alapú OCR** – Ha csak egy adott területre (pl. táblázatra) van szükséged, előbb vágd le a képet, hogy csökkentsd a zajt. +4. **Biztonsági szűrés** – A `result.confidence` karakterenként ad pontszámot; alacsony biztonságú eredményeket programozottan eldobhatod. + +--- + +## Teljes működő szkript + +Az alább látható szkript másolás‑beillesztésre kész, és tartalmazza a fent tárgyalt minden lépést. Mentsd el `improve_ocr_accuracy.py` néven, majd futtasd a parancssorból. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Futtatás: + +```bash +python improve_ocr_accuracy.py +``` + +A korábban bemutatott, szépen formázott kimenetet kell látnod. + +--- + +## Összegzés + +Most egy egyszerű módszert mutattunk be a **OCR pontosság javítására** Pythonban: + +1. **OCR nyelv beállítása** a dokumentumodnak megfelelően. +2. **Kép helyes betöltése**, hogy a motor a megfelelő pixelekkel dolgozzon. +3. **OCR végrehajtása** egyetlen metódushívással. +4. **Szöveg kinyerése a képből** és az eredmény ellenőrzése. +5. **Egyedi szótár hozzáadása**, hogy a szakterületedre jellemző kifejezéseket rögzítsd. + +Ez a teljes munkafolyamat – a nyers képtől a tiszta, kereshető szövegig – egy rendezett, újrahasználható szkriptben van összefoglalva. + +Ha készen állsz a következő kihívásra, kísérletezz képelőfeldolgozással (kontraszt, kiegyenesítés), vagy állíts be többnyelvű felismertetést az `ocr.Language.English | ocr.Language.German` használatával. Ugyanezek a elvek érvényesek, és tovább **javítják az OCR pontosságát** a különböző dokumentumtípusoknál. + +Van kérdésed vagy egy különös edge case? Írj kommentet alább, és jó kódolást kívánok! + +![improve OCR accuracy + + +## 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 tartalmaz teljes, működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy könnyedén elsajátíthasd az API további funkcióit, és alternatív megvalósítási módokat is felfedezhess a saját projektjeidben. + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/hungarian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..d6acaf2ae --- /dev/null +++ b/ocr/hungarian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Végezzen OCR-t képen a Python OCR könyvtárával. Tanulja meg, hogyan lehet + szöveget észlelni a képen, szöveget felismerni JPEG-ből, és hatékonyan kinyerni + a szöveget a beolvasott képről. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: hu +og_description: Végezzen OCR-t képen Python segítségével, és nyerjen ki szöveget beolvasott + fájlokból. Ez az útmutató lépésről lépésre végigvezet a képek betöltésén, kiegyenesítésén + és a szöveg felismerésén. +og_title: OCR végrehajtása képen Pythonban – Teljes szövegkinyerési útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: OCR végrehajtása képen Pythonban – Teljes szövegkinyerési útmutató +url: /hu/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kép OCR végrehajtása Pythonban – Teljes szövegkinyerési útmutató + +Valaha is szükséged volt **OCR végrehajtására képfájlokon**, de a kód rejtélyesnek tűnt? Nem vagy egyedül. Akár egy kupac beolvasott nyugtát szeretnél kereshető PDF‑vé alakítani, akár egy JPEG‑ből szeretnél feliratokat kinyerni egy adat‑tudományi projekthez, a szöveg felismerése JPEG‑ekből és más formátumokból ma már elengedhetetlen képesség minden fejlesztő számára. + +Ebben a bemutatóban egy teljes, futtatható példán keresztül mutatjuk be, hogyan **detektálj szöveget képfájlokból**, **nyerd ki a szöveget beolvasott képdokumentumokból**, és még **tölts be képet OCR‑hez** néhány sorban. A végére egy stabil, termelés‑kész kódrészletet kapsz, amelyet egyszerűen beilleszthetsz a saját projektjeidbe – hiányzó importok nélkül, homályos „lásd a dokumentációt” hivatkozások nélkül. + +## Mit fogsz építeni + +- Egy apró Python‑szkriptet, amely létrehoz egy OCR‑motort, engedélyezi az automatikus kiegyenesítést, betölti a JPEG‑et (vagy bármely támogatott formátumot), és kiírja a felismert szöveget. +- Magyarázatokat arra, **miért** fontos minden beállítás, nem csak arra, **hogyan** kell beírni. +- Tippeket többoldalas PDF‑ek, nem‑angol nyelvek és gyakori buktatók, például elmosódott beolvasások kezelésére. + +### Előfeltételek + +- Python 3.8+ telepítve (a példa a `ocr` csomagot használja, amely a `pip install ocr-lib` paranccsal érhető el – cseréld le a saját könyvtárad nevére). +- Alapvető ismeretek a Python függvényekről és a virtuális környezetekről. +- Egy képfájl (JPEG, PNG, TIFF), amelyet feldolgozni szeretnél; a példában `skewed_page.jpg` a helyettesítő név. + +> **Pro tipp:** Windows rendszeren futtasd a terminált rendszergazdaként az OCR‑könyvtár telepítésekor, hogy elkerüld a jogosultsági problémákat. + +--- + +## OCR végrehajtása képen – Beállítás és konfiguráció + +Az első dolog, amire szükséged van, egy tiszta OCR‑motor példány. Gondolj rá úgy, mint a művelet agyára; megfelelő konfiguráció nélkül még a legélesebb kép is értelmetlen szöveget ad vissza. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Miért fontos:** +Az `engine.language` beállítása szűkíti a karakterkészletet, amelyet az OCR‑motor elvár, ez drámaian növeli a pontosságot. Ha kihagyod, a motor kitalálja, gyakran félreolvassa az egyszerű szavakat. + +--- + +## Automatikus kiegyenesítés engedélyezése – Döntött beolvasások javítása + +A beolvasott oldalak ritkán tökéletesen síkak. Egy enyhe dőlés megzavarhatja a karakterszegmentálást, a „Hello” helyett „H3llo” jelenik meg. Az `auto_deskew` jelző elvégzi a nehéz munkát helyetted. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Szélsőséges eset:** Ha tudod, hogy a képeid már egyenesek, a deskew letiltása néhány milliszekundummal csökkentheti a feldolgozási időt – hasznos, ha több ezer oldalt kell batch‑feladatban kezelni. + +--- + +## Kép betöltése OCR‑hez – JPEG, PNG, TIFF támogatás + +Most ténylegesen **betöltjük a képet OCR‑hez**. Az `ocr.Image.load` metódus rugalmas; bármely támogatott raszteres formátum útvonalát elfogadja. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Miért kulcsfontosságú ez a lépés:** A könyvtár beolvassa a fájlt egy belső bitmap‑be, szükség esetén színteret konvertál. Ennek kihagyása vagy egy nyers bájtfolyam átadása `FileNotFoundError`‑t vagy, rosszabb esetben, csendes, üres eredményt eredményez. + +Ha kifejezetten **szöveget szeretnél felismerni JPEG** fájlokból, csak győződj meg róla, hogy a fájlkiterjesztés `.jpeg` vagy `.jpg`. Ugyanez a hívás működik PNG (`.png`) vagy TIFF (`.tif`) esetén módosítás nélkül. + +--- + +## OCR végrehajtása képen – Motor futtatása + +Miután a motor előkészítve és a kép a memóriában van, itt az ideje **OCR végrehajtásának a képen**. Ez az egyetlen sor végzi a nehéz munkát: előfeldolgozás, szegmentálás, osztályozás és szövegösszeállítás. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Mi történik a háttérben?** +- A motor alkalmazza a deskew transzformációt (ha engedélyezve van). +- Egy neurális hálózatot vagy Tesseract backendet futtat a karakterek azonosítására. +- Végül a karaktereket szavakká és sorokká fűzi, egy gazdag `result` objektumot visszaadva. + +--- + +## Szöveg kinyerése beolvasott képből – Eredmények megjelenítése + +Az utolsó lépés **szöveg kinyerése beolvasott képből** és annak kiírása. A `result.text` attribútum tartalmazza a tiszta szöveges reprezentációt. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +A tipikus kimenet például: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Ha az OCR‑motor nem talál karaktereket, a `result.text` egy üres string lesz. Ilyenkor ellenőrizd a kép minőségét, vagy fontold meg a `engine.confidence_threshold` tulajdonság módosítását (ha a könyvtárad támogatja). + +--- + +## Gyakori variációk kezelése + +### Szöveg felismerése JPEG‑ből vs PNG‑ből + +Mindkét formátum támogatott, de a JPEG tömörítés artefaktusokat hozhat létre, amelyek megzavarhatják a motort. Ha gyakran előfordulnak hibás felismerések, próbáld meg a JPEG‑et először PNG‑re konvertálni: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Szöveg detektálása több nyelven + +Ha a dokumentum keveri az angolt és a spanyolt, állíts be többnyelvű módot: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +A motor ekkor mindkét ábécét figyelembe veszi a felismerés során. + +### Szöveg kinyerése beolvasott PDF‑ekből + +PDF‑ek esetén először minden oldalt rasterizálni kell képpé. Az olyan könyvtárak, mint a `pdf2image`, ezt egyszerűvé teszik: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Teljes működő példa + +Az alábbiakban a teljes szkript látható, amelyet egyszerűen másolj be egy `ocr_demo.py` fájlba. Tartalmaz hibakezelést és egy kis segédfüggvényt a futási idő mérésére. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Várható kimenet** (tiszta beolvasás esetén): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Gyakran Ismételt Kérdések + +**K: Futtatható ez egy fej nélküli szerveren?** +V: Természetesen. A könyvtár GUI nélkül is működik; csak győződj meg róla, hogy a szükséges natív binárisok (pl. Tesseract) telepítve vannak a szerveren. + +**K: Mi a teendő, ha a kép elmosódott?** +V: Fontold meg egy élesítő szűrő hozzáadását a `engine.recognize` előtt. Sok OCR‑könyvtárban elérhető az `image_preprocessing.sharpen = True`, vagy használhatod az OpenCV `cv2.GaussianBlur` visszafelé alkalmazását. + +**K: Támogatja a szkript a kötegelt feldolgozást?** +V: Igen. Csak csomagold be a `perform_ocr`‑t egy ciklusba, amely egy fájlútvonal‑listát dolgoz fel, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/hungarian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..ca4352a75 --- /dev/null +++ b/ocr/hungarian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-19 +description: Végezzen OCR-t képen az Aspose OCR Java használatával. Tanulja meg, hogyan + töltsön be képet OCR-hez, használja az Aspose licencet, és percek alatt nyerjen + ki szöveget a képből. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: hu +og_description: Végezzen OCR-t képen az Aspose OCR Java segítségével. Ez az útmutató + bemutatja, hogyan használja az Aspose licencet, hogyan töltse be a képet OCR-hez, + és hogyan nyerjen ki szöveget a képből hatékonyan. +og_title: OCR végrehajtása képen az Aspose OCR Java segítségével – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: OCR végrehajtása képen az Aspose OCR Java-val – Teljes lépésről‑lépésre útmutató +url: /hu/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR végrehajtása képen Aspose OCR Java‑val – Teljes lépésről‑lépésre útmutató + +Valaha is szükséged volt **OCR végrehajtására képen** fájlokon, de nem tudtad, melyik könyvtár ad megbízható eredményt anélkül, hogy rengeteg konfigurációra lenne szükség? Nem vagy egyedül. Sok valós projektben – gondolj útlevél beolvasására, számlák digitalizálására vagy szöveg kinyerésére képernyőképekből – a szöveg gyors felismerése a képadatokból igazi játékváltó. + +Ebben a tutorialban egy gyakorlati példán keresztül mutatjuk be, hogyan **végezz OCR‑t képen** az Aspose OCR for Java segítségével. Kitérünk a licenc alkalmazásától a kép betöltéséig, a motor futtatásáig, és végül a **szöveg kinyerésére képről**, hogy azt később felhasználhasd. Felesleges szócséplés nélkül, csak egy működő megoldás, amit egyszerűen átmásolhatsz. + +## Mit fogsz megtanulni + +- Hogyan **használd az Aspose licencet** egy Java projektben. +- A pontos kód, amely **betölti a képet OCR‑hez**, és a motor automatikusan felismeri a nyelveket. +- Lépésről‑lépésre útmutató a **szöveg képen** tartalmának **felismeréséhez** és a **szöveg kinyeréséhez képről** biztonságosan. +- Tippek a gyakori buktatók kezelésére (üres eredmények, nem támogatott formátumok, memória‑problémák). + +> **Előfeltételek** – Java 8 vagy újabb, Maven vagy Gradle a függőségkezeléshez, valamint egy Aspose OCR for Java licencfájl (vagy használhatod értékelő módban). + +--- + +## Hogyan végezz OCR‑t képen Aspose OCR Java‑val + +Az alábbi teljes, futtatható Java program bemutatja a teljes folyamatot. Mentsd el `AsposeOcrDemo.java` néven, és futtasd a kedvenc IDE‑dben vagy parancssorból. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Várt konzolkimenet + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Ha licencfájl nélkül futtatod a programot, az első sor egyszerűen azt jelzi, hogy értékelő módban vagy, de az OCR továbbra is működik. + +--- + +## Aspose licenc beállítása és használata + +### Miért fontos a licenc + +Az értékelő módban való futtatás rendben van gyors tesztekhez, de vízjelet ad a kimenetre, és korlátozza az egy futtatás során feldolgozható oldalak számát. A **use aspose license** lépés eltávolítja ezeket a korlátozásokat, és jelzi az Aspose‑nak, hogy fizető ügyfél vagy. + +### Hogyan szerezd be és alkalmazd + +1. Vásárolj licencet az Aspose áruházban. +2. Töltsd le a `Aspose.OCR.Java.lic` fájlt. +3. Helyezd el egy olyan helyre, ahonnan az alkalmazásod olvasni tudja – általában a `src/main/resources` mappában. +4. Hívd meg `new License().setLicense("Aspose.OCR.Java.lic");` minden OCR‑munkát megelőzően, ahogy a fenti kódban látható. + +> **Pro tipp:** Ha szerverre telepítesz, használj abszolút elérési utat vagy osztály‑útvonal‑erőforrás‑betöltőt, hogy elkerüld a `FileNotFoundException`‑t. + +--- + +## Kép betöltése OCR feldolgozáshoz + +A `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` sor a **load image for OCR** lépés központja. Az Aspose OCR számos formátumot támogat: PNG, JPEG, BMP, TIFF, sőt többoldalas PDF‑eket is (az Aspose.Pdf‑vel kombinálva). + +### Gyakori buktatók + +| Issue | Symptom | Fix | +|-------|---------|-----| +| Rossz fájlútvonal | `FileNotFoundException` | Ellenőrizd a útvonalat; használd a `Paths.get(...)`‑t az OS‑független elválasztókhoz. | +| Nem támogatott formátum | `UnsupportedOperationException` | Konvertáld a képet PNG‑re vagy JPEG‑re a betöltés előtt. | +| Nagy kép ( > 10 MP) | Memória‑hiány hibák | Kicsinyítsd le a képet a `java.awt.Image` segítségével, mielőtt az Aspose‑nak átadnád. | + +--- + +## Szöveg kinyerése képről és az eredmények kezelése + +Miután az OCR motor befejeződött, az `OcrResult` objektum tartalmazza a felismert karakterláncot. Itt történik a **szöveg kinyerése képről** további feldolgozáshoz – adatbázisba mentés, keresőindex feltöltése vagy downstream NLP pipeline‑ba való betáplálás. + +### Több nyelv kezelése + +Mivel `engine.setLanguage(Language.Auto)`‑t állítottunk be, az Aspose megpróbálja a nyelveket futás közben felismerni. Ha előre tudod a nyelvet (pl. minden dokumentum orosz), cseréld a `Language.Auto`‑t `Language.Russian`‑ra a teljesítmény növelése érdekében. + +### Utófeldolgozási tippek + +- **Üres karakterek eltávolítása**: `result.getText().trim()`. +- **Sorvégek normalizálása**: `result.getText().replace("\r\n", "\n")`. +- **Nem nyomtatható karakterek eltávolítása**: használj regex‑et, például `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Szöveg képen felismerése haladó beállításokkal (opcionális) + +Ha finomabb vezérlésre van szükséged, az Aspose OCR további tulajdonságokat kínál: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Ezek a finomhangolások hasznosak, ha olyan beolvasott dokumentumokkal dolgozol, amelyek ferdeséget vagy alacsony kontrasztot mutatnak. + +--- + +## Teljes működő példa összefoglaló + +Mindent összegezve, a végső program a következőket hajtja végre sorrendben: + +1. **Perform OCR on image** – egy `OcrEngine` létrehozásával. +2. **Use Aspose license** – opcionális, de ajánlott. +3. **Load image for OCR** – a `Image.load` segítségével. +4. **Set language detection** – `Language.Auto` a **recognize text image** automatikus felismeréséhez. +5. **Extract text from image** – az eredmény kiírása, üres válaszok elegáns kezelése. + +A kódrészletet közvetlenül beillesztheted egy Maven projektbe a következő függőséggel: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Futtasd a `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` parancsot, és figyeld, ahogy a konzol megjeleníti a felismert szöveget. + +--- + +## Összegzés + +Most már tudod, hogyan **perform OCR on image** fájlokon az Aspose OCR for Java segítségével, a licenc alkalmazásától a **loading the image for OCR**, a **recognizing text image** tartalomig, és végül a **extracting text from image** downstream felhasználásra. A megközelítés egyszerű, több nyelvet is natívan támogat, és szükség esetén bővíthető haladó előfeldolgozási lehetőségekkel. + +Mi a következő lépés? Próbáld meg az OCR kimenetet egy keresőindexbe betáplálni, PDF‑eket generálni a kinyert szöveggel, vagy kísérletezz különböző képformátumokkal. A lehetőségek végtelenek, és az Aspose robusztus API‑ja révén több időt tölthetsz funkciók építésével, mint az OCR‑kudarcok megoldásával. + +Van kérdésed vagy egy szokatlan esetbe ütköztél? Írj egy megjegyzést alább – jó kódolást! + + +## 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 tartalmaz teljesen működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy könnyedén elsajátíthasd az API további funkcióit és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan nyerj ki szöveget képről URL‑ről az Aspose.OCR for Java használatával](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Kép konvertálása szöveggé Java‑ban az Aspose.OCR BufferedImage‑el](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Szöveg kinyerése képről Java‑ban az Aspose.OCR Detect Areas Mode‑val](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..402909dd3 --- /dev/null +++ b/ocr/indonesian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Buat PDF yang dapat dicari dari gambar menggunakan Python OCR. Pelajari + cara mengonversi OCR ke PDF, mengekstrak teks dari gambar, dan melakukan OCR pada + gambar dengan cepat. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: id +og_description: Buat PDF yang dapat dicari dari gambar dengan Python OCR. Panduan + ini menunjukkan cara mengonversi OCR ke PDF, mengekstrak teks dari gambar, dan melakukan + OCR pada gambar. +og_title: Membuat PDF yang Dapat Dicari dengan Python – Panduan Pemrograman Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Buat PDF yang Dapat Dicari dengan Python – Panduan Lengkap Langkah demi Langkah +url: /id/python-java/general/create-searchable-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 >}} + +# Buat Searchable PDF di Python – Panduan Lengkap Langkah‑per‑Langkah + +Pernah perlu **membuat searchable PDF** dari kwitansi yang dipindai tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian—banyak pengembang mengalami kebuntuan yang sama ketika pertama kali mencoba mengubah gambar teks menjadi PDF yang sebenarnya dapat dicari. + +Dalam tutorial ini kami akan membahas solusi praktis yang memungkinkan Anda **melakukan OCR pada gambar**, mengubah hasil OCR menjadi **searchable PDF**, dan bahkan mengambil teks mentah jika Anda membutuhkannya untuk pemrosesan lebih lanjut. Tanpa basa‑basi, hanya contoh yang dapat langsung Anda salin‑tempel ke proyek Anda hari ini. + +## Apa yang Akan Anda Pelajari + +- Cara menyiapkan mesin OCR ringan di Python +- Langkah‑langkah tepat untuk **convert OCR to PDF** dan menyimpannya sebagai dokumen yang dapat dicari +- Cara **extract text from image** untuk analisis lanjutan +- Tips menangani jebakan umum seperti orientasi gambar dan file besar +- Skrip lengkap yang dapat dijalankan dan Anda dapat sesuaikan dengan kasus penggunaan Anda + +### Prasyarat + +- Python 3.8+ terpasang di mesin Anda +- Familiaritas dasar dengan pip dan virtual environment (opsional tetapi disarankan) +- File gambar (PNG, JPEG, dll.) yang berisi teks yang jelas dan dapat dibaca mesin + +Jika Anda sudah memiliki semuanya, mari kita mulai. + +## Langkah 1: Instal Library yang Diperlukan + +Potongan kode yang Anda lihat sebelumnya menggunakan paket fiktif `ocr`, tetapi ide yang sama berlaku untuk library dunia nyata seperti **EasyOCR**, **pytesseract**, atau **pdfminer.six**. Untuk panduan ini kami akan menggunakan **EasyOCR** karena berbasis Python murni, mendukung banyak bahasa, dan menyediakan metode konversi PDF yang berguna melalui helper tambahan. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Instal di dalam virtual environment (`python -m venv venv && source venv/bin/activate`) untuk menjaga ketergantungan Anda tetap rapi. + +## Langkah 2: Inisialisasi Mesin OCR – Perform OCR on Image + +Setelah library siap, kami membuat mesin OCR dan memberitahukannya untuk bekerja dengan teks bahasa Inggris. Ini adalah tempat pertama kami **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Mengapa kami memerlukan objek reader khusus? EasyOCR memuat model bahasa sebelumnya, sehingga menggunakan kembali `reader` yang sama untuk beberapa gambar jauh lebih efisien daripada menginisialisasinya kembali setiap kali. + +## Langkah 3: Muat Gambar – Extract Text from Image + +Mari kita bawa gambar ke memori. Langkah ini adalah tempat kami **extract text from image** nanti, tetapi untuk saat ini kami hanya memuatnya. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Jika gambar Anda terbalik atau miring, pertimbangkan menggunakan metode `rotate` atau `transpose` dari Pillow sebelum memberikannya ke mesin OCR. Pemeriksaan visual cepat dapat menghemat berjam‑jam debugging nanti. + +## Langkah 4: Jalankan Mesin OCR dan Tangkap Hasil + +Berikut inti proses—mengirim gambar ke mesin OCR dan menerima kembali data terstruktur. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Flag `detail=1` memberi kami bounding box, yang akan kami perlukan saat nanti **convert OCR to PDF**. Jika Anda hanya membutuhkan string mentah, setel `detail=0`. + +## Langkah 5: Konversi Hasil OCR ke Searchable PDF – Convert OCR to PDF + +EasyOCR tidak menyediakan penulis PDF langsung, tetapi kami dapat merakit PDF sendiri menggunakan Pillow dan library `reportlab`. Untuk menjaga tutorial tetap ringan, kami akan menggunakan `fpdf2`, yang memungkinkan kami menyematkan gambar asli dan menimpa teks tak terlihat. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Apa yang baru saja terjadi? Kami menempatkan gambar hasil pemindaian sebagai lapisan terlihat, kemudian menulis kata‑kata yang dikenali di atasnya menggunakan teks putih yang menyatu dengan latar belakang putih. Alat pencarian tetap dapat membaca lapisan tersembunyi, sehingga PDF menjadi **searchable** tanpa mengubah tampilan visual. + +## Langkah 6: Simpan Byte PDF – Convert Image to PDF + +Jika Anda lebih suka menangani PDF di memori (misalnya, mengirimnya melalui API), Anda dapat menangkap byte‑nya alih‑alih menulis langsung ke disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Baris itu menunjukkan alur kerja klasik **convert image to PDF**: Anda memulai dengan gambar, menjalankan OCR, menimpa teks, dan akhirnya menghasilkan aliran PDF. + +## Langkah 7: Verifikasi Hasil – Pemeriksaan Cepat + +Setelah Anda menjalankan skrip, buka `receipt_searchable.pdf` di penampil PDF apa pun dan coba kotak pencarian (Ctrl + F). Ketik kata yang Anda tahu ada di kwitansi—jika melompat ke posisi yang tepat, Anda telah berhasil **create searchable pdf**! + +Jika pencarian gagal, periksa kembali: + +1. Skor kepercayaan OCR (`conf` values). Kepercayaan rendah dapat berarti gambar blur. +2. Koordinat bounding box—kadang EasyOCR melaporkannya dengan orientasi yang berbeda. +3. Pastikan penampil PDF tidak disetel ke mode “hanya gambar” (jarang, tetapi beberapa penampil memiliki opsi tersebut). + +## Skrip Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut file Python lengkap yang siap dijalankan: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Simpan ini sebagai `searchable_pdf.py`, ganti placeholder `YOUR_DIRECTORY` dengan jalur yang sebenarnya, dan jalankan: + +```bash +python searchable_pdf.py +``` + +Anda akan melihat pesan konfirmasi dan PDF searchable baru yang berada di folder Anda. + +## Pertanyaan Umum & Kasus Tepi + +**Bagaimana jika gambar berwarna?** +EasyOCR bekerja dengan gambar grayscale maupun berwarna, tetapi mengonversi ke grayscale (`pil_image.convert("L")`) kadang dapat meningkatkan akurasi pada pemindaian yang berisik. + +**Bisakah saya menangani PDF multi‑halaman?** +Ya—lakukan loop pada setiap gambar halaman, jalankan langkah OCR, dan tambahkan setiap halaman ke objek `FPDF` yang sama. Ingat untuk mereset kursor (`self.add_page()`) untuk setiap gambar baru. + +**Apakah ada cara untuk mempertahankan lapisan teks asli alih‑alih teks putih tak terlihat?** +Jika Anda membutuhkan PDF “teks‑di‑bawah‑gambar” yang sesungguhnya (misalnya, untuk aksesibilitas), pertimbangkan menggunakan `pdfminer` atau `pikepdf` untuk menyematkan lapisan teks tersembunyi dengan tag PDF yang tepat. Itu lebih lanjutan, tetapi prinsipnya tetap sama: gambar latar + teks overlay. + +**Bagaimana jika kepercayaan OCR rendah?** +Anda dapat menyaring kata‑kata dengan kepercayaan rendah: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Kesimpulan – Apa yang Kami Capai + +Kami memulai dengan gambar sederhana kwitansi, **performed OCR on image**, mengekstrak string yang dikenali, dan akhirnya **create searchable pdf** yang berperilaku seperti dokumen yang dipindai secara profesional. Proses ini mencakup semua kata kunci sekunder—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, dan **perform OCR on image**—sehingga Anda kini memiliki kotak peralatan yang dapat digunakan kembali untuk proyek serupa apa pun. + +### Langkah Selanjutnya + +- Bereksperimen dengan bahasa lain dengan memberikan kode ISO mereka ke `easyocr.Reader(['en', 'es'])`. +- Ganti EasyOCR dengan Tesseract jika Anda membutuhkan solusi sepenuhnya offline; sisa pipeline tetap sama. +- Tambahkan visualisasi kepercayaan OCR (gambar bounding box pada gambar) untuk men-debug pemindaian yang bermasalah. + +Ada variasi yang ingin Anda bagikan? Tinggalkan komentar, fork + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait 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 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/) +- [Konversi Gambar ke PDF C# – Simpan Hasil OCR Multi‑halaman](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Cara OCR Gambar – Perform OCR on Image dalam 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/indonesian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/indonesian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..1323474a8 --- /dev/null +++ b/ocr/indonesian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: Ekstrak teks dari gambar di Python dengan mesin OCR sederhana. Pelajari + cara mengonversi gambar yang dipindai menjadi teks, mengenali teks dari foto, dan + menampilkan daftar file gambar di Python secara efisien. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: id +og_description: Ekstrak teks dari gambar di Python menggunakan mesin OCR ringan. Panduan + ini menunjukkan cara mengonversi gambar yang dipindai menjadi teks, mengenali teks + dari foto, dan menampilkan daftar file gambar di Python dalam beberapa langkah. +og_title: Ekstrak Teks dari Gambar di Python – Panduan OCR Batch Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Ekstrak Teks dari Gambar dengan Python – Panduan OCR Batch Lengkap +url: /id/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ekstrak Teks dari Gambar dengan Python – Panduan OCR Batch Lengkap + +Pernah membutuhkan untuk **extract text from images** tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian—para pengembang terus-menerus menghadapi tantangan mengubah PDF yang dipindai, kwitansi yang difoto, atau screenshot menjadi teks yang dapat dicari. Dalam tutorial ini kami akan membahas contoh lengkap yang siap‑jalan yang menunjukkan cara **convert scanned images to text**, mengenali teks dari gambar, dan bahkan **list image files python**‑style. Pada akhir Anda akan memiliki skrip yang dapat digunakan kembali yang memproses seluruh folder sekaligus. + +Kami akan membahas semua yang Anda butuhkan: pustaka yang diperlukan, mengapa setiap langkah penting, penanganan kasus tepi, dan sedikit pemecahan masalah. Tidak perlu mencari dokumentasi eksternal; kode di bawah ini berdiri sendiri, dan penjelasannya menjawab “bagaimana” *dan* “mengapa”. Buka IDE favorit Anda, dan mari kita mulai. + +--- + +## Apa yang Akan Anda Bangun + +- Inisialisasi mesin OCR (kami akan menggunakan paket `ocr` untuk ilustrasi). +- Pindai sebuah direktori dan **list image files python**‑style, menyaring PNG, JPG, dan TIFF. +- Jalankan operasi **batch OCR** pada semua gambar yang ditemukan. +- Cetak teks yang diekstrak untuk setiap file, dengan label yang jelas. + +> **Pro tip:** Jika Anda belum menginstal pustaka `ocr`, Anda dapat menggantinya dengan `pytesseract` dengan beberapa perubahan kecil—logika inti tetap sama. + +--- + +## Prasyarat + +- Python 3.8+ (skrip ini menggunakan f‑strings dan type hints). +- Sebuah pustaka OCR yang menyediakan `OcrEngine` dengan `recognize_batch`. Untuk panduan ini kami mengasumsikan paket `ocr` fiktif, tetapi pola ini bekerja dengan pustaka nyata. +- Sebuah folder yang berisi file gambar yang ingin Anda proses (`.png`, `.jpg`, `.tif`). + +--- + +## Langkah 1 – Instal & Impor Modul yang Diperlukan + +Pertama, pastikan paket OCR tersedia. Jika Anda menggunakan pustaka nyata seperti `pytesseract`, ganti impor sesuai. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Why this matters:** Mengimpor `os` memberi kita penanganan path lintas‑platform, sementara `typing.List` membantu dengan autocomplete IDE dan membuat kode tahan masa depan. + +--- + +## Langkah 2 – **Extract Text from Images**: Inisialisasi Mesin OCR + +Membuat mesin adalah langkah pertama menuju pekerjaan OCR apa pun. Kami juga mengatur bahasa ke auto‑detect sehingga mesin dapat menangani dokumen dengan bahasa campuran. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explanation:** Dengan membungkus pembuatan mesin dalam sebuah fungsi, kami menjaga kode tetap modular. Jika nanti Anda perlu menyesuaikan DPI atau mode OCR, Anda hanya mengedit satu tempat ini. + +--- + +## Langkah 3 – **List Image Files Python**: Kumpulkan File dari Direktori + +Sekarang kita perlu menemukan setiap gambar yang ingin diproses. List comprehension di bawah ini mencerminkan pola “list image files python” yang umum. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge case handling:** Fungsi ini mengabaikan sub‑folder (Anda dapat menambahkan rekursi nanti) dan secara otomatis menyaring file tersembunyi karena biasanya tidak berakhiran ekstensi yang didukung. + +--- + +## Langkah 4 – **Convert Scanned Images to Text**: Jalankan Batch OCR + +Sebagian besar pustaka OCR menyediakan metode batch yang jauh lebih cepat dibandingkan memproses satu gambar sekaligus. Berikut cara memanggilnya. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Why batch?** Mengirim semua gambar sekaligus mengurangi overhead (mis., memuat model OCR berulang kali) dan sering menghasilkan pemanfaatan CPU/GPU yang lebih baik. + +--- + +## Langkah 5 – **Recognize Text from Pictures**: Tampilkan Hasil + +Akhirnya, kami mengiterasi nama file yang dipasangkan dengan hasil OCR, mencetak header bersih untuk setiap gambar. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** `strip()` menghapus spasi kosong di awal/akhir yang sering ditambahkan OCR. + +--- + +## Script Lengkap – Gabungkan Semua + +Berikut adalah program lengkap yang dapat dijalankan. Simpan sebagai `batch_ocr.py` dan jalankan `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Output yang Diharapkan + +Dengan asumsi folder berisi `invoice1.png` dan `receipt.jpg`, Anda mungkin melihat: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Setiap blok jelas berlabel, membuat pemrosesan selanjutnya (mis., menyimpan ke basis data) menjadi sederhana. + +--- + +## Menangani Kendala Umum + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **Tidak ada teks muncul** | Bahasa OCR tidak terdeteksi atau gambar terlalu kontras rendah. | Paksa bahasa (`engine.language = ocr.Language.English`) atau pra‑proses gambar (tingkatkan kontras). | +| **Kesalahan memori pada batch besar** | Mesin mencoba memuat semua gambar sekaligus. | Bagi `image_files` menjadi potongan (`batch_size = 20`) dan panggil `recognize_batch` berulang kali. | +| **Format file tidak didukung** | Anda menambahkan `.gif` atau `.bmp`. | Perluas tuple `supported_exts` atau konversi gambar ke PNG/JPG terlebih dahulu. | +| **Unicode rusak** | OCR mengembalikan bytes alih-alih string. | Pastikan pustaka OCR mengeluarkan Unicode (`result.text.decode('utf‑8')` jika diperlukan). | + +--- + +## Memperluas Alur Kerja + +Sekarang Anda dapat **extract text from images**, pertimbangkan langkah selanjutnya berikut: + +- **Export to CSV** – Tulis setiap nama file dan teks yang diekstrak ke spreadsheet untuk analisis. +- **Parallel processing** – Gunakan `concurrent.futures.ThreadPoolExecutor` untuk menangani beberapa batch secara bersamaan. +- **Integrate with cloud OCR** – Ganti mesin lokal dengan Google Vision atau Azure OCR untuk akurasi lebih tinggi pada tata letak kompleks. +- **Add image preprocessing** – Pustaka seperti Pillow atau OpenCV dapat memperbaiki kemiringan, mengurangi noise, atau melakukan threshold pada gambar sebelum OCR, meningkatkan hasil. + +Semua ide ini secara alami melibatkan fungsi inti yang sama yang telah kami buat, jadi Anda tidak perlu memulai dari nol. + +--- + +## Kesimpulan + +Kami baru saja membahas solusi lengkap untuk **extract text from images** dengan Python, mencakup semua hal mulai dari **list image files python** hingga **recognize text from pictures** dan akhirnya **convert scanned images to text** dalam batch yang rapi. Skrip ini sengaja sederhana namun cukup fleksibel untuk menjadi fondasi proyek yang lebih besar—apakah Anda mendigitalkan kwitansi, membangun arsip yang dapat dicari, atau menggerakkan pipeline ekstraksi data. + +Cobalah, sesuaikan langkah pra‑proses, dan saksikan akurasi OCR Anda meningkat. Jika Anda menemui kendala, tinjau kembali tabel “Menangani Kendala Umum”; kebanyakan masalah dapat diselesaikan dengan perubahan konfigurasi kecil. + +Siap untuk tantangan berikutnya? Coba tambahkan langkah konversi PDF‑ke‑gambar menggunakan `pdf2image`, lalu masukkan gambar tersebut langsung ke pipeline yang sama. Langit adalah batasnya ketika Anda menggabungkan OCR dengan ekosistem Python yang kaya. + +Selamat coding, dan semoga teks Anda selalu terbaca! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait 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. + +- [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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/indonesian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..7d4fcf3df --- /dev/null +++ b/ocr/indonesian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-06-19 +description: Ekstrak teks dari gambar menggunakan Python OCR. Pelajari deteksi bahasa + otomatis, pemrosesan paralel, dan pengenalan batch dalam tutorial singkat. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: id +og_description: Ekstrak teks dari gambar dengan Python OCR. Panduan ini menunjukkan + deteksi bahasa otomatis, pemrosesan paralel, dan pengenalan batch dalam satu tutorial. +og_title: Ekstrak Teks dari Gambar di Python – Panduan OCR Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Ekstrak Teks dari Gambar di Python – Panduan OCR Lengkap +url: /id/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ekstrak teks dari gambar di Python – Panduan OCR Lengkap + +Pernah bertanya-tanya bagaimana cara **mengekstrak teks dari gambar** tanpa harus mengetik setiap kata secara manual? Anda tidak sendirian. Baik Anda sedang mendigitalkan kwitansi lama, membangun arsip dokumen yang dapat dicari, atau sekadar bermain dengan trik AI keren, kemampuan mengambil teks dari gambar adalah keterampilan yang wajib dimiliki oleh setiap pengembang Python saat ini. + +Dalam tutorial ini kami akan membahas contoh lengkap yang siap dijalankan yang **mengekstrak teks dari gambar** menggunakan mesin OCR populer. Kami akan membahas deteksi bahasa otomatis, pemrosesan paralel untuk kecepatan, dan pengenalan gambar batch sehingga Anda dapat menangani puluhan file dalam hitungan detik. Kedengarannya seperti yang Anda butuhkan? Mari kita mulai. + +## Apa yang Akan Anda Pelajari + +- Cara menginstansiasi mesin OCR dengan `ocr.OcrEngine`. +- Mengaktifkan **deteksi bahasa otomatis** sehingga mesin memilih bahasa yang tepat secara otomatis. +- Mengonfigurasi **OCR pemrosesan paralel** dengan thread pool khusus. +- Menjalankan **pengenalan gambar batch** pada daftar file. +- Mencetak teks yang dikenali untuk setiap gambar, siap disimpan atau diindeks. + +Tidak diperlukan dokumentasi eksternal—semua yang Anda butuhkan ada di sini, dan kode berfungsi langsung dengan paket `ocr` (pasang dengan `pip install ocr`). + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +1. Python 3.8 atau yang lebih baru terpasang. +2. Paket `ocr` (`pip install ocr`). +3. Sebuah folder berisi gambar PNG (atau JPG) yang ingin Anda proses. +4. Familiaritas dasar dengan fungsi dan loop Python. + +Itu saja—tidak ada dependensi berat, tidak ada keajaiban GPU, hanya Python biasa. + +![ekstrak teks dari gambar contoh](https://example.com/ocr-demo.png "Tangkapan layar menunjukkan output ekstrak teks dari gambar") + +*Alt text: contoh tangkapan layar demo ekstrak teks dari gambar* + +## Langkah 1 – Siapkan Mesin OCR (Kata Kunci Utama dalam Aksi) + +Hal pertama yang harus dilakukan: buat instance mesin OCR. Anggap `ocr.OcrEngine()` sebagai otak di balik operasi; ia tahu cara membaca karakter, baris, dan paragraf. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Mengapa kita memerlukan mesin yang eksplisit? Karena **penggunaan ocr.OcrEngine** memberi Anda kontrol detail atas pengaturan bahasa, threading, dan lainnya. Ini adalah cara paling fleksibel untuk **mengekstrak teks dari gambar** dibandingkan dengan helper satu baris. + +## Langkah 2 – Biarkan Mesin Mendeteksi Bahasa Secara Otomatis + +Sebagian besar perpustakaan OCR mengharuskan Anda memberi tahu bahasa yang harus dicari. Itu tidak masalah untuk proyek satu bahasa, tetapi merepotkan untuk batch campuran bahasa. Untungnya, paket `ocr` mendukung **deteksi bahasa otomatis**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Menetapkan `engine.language` ke `ocr.Language.Auto` memberi tahu mesin untuk mengendus setiap gambar dan memilih model bahasa yang sesuai. Baris kecil ini menghemat jam konfigurasi manual ketika Anda berurusan dengan dokumen internasional. + +## Langkah 3 – Percepat dengan OCR Pemrosesan Paralel + +Jika Anda memiliki empat core CPU atau lebih, mengapa tidak memanfaatkannya? Mesin dapat memulai thread pool, memungkinkan beberapa gambar diproses secara bersamaan. Di sinilah **OCR pemrosesan paralel** bersinar. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Silakan sesuaikan angka `4` berdasarkan mesin Anda. Lebih banyak thread → batch lebih cepat, tetapi ingat setiap thread mengonsumsi memori, jadi temukan titik optimal untuk lingkungan Anda. + +## Langkah 4 – Kumpulkan Gambar yang Ingin Diproses + +Sekarang kita memerlukan daftar path file. Anda dapat membuat daftar ini secara manual, membacanya dari CSV, atau menggunakan `glob`. Untuk kejelasan, kami akan menuliskan daftar pendek secara hard‑code: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Ganti `YOUR_DIRECTORY` dengan path sebenarnya di sistem Anda. Jika Anda memiliki puluhan file, `glob.glob("*.png")` akan melakukan pekerjaan berat. + +## Langkah 5 – Jalankan Pengenalan Gambar Batch + +Berikut inti tutorial: satu panggilan yang memproses setiap gambar dalam `files` dan mengembalikan daftar objek hasil. Inilah fitur **pengenalan gambar batch** yang membuat OCR skala besar menjadi praktis. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Di balik layar, mesin mendistribusikan setiap file ke empat worker thread yang telah kami konfigurasikan sebelumnya, sambil juga mendeteksi bahasa secara otomatis untuk setiap gambar. Metode ini mengembalikan daftar di mana setiap elemen berisi teks yang dikenali dan metadata. + +## Langkah 6 – Cetak (atau Simpan) Teks yang Diekstrak + +Akhirnya, kami melakukan loop atas hasil dan mencetak teksnya. Dalam proyek nyata Anda mungkin akan menulisnya ke basis data atau file CSV, tetapi mencetak membuat contoh tetap sederhana. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Output yang diharapkan** (dipotong untuk singkat): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Setiap blok menampilkan nama file diikuti oleh string hasil OCR. Jika sebuah gambar berisi beberapa bahasa, Anda akan melihat karakter yang sesuai muncul berkat langkah **deteksi bahasa otomatis** sebelumnya. + +## Tips Pro & Kesalahan Umum + +- **Kualitas gambar penting** – gambar blur atau kontras rendah akan menghasilkan sampah. Lakukan pra‑proses dengan OpenCV (`cv2.threshold`, `cv2.resize`) jika diperlukan. +- **Jumlah thread vs. I/O** – Jika gambar Anda berada di drive jaringan yang lambat, menambah thread mungkin tidak membantu. Pantau penggunaan CPU dengan `top` atau `Task Manager`. +- **Penanganan Unicode** – `result.text` adalah string Unicode. Saat menulis ke file, buka dengan `encoding="utf‑8"` untuk menghindari `UnicodeEncodeError`. +- **Penggunaan memori** – PDF besar dapat mengonsumsi banyak RAM. Jika Anda menemui `MemoryError`, kurangi ukuran thread pool atau proses gambar dalam potongan lebih kecil. + +## Skrip Lengkap yang Siap Pakai + +Berikut adalah skrip lengkap yang dapat Anda salin‑tempel yang mencakup semua langkah yang telah dibahas. Simpan sebagai `batch_ocr.py` dan jalankan dengan `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Jalankan seperti ini: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Anda akan melihat blok teks yang diformat rapi untuk setiap gambar, membuktikan bahwa Anda dapat **mengekstrak teks dari gambar** secara skala. + +## Apa Selanjutnya? + +Sekarang Anda telah menguasai dasar **mengekstrak teks dari gambar** dengan Python, pertimbangkan untuk mengeksplorasi: + +- **Pasca‑pemrosesan**: bersihkan output OCR dengan regex atau perpustakaan bahasa alami. +- **Konversi PDF**: masukkan string yang diekstrak ke generator PDF untuk PDF yang dapat dicari. +- **Layanan OCR Cloud**: bandingkan hasil `ocr` on‑prem dengan Google Vision atau Azure OCR untuk akurasi pada kasus tepi. +- **Frontend GUI**: bangun aplikasi Flask atau FastAPI kecil yang memungkinkan pengguna mengunggah gambar dan langsung melihat teks yang diekstrak. + +Masing‑masing topik ini dibangun di atas fondasi **perpustakaan OCR Python** yang baru saja Anda siapkan, dan semuanya mendapat manfaat dari trik **OCR pemrosesan paralel** yang kami gunakan di sini. + +--- + +*Selamat coding! Jika Anda menemui kendala, tinggalkan komentar di bawah—saya selalu siap membantu mengatasi masalah OCR.* + + +## 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 yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/indonesian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..d6d3d5c9b --- /dev/null +++ b/ocr/indonesian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-06-19 +description: Cara mengekstrak PDF menggunakan OCR di Python – tutorial langkah demi + langkah yang mencakup mengekstrak teks dari PDF, mengenali teks dari gambar, dan + contoh OCR Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: id +og_description: Cara mengekstrak PDF menggunakan OCR di Python. Pelajari cara mengekstrak + teks dari PDF, mengenali teks dari gambar, dan lihat contoh lengkap OCR dengan Python. +og_title: Cara Mengekstrak Teks PDF dengan OCR di Python – Tutorial Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Cara Mengekstrak Teks PDF dengan OCR di Python – Panduan Lengkap +url: /id/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Mengekstrak Teks PDF dengan OCR di Python – Panduan Lengkap + +Pernah bertanya-tanya **cara mengekstrak PDF** ketika file hanya berupa gambar yang dipindai? Anda bukan satu-satunya. Dalam banyak proyek dunia nyata—seperti kontrak, faktur, atau arsip bersejarah—PDF yang Anda terima tidak memiliki teks yang dapat dipilih. Kabar baik? Beberapa baris Python dapat mengubah halaman yang hanya berupa gambar menjadi teks yang dapat dicari dan diedit. + +Dalam tutorial ini kami akan membahas contoh **OCR Python** yang praktis, yang membaca PDF, merender halaman pertamanya sebagai gambar, dan kemudian **mengekstrak teks dari PDF** menggunakan mesin OCR. Pada akhir tutorial Anda akan tahu persis **cara membaca PDF dengan OCR**, mengapa setiap langkah penting, dan bagaimana menyesuaikan kode untuk dokumen multi‑halaman atau bahasa yang berbeda. + +## Apa yang Akan Anda Pelajari + +- Menginstal dan menyiapkan perpustakaan OCR yang handal untuk Python. +- Mengonversi halaman PDF menjadi gambar yang cocok untuk OCR. +- **Mengenali teks dari gambar** dan mengambil string Unicode yang bersih. +- Kesulitan umum (PDF beresolusi rendah, halaman terrotasi) dan cara menghindarinya. +- Memperluas skrip untuk menangani banyak halaman atau pemrosesan batch. + +**Prasyarat**: Python 3.8+, pip, dan pemahaman dasar tentang lingkungan virtual. Tidak diperlukan pengalaman OCR sebelumnya—cukup ikuti langkahnya. + +--- + +## ## Cara Mengekstrak Teks PDF dengan OCR di Python + +Header H2 ini berisi kata kunci utama kami tepat di tempat yang disukai mesin pencari. Mari langsung menyelam ke kode. + +### Langkah 1 – Instal Paket yang Diperlukan + +Pertama, kami memerlukan mesin OCR. Contoh di bawah menggunakan paket **ocr** yang populer (pembungkus tipis di atas Tesseract). Jika Anda lebih suka backend yang berbeda, konsepnya tetap sama. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** Di Linux, Anda juga memerlukan binary Tesseract: `sudo apt-get install tesseract-ocr`. Pengguna macOS dapat mengunduhnya via Homebrew: `brew install tesseract`. + +### Langkah 2 – Inisialisasi Mesin OCR dan Atur Bahasa + +Sekarang kami memulai mesin dan memberitahunya untuk mencari karakter bahasa Inggris. Anda dapat mengganti `ocr.Language.English` dengan kode bahasa lain yang didukung. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Mengapa ini penting:** Menentukan bahasa secara signifikan meningkatkan akurasi karena mesin dapat menerapkan kamus dan model karakter khusus bahasa. + +### Langkah 3 – Muat Halaman PDF sebagai Gambar + +OCR bekerja pada gambar raster, bukan objek PDF. Helper `ocr.Image.from_pdf` merender halaman yang dipilih menjadi bitmap. Sesuaikan `page_number` untuk halaman lain (indeks berbasis 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** Jika PDF berisi grafik vektor bukan gambar yang dipindai, Anda mungkin mendapatkan render yang tajam. Untuk pemindaian beresolusi rendah, pertimbangkan meningkatkan DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Langkah 4 – Mengenali Teks dari Gambar yang Dirender + +Berikut inti dari **ocr python example**. Mesin memproses bitmap dan mengembalikan objek yang berisi string yang diekstrak. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Atribut `ocr_result.text` menyimpan output teks biasa, mempertahankan jeda baris bila memungkinkan. + +### Langkah 5 – Cetak atau Simpan Teks yang Diekstrak + +Akhirnya, kami menampilkan hasilnya. Dalam aplikasi nyata Anda mungkin akan menulis ke file atau basis data. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Menjalankan skrip seharusnya menampilkan sesuatu seperti: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Itulah alur kerja **mengekstrak teks dari pdf** lengkap menggunakan OCR. + +--- + +## ## Mengenali Teks dari Gambar – Menyetel Akurasi + +Jika Anda hanya tertarik pada **mengenali teks dari gambar** (misalnya, JPEG dari kwitansi), Anda dapat melewatkan langkah konversi PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips untuk hasil yang lebih baik:** + +- **Pra‑proses** gambar: konversi ke skala abu‑abu, terapkan thresholding, atau deskew. Pillow memudahkan hal ini. +- **Tingkatkan DPI** saat merender PDF: resolusi lebih tinggi memberi mesin OCR lebih banyak detail. +- **Aktifkan konfigurasi mesin OCR** untuk segmentasi halaman (`ocr_engine.config = "--psm 6"` untuk blok seragam). + +--- + +## ## Membaca PDF dengan OCR – Menangani Banyak Halaman + +Sebagian besar kontrak memiliki beberapa halaman. Melakukan loop pada setiap halaman sangat mudah: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Fungsi ini **membaca PDF dengan OCR**, menggabungkan output, dan menyisipkan penanda jeda halaman yang jelas. Anda kemudian dapat memasukkan `full_text` ke indeks pencarian atau menyimpannya sebagai file `.txt`. + +--- + +## ## Kesulitan Umum dan Cara Memperbaikinya + +| Gejala | Penyebab Kemungkinan | Solusi | +|---------|----------------------|--------| +| Karakter kacau, banyak `?` | Bahasa salah atau file data bahasa tidak ada | Instal paket bahasa Tesseract yang tepat (`tesseract-ocr-`) dan atur `ocr_engine.language`. | +| Baris hilang atau kata terpotong | DPI rendah (di bawah 150) | Render PDF pada 300 DPI atau lebih tinggi (`dpi=300`). | +| Teks terrotasi atau terbalik | Halaman yang dipindai tidak tegak | Gunakan `ocr.Image.deskew(page_image)` sebelum pengenalan. | +| Pemrosesan lambat pada PDF besar | Memproses halaman secara berurutan pada satu thread | Paralelisasi dengan `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Memperluas Contoh OCR Python + +- **Ekspor ke PDF/A**: Setelah ekstraksi, Anda dapat menyematkan teks kembali ke PDF yang dapat dicari menggunakan `reportlab` atau `pypdf2`. +- **Deteksi bahasa**: Gunakan `langdetect` pada output OCR untuk secara dinamis mengganti `ocr_engine.language`. +- **Pemrosesan batch**: Jelajahi direktori dengan `os.listdir` dan terapkan `extract_all_pages` pada setiap file. + +--- + +## ## Output yang Diharapkan dan Verifikasi + +Saat Anda menjalankan skrip pada pemindaian yang jelas dan berbahasa Inggris, Anda harus melihat blok teks bersih dengan tanda baca yang tepat. Verifikasi dengan: + +1. Membandingkan beberapa baris dengan gambar hasil pindai asli. +2. Menjalankan hitung kata sederhana (`len(ocr_result.text.split())`) untuk memastikan output tidak kosong. +3. Opsional, mengirimkan hasil ke pemeriksa ejaan seperti `pyspellchecker` untuk menemukan kesalahan OCR. + +--- + +## Kesimpulan + +Kami telah membahas **cara mengekstrak PDF** ketika parsing tradisional gagal, mendemonstrasikan contoh **ocr python** lengkap, dan menjelaskan cara **mengenali teks dari gambar** serta **membaca PDF dengan OCR** untuk skenario satu‑halaman maupun multi‑halaman. Dengan potongan kode di atas Anda kini dapat mengubah PDF yang dipindai menjadi teks yang dapat dicari dan diedit—tidak lagi harus mengetik ulang secara manual. + +Langkah selanjutnya? Coba ganti bahasa ke Spanyol (`ocr.Language.Spanish`) atau bereksperimen dengan teknik pra‑proses gambar untuk meningkatkan akurasi. Jika Anda membangun sistem manajemen dokumen, pertimbangkan mengindeks teks yang diekstrak dengan Elasticsearch untuk pencarian super cepat. + +Ada pertanyaan atau menemukan PDF yang aneh? Tinggalkan komentar, dan selamat coding! + +![Cara mengekstrak PDF menggunakan OCR di Python](image.png "Cara mengekstrak PDF menggunakan OCR di Python") + + +## 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-demi-Langkah](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Mengenali Teks PDF – Operasi OCR dengan Aspose.OCR untuk Java](/ocr/english/java/ocr-operations/) +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/indonesian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..29a4ac4f2 --- /dev/null +++ b/ocr/indonesian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-19 +description: Pelajari cara menggunakan OCR di Java dengan Aspose. Panduan langkah + demi langkah ini mencakup meluruskan gambar secara otomatis, deteksi bahasa otomatis, + dan mengekstrak teks dari gambar dengan mudah. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: id +og_description: 'Cara menggunakan OCR di Java dengan Aspose: panduan lengkap yang + mencakup otomatis memperbaiki kemiringan gambar, deteksi bahasa otomatis, dan mengekstrak + teks dari gambar.' +og_title: Cara Menggunakan OCR di Java dengan Aspose – Panduan Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Cara Menggunakan OCR di Java dengan Aspose – Panduan Lengkap +url: /id/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Menggunakan OCR di Java dengan Aspose – Panduan Lengkap + +Pernah bertanya‑tanya **cara menggunakan OCR** dalam proyek Java tanpa harus menggaruk kepala karena konfigurasi? Anda tidak sendirian. Banyak pengembang menemui kebuntuan ketika harus **mengekstrak teks gambar** dengan cepat, terutama bila pemindaian sumber miring atau ditulis dalam bahasa yang tidak dikenal. + +Dalam tutorial ini kami akan menunjukkan contoh langsung yang memperlihatkan cara menggunakan OCR dengan Aspose, termasuk **auto deskew images**, **auto language detection**, dan seluruh pipeline **ocr image preprocessing**. Pada akhir tutorial Anda akan memiliki potongan kode yang siap dijalankan yang mencetak teks yang dikenali ke konsol, serta memahami mengapa setiap pengaturan penting. + +> **Apa yang akan Anda dapatkan:** program Java lengkap yang dapat dijalankan, penjelasan setiap baris, tips menangani kasus tepi, dan ide untuk memperluas solusi ke pemrosesan batch atau PDF. + +--- + +## Prasyarat + +- Java 17 (atau JDK terbaru lainnya) terpasang dan terkonfigurasi. +- Maven atau Gradle untuk manajemen dependensi (kami akan menunjukkan koordinat Maven). +- File lisensi Aspose OCR untuk Java (`Aspose.OCR.Java.lic`). Jika Anda hanya menguji, Anda dapat melewatkan langkah lisensi, tetapi versi percobaan gratis akan menambahkan watermark. +- Gambar contoh (`your_image.png`) ditempatkan di lokasi yang dapat diakses oleh kode. + +> **Pro tip:** simpan gambar Anda dalam folder `resources` khusus dan muat melalui classpath; ini menghindari masalah jalur pada berbagai OS. + +--- + +## Langkah 1: Siapkan Proyek dan Tambahkan Dependensi Aspose OCR + +Buat proyek Maven baru (atau gunakan yang sudah ada) dan tambahkan berikut ke `pom.xml` Anda: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Jalankan `mvn clean install` untuk mengunduh pustaka. Jika Anda lebih suka Gradle, setaraannya adalah: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Sekarang Anda memiliki kelas **ocr image preprocessing** di classpath. + +--- + +## Langkah 2: Terapkan Lisensi Aspose OCR Anda (Opsional namun Disarankan) + +Jika Anda memiliki lisensi, terapkan di awal metode `main` Anda. Melewatkan langkah ini tetap dapat berjalan, tetapi versi gratis menambahkan watermark “Demo” pada output. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Mengapa ini penting:** Versi berlisensi menghapus batas penggunaan dan menonaktifkan watermark, memberikan hasil bersih yang siap produksi. + +--- + +## Langkah 3: Buat Instance Mesin OCR + +Mesin adalah inti dari proses. Menginstansiasinya memberi Anda akses ke semua opsi **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Pada titik ini mesin sudah siap, tetapi akan menggunakan pengaturan default yang mungkin tidak optimal untuk dokumen yang dipindai. Mari kita ubah beberapa pengaturan. + +--- + +## Langkah 4: Aktifkan Auto Deskew Images untuk Pemindaian Lebih Bersih + +Pemindaian miring adalah masalah umum. Aspose menyediakan fitur **auto deskew images** yang secara otomatis meluruskan gambar sebelum pengenalan. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Cara kerjanya:** Algoritma menganalisis sudut baseline teks dan memutar gambar ke orientasi tegak yang paling mungkin. Ini secara dramatis meningkatkan akurasi untuk foto yang diambil dengan ponsel. + +--- + +## Langkah 5: Aktifkan Deteksi Bahasa Otomatis + +Jika Anda tidak mengetahui bahasa gambar sumber, biarkan mesin yang menentukannya. Ini adalah pengaturan **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Saat Anda mengaktifkannya, Aspose memindai glif dan memilih model bahasa yang paling mungkin, mendukung lebih dari 30 bahasa secara bawaan. + +--- + +## Langkah 6: Muat Gambar yang Ingin Diakui + +Anda dapat memuat gambar dari disk, URL, atau bahkan array byte. Untuk kesederhanaan, kami akan membaca dari file lokal. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** Jika Anda menangani gambar berukuran besar, pertimbangkan menurunkan resolusinya terlebih dahulu dengan `engine.getImagePreprocessing().setResizeFactor(0.5)` untuk mempercepat pemrosesan tanpa kehilangan banyak detail. + +--- + +## Langkah 7: Lakukan Pengakuan OCR dan Ekstrak Teks Gambar + +Sekarang mesin melakukan magisnya. Metode `recognize` mengembalikan objek `OcrResult` yang berisi teks yang dikenali, skor kepercayaan, dan lainnya. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Konsol akan menampilkan teks polos yang diekstrak dari gambar—ini adalah hasil utama **extract text image** yang ingin kami capai. + +--- + +## Contoh Lengkap yang Berfungsi + +Berikut adalah kelas Java lengkap yang mengikat semua langkah. Salin‑tempel ke `src/main/java/com/example/OcrDemo.java` dan jalankan. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Output yang Diharapkan + +Jika gambar berisi frasa “Hello World” pada pemindaian bersih, Anda akan melihat: + +``` +=== Recognized Text === +Hello World +``` + +Untuk dokumen yang lebih kompleks (misalnya kwitansi multibahasa), output akan mencakup baris baru dan kode bahasa yang terdeteksi. + +--- + +## Kesalahan Umum & Pro Tips + +| Masalah | Mengapa Terjadi | Solusi | +|---------|-----------------|--------| +| **Karakter sampah** | Gambar terlalu gelap atau berisik. | Aktifkan `engine.getImagePreprocessing().setBinarization(true)` atau sesuaikan kontras secara manual. | +| **Bahasa salah** | Deteksi otomatis gagal pada halaman campuran bahasa. | Setel `engine.setLanguage(Language.English)` (atau enum yang sesuai) untuk memaksa bahasa tertentu. | +| **Pemrosesan lambat** | Gambar beresolusi sangat tinggi. | Turunkan skala dengan `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Kesalahan out‑of‑memory** | Batch besar gambar dimuat sekaligus. | Proses gambar secara berurutan dan panggil `engine.dispose()` setelah setiap run. | + +> **Ingat:** Mesin OCR aman untuk thread pada operasi baca‑saja, tetapi membuat instance baru per thread menghindari bug status tersembunyi. + +--- + +## Memperluas Solusi + +Setelah Anda mengetahui **cara menggunakan OCR** dengan Aspose, Anda mungkin ingin: + +1. **Memproses PDF** – Konversi tiap halaman PDF menjadi gambar (`PdfConverter`) lalu masukkan ke pipeline yang sama. +2. **Proses batch folder** – Loop melalui file dalam direktori, terapkan langkah yang sama, dan tulis hasil ke CSV. +3. **Integrasi dengan layanan web** – Ekspose logika OCR melalui `@RestController` Spring Boot yang menerima unggahan multipart. + +Semua skenario tersebut menggunakan konfigurasi **ocr image preprocessing** yang sama seperti yang kami bangun di sini. + +--- + +## Kesimpulan + +Kami telah membahas **cara menggunakan OCR** di Java dengan Aspose dari awal hingga akhir: menerapkan lisensi, membuat mesin, mengaktifkan **auto deskew images**, mengaktifkan **auto language detection**, memuat gambar, dan akhirnya **extract text image** dengan satu `System.out.println`. Kode ini sepenuhnya mandiri, berjalan pada JDK terbaru, dan menunjukkan praktik terbaik untuk akurasi serta kinerja. + +Cobalah dengan gambar Anda sendiri—mungkin kontrak yang dipindai atau tangkapan layar kwitansi. Sesuaikan flag preprocessing, bereksperimen dengan bahasa berbeda, dan Anda akan segera melihat mengapa pustaka OCR Aspose menjadi pilihan solid untuk ekstraksi teks produksi. + +Ada pertanyaan atau ingin berbagi hasil? Tinggalkan komentar di bawah atau hubungi saya di GitHub. Selamat coding! + +--- + +![Contoh cara menggunakan OCR di Java](/images/ocr-java-example.png "Cara menggunakan OCR di Java – tangkapan layar demo Aspose") + + +## 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 yang dapat dijalankan dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/indonesian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..e05029a8e --- /dev/null +++ b/ocr/indonesian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Tingkatkan akurasi OCR di Python menggunakan Aspose OCR. Pelajari cara + mengatur bahasa OCR, memuat gambar untuk OCR, dan mengekstrak teks dari gambar dengan + kamus khusus. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: id +og_description: Tingkatkan akurasi OCR di Python dengan mengatur bahasa OCR, memuat + gambar untuk OCR, dan mengekstrak teks dari gambar menggunakan kamus khusus. +og_title: Tingkatkan Akurasi OCR di Python – Panduan Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Meningkatkan Akurasi OCR di Python – Panduan Lengkap +url: /id/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tingkatkan Akurasi OCR di Python – Panduan Lengkap + +Pernah bertanya-tanya bagaimana cara **meningkatkan akurasi OCR** ketika teks yang Anda pindai berisi simbol aneh, kode produk, atau nama merek? Anda tidak sendirian. Dalam banyak proyek mesin default hanya menghasilkan teks tak terbaca, dan itu benar‑benar menghambat produktivitas. + +Dalam tutorial ini kami akan menelusuri contoh praktis end‑to‑end yang menunjukkan cara **mengatur bahasa OCR**, **memuat gambar untuk OCR**, **melakukan OCR pada gambar**, dan akhirnya **mengekstrak teks dari gambar** dengan kamus khusus yang meningkatkan tingkat pengenalan. Pada akhir tutorial Anda akan memiliki skrip siap‑jalankan yang dapat Anda sisipkan ke dalam basis kode Python mana pun. + +## Apa yang Akan Anda Dapatkan + +- Skrip Python yang berfungsi penuh menggunakan Aspose OCR untuk membaca file PNG. +- Kemampuan untuk **meningkatkan akurasi OCR** dengan mengonfigurasi bahasa dan daftar kata khusus. +- Penjelasan jelas mengapa setiap pengaturan penting, plus tip untuk menangani kasus tepi seperti karakter non‑Latin. +- Daftar periksa cepat untuk memecahkan masalah umum pada OCR. + +### Prasyarat + +- Python 3.8 atau lebih baru terpasang di mesin Anda. +- Paket `aspose-ocr` (pasang lewat `pip install aspose-ocr`). +- Gambar contoh (`technical_doc.png`) yang berisi teks yang ingin Anda baca. +- Familiaritas dasar dengan Python—tidak diperlukan hal yang rumit. + +> **Pro tip:** Jika Anda bekerja di lingkungan virtual, aktifkan terlebih dahulu sebelum menginstal paket. Ini menjaga ketergantungan tetap rapi dan menghindari benturan versi. + +--- + +## Langkah 1: Instal dan Impor Aspose OCR + +Langkah pertama—mari kita tambahkan pustaka ke lingkungan dan mengimpor komponen yang diperlukan. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Namespace `aspose.ocr` memberi Anda akses ke kelas `OcrEngine`, yang merupakan inti proses OCR. Mengimpornya di sini membuat sisa skrip tetap bersih dan mudah dibaca. + +--- + +## Langkah 2: Buat OCR Engine dan **Atur Bahasa OCR** + +Mengapa bahasa penting? Mesin OCR mengandalkan model khusus bahasa untuk mengenali bentuk karakter dan pola kata. Jika Anda memberi tahu mesin bahwa Anda memindai teks berbahasa Inggris, ia akan mengabaikan glif Cyrillic dan fokus pada alfabet Latin, secara dramatis **meningkatkan akurasi OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Catatan:** Aspose OCR mendukung lebih dari 50 bahasa. Ganti `ocr.Language.English` dengan `ocr.Language.Spanish`, `ocr.Language.French`, dll., jika dokumen Anda bukan bahasa Inggris. + +--- + +## Langkah 3: Definisikan **Kamus Khusus** untuk Meningkatkan Akurasi + +Bayangkan Anda memindai faktur yang berisi kata “AsposeOCR” atau kode produk seperti “SKU12345”. Mesin tidak mengenal istilah tersebut, sehingga menebak secara keliru. Menyediakan daftar kata khusus memberi tahu mesin, *“Hei, string ini sah—jangan coba koreksi.”* Itu adalah cara cepat untuk **meningkatkan akurasi OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Anda dapat memuat daftar ini dari file atau basis data jika memiliki ratusan entri—cukup simpan dalam list Python untuk kesederhanaan. + +--- + +## Langkah 4: **Muat Gambar untuk OCR** + +Sekarang kita membutuhkan gambar. Metode `Image.load` menerima jalur ke format raster yang didukung (PNG, JPEG, BMP, dll.). Jika file tidak ditemukan, mesin akan melempar pengecualian, jadi kita akan menyiapkan penanganan. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Mengapa langkah ini penting:** Memuat gambar dengan benar memastikan mesin bekerja dengan data piksel tepat yang ingin Anda analisis. File rusak atau jalur yang salah adalah sumber frustrasi yang umum. + +--- + +## Langkah 5: **Lakukan OCR pada Gambar** dan Ekstrak Hasil + +Dengan mesin yang telah dikonfigurasi dan gambar siap, pengenalan sebenarnya cukup dengan satu pemanggilan metode. Objek hasil berisi teks mentah, skor kepercayaan, dan bahkan informasi tata letak jika Anda membutuhkannya nanti. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Jika Anda perlu **mengekstrak teks dari gambar** baris per baris, Anda dapat memisahkan dengan karakter baris baru: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Langkah 6: Verifikasi Output – Apakah Benar‑benar **Meningkatkan Akurasi OCR**? + +Mari cetak hasilnya dan lihat apakah kamus khusus kami membuat perbedaan. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Output tipikal untuk gambar contoh mungkin terlihat seperti: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Perhatikan bagaimana nama merek, karakter Yunani, dan kode produk muncul persis seperti yang kami definisikan. Tanpa kamus khusus, mesin akan mencoba “mengoreksi” mereka, sering menghasilkan sesuatu seperti “Aspose OCR” atau “SKU 1234”. + +--- + +## Kesalahan Umum & Cara Menanganinya + +| Masalah | Mengapa Terjadi | Solusi | +|-------|----------------|-----| +| **Karakter sampah** | Bahasa yang salah atau gambar beresolusi rendah | Pastikan `engine.language` cocok dengan bahasa sumber dan gunakan pemindaian DPI tinggi (300 dpi atau lebih). | +| **Kata khusus diabaikan** | Kamus tidak terpasang atau ada typo pada nama properti | Periksa kembali `engine.text_processing.custom_dictionary = …`. | +| **File tidak ditemukan** | Jalur salah atau izin file kurang | Gunakan `os.path.abspath()` untuk memverifikasi jalur absolut; jalankan skrip dengan izin yang tepat. | +| **Pemrosesan lambat** | Gambar besar atau banyak halaman | Praproses gambar (pangkas, ubah ukuran) atau gunakan `engine.recognize(image, max_threads=4)` untuk paralelisasi. | + +--- + +## Melangkah Lebih Jauh: Penyesuaian Lanjutan untuk **Meningkatkan Akurasi OCR** + +1. **Pra‑pemrosesan** – Terapkan peningkatan kontras atau binarisasi dengan Pillow sebelum memberi gambar ke Aspose OCR. +2. **Banyak Bahasa** – Atur `engine.language = ocr.Language.English | ocr.Language.French` untuk mengaktifkan pengenalan dwibahasa. +3. **OCR Berbasis Wilayah** – Jika Anda hanya membutuhkan area tertentu (misalnya tabel), pangkas gambar terlebih dahulu untuk mengurangi noise. +4. **Penyaringan Kepercayaan** – `result.confidence` memberikan skor per‑karakter; Anda dapat membuang hasil dengan kepercayaan rendah secara programatik. + +--- + +## Skrip Lengkap yang Siap Pakai + +Berikut adalah skrip lengkap yang dapat Anda salin‑tempel. Simpan sebagai `improve_ocr_accuracy.py` dan jalankan dari command line. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Jalankan: + +```bash +python improve_ocr_accuracy.py +``` + +Anda akan melihat output terformat rapi yang kami tampilkan sebelumnya. + +--- + +## Kesimpulan + +Kami baru saja membahas cara sederhana untuk **meningkatkan akurasi OCR** di Python dengan: + +1. **Mengatur bahasa OCR** agar cocok dengan dokumen Anda. +2. **Memuat gambar dengan benar** sehingga mesin melihat piksel yang tepat. +3. **Melakukan OCR pada gambar** dengan satu pemanggilan metode. +4. **Mengekstrak teks dari gambar** dan memverifikasi hasilnya. +5. **Menambahkan kamus khusus** untuk mengunci istilah domain‑spesifik. + +Itulah seluruh alur kerja—dari foto mentah ke teks bersih yang dapat dicari—dalam skrip yang rapi dan dapat digunakan kembali. + +Jika Anda siap untuk tantangan berikutnya, coba bereksperimen dengan pra‑pemrosesan gambar (kontras, deskew) atau beralih ke pengaturan multibahasa menggunakan `ocr.Language.English | ocr.Language.German`. Prinsip yang sama berlaku, dan Anda akan terus **meningkatkan akurasi OCR** pada kumpulan dokumen yang lebih luas. + +Ada pertanyaan atau kasus tepi yang aneh? Tinggalkan komentar di bawah, dan selamat coding! + +![improve OCR accuracy + + +## 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. + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/indonesian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..ba5a4894e --- /dev/null +++ b/ocr/indonesian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Lakukan OCR pada gambar menggunakan pustaka OCR Python. Pelajari cara + mendeteksi teks dari gambar, mengenali teks dari JPEG, dan mengekstrak teks dari + gambar yang dipindai secara efisien. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: id +og_description: Lakukan OCR pada gambar dengan Python dan ekstrak teks dari file yang + dipindai. Panduan ini memandu Anda melalui proses memuat gambar, memperbaiki kemiringan, + dan mengenali teks langkah demi langkah. +og_title: Lakukan OCR pada Gambar di Python – Panduan Ekstraksi Teks Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Lakukan OCR pada Gambar di Python – Panduan Ekstraksi Teks Lengkap +url: /id/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lakukan OCR pada Gambar di Python – Panduan Ekstraksi Teks Lengkap + +Pernah perlu **melakukan OCR pada file gambar** tetapi terhambat karena kodenya terlihat misterius? Anda tidak sendirian. Baik Anda mengubah tumpukan struk yang dipindai menjadi PDF yang dapat dicari atau mengekstrak keterangan dari JPEG untuk proyek data‑science, kemampuan mengenali teks dari JPEG dan format lainnya adalah keterampilan yang wajib dimiliki oleh setiap pengembang saat ini. + +Dalam tutorial ini kami akan menelusuri contoh lengkap yang dapat dijalankan yang menunjukkan cara **mendeteksi teks dari file gambar**, **mengekstrak teks dari dokumen gambar yang dipindai**, dan bahkan **memuat gambar untuk OCR** hanya dalam beberapa baris kode. Pada akhir tutorial, Anda akan memiliki potongan kode siap produksi yang dapat Anda sisipkan ke dalam proyek Anda—tanpa impor yang hilang, tanpa shortcut “lihat dokumen”. + +## Apa yang Akan Anda Bangun + +- Skrip Python kecil yang membuat mesin OCR, mengaktifkan auto‑deskew, memuat JPEG (atau format lain yang didukung), dan mencetak teks yang dikenali. +- Penjelasan **mengapa** setiap pengaturan penting, bukan hanya **bagaimana** menuliskannya. +- Tips untuk menangani PDF multi‑halaman, bahasa non‑Inggris, dan jebakan umum seperti pemindaian yang buram. + +### Prasyarat + +- Python 3.8+ terpasang (contoh menggunakan paket `ocr` yang tersedia via `pip install ocr-lib` – ganti dengan nama pustaka Anda yang sebenarnya). +- Familiaritas dasar dengan fungsi Python dan lingkungan virtual. +- File gambar (JPEG, PNG, TIFF) yang ingin Anda proses; kami akan menggunakan `skewed_page.jpg` sebagai placeholder. + +> **Pro tip:** Jika Anda menggunakan Windows, jalankan terminal Anda sebagai Administrator saat menginstal pustaka OCR untuk menghindari masalah izin. + +--- + +## Lakukan OCR pada Gambar – Penyiapan dan Konfigurasi + +Hal pertama yang Anda butuhkan adalah instance mesin OCR yang bersih. Anggap saja ini sebagai otak di balik operasi; tanpa konfigurasi yang tepat, bahkan gambar paling tajam pun akan menghasilkan teks yang tidak dapat dibaca. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Mengapa ini penting:** +Menetapkan `engine.language` mempersempit set karakter yang diharapkan mesin OCR, secara dramatis meningkatkan akurasi. Jika Anda melewatkannya, mesin akan menebak, sering kali salah membaca kata sederhana. + +--- + +## Aktifkan Deskew Otomatis – Memperbaiki Pemindaian yang Miring + +Halaman yang dipindai jarang sekali benar‑benar datar. Kemiringan sedikit dapat mengacaukan segmentasi karakter, mengubah “Hello” menjadi “H3llo”. Flag `auto_deskew` melakukan pekerjaan berat untuk Anda. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Kasus khusus:** Jika Anda tahu gambar Anda sudah lurus, menonaktifkan deskew dapat menghemat beberapa milidetik waktu pemrosesan—berguna saat menangani ribuan halaman dalam pekerjaan batch. + +--- + +## Muat Gambar untuk OCR – Mendukung JPEG, PNG, TIFF + +Sekarang kita benar‑benar **memuat gambar untuk OCR**. Metode `ocr.Image.load` fleksibel; ia menerima path ke format raster apa pun yang didukung. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Mengapa langkah ini krusial:** Pustaka membaca file ke dalam bitmap internal, menerapkan konversi ruang warna bila diperlukan. Melewatkan langkah ini dan mengirim aliran byte mentah akan memunculkan `FileNotFoundError` atau, lebih buruk, menghasilkan hasil kosong secara diam‑diam. + +Jika Anda perlu **mengenali teks dari file JPEG** secara khusus, pastikan ekstensi file adalah `.jpeg` atau `.jpg`. Pemanggilan yang sama juga bekerja untuk PNG (`.png`) atau TIFF (`.tif`) tanpa modifikasi. + +--- + +## Lakukan OCR pada Gambar – Menjalankan Mesin + +Dengan mesin yang sudah dipersiapkan dan gambar berada di memori, saatnya **melakukan OCR pada data gambar**. Satu baris ini melakukan semua pekerjaan berat: pra‑pemrosesan, segmentasi, klasifikasi, dan penyusunan teks. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Apa yang terjadi di balik layar?** +- Mesin menerapkan transformasi deskew (jika diaktifkan). +- Ia menjalankan jaringan saraf atau backend Tesseract untuk mengidentifikasi karakter. +- Akhirnya, ia menyatukan karakter menjadi kata dan baris, mengembalikan objek `result` yang kaya. + +--- + +## Ekstrak Teks dari Gambar yang Dipindai – Tampilkan Hasilnya + +Langkah terakhir adalah **mengekstrak teks dari gambar yang dipindai** dan menampilkannya. Atribut `result.text` berisi representasi teks polos. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Contoh output biasanya seperti ini: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Jika mesin OCR gagal menemukan karakter apa pun, `result.text` akan menjadi string kosong. Dalam kasus tersebut, periksa kembali kualitas gambar atau pertimbangkan menyesuaikan properti `engine.confidence_threshold` (jika pustaka Anda mendukungnya). + +--- + +## Menangani Variasi Umum + +### Mengenali Teks dari JPEG vs PNG + +Kedua format didukung, tetapi kompresi JPEG dapat menimbulkan artefak yang membingungkan mesin. Jika Anda sering melihat kesalahan pengenalan, coba konversi JPEG ke PNG terlebih dahulu: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Mendeteksi Teks dari Gambar dengan Banyak Bahasa + +Jika dokumen Anda mencampur Bahasa Inggris dan Spanyol, atur mode multibahasa: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Mesin kemudian akan mempertimbangkan kedua alfabet selama proses pengenalan. + +### Ekstrak Teks dari PDF yang Dipindai + +Untuk PDF, Anda harus meraster setiap halaman menjadi gambar terlebih dahulu. Pustaka seperti `pdf2image` mempermudah proses ini: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Contoh Lengkap yang Berfungsi + +Berikut adalah skrip lengkap yang dapat Anda salin‑tempel ke dalam file `ocr_demo.py`. Skrip ini mencakup penanganan error dan helper kecil untuk mengukur waktu eksekusi. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Output yang diharapkan** (asumsi pemindaian jelas): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Pertanyaan yang Sering Diajukan + +**T: Bisakah saya menjalankannya di server tanpa tampilan (headless)?** +J: Tentu saja. Pustaka berfungsi tanpa GUI; pastikan binari native yang diperlukan (misalnya Tesseract) terinstal di server. + +**T: Bagaimana jika gambar blur?** +J: Pertimbangkan menambahkan filter penajaman sebelum `engine.recognize`. Banyak pustaka OCR menyediakan `image_preprocessing.sharpen = True` atau Anda dapat menggunakan `cv2.GaussianBlur` dari OpenCV secara terbalik. + +**T: Apakah skrip ini mendukung pemrosesan batch?** +J: Ya. Bungkus `perform_ocr` dalam loop yang iterasi daftar path file, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/indonesian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..3ab9872cd --- /dev/null +++ b/ocr/indonesian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-19 +description: Lakukan OCR pada gambar menggunakan Aspose OCR Java. Pelajari cara memuat + gambar untuk OCR, menggunakan lisensi Aspose, dan mengekstrak teks dari gambar dalam + hitungan menit. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: id +og_description: Lakukan OCR pada gambar dengan Aspose OCR Java. Panduan ini menunjukkan + cara menggunakan lisensi Aspose, memuat gambar untuk OCR, dan mengekstrak teks dari + gambar secara efisien. +og_title: Lakukan OCR pada Gambar dengan Aspose OCR Java – Tutorial Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Lakukan OCR pada Gambar dengan Aspose OCR Java – Panduan Lengkap Langkah demi + Langkah +url: /id/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lakukan OCR pada Gambar dengan Aspose OCR Java – Panduan Lengkap Langkah‑per‑Langkah + +Pernah membutuhkan **melakukan OCR pada gambar** tetapi tidak yakin pustaka mana yang memberikan hasil dapat diandalkan tanpa banyak konfigurasi? Anda tidak sendirian. Dalam banyak proyek dunia nyata—misalnya memindai paspor, mendigitalkan faktur, atau mengambil teks dari screenshot—kemampuan mengenali data teks gambar dengan cepat adalah pengubah permainan. + +Dalam tutorial ini kami akan menunjukkan contoh langsung yang memperlihatkan cara **melakukan OCR pada gambar** menggunakan Aspose OCR untuk Java. Kami akan membahas semuanya mulai dari menerapkan lisensi Aspose Anda hingga memuat gambar, menjalankan mesin, dan akhirnya **mengekstrak teks dari gambar** sehingga Anda dapat menggunakannya lebih lanjut. Tanpa basa‑basi, hanya solusi kerja yang dapat Anda salin‑tempel. + +## Apa yang Akan Anda Dapatkan + +- Gambaran jelas tentang cara **menggunakan lisensi Aspose** dalam proyek Java. +- Kode tepat yang diperlukan untuk **memuat gambar untuk OCR** dan membiarkan mesin mendeteksi bahasa secara otomatis. +- Instruksi langkah‑per‑langkah untuk **mengenali teks gambar** dan **mengekstrak teks dari gambar** dengan aman. +- Tips menangani jebakan umum (hasil kosong, format tidak didukung, dan masalah memori). + +> **Prasyarat** – Java 8 atau lebih baru, Maven atau Gradle untuk manajemen dependensi, dan file lisensi Aspose OCR untuk Java (atau Anda dapat menjalankan dalam mode evaluasi). + +--- + +## Cara Melakukan OCR pada Gambar dengan Aspose OCR Java + +Berikut adalah program Java lengkap yang siap dijalankan yang mendemonstrasikan seluruh alur. Simpan sebagai `AsposeOcrDemo.java` dan jalankan dari IDE atau baris perintah Anda. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Output Konsol yang Diharapkan + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Jika Anda menjalankan program tanpa file lisensi, baris pertama hanya akan menyatakan bahwa Anda berada dalam mode evaluasi, tetapi OCR tetap berfungsi. + +--- + +## Menyiapkan dan Menggunakan Lisensi Aspose + +### Mengapa Lisensi Penting + +Menjalankan pustaka dalam mode evaluasi memang cukup untuk pengujian cepat, tetapi akan menambahkan watermark pada output dan membatasi jumlah halaman yang dapat diproses per run. Langkah **menggunakan lisensi Aspose** menghilangkan batasan ini dan memberi sinyal kepada Aspose bahwa Anda adalah pelanggan berbayar. + +### Cara Mendapatkan dan Menerapkannya + +1. Beli lisensi dari toko Aspose. +2. Unduh file `Aspose.OCR.Java.lic`. +3. Letakkan di lokasi yang dapat dibaca aplikasi Anda—biasanya folder `src/main/resources`. +4. Panggil `new License().setLicense("Aspose.OCR.Java.lic");` sebelum melakukan pekerjaan OCR apa pun, seperti yang ditunjukkan pada kode di atas. + +> **Tips pro:** Jika Anda menyebarkan ke server, gunakan path absolut atau pemuat sumber daya class‑path untuk menghindari `FileNotFoundException`. + +--- + +## Memuat Gambar untuk Proses OCR + +Baris `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` adalah inti dari langkah **memuat gambar untuk OCR**. Aspose OCR mendukung berbagai format: PNG, JPEG, BMP, TIFF, dan bahkan PDF multi‑halaman (ketika digabungkan dengan Aspose.Pdf). + +### Jebakan Umum + +| Masalah | Gejala | Solusi | +|---------|--------|--------| +| Path file salah | `FileNotFoundException` | Periksa kembali path; gunakan `Paths.get(...)` untuk pemisah yang independen OS. | +| Format tidak didukung | `UnsupportedOperationException` | Konversi gambar ke PNG atau JPEG sebelum memuatnya. | +| Gambar sangat besar ( > 10 MP) | Kesalahan out‑of‑memory | Turunkan skala gambar menggunakan `java.awt.Image` sebelum diberikan ke Aspose. | + +--- + +## Mengekstrak Teks dari Gambar dan Menangani Hasil + +Setelah mesin OCR selesai, objek `OcrResult` berisi string yang dikenali. Di sinilah kami **mengekstrak teks dari gambar** untuk pemrosesan lebih lanjut—menyimpan ke basis data, mengisi indeks pencarian, atau memasukkannya ke pipeline NLP downstream. + +### Menangani Banyak Bahasa + +Karena kami mengatur `engine.setLanguage(Language.Auto)`, Aspose akan mencoba mendeteksi bahasa secara otomatis. Jika Anda sudah mengetahui bahasa sebelumnya (misalnya semua dokumen berbahasa Rusia), Anda dapat mengganti `Language.Auto` dengan `Language.Russian` untuk meningkatkan performa. + +### Tips Pasca‑Pemrosesan + +- **Trim spasi putih**: `result.getText().trim()`. +- **Normalisasi akhir baris**: `result.getText().replace("\r\n", "\n")`. +- **Hapus karakter non‑printable**: gunakan regex seperti `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Mengenali Teks Gambar dengan Opsi Lanjutan (Opsional) + +Jika Anda memerlukan kontrol yang lebih halus, Aspose OCR menawarkan properti tambahan: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Penyesuaian ini berguna ketika Anda berurusan dengan dokumen yang dipindai yang memiliki kemiringan atau kontras rendah. + +--- + +## Ringkasan Contoh Kerja Lengkap + +Menggabungkan semuanya, program akhir melakukan hal‑hal berikut secara berurutan: + +1. **Melakukan OCR pada gambar** – dengan membuat `OcrEngine`. +2. **Menggunakan lisensi Aspose** – opsional namun disarankan. +3. **Memuat gambar untuk OCR** – melalui `Image.load`. +4. **Mengatur deteksi bahasa** – `Language.Auto` untuk **mengenali teks gambar** secara otomatis. +5. **Mengekstrak teks dari gambar** – mencetak hasil, menangani respons kosong dengan elegan. + +Anda dapat menyalin blok kode di atas langsung ke proyek Maven dengan dependensi berikut: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Jalankan `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` dan saksikan konsol menampilkan teks yang dikenali. + +--- + +## Kesimpulan + +Kami baru saja menunjukkan cara **melakukan OCR pada gambar** menggunakan Aspose OCR untuk Java, mulai dari menerapkan lisensi hingga **memuat gambar untuk OCR**, **mengenali teks gambar**, dan akhirnya **mengekstrak teks dari gambar** untuk penggunaan downstream. Pendekatannya sederhana, bekerja dengan banyak bahasa secara bawaan, dan dapat diperluas dengan opsi pra‑pemrosesan lanjutan bila diperlukan. + +Apa selanjutnya? Cobalah mengirim output OCR ke indeks pencarian, menghasilkan PDF dengan teks yang diekstrak, atau bereksperimen dengan format gambar yang berbeda. Kemungkinannya tak terbatas, dan dengan API Aspose yang kuat Anda akan menghabiskan lebih banyak waktu membangun fitur daripada bergulat dengan keanehan OCR. + +Punya pertanyaan atau menemukan kasus tepi? Tinggalkan komentar di bawah—selamat coding! + +## 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 sendiri. + +- [Cara mengekstrak teks dari gambar dari URL menggunakan Aspose.OCR untuk Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Mengonversi Gambar ke Teks di Java menggunakan Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Mengekstrak Teks dari Gambar Java dengan Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/italian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ecf25cac2 --- /dev/null +++ b/ocr/italian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-19 +description: Crea PDF ricercabile da un'immagine usando OCR con Python. Impara a convertire + l'OCR in PDF, estrarre il testo dall'immagine ed eseguire rapidamente l'OCR sull'immagine. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: it +og_description: Crea PDF ricercabile da un'immagine con Python OCR. Questa guida mostra + come convertire l'OCR in PDF, estrarre il testo dall'immagine ed eseguire l'OCR + sull'immagine. +og_title: Crea PDF ricercabile in Python – Guida completa alla programmazione +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Crea PDF Ricercabile in Python – Guida Completa Passo‑Passo +url: /it/python-java/general/create-searchable-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 >}} + +# Crea PDF Ricercabile in Python – Guida Completa Passo‑Passo + +Hai mai avuto bisogno di **creare PDF ricercabile** da una ricevuta scansionata ma non sapevi da dove cominciare? Non sei solo—molti sviluppatori incontrano lo stesso ostacolo quando provano per la prima volta a trasformare un'immagine di testo in un PDF effettivamente ricercabile. + +In questo tutorial ti guideremo attraverso una soluzione pratica che ti permette di **eseguire OCR su immagine**, trasformare quel risultato OCR in un **PDF ricercabile**, e persino estrarre il testo grezzo se ti serve per ulteriori elaborazioni. Nessun superfluo, solo un esempio funzionante che puoi copiare‑incollare nel tuo progetto oggi. + +## Cosa Imparerai + +- Come configurare un motore OCR leggero in Python +- I passaggi esatti per **convertire OCR in PDF** e salvarlo come documento ricercabile +- Modi per **estrarre testo da immagine** per analisi successive +- Consigli per gestire problemi comuni come l'orientamento dell'immagine e file di grandi dimensioni +- Uno script completo e eseguibile che puoi adattare al tuo caso d'uso + +### Prerequisiti + +- Python 3.8+ installato sulla tua macchina +- Familiarità di base con pip e ambienti virtuali (opzionale ma consigliato) +- Un file immagine (PNG, JPEG, ecc.) che contiene testo chiaro e leggibile da macchina + +Se li hai, tuffiamoci. + +## Passo 1: Installa la Libreria Necessaria + +Il frammento di codice che hai visto in precedenza utilizza un pacchetto fittizio `ocr`, ma le stesse idee si applicano a librerie reali come **EasyOCR**, **pytesseract** o **pdfminer.six**. Per questa guida useremo **EasyOCR** perché è puro Python, supporta molte lingue e restituisce un comodo metodo di conversione PDF tramite un helper ausiliario. + +```bash +pip install easyocr pillow +``` + +> **Consiglio:** Installa all'interno di un ambiente virtuale (`python -m venv venv && source venv/bin/activate`) per mantenere ordinate le dipendenze. + +## Passo 2: Inizializza il Motore OCR – Esegui OCR su Immagine + +Ora che la libreria è pronta, creiamo un motore OCR e gli diciamo di lavorare con testo inglese. Questo è il primo punto in cui **eseguiamo OCR su immagine**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Perché abbiamo bisogno di un oggetto reader dedicato? EasyOCR pre‑carica i modelli linguistici, quindi riutilizzare lo stesso `reader` per più immagini è molto più efficiente rispetto a reinizializzarlo ogni volta. + +## Passo 3: Carica l'Immagine – Estrai Testo da Immagine + +Portiamo l'immagine in memoria. Questo passaggio è dove **estrarremo testo da immagine** più tardi, ma per ora la carichiamo semplicemente. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Se la tua immagine è capovolta o inclinata, considera di usare i metodi `rotate` o `transpose` di Pillow prima di passarla al motore OCR. Un rapido controllo visivo può salvarti ore di debug in seguito. + +## Passo 4: Esegui il Motore OCR e Cattura i Risultati + +Ecco il cuore del processo—inviare l'immagine al motore OCR e ottenere dati strutturati. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Il flag `detail=1` ci fornisce le bounding box, che ci serviranno quando più tardi **convertiremo OCR in PDF**. Se ti interessano solo le stringhe grezze, imposta `detail=0`. + +## Passo 5: Converti il Risultato OCR in un PDF Ricercabile – Converti OCR in PDF + +EasyOCR non fornisce un writer PDF diretto, ma possiamo assemblare il PDF noi stessi usando Pillow e la libreria `reportlab`. Per mantenere il tutorial leggero, useremo `fpdf2`, che ci permette di incorporare l'immagine originale e sovrapporre testo invisibile. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Cosa è successo? Abbiamo posizionato l'immagine scansionata come livello visibile, poi scritto le parole riconosciute sopra usando testo bianco che si fonde con lo sfondo bianco. Gli strumenti di ricerca leggono comunque il livello nascosto, così il PDF diventa **ricercabile** senza alterare l'aspetto visivo. + +## Passo 6: Salva i Byte del PDF – Converti Immagine in PDF + +Se preferisci gestire il PDF in memoria (ad esempio, inviandolo tramite un'API), puoi catturare i byte invece di scrivere direttamente su disco. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Quella riga dimostra il classico workflow **convertire immagine in PDF**: parti da un'immagine, esegui OCR, sovrapponi testo e infine emetti uno stream PDF. + +## Passo 7: Verifica il Risultato – Controlli Rapidi + +Dopo aver eseguito lo script, apri `receipt_searchable.pdf` in qualsiasi visualizzatore PDF e prova la casella di ricerca (Ctrl + F). Digita una parola che sai comparire nella ricevuta—se il visualizzatore salta al punto giusto, hai **creato con successo un PDF ricercabile**! + +Se la ricerca fallisce, ricontrolla: + +1. I punteggi di confidenza OCR (`conf`). Una bassa confidenza può indicare che l'immagine è sfocata. +2. Le coordinate delle bounding box—a volte EasyOCR le riporta in un'orientazione diversa. +3. Che il visualizzatore PDF non sia impostato in modalità “solo immagine” (raro, ma alcuni visualizzatori hanno questa opzione). + +## Script Completo Funzionante + +Unendo tutto, ecco il file Python completo e pronto all'uso: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Salva questo file come `searchable_pdf.py`, sostituisci i placeholder `YOUR_DIRECTORY` con percorsi reali, e avvia: + +```bash +python searchable_pdf.py +``` + +Dovresti vedere un messaggio di conferma e un nuovo PDF ricercabile nella tua cartella. + +## Domande Frequenti & Casi Limite + +**Cosa succede se l'immagine è a colori?** +EasyOCR funziona sia con immagini in scala di grigi che a colori, ma convertire in scala di grigi (`pil_image.convert("L")`) a volte migliora la precisione su scansioni rumorose. + +**Posso gestire PDF multi‑pagina?** +Sì—itera su ogni immagine di pagina, esegui i passaggi OCR e aggiungi ogni pagina allo stesso oggetto `FPDF`. Ricorda di resettare il cursore (`self.add_page()`) per ogni nuova immagine. + +**C'è un modo per mantenere il livello di testo originale invece del testo bianco invisibile?** +Se ti serve un vero PDF “testo‑sotto‑immagine” (ad esempio per l'accessibilità), considera l'uso di `pdfminer` o `pikepdf` per incorporare un livello di testo nascosto con i tag PDF appropriati. È più avanzato, ma il principio resta lo stesso: immagine di sfondo + testo sovrapposto. + +**Cosa fare se la confidenza OCR è bassa?** +Puoi filtrare le parole a bassa confidenza: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Conclusione – Cosa Abbiamo Raggiunto + +Abbiamo iniziato con una semplice immagine di una ricevuta, **eseguito OCR su immagine**, estratto le stringhe riconosciute e infine **creato un PDF ricercabile** che si comporta come qualsiasi documento scansionato professionalmente. Il processo ha coperto tutte le parole chiave secondarie—**convertire OCR in PDF**, **estrarre testo da immagine**, **convertire immagine in PDF**, e **eseguire OCR su immagine**—così ora disponi di una cassetta degli attrezzi riutilizzabile per qualsiasi progetto simile. + +### Prossimi Passi + +- Sperimenta con altre lingue passando i loro codici ISO a `easyocr.Reader(['en', 'es'])`. +- Sostituisci EasyOCR con Tesseract se ti serve una soluzione completamente offline; il resto della pipeline rimane invariato. +- Aggiungi la visualizzazione della confidenza OCR (disegna le bounding box sull'immagine) per debug di scansioni problematiche. + +Hai un'idea da condividere? Lascia un commento, fai fork + +## 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/) +- [Converti Immagini in PDF C# – Salva Risultato OCR Multipagina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Come OCR Immagine – Esegui OCR su Immagine nel Riconoscimento Immagini 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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/italian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..b0f14bfa9 --- /dev/null +++ b/ocr/italian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: Estrai il testo dalle immagini in Python con un semplice motore OCR. + Scopri come convertire le immagini scannerizzate in testo, riconoscere il testo + dalle foto e elencare i file immagine in Python in modo efficiente. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: it +og_description: Estrai testo dalle immagini in Python usando un motore OCR leggero. + Questa guida ti mostra come convertire immagini scannerizzate in testo, riconoscere + il testo dalle foto e elencare i file immagine in Python in pochi passaggi. +og_title: Estrai testo dalle immagini in Python – Guida completa all'OCR batch +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Estrai testo dalle immagini in Python – Guida completa all'OCR batch +url: /it/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Estrarre Testo da Immagini in Python – Guida Completa all'OCR di Massa + +Hai mai dovuto **estrarre testo da immagini** ma non sapevi da dove cominciare? Non sei solo: gli sviluppatori affrontano costantemente la sfida di trasformare PDF scansionati, ricevute fotografate o screenshot in testo ricercabile. In questo tutorial percorreremo un esempio completo, pronto‑all'uso, che mostra come **convertire immagini scansionate in testo**, riconoscere il testo dalle foto e persino **list image files python**. Alla fine avrai uno script riutilizzabile che elabora un’intera cartella in un solo passaggio. + +Copriamo tutto ciò di cui hai bisogno: librerie richieste, perché ogni passaggio è importante, gestione dei casi limite e un po' di troubleshooting. Non è necessario consultare documentazione esterna; il codice qui sotto è autonomo e le spiegazioni rispondono al “come” *e* al “perché”. Apri il tuo IDE preferito e cominciamo. + +--- + +## Cosa Costruirai + +- Inizializzare un motore OCR (useremo il pacchetto `ocr` a scopo illustrativo). +- Scansionare una directory e **list image files python**, filtrando PNG, JPG e TIFF. +- Eseguire un’operazione **batch OCR** su tutte le immagini trovate. +- Stampare il testo estratto per ogni file, con etichetta chiara. + +> **Consiglio professionale:** Se non hai la libreria `ocr` installata, puoi sostituirla con `pytesseract` con poche modifiche minori – la logica di base rimane invariata. + +--- + +## Prerequisiti + +- Python 3.8+ (lo script usa f‑strings e type hints). +- Una libreria OCR che esponga un `OcrEngine` con `recognize_batch`. Per questa guida assumiamo un pacchetto fittizio `ocr`, ma il modello funziona anche con librerie reali. +- Una cartella contenente i file immagine da elaborare (`.png`, `.jpg`, `.tif`). + +--- + +## Passo 1 – Installa & Importa i Moduli Necessari + +Per prima cosa, assicurati che il pacchetto OCR sia disponibile. Se usi una libreria reale come `pytesseract`, sostituisci l’importazione di conseguenza. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Perché è importante:** L’importazione di `os` fornisce una gestione dei percorsi cross‑platform, mentre `typing.List` aiuta l’autocompletamento nell’IDE e rende il codice più robusto per il futuro. + +--- + +## Passo 2 – **Extract Text from Images**: Inizializza il Motore OCR + +Creare il motore è il primo passo per qualsiasi lavoro di OCR. Impostiamo anche la lingua su auto‑rilevamento così il motore può gestire documenti multilingua. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Spiegazione:** Incapsulando la creazione del motore in una funzione manteniamo il codice modulare. Se in seguito dovrai modificare DPI o modalità OCR, dovrai intervenire solo in questo punto. + +--- + +## Passo 3 – **List Image Files Python**: Raccogli i File da una Directory + +Ora dobbiamo individuare ogni immagine da elaborare. La list comprehension qui sotto rispecchia il tipico pattern “list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Gestione dei casi limite:** La funzione ignora le sotto‑cartelle (puoi aggiungere ricorsione in seguito) e filtra automaticamente i file nascosti perché tipicamente non terminano con le estensioni supportate. + +--- + +## Passo 4 – **Convert Scanned Images to Text**: Esegui il Batch OCR + +La maggior parte delle librerie OCR fornisce un metodo batch molto più veloce rispetto all’elaborazione immagine per immagine. Ecco come lo invochiamo. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Perché batch?** Inviare tutte le immagini in una volta riduce l’overhead (ad es., il caricamento ripetuto del modello OCR) e spesso migliora l’utilizzo di CPU/GPU. + +--- + +## Passo 5 – **Recognize Text from Pictures**: Visualizza i Risultati + +Infine, iteriamo sui nomi dei file associati ai risultati OCR, stampando un’intestazione pulita per ogni immagine. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Suggerimento:** `strip()` rimuove gli spazi bianchi iniziali/finali che l’OCR aggiunge spesso. + +--- + +## Script Completo – Metti Tutto Insieme + +Di seguito trovi il programma completo, eseguibile. Salvalo come `batch_ocr.py` ed esegui `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Output Atteso + +Supponendo che la cartella contenga `invoice1.png` e `receipt.jpg`, potresti vedere: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Ogni blocco è chiaramente etichettato, rendendo semplice l’elaborazione successiva (ad es., salvataggio in un database). + +--- + +## Gestione dei Problemi Comuni + +| Problema | Perché Accade | Soluzione Rapida | +|----------|----------------|------------------| +| **Nessun testo appare** | Lingua OCR non rilevata o immagine a basso contrasto. | Forza una lingua (`engine.language = ocr.Language.English`) o pre‑elabora le immagini (aumenta il contrasto). | +| **Errore di memoria su batch grandi** | Il motore tenta di caricare tutte le immagini contemporaneamente. | Dividi `image_files` in blocchi (`batch_size = 20`) e chiama `recognize_batch` più volte. | +| **Formato file non supportato** | Hai aggiunto un `.gif` o `.bmp`. | Estendi la tupla `supported_exts` o converti le immagini in PNG/JPG prima. | +| **Caratteri Unicode corrotti** | L’OCR restituisce byte anziché stringhe. | Assicurati che la libreria OCR restituisca Unicode (`result.text.decode('utf‑8')` se necessario). | + +--- + +## Estendere il Flusso di Lavoro + +Ora che sai **extract text from images**, considera i prossimi passi: + +- **Esporta in CSV** – Scrivi ogni nome file e il relativo testo estratto in un foglio di calcolo per analisi. +- **Elaborazione parallela** – Usa `concurrent.futures.ThreadPoolExecutor` per gestire più batch contemporaneamente. +- **Integra con OCR cloud** – Sostituisci il motore locale con Google Vision o Azure OCR per maggiore precisione su layout complessi. +- **Aggiungi pre‑elaborazione immagini** – Librerie come Pillow o OpenCV possono deskew, denoise o threshold le immagini prima dell’OCR, migliorando i risultati. + +Tutte queste idee utilizzano le stesse funzioni di base che abbiamo costruito, quindi non dovrai ricominciare da zero. + +--- + +## Conclusione + +Abbiamo appena percorso una soluzione completa per **extract text from images** in Python, coprendo tutto, da **list image files python** a **recognize text from pictures** fino a **convert scanned images to text** in un batch ordinato. Lo script è deliberatamente semplice ma sufficientemente flessibile da fungere da base per progetti più grandi—che tu stia digitalizzando ricevute, creando un archivio ricercabile o alimentando una pipeline di estrazione dati. + +Provalo, modifica i passaggi di pre‑elaborazione e osserva come la precisione dell’OCR migliora. Se incontri intoppi, ricontrolla la tabella “Gestione dei Problemi Comuni”; la maggior parte dei problemi si risolve con una piccola modifica di configurazione. + +Pronto per la prossima sfida? Prova ad aggiungere una fase di conversione PDF‑to‑image usando `pdf2image`, poi alimenta quelle immagini direttamente nello stesso flusso. Il cielo è il limite quando combini OCR e l’ecosistema ricco di Python. + +Buon coding, e che il tuo testo sia sempre leggibile! + +## 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 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/) +- [Extract Text Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/italian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..ccd8ca233 --- /dev/null +++ b/ocr/italian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-06-19 +description: estrai testo dalle immagini usando Python OCR. impara il rilevamento + automatico della lingua, l'elaborazione parallela e il riconoscimento batch in un + tutorial conciso. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: it +og_description: estrarre testo dalle immagini con Python OCR. Questa guida mostra + il rilevamento automatico della lingua, l'elaborazione parallela e il riconoscimento + batch in un unico tutorial. +og_title: estrarre testo dalle immagini in Python – Guida completa OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Estrarre testo dalle immagini in Python – Guida completa all'OCR +url: /it/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# estrarre testo dalle immagini in Python – Guida completa OCR + +Ti sei mai chiesto come **estrarre testo dalle immagini** senza dover digitare manualmente ogni parola? Non sei il solo. Che tu stia digitalizzando vecchie ricevute, creando un archivio di documenti ricercabili, o semplicemente sperimentando con trucchi AI, la capacità di estrarre testo dalle foto è una competenza indispensabile per qualsiasi sviluppatore Python oggi. + +In questo tutorial percorreremo un esempio completo, pronto‑da‑eseguire, che **estrae testo dalle immagini** usando un motore OCR popolare. Copriremo il rilevamento automatico della lingua, l’elaborazione parallela per la velocità e il riconoscimento batch di immagini così potrai gestire decine di file in pochi secondi. Ti sembra quello che ti serve? Immergiamoci. + +## Cosa imparerai + +- Come istanziare il motore OCR con `ocr.OcrEngine`. +- Abilitare **il rilevamento automatico della lingua** così il motore sceglie da solo la lingua corretta. +- Configurare **OCR con elaborazione parallela** tramite un pool di thread personalizzato. +- Eseguire **riconoscimento batch di immagini** su un elenco di file. +- Stampare il testo riconosciuto per ogni immagine, pronto per essere salvato o indicizzato. + +Nessuna documentazione esterna necessaria—tutto ciò che ti serve è qui, e il codice funziona subito con il pacchetto `ocr` (installalo con `pip install ocr`). + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +1. Python 3.8 o versioni successive installate. +2. Il pacchetto `ocr` (`pip install ocr`). +3. Una cartella di immagini PNG (o JPG) che desideri elaborare. +4. Familiarità di base con funzioni e cicli Python. + +È tutto—nessuna dipendenza pesante, nessuna magia GPU, solo puro Python. + +![estrarre testo dalle immagini esempio](https://example.com/ocr-demo.png "Screenshot che mostra l'output dell'estrazione di testo dalle immagini") + +*Testo alternativo: screenshot della demo di estrazione testo dalle immagini* + +## Passo 1 – Configura il motore OCR (Parola chiave principale in azione) + +Prima di tutto: crea un'istanza del motore OCR. Pensa a `ocr.OcrEngine()` come al cervello dell'operazione; sa come leggere caratteri, righe e paragrafi. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Perché serve un motore esplicito? Perché l'**uso di ocr.OcrEngine** ti dà un controllo fine su impostazioni linguistiche, threading e altro. È il modo più flessibile per **estrarre testo dalle immagini** rispetto ai helper monolitici. + +## Passo 2 – Lascia che il motore rilevi automaticamente le lingue + +La maggior parte delle librerie OCR richiede di indicare la lingua da cercare. Va bene per un progetto monolingua, ma è ingombrante per un batch multilingua. Fortunatamente, il pacchetto `ocr` supporta **il rilevamento automatico della lingua**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Impostare `engine.language` su `ocr.Language.Auto` dice al motore di analizzare ogni immagine e scegliere il modello linguistico appropriato. Questa piccola riga ti fa risparmiare ore di configurazione manuale quando lavori con documenti internazionali. + +## Passo 3 – Accelerare con OCR a elaborazione parallela + +Se hai quattro o più core CPU, perché non usarli? Il motore può avviare un pool di thread, consentendo l'elaborazione simultanea di più immagini. Qui è dove **OCR a elaborazione parallela** brilla. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Sentiti libero di regolare il numero `4` in base alla tua macchina. Più thread → esecuzioni batch più rapide, ma ricorda che ogni thread consuma memoria, quindi trova il punto ottimale per il tuo ambiente. + +## Passo 4 – Raccogli le immagini da elaborare + +Ora ci serve un elenco di percorsi file. Puoi costruirlo manualmente, leggerlo da un CSV, o usare `glob`. Per chiarezza, inseriremo una lista breve hard‑coded: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Sostituisci `YOUR_DIRECTORY` con il percorso reale sul tuo sistema. Se hai decine di file, un rapido `glob.glob("*.png")` farà il lavoro pesante. + +## Passo 5 – Esegui il riconoscimento batch di immagini + +Ecco il cuore del tutorial: una singola chiamata che elabora ogni immagine in `files` e restituisce un elenco di oggetti risultato. Questa è la funzionalità di **riconoscimento batch di immagini** che rende pratico l'OCR su larga scala. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Dietro le quinte, il motore distribuisce ogni file tra i quattro thread di lavoro configurati prima, rilevando automaticamente la lingua per ogni immagine. Il metodo restituisce una lista in cui ogni elemento contiene il testo riconosciuto e i metadati. + +## Passo 6 – Stampa (o salva) il testo estratto + +Infine, cicliamo sui risultati e stampiamo il testo. In un progetto reale probabilmente lo scriveresti in un database o in un file CSV, ma la stampa mantiene l'esempio semplice. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Output previsto** (troncato per brevità): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Ogni blocco mostra il nome file seguito dalla stringa derivata dall'OCR. Se un'immagine contiene più lingue, vedrai i caratteri appropriati grazie al passo precedente di **rilevamento automatico della lingua**. + +## Consigli professionali & insidie comuni + +- **La qualità dell'immagine conta** – foto sfocate o a basso contrasto produrranno spazzatura. Pre‑processa con OpenCV (`cv2.threshold`, `cv2.resize`) se necessario. +- **Numero di thread vs I/O** – Se le tue immagini sono su un disco di rete lento, più thread potrebbero non aiutare. Monitora l'uso CPU con `top` o il **Task Manager**. +- **Gestione Unicode** – `result.text` è una stringa Unicode. Quando scrivi su file, aprili con `encoding="utf‑8"` per evitare `UnicodeEncodeError`. +- **Uso della memoria** – PDF grandi possono consumare molta RAM. Se incontri `MemoryError`, riduci la dimensione del pool di thread o elabora le immagini in blocchi più piccoli. + +## Script completo funzionante + +Di seguito trovi lo script completo, pronto per il copia‑incolla, che incorpora tutti i passaggi discussi. Salvalo come `batch_ocr.py` ed esegui `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Eseguilo così: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Vedrai un blocco di testo ben formattato per ogni immagine, dimostrando che puoi **estrarre testo dalle immagini** su larga scala. + +## Qual è il prossimo passo? + +Ora che hai padroneggiato le basi di **estrarre testo dalle immagini** con Python, considera di approfondire: + +- **Post‑processing**: pulire l'output OCR con regex o librerie di linguaggio naturale. +- **Conversione PDF**: alimentare le stringhe estratte in un generatore PDF per PDF ricercabili. +- **Servizi OCR cloud**: confrontare i risultati on‑prem `ocr` con Google Vision o Azure OCR per casi limite di accuratezza. +- **Front‑end GUI**: costruire una piccola app Flask o FastAPI che permetta agli utenti di caricare immagini e vedere immediatamente il testo estratto. + +Ognuno di questi argomenti si basa sul **Python OCR library** che hai appena configurato, e tutti beneficiano degli stessi trucchi di **OCR a elaborazione parallela** usati qui. + +--- + +*Buona programmazione! Se incontri difficoltà, lascia un commento qui sotto—sono sempre pronto a risolvere i problemi legati all'OCR.* + +## 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 ulteriori funzionalità API 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/) +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/italian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/italian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..8f8e0a01e --- /dev/null +++ b/ocr/italian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-06-19 +description: Come estrarre PDF usando OCR in Python – tutorial passo‑passo che copre + l'estrazione del testo da PDF, il riconoscimento del testo da immagine e un esempio + di OCR in Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: it +og_description: Come estrarre PDF usando OCR in Python. Impara a estrarre testo da + PDF, riconoscere il testo da un'immagine e vedere un esempio completo di OCR in + Python. +og_title: Come estrarre il testo PDF con OCR in Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Come estrarre il testo PDF con OCR in Python – Guida completa +url: /it/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come estrarre testo PDF con OCR in Python – Guida completa + +Ti sei mai chiesto **come estrarre PDF** quando il file è solo un'immagine scansionata? Non sei l'unico. In molti progetti reali—pensate a contratti, fatture o archivi storici—il PDF che ricevi non contiene testo selezionabile. La buona notizia? Poche righe di Python possono trasformare quelle pagine solo immagine in testo ricercabile e modificabile. + +In questo tutorial percorreremo un **esempio OCR Python** pratico che legge un PDF, rende la sua prima pagina come immagine e poi **estrae testo dal PDF** usando un motore OCR. Alla fine saprai esattamente **come leggere PDF con OCR**, perché ogni passaggio è importante e come adattare il codice per documenti multi‑pagina o lingue diverse. + +## Cosa imparerai + +- Installa e configura una libreria OCR affidabile per Python. +- Converti le pagine PDF in immagini adatte all'OCR. +- **Riconosci il testo da un'immagine** e recupera stringhe Unicode pulite. +- Problemi comuni (PDF a bassa risoluzione, pagine ruotate) e come evitarli. +- Estendere lo script per gestire più pagine o l'elaborazione batch. + +**Prerequisiti**: Python 3.8+, pip e una conoscenza di base degli ambienti virtuali. Nessuna esperienza pregressa con OCR richiesta—basta seguire. + +--- + +## ## Come estrarre testo PDF con OCR in Python + +Questo header H2 contiene la nostra parola chiave principale proprio dove i motori di ricerca amano vederla. Immergiamoci subito nel codice. + +### Step 1 – Install the Required Packages + +Prima di tutto, ci serve un motore OCR. L'esempio qui sotto utilizza il popolare pacchetto **ocr** (un thin wrapper attorno a Tesseract). Se preferisci un backend diverso, i concetti rimangono gli stessi. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** Su Linux, avrai anche bisogno del binario Tesseract: `sudo apt-get install tesseract-ocr`. Gli utenti macOS possono ottenerlo tramite Homebrew: `brew install tesseract`. + +### Step 2 – Initialize the OCR Engine and Set Language + +Ora avviamo il motore e gli diciamo di cercare caratteri inglesi. Puoi sostituire `ocr.Language.English` con qualsiasi codice lingua supportato. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Perché è importante:** Specificare la lingua migliora drasticamente l'accuratezza perché il motore può applicare dizionari e modelli di caratteri specifici per la lingua. + +### Step 3 – Load a PDF Page as an Image + +L'OCR funziona su immagini raster, non su oggetti PDF. L'helper `ocr.Image.from_pdf` rende la pagina scelta in una bitmap. Regola `page_number` per altre pagine (indice a partire da 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** Se il PDF contiene grafica vettoriale anziché immagini scansionate, potresti ottenere un rendering nitido. Per scansioni a bassa risoluzione, considera di aumentare il DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Step 4 – Recognize Text from the Rendered Image + +Ecco il cuore del **ocr python example**. Il motore elabora la bitmap e restituisce un oggetto contenente la stringa estratta. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +L'attributo `ocr_result.text` contiene l'output in plain‑text, preservando i ritorni a capo dove possibile. + +### Step 5 – Print or Store the Extracted Text + +Infine, mostriamo il risultato. In un'applicazione reale probabilmente scriveresti su un file o su un database. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Eseguendo lo script dovrebbe comparire qualcosa del genere: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Questo è un flusso di lavoro completo **estrarre testo da pdf** usando OCR. + +--- + +## ## Riconosci testo da immagine – Ottimizzare l'accuratezza + +Se ti interessa solo **riconoscere testo da immagine** (ad esempio un JPEG di una ricevuta), puoi saltare il passaggio di conversione PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Suggerimenti per risultati migliori:** + +- **Pre‑processa** l'immagine: converti in scala di grigi, applica sogliatura o correggi l'inclinazione. Pillow lo rende facile. +- **Aumenta DPI** durante il rendering del PDF: una risoluzione più alta fornisce più dettagli al motore OCR. +- **Abilita la configurazione del motore OCR** per la segmentazione delle pagine (`ocr_engine.config = "--psm 6"` per blocchi uniformi). + +--- + +## ## Leggi PDF con OCR – Gestire più pagine + +La maggior parte dei contratti si estende su più pagine. Iterare su ciascuna pagina è semplice: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Questa funzione **legge PDF con OCR**, concatena l'output e inserisce un chiaro marcatore di interruzione di pagina. Puoi quindi alimentare `full_text` in un indice di ricerca o salvarlo come file `.txt`. + +--- + +## ## Problemi comuni e come risolverli + +| Sintomo | Probabile causa | Soluzione | +|---------|-----------------|-----------| +| Caratteri confusi, molti `?` | Lingua errata o file di dati della lingua mancanti | Installa il pacchetto lingua Tesseract corretto (`tesseract-ocr-`) e imposta `ocr_engine.language`. | +| Linee mancanti o parole troncate | Bassa DPI (meno di 150) | Renderizza il PDF a 300 DPI o superiore (`dpi=300`). | +| Il testo è ruotato o capovolto | Pagina scansionata non orientata correttamente | Usa `ocr.Image.deskew(page_image)` prima del riconoscimento. | +| Elaborazione lenta su PDF grandi | Elaborazione delle pagine sequenzialmente su un singolo thread | Parallelizza con `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Estendere l'esempio OCR Python + +- **Esporta in PDF/A**: Dopo l'estrazione, puoi incorporare il testo in un PDF ricercabile usando `reportlab` o `pypdf2`. +- **Rilevamento della lingua**: Usa `langdetect` sull'output OCR per cambiare dinamicamente `ocr_engine.language`. +- **Elaborazione batch**: Scorri una directory con `os.listdir` e applica `extract_all_pages` a ogni file. + +--- + +## ## Output atteso e verifica + +Quando esegui lo script su una scansione chiara in lingua inglese, dovresti vedere un blocco di testo pulito con punteggiatura corretta. Verifica tramite: + +1. Confrontare alcune righe con l'immagine scansionata originale. +2. Eseguire un semplice conteggio parole (`len(ocr_result.text.split())`) per assicurarsi che l'output non sia vuoto. +3. Facoltativamente, passare il risultato a un correttore ortografico come `pyspellchecker` per individuare errori OCR. + +--- + +## Conclusione + +Abbiamo coperto **come estrarre PDF** quando il parsing tradizionale fallisce, mostrato un **esempio OCR python** completo e spiegato come **riconoscere testo da immagine** e **leggere PDF con OCR** per scenari sia a pagina singola che multi‑pagina. Con gli snippet di codice sopra puoi ora trasformare qualsiasi PDF scansionato in testo ricercabile e modificabile—niente più digitazione manuale. + +Prossimi passi? Prova a cambiare la lingua in spagnolo (`ocr.Language.Spanish`) o sperimenta tecniche di pre‑processamento dell'immagine per aumentare l'accuratezza. Se stai costruendo un sistema di gestione documentale, considera di indicizzare il testo estratto con Elasticsearch per ricerche ultra‑veloci. + +Hai domande o ti imbatti in un PDF strano? Lascia un commento, e buon coding! + +![Come estrarre PDF usando OCR in Python](image.png "Come estrarre PDF usando OCR in Python") + +## 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/) +- [Riconosci testo PDF – Operazioni OCR con Aspose.OCR per Java](/ocr/english/java/ocr-operations/) +- [Estrai testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/italian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..5b0c7b2c0 --- /dev/null +++ b/ocr/italian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-19 +description: Impara a utilizzare l'OCR in Java con Aspose. Questa guida passo passo + copre la correzione automatica dell'inclinazione delle immagini, il rilevamento + automatico della lingua e l'estrazione facile del testo dalle immagini. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: it +og_description: 'Come utilizzare l''OCR in Java con Aspose: una guida completa che + copre il raddrizzamento automatico delle immagini, il rilevamento automatico della + lingua e l''estrazione del testo dalle foto.' +og_title: Come utilizzare l'OCR in Java con Aspose – Guida completa +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Come utilizzare l'OCR in Java con Aspose – Guida completa +url: /it/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come usare OCR in Java con Aspose – Guida completa + +Ti sei mai chiesto **come usare OCR** in un progetto Java senza impazzire con la configurazione? Non sei l’unico. Molti sviluppatori si trovano in difficoltà quando devono **estrarre testo da immagini** rapidamente, soprattutto quando le scansioni di origine sono storte o scritte in una lingua sconosciuta. + +In questo tutorial vedremo un esempio pratico che mostra esattamente come usare OCR con Aspose, includendo **auto deskew images**, **auto language detection** e l’intera pipeline di **ocr image preprocessing**. Alla fine avrai uno snippet pronto da eseguire che stampa il testo riconosciuto sulla console, e comprenderai perché ogni impostazione è importante. + +> **Cosa otterrai:** un programma Java completo e eseguibile, spiegazioni di ogni riga, consigli per gestire i casi limite e idee per estendere la soluzione a elaborazione batch o PDF. + +--- + +## Prerequisiti + +- Java 17 (o qualsiasi JDK recente) installato e configurato. +- Maven o Gradle per la gestione delle dipendenze (mostreremo le coordinate Maven). +- Un file di licenza Aspose OCR per Java (`Aspose.OCR.Java.lic`). Se stai solo testando, puoi saltare il passaggio della licenza, ma la versione di prova aggiungerà una filigrana. +- Un’immagine di esempio (`your_image.png`) posizionata in un percorso accessibile al codice. + +> **Pro tip:** conserva le tue immagini in una cartella dedicata `resources` e caricale tramite il classpath; evita problemi di percorsi su sistemi operativi diversi. + +--- + +## Passo 1: Configura il progetto e aggiungi la dipendenza Aspose OCR + +Crea un nuovo progetto Maven (o usa quello esistente) e aggiungi quanto segue al tuo `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Esegui `mvn clean install` per scaricare la libreria. Se preferisci Gradle, l’equivalente è: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Ora hai le classi di **ocr image preprocessing** nel tuo classpath. + +--- + +## Passo 2: Applica la licenza Aspose OCR (Opzionale ma consigliato) + +Se possiedi una licenza, applicala subito all’inizio del tuo metodo `main`. Saltare questo passaggio funziona, ma la versione gratuita aggiunge una filigrana “Demo” sull’output. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Perché è importante:** la versione con licenza rimuove i limiti d’uso e disattiva la filigrana, fornendoti risultati puliti e pronti per la produzione. + +--- + +## Passo 3: Crea l’istanza del motore OCR + +Il motore è il cuore del processo. Instanziarlo ti dà accesso a tutte le opzioni di **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +A questo punto il motore è pronto, ma utilizzerà le impostazioni predefinite, che potrebbero non essere ottimali per documenti scansionati. Modifichiamo qualche parametro. + +--- + +## Passo 4: Abilita Auto Deskew Images per scansioni più pulite + +Le scansioni inclinate sono un problema comune. Aspose fornisce la funzionalità **auto deskew images** che raddrizza automaticamente l’immagine prima del riconoscimento. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Come funziona:** l’algoritmo analizza gli angoli della linea di base del testo e ruota l’immagine verso l’orientamento più probabile. Questo migliora notevolmente l’accuratezza per foto scattate con il telefono. + +--- + +## Passo 5: Attiva Auto Language Detection + +Se non conosci la lingua dell’immagine di origine, lascia che il motore la individui. Questa è l’impostazione **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Quando la abiliti, Aspose analizza i glifi e seleziona il modello linguistico più probabile, supportando oltre 30 lingue pronte all’uso. + +--- + +## Passo 6: Carica l’immagine da riconoscere + +Puoi caricare un’immagine da disco, da un URL o anche da un array di byte. Per semplicità, leggeremo da un file locale. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Suggerimento:** se lavori con immagini di grandi dimensioni, considera di ridimensionarle prima con `engine.getImagePreprocessing().setResizeFactor(0.5)` per velocizzare l’elaborazione senza perdere troppi dettagli. + +--- + +## Passo 7: Esegui il riconoscimento OCR ed estrai il testo dall’immagine + +Ora il motore fa la sua magia. Il metodo `recognize` restituisce un oggetto `OcrResult` che contiene il testo riconosciuto, i punteggi di confidenza e altro. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +La console mostrerà il testo semplice estratto dall’immagine—questo è il risultato principale di **extract text image** che ci siamo prefissati. + +--- + +## Esempio completo funzionante + +Di seguito trovi la classe Java completa che mette insieme tutti i passaggi. Copiala in `src/main/java/com/example/OcrDemo.java` ed eseguila. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Output previsto + +Se l’immagine contiene la frase “Hello World” su una scansione pulita, vedrai: + +``` +=== Recognized Text === +Hello World +``` + +Per documenti più complessi (ad esempio ricevute multilingue), l’output includerà interruzioni di riga e il codice della lingua rilevata. + +--- + +## Problemi comuni & Pro Tips + +| Problema | Perché accade | Soluzione | +|----------|---------------|-----------| +| **Caratteri spazzatura** | L’immagine è troppo scura o rumorosa. | Abilita `engine.getImagePreprocessing().setBinarization(true)` o regola manualmente il contrasto. | +| **Lingua errata** | L’autodetect fallisce su pagine multilingue. | Imposta `engine.setLanguage(Language.English)` (o l’enum appropriato) per forzare una lingua specifica. | +| **Elaborazione lenta** | Immagini a risoluzione molto alta. | Ridimensiona con `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Errori Out‑of‑memory** | Grande batch di immagini caricate contemporaneamente. | Elabora le immagini una alla volta e chiama `engine.dispose()` dopo ogni esecuzione. | + +> **Ricorda:** il motore OCR è thread‑safe per operazioni di sola lettura, ma creare una nuova istanza per thread evita bug legati a stato nascosto. + +--- + +## Estendere la soluzione + +Ora che sai **come usare OCR** con Aspose, potresti voler: + +1. **Elaborare PDF** – Converti ogni pagina PDF in immagine (`PdfConverter`) e passala alla stessa pipeline. +2. **Processare in batch una cartella** – Scorri i file in una directory, applica gli stessi passaggi e scrivi i risultati in un CSV. +3. **Integrare con un servizio web** – Esporre la logica OCR tramite un `@RestController` di Spring Boot che accetta upload multipart. + +Tutti questi scenari riutilizzano la stessa configurazione di **ocr image preprocessing** costruita qui. + +--- + +## Conclusione + +Abbiamo coperto **come usare OCR** in Java con Aspose dall’inizio alla fine: applicare la licenza, creare il motore, attivare **auto deskew images**, abilitare **auto language detection**, caricare un’immagine e infine **extract text image** con un singolo `System.out.println`. Il codice è completamente autonomo, funziona su qualsiasi JDK recente e dimostra le migliori pratiche per accuratezza e performance. + +Provalo con le tue foto—magari un contratto scansionato o uno screenshot di una ricevuta. Modifica i flag di preprocessing, sperimenta con lingue diverse, e vedrai subito perché la libreria OCR di Aspose è una scelta solida per estrazioni di testo di livello produttivo. + +Hai domande o vuoi condividere i tuoi risultati? Lascia un commento qui sotto o scrivimi su GitHub. Buon coding! + +--- + +![Esempio di utilizzo OCR in Java](/images/ocr-java-example.png "Come usare OCR in Java – Screenshot demo Aspose") + + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che approfondiscono le tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell’API e a esplorare approcci alternativi nei tuoi progetti. + +- [Come fare OCR di testo immagine con lingua usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Estrarre testo da immagine Java con Aspose.OCR in modalità Detect Areas](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Come usare OCR - Tecniche avanzate con Aspose.OCR per Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/italian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..dcc9e1f48 --- /dev/null +++ b/ocr/italian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,318 @@ +--- +category: general +date: 2026-06-19 +description: Migliora l'accuratezza OCR in Python usando Aspose OCR. Scopri come impostare + la lingua OCR, caricare l'immagine per l'OCR e estrarre il testo dall'immagine con + un dizionario personalizzato. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: it +og_description: Migliora l'accuratezza OCR in Python impostando la lingua OCR, caricando + un'immagine per l'OCR ed estraendo il testo dall'immagine con un dizionario personalizzato. +og_title: Migliora l'accuratezza dell'OCR in Python – Guida passo passo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Migliora l'accuratezza OCR in Python – Guida completa +url: /it/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Migliorare l'accuratezza OCR in Python – Guida completa + +Ti sei mai chiesto come **migliorare l'accuratezza OCR** quando il testo che stai scansionando contiene simboli strani, codici prodotto o nomi di marchi? Non sei solo. In molti progetti il motore predefinito restituisce solo spazzatura, e questo è un vero ostacolo alla produttività. + +In questo tutorial percorreremo un esempio pratico, end‑to‑end, che ti mostrerà come **impostare la lingua OCR**, **caricare l'immagine per OCR**, **eseguire OCR sull'immagine** e infine **estrarre testo dall'immagine** con un dizionario personalizzato che aumenta i tassi di riconoscimento. Alla fine avrai uno script pronto all'uso da inserire in qualsiasi codebase Python. + +## Cosa otterrai + +- Uno script Python completamente funzionale che utilizza Aspose OCR per leggere un file PNG. +- La capacità di **migliorare l'accuratezza OCR** configurando la lingua e una lista di parole personalizzata. +- Spiegazioni chiare del perché ogni impostazione è importante, più consigli per gestire casi limite come caratteri non latini. +- Una rapida checklist per la risoluzione dei problemi OCR più comuni. + +### Prerequisiti + +- Python 3.8 o versioni successive installato sulla tua macchina. +- Pacchetto `aspose-ocr` (installalo via `pip install aspose-ocr`). +- Un'immagine di esempio (`technical_doc.png`) che contiene il testo che vuoi leggere. +- Familiarità di base con Python—nulla di complesso è richiesto. + +> **Pro tip:** Se lavori in un ambiente virtuale, attivalo prima di installare il pacchetto. Mantiene le dipendenze ordinate ed evita conflitti di versione. + +--- + +## Passo 1: Installa e importa Aspose OCR + +First things first—let’s get the library into our environment and import the pieces we need. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Il namespace `aspose.ocr` ti dà accesso alla classe `OcrEngine`, che è il cuore del processo OCR. Importarla qui mantiene il resto dello script pulito e leggibile. + +--- + +## Passo 2: Crea un motore OCR e **Imposta la lingua OCR** + +Perché la lingua è importante? I motori OCR si basano su modelli specifici per lingua per riconoscere forme di caratteri e pattern di parole. Se indichi al motore che stai scansionando testo in inglese, ignorerà i glifi cirillici e si concentrerà sull'alfabeto latino, migliorando drasticamente **l'accuratezza OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Nota:** Aspose OCR supporta oltre 50 lingue. Sostituisci `ocr.Language.English` con `ocr.Language.Spanish`, `ocr.Language.French`, ecc., se il tuo documento non è in inglese. + +--- + +## Passo 3: Definisci un **Dizionario personalizzato** per aumentare l'accuratezza + +Immagina di scansionare fatture che contengono la parola “AsposeOCR” o codici prodotto come “SKU12345”. Il motore non conosce questi termini, quindi indovina in modo errato. Fornire una lista di parole personalizzata dice al motore: *“Ehi, queste stringhe sono legittime—non cercare di correggerle.”* È una vittoria rapida per **migliorare l'accuratezza OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Puoi caricare questa lista da un file o da un database se hai centinaia di voci—mantienila semplicemente in una lista Python per semplicità. + +--- + +## Passo 4: **Carica l'immagine per OCR** + +Ora ci serve un'immagine. Il metodo `Image.load` accetta un percorso a qualsiasi formato raster supportato (PNG, JPEG, BMP, ecc.). Se il file non viene trovato, il motore lancia un'eccezione, quindi proteggiamo il codice da questo caso. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Perché questo passo è importante:** Caricare correttamente l'immagine garantisce che il motore lavori con i dati pixel esatti che intendi analizzare. File corrotti o percorsi errati sono una fonte comune di frustrazione. + +--- + +## Passo 5: **Esegui OCR sull'immagine** e estrai i risultati + +Con il motore configurato e l'immagine pronta, il riconoscimento vero e proprio è una singola chiamata di metodo. L'oggetto risultato contiene il testo grezzo, i punteggi di confidenza e persino informazioni di layout se ti servono in seguito. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Se devi **estrarre testo dall'immagine** riga per riga, puoi suddividere sulla sequenza di newline: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Passo 6: Verifica l'output – Migliora davvero **l'accuratezza OCR**? + +Stampiamo il risultato e vediamo se il nostro dizionario personalizzato ha fatto la differenza. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Un tipico output per l'immagine di esempio potrebbe apparire così: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Nota come il nome del brand, il carattere greco e il codice prodotto compaiano esattamente come li abbiamo definiti. Senza il dizionario personalizzato, il motore avrebbe cercato di “correggerli”, producendo spesso qualcosa come “Aspose OCR” o “SKU 1234”. + +--- + +## Problemi comuni e come affrontarli + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| **Caratteri spazzatura** | Lingua impostata in modo errato o immagine a bassa risoluzione | Assicurati che `engine.language` corrisponda alla lingua di origine e usa una scansione ad alta DPI (300 dpi o superiore). | +| **Parole personalizzate ignorate** | Dizionario non collegato o errore di battitura nel nome della proprietà | Verifica `engine.text_processing.custom_dictionary = …`. | +| **File non trovato** | Percorso errato o permessi di file mancanti | Usa `os.path.abspath()` per verificare il percorso assoluto; esegui lo script con i permessi appropriati. | +| **Elaborazione lenta** | Immagini grandi o molte pagine | Pre‑processa l'immagine (ritaglio, ridimensionamento) o usa `engine.recognize(image, max_threads=4)` per parallelizzare. | + +--- + +## Approfondimenti: Ottimizzazioni avanzate per **migliorare l'accuratezza OCR** + +1. **Pre‑processing** – Applica miglioramento del contrasto o binarizzazione con Pillow prima di passare l'immagine a Aspose OCR. +2. **Multiple Languages** – Imposta `engine.language = ocr.Language.English | ocr.Language.French` per abilitare il riconoscimento bilingue. +3. **Region‑Based OCR** – Se ti serve solo un'area specifica (ad es. una tabella), ritaglia prima l'immagine per ridurre il rumore. +4. **Confidence Filtering** – `result.confidence` fornisce un punteggio per carattere; puoi scartare i risultati a bassa confidenza programmaticamente. + +--- + +## Script completo funzionante + +Di seguito trovi lo script completo, pronto per il copia‑incolla, che incorpora tutti i passaggi discussi. Salvalo come `improve_ocr_accuracy.py` ed eseguilo dalla riga di comando. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Eseguilo: + +```bash +python improve_ocr_accuracy.py +``` + +Dovresti vedere l'output formattato bene che abbiamo mostrato in precedenza. + +--- + +## Conclusione + +Abbiamo appena coperto un modo semplice per **migliorare l'accuratezza OCR** in Python tramite: + +1. **Impostare la lingua OCR** per corrispondere al tuo documento. +2. **Caricare correttamente l'immagine** così il motore vede i pixel giusti. +3. **Eseguire OCR sull'immagine** con una singola chiamata di metodo. +4. **Estrarre testo dall'immagine** e confermare il risultato. +5. **Aggiungere un dizionario personalizzato** per fissare termini specifici del dominio. + +Questo è l'intero flusso di lavoro—da immagine grezza a testo pulito e ricercabile—impacchettato in uno script riutilizzabile. + +Se sei pronto per la prossima sfida, prova a sperimentare con il pre‑processing dell'immagine (contrasto, deskew) o passa a una configurazione multilingue usando `ocr.Language.English | ocr.Language.German`. Gli stessi principi si applicano, e continuerai a **migliorare l'accuratezza OCR** su un più ampio set di documenti. + +Hai domande o un caso limite strano? Lascia un commento qui sotto, e buona programmazione! + +![improve OCR accuracy + + +## 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 dall'immagine – Ottimizzazione OCR con Aspose.OCR per .NET](/ocr/english/net/ocr-optimization/) +- [Riconosci testo immagine con Aspose OCR per più lingue](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Come impostare il valore di soglia nel riconoscimento OCR di immagini](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/italian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..126188e15 --- /dev/null +++ b/ocr/italian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Esegui OCR su un'immagine usando la libreria OCR di Python. Scopri come + rilevare il testo da un'immagine, riconoscere il testo da un JPEG e estrarre il + testo da un'immagine scansionata in modo efficiente. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: it +og_description: Esegui OCR su un'immagine con Python ed estrai il testo da file scansionati. + Questa guida ti accompagna passo passo nel caricamento delle immagini, nella correzione + dell'inclinazione e nel riconoscimento del testo. +og_title: Esegui OCR su un'immagine in Python – Guida completa all'estrazione del + testo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Esegui OCR su un'immagine in Python – Guida completa all'estrazione del testo +url: /it/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esegui OCR su Immagine in Python – Guida Completa all'Estrazione del Testo + +Ti è mai capitato di dover **perform OCR on image** su file immagine ma di scontrarti con un muro perché il codice sembrava criptico? Non sei l'unico. Che tu stia trasformando una pila di ricevute scannerizzate in PDF ricercabili o estraendo didascalie da un JPEG per un progetto di data‑science, la capacità di riconoscere testo da JPEG e altri formati è una competenza indispensabile per qualsiasi sviluppatore oggi. + +In questo tutorial passeremo in rassegna un esempio completo e eseguibile che ti mostra come **detect text from image** file, **extract text from scanned image** documenti, e persino **load image for OCR** in poche righe. Alla fine avrai uno snippet solido, pronto per la produzione, che potrai inserire nei tuoi progetti—senza import mancanti, senza vaghi shortcut “see docs”. + +## Cosa Costruirai + +- Un piccolo script Python che crea un motore OCR, abilita l'auto‑deskew, carica un JPEG (o qualsiasi formato supportato) e stampa il testo riconosciuto. +- Spiegazioni del **why** di ogni impostazione, non solo del **how** da digitare. +- Suggerimenti per gestire PDF multi‑pagina, lingue non inglesi e problemi comuni come scansioni sfocate. + +### Prerequisiti + +- Python 3.8+ installato (l'esempio utilizza il pacchetto `ocr` disponibile tramite `pip install ocr-lib` – sostituisci con il nome della tua libreria reale). +- Familiarità di base con le funzioni Python e gli ambienti virtuali. +- Un file immagine (JPEG, PNG, TIFF) che desideri elaborare; useremo `skewed_page.jpg` come segnaposto. + +> **Pro tip:** Se sei su Windows, esegui il terminale come Amministratore quando installi la libreria OCR per evitare problemi di permessi. + +--- + +## Esegui OCR su Immagine – Configurazione e Setup + +La prima cosa di cui hai bisogno è un'istanza pulita del motore OCR. Pensala come il cervello dell'operazione; senza una configurazione adeguata, anche l'immagine più nitida restituirà nonsense. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters:** +Impostare `engine.language` restringe il set di caratteri che il motore OCR si aspetta, aumentando drasticamente l'accuratezza. Se lo salti, il motore proverà a indovinare, spesso leggendo male parole semplici. + +## Abilita Deskew Automatico – Correggi Scansioni Inclinate + +Le pagine scannerizzate raramente sono perfettamente piatte. Una leggera inclinazione può compromettere la segmentazione dei caratteri, trasformando “Hello” in “H3llo”. Il flag `auto_deskew` fa il lavoro pesante per te. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** Se sai che le tue immagini sono già dritte, disabilitare il deskew può risparmiare qualche millisecondo di tempo di elaborazione—utile quando si gestiscono migliaia di pagine in un lavoro batch. + +## Carica Immagine per OCR – Supporto JPEG, PNG, TIFF + +Ora carichiamo effettivamente **load image for OCR**. Il metodo `ocr.Image.load` è flessibile; accetta un percorso a qualsiasi formato raster supportato. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial:** La libreria legge il file in un bitmap interno, applicando eventuali conversioni di spazio colore necessarie. Saltare questo passaggio e passare un flusso di byte grezzo genererebbe un `FileNotFoundError` o, peggio, produrrebbe silenziosamente risultati vuoti. + +Se hai bisogno di **recognize text from JPEG** file specificamente, assicurati semplicemente che l'estensione del file sia `.jpeg` o `.jpg`. La stessa chiamata funziona per PNG (`.png`) o TIFF (`.tif`) senza modifiche. + +## Esegui OCR su Immagine – Esecuzione del Motore + +Con il motore pronto e l'immagine in memoria, è il momento di **perform OCR on image** sui dati. Questa singola riga fa il lavoro pesante: pre‑processing, segmentazione, classificazione e assemblaggio del testo. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood?** +- Il motore applica la trasformazione deskew (se abilitata). +- Esegue una rete neurale o il backend Tesseract per identificare i caratteri. +- Infine, unisce i caratteri in parole e linee, restituendo un ricco oggetto `result`. + +## Estrai Testo da Immagine Scannerizzata – Visualizza i Risultati + +L'ultimo passaggio è **extract text from scanned image** e visualizzarlo. L'attributo `result.text` contiene la rappresentazione plain‑text. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Un output tipico appare così: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Se il motore OCR non riesce a trovare alcun carattere, `result.text` sarà una stringa vuota. In tal caso, ricontrolla la qualità dell'immagine o considera di regolare la proprietà `engine.confidence_threshold` (se la tua libreria la supporta). + +## Gestione delle Varianti Comuni + +### Riconosci Testo da JPEG vs PNG + +Entrambi i formati sono supportati, ma la compressione JPEG può introdurre artefatti che confondono il motore. Se noti frequenti errori di riconoscimento, prova a convertire prima il JPEG in PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Rileva Testo da Immagine con più Lingue + +Se il tuo documento mescola inglese e spagnolo, imposta una modalità multilingue: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Il motore considererà allora entrambi gli alfabeti durante il riconoscimento. + +### Estrai Testo da PDF Scannerizzati + +Per i PDF, è necessario rasterizzare prima ogni pagina in un'immagine. Librerie come `pdf2image` rendono questo semplice: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +## Esempio Completo Funzionante + +Di seguito trovi lo script completo che puoi copiare‑incollare in un file `ocr_demo.py`. Include la gestione degli errori e un piccolo helper per misurare il tempo di esecuzione. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (supponendo una scansione chiara): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +## Domande Frequenti + +**Q: Posso eseguirlo su un server headless?** +A: Assolutamente. La libreria funziona senza GUI; basta assicurarsi che i binari nativi necessari (ad esempio, Tesseract) siano installati sul server. + +**Q: E se l'immagine è sfocata?** +A: Considera di aggiungere un filtro di nitidezza prima di `engine.recognize`. Molte librerie OCR espongono `image_preprocessing.sharpen = True` oppure puoi usare `cv2.GaussianBlur` di OpenCV in modo inverso. + +**Q: Lo script supporta l'elaborazione batch?** +A: Sì. Avvolgi `perform_ocr` in un ciclo su una lista di percorsi file, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/italian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..745b8bc39 --- /dev/null +++ b/ocr/italian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Esegui OCR su un'immagine usando Aspose OCR Java. Scopri come caricare + l'immagine per l'OCR, utilizzare la licenza Aspose e estrarre il testo dall'immagine + in pochi minuti. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: it +og_description: Esegui OCR su un'immagine con Aspose OCR Java. Questa guida mostra + come utilizzare la licenza Aspose, caricare l'immagine per l'OCR ed estrarre il + testo dall'immagine in modo efficiente. +og_title: Esegui OCR su immagine con Aspose OCR Java – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Esegui OCR su un'immagine con Aspose OCR Java – Guida completa passo passo +url: /it/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esegui OCR su Immagine con Aspose OCR Java – Guida Completa Passo‑per‑Passo + +Hai mai dovuto **eseguire OCR su file immagine** ma non eri sicuro quale libreria ti garantisse risultati affidabili senza una miriade di configurazioni? Non sei solo. In molti progetti reali—pensa alla scansione di passaporti, alla digitalizzazione di fatture o all'estrazione di testo da screenshot—la capacità di riconoscere rapidamente i dati testuali di un'immagine è un vero punto di svolta. + +In questo tutorial percorreremo un esempio pratico che mostra esattamente come **eseguire OCR su immagine** usando Aspose OCR per Java. Copriremo tutto, dalla applicazione della licenza Aspose al caricamento dell’immagine, all’esecuzione del motore e, infine, **estrarre testo dall’immagine** per usarlo a valle. Niente fronzoli, solo una soluzione funzionante da copiare‑incollare. + +## Cosa Imparerai + +- Una visione chiara di come **usare la licenza Aspose** in un progetto Java. +- Il codice esatto necessario per **caricare l’immagine per OCR** e lasciare che il motore rilevi automaticamente le lingue. +- Istruzioni passo‑per‑passo per **riconoscere il contenuto testuale dell’immagine** e **estrarre testo dall’immagine** in modo sicuro. +- Suggerimenti per gestire le difficoltà più comuni (risultati vuoti, formati non supportati e problemi di memoria). + +> **Prerequisiti** – Java 8 o superiore, Maven o Gradle per la gestione delle dipendenze, e un file di licenza Aspose OCR per Java (oppure puoi eseguire in modalità di valutazione). + +--- + +## Come Eseguire OCR su Immagine con Aspose OCR Java + +Di seguito trovi il programma Java completo, pronto per l’esecuzione, che dimostra l’intero flusso. Salvalo come `AsposeOcrDemo.java` ed eseguilo dal tuo IDE o dalla riga di comando. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Output Atteso sulla Console + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Se avvii il programma senza un file di licenza, la prima riga indicherà semplicemente che sei in modalità di valutazione, ma l’OCR funzionerà comunque. + +--- + +## Configurare e Usare la Licenza Aspose + +### Perché la Licenza è Importante + +Eseguire la libreria in modalità di valutazione va bene per test rapidi, ma aggiunge una filigrana all’output e limita il numero di pagine che puoi elaborare per esecuzione. Applicare il passaggio **usare licenza Aspose** rimuove queste restrizioni e segnala ad Aspose che sei un cliente pagante. + +### Come Ottenere e Applicare la Licenza + +1. Acquista una licenza dallo store Aspose. +2. Scarica il file `Aspose.OCR.Java.lic`. +3. Posizionalo in una cartella leggibile dall’applicazione—tipicamente la cartella `src/main/resources`. +4. Chiama `new License().setLicense("Aspose.OCR.Java.lic");` prima di qualsiasi operazione OCR, come mostrato nel codice sopra. + +> **Consiglio professionale:** Se distribuisci su un server, usa un percorso assoluto o un loader di risorse dal class‑path per evitare `FileNotFoundException`. + +--- + +## Caricare l’Immagine per l’Elaborazione OCR + +La riga `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` è il cuore del passaggio **caricare immagine per OCR**. Aspose OCR supporta un’ampia gamma di formati: PNG, JPEG, BMP, TIFF e persino PDF multi‑pagina (quando combinato con Aspose.Pdf). + +### Problemi Comuni + +| Problema | Sintomo | Soluzione | +|----------|----------|-----------| +| Percorso file errato | `FileNotFoundException` | Ricontrolla il percorso; usa `Paths.get(...)` per separatori indipendenti dal sistema operativo. | +| Formato non supportato | `UnsupportedOperationException` | Converti l’immagine in PNG o JPEG prima del caricamento. | +| Immagine enorme ( > 10 MP) | Errori di out‑of‑memory | Ridimensiona l’immagine usando `java.awt.Image` prima di passarla ad Aspose. | + +--- + +## Estrarre Testo dall’Immagine e Gestire i Risultati + +Una volta che il motore OCR termina, l’oggetto `OcrResult` contiene la stringa riconosciuta. È qui che **estraiamo testo dall’immagine** per ulteriori elaborazioni—salvataggio in un database, indicizzazione di ricerca o alimentazione di una pipeline NLP a valle. + +### Gestire più Lingue + +Poiché impostiamo `engine.setLanguage(Language.Auto)`, Aspose tenterà di rilevare le lingue al volo. Se conosci la lingua in anticipo (ad esempio tutti i documenti sono in russo), puoi sostituire `Language.Auto` con `Language.Russian` per migliorare le prestazioni. + +### Suggerimenti di Post‑Processing + +- **Rimuovi spazi bianchi**: `result.getText().trim()`. +- **Normalizza le terminazioni di riga**: `result.getText().replace("\r\n", "\n")`. +- **Elimina caratteri non stampabili**: usa una regex come `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Riconoscere Testo nell’Immagine con Opzioni Avanzate (Facoltativo) + +Se ti serve un controllo più fine, Aspose OCR offre proprietà aggiuntive: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Queste regolazioni sono utili quando lavori con documenti scansionati affetti da inclinazione o basso contrasto. + +--- + +## Riepilogo dell’Esempio Completo + +Mettendo tutto insieme, il programma finale esegue, in ordine: + +1. **Eseguire OCR su immagine** – creando un `OcrEngine`. +2. **Usare licenza Aspose** – opzionale ma consigliato. +3. **Caricare immagine per OCR** – tramite `Image.load`. +4. **Impostare il rilevamento lingua** – `Language.Auto` per **riconoscere testo immagine** automaticamente. +5. **Estrarre testo dall’immagine** – stampare il risultato, gestendo risposte vuote in modo elegante. + +Puoi copiare il blocco di codice sopra direttamente in un progetto Maven con questa dipendenza: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Esegui `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` e osserva la console che visualizza il testo riconosciuto. + +--- + +## Conclusione + +Abbiamo appena mostrato come **eseguire OCR su file immagine** usando Aspose OCR per Java, dalla applicazione della licenza al **caricamento dell’immagine per OCR**, al **riconoscimento del contenuto testuale dell’immagine** e infine all’**estrazione del testo dall’immagine** per usi successivi. L’approccio è lineare, funziona con più lingue out‑of‑the‑box e può essere esteso con opzioni avanzate di pre‑processing quando necessario. + +Qual è il prossimo passo? Prova a inviare l’output OCR a un indice di ricerca, genera PDF con il testo estratto o sperimenta con formati immagine diversi. Le possibilità sono infinite, e con l’API robusta di Aspose spenderai più tempo a costruire funzionalità che a combattere con le stranezze dell’OCR. + +Hai domande o incontri un caso limite? Lascia un commento qui sotto—buona programmazione! + +## 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‑per‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1af136ac2 --- /dev/null +++ b/ocr/japanese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR を使用して画像から検索可能な PDF を作成します。OCR を PDF に変換し、画像からテキストを抽出し、画像上で + OCR を迅速に実行する方法を学びましょう。 +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: ja +og_description: Python OCRで画像から検索可能なPDFを作成する。このガイドでは、OCRをPDFに変換する方法、画像からテキストを抽出する方法、そして画像に対してOCRを実行する方法を示します。 +og_title: Pythonで検索可能なPDFを作成 – 完全プログラミング解説 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Pythonで検索可能なPDFを作成する – 完全ステップバイステップガイド +url: /ja/python-java/general/create-searchable-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を作成する – 完全ステップバイステップガイド + +スキャンしたレシートから **searchable PDF** を作成したいと思ったことはありませんか?でも、どこから始めればいいか分からない…という方は多いです。テキストの画像を実際に検索できる PDF に変換しようとしたときに、最初に壁にぶつかる開発者は多数います。 + +このチュートリアルでは、**画像に対して OCR を実行**し、その OCR 結果を **searchable PDF** に変換し、さらに必要に応じて生テキストを抽出する実用的な解決策を順を追って解説します。余計な説明は省き、すぐにプロジェクトにコピペできる動作例を提供します。 + +## 学べること + +- Python で軽量な OCR エンジンをセットアップする方法 +- **OCR を PDF に変換**して検索可能なドキュメントとして保存する手順 +- **画像からテキストを抽出**して下流処理に利用する方法 +- 画像の向きや大容量ファイルなど、よくある落とし穴への対処法 +- 実際に動作する完全なスクリプト(自分のユースケースに合わせてカスタマイズ可能) + +### 前提条件 + +- Python 3.8+ がインストールされていること +- pip と仮想環境の基本的な使い方が分かっていること(任意ですが推奨) +- 明瞭で機械可読なテキストを含む画像ファイル(PNG、JPEG など) + +上記が揃っていれば、さっそく始めましょう。 + +## Step 1: 必要なライブラリをインストール + +先ほどのコードスニペットでは架空の `ocr` パッケージを使用しましたが、実際のライブラリとしては **EasyOCR**、**pytesseract**、**pdfminer.six** などが利用できます。このガイドでは、純粋な Python 実装で多言語対応かつ便利な PDF 変換ヘルパーを持つ **EasyOCR** を使用します。 + +```bash +pip install easyocr pillow +``` + +> **プロのコツ:** 仮想環境内でインストールすると依存関係が整理しやすくなります(`python -m venv venv && source venv/bin/activate`)。 + +## Step 2: OCR エンジンを初期化 – 画像に対して OCR を実行 + +ライブラリの準備ができたら、OCR エンジンを作成し、英語テキスト用に設定します。ここが **画像に対して OCR を実行**する最初のステップです。 + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +なぜ専用のリーダーオブジェクトが必要かというと、EasyOCR は言語モデルを事前にロードするため、複数画像に対して同じ `reader` を再利用する方が毎回再初期化するよりもはるかに効率的です。 + +## Step 3: 画像を読み込む – 画像からテキストを抽出 + +画像をメモリに読み込みます。この段階ではまだ **画像からテキストを抽出** する準備だけです。 + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +画像が逆さまだったり歪んでいる場合は、OCR エンジンに渡す前に Pillow の `rotate` や `transpose` メソッドで補正するとよいでしょう。簡単な目視確認だけでもデバッグ時間を大幅に削減できます。 + +## Step 4: OCR エンジンを実行し結果を取得 + +ここがプロセスの核心です。画像を OCR エンジンに渡し、構造化されたデータを受け取ります。 + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +`detail=1` フラグを付けるとバウンディングボックスが取得でき、後で **OCR を PDF に変換**する際に必要になります。文字列だけが欲しい場合は `detail=0` に設定してください。 + +## Step 5: OCR 結果を検索可能な PDF に変換 – OCR を PDF に変換 + +EasyOCR には直接 PDF を書き出す機能はありませんが、Pillow と `reportlab`、そして軽量な `fpdf2` を組み合わせて自前で PDF を作成できます。ここでは画像を表示レイヤーとして貼り付け、見えないテキストを重ねる手法を取ります。 + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +何が起きたかというと、スキャン画像を可視レイヤーとして配置し、その上に白いテキスト(背景と同色)で認識した文字列を書き込んでいます。検索ツールは隠れたテキスト層を読むため、見た目は変わらず **searchable** な PDF が完成します。 + +## Step 6: PDF バイト列を取得 – 画像を PDF に変換 + +PDF をディスクに直接書き出す代わりに、メモリ上でバイト列として取得したい場合は以下のようにします。 + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +この一行で、典型的な **convert image to PDF** ワークフロー(画像 → OCR → テキストオーバーレイ → PDF ストリーム生成)を実演しています。 + +## Step 7: 結果を確認 – 簡易チェック + +スクリプト実行後、`receipt_searchable.pdf` を任意の PDF ビューアで開き、検索ボックス(Ctrl + F)でレシートに含まれる単語を入力してみてください。正しい位置にジャンプすれば **searchable pdf を作成**できています! + +検索が機能しない場合は、以下を再確認してください。 + +1. OCR の信頼度スコア(`conf` 値)。低いと画像がぼやけている可能性があります。 +2. バウンディングボックスの座標 – EasyOCR が異なる向きで報告することがあります。 +3. PDF ビューアが「画像のみ」モードになっていないか(稀ですが、一部のビューアにその設定があります)。 + +## 完全動作スクリプト + +すべてをまとめた、すぐに実行できる Python ファイルは以下の通りです。 + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +`searchable_pdf.py` という名前で保存し、`YOUR_DIRECTORY` のプレースホルダーを実際のパスに置き換えてから実行してください。 + +```bash +python searchable_pdf.py +``` + +実行すると確認メッセージが表示され、フォルダ内に新しい **searchable PDF** が生成されます。 + +## よくある質問とエッジケース + +**画像がカラーの場合はどうすれば?** +EasyOCR はグレースケール・カラーどちらでも動作しますが、ノイズが多いスキャンでは `pil_image.convert("L")` でグレースケール化すると精度が向上することがあります。 + +**マルチページ PDF に対応できるか?** +可能です。各ページ画像に対して同じ OCR 手順を実行し、同一の `FPDF` オブジェクトに `self.add_page()` でページを追加していきます。 + +**テキスト層を白文字ではなく、実際の「テキスト下画像」レイヤーにしたい** +アクセシビリティが必要な場合は、`pdfminer` や `pikepdf` を使って隠しテキスト層を PDF タグ付きで埋め込む方法があります。高度な手法ですが、基本は「背景画像 + テキストオーバーレイ」という考え方は変わりません。 + +**OCR の信頼度が低い場合は?** +信頼度が低い単語を除外することができます。 + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## まとめ – 達成したこと + +レシートの画像から **画像に対して OCR を実行**し、認識文字列を抽出、最終的に **searchable pdf** を作成しました。プロセス全体で **OCR を PDF に変換**、**画像からテキストを抽出**、**画像を PDF に変換**、**画像に対して OCR を実行**という二次キーワードをすべて網羅していますので、同様のプロジェクトで再利用できるツールボックスが手に入りました。 + +### 次のステップ + +- `easyocr.Reader(['en', 'es'])` のように ISO コードを追加して他言語に挑戦する。 +- 完全オフラインが必要な場合は Tesseract に置き換えても、パイプラインは同じです。 +- 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/japanese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..99672ff3f --- /dev/null +++ b/ocr/japanese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-19 +description: シンプルなOCRエンジンを使ってPythonで画像からテキストを抽出します。スキャンした画像をテキストに変換する方法、画像からテキストを認識する方法、そしてPythonで画像ファイルを効率的に一覧表示する方法を学びましょう。 +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: ja +og_description: 軽量なOCRエンジンを使用して、Pythonで画像からテキストを抽出します。このガイドでは、スキャンした画像をテキストに変換し、画像からテキストを認識し、Pythonで画像ファイルを一覧表示する方法を数ステップで紹介します。 +og_title: Pythonで画像からテキストを抽出する – 完全バッチOCRガイド +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Pythonで画像からテキストを抽出する – 完全バッチOCRガイド +url: /ja/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonで画像からテキストを抽出 – 完全バッチOCRガイド + +画像から**テキストを抽出**したいけど、どこから始めればいいか分からないことはありませんか?開発者はスキャンしたPDF、撮影したレシート、スクリーンショットなどを検索可能なテキストに変換する課題に日々直面しています。このチュートリアルでは、**スキャン画像をテキストに変換**し、画像からテキストを認識し、さらに**list image files python**スタイルで画像ファイルを列挙する、実行可能な完全なサンプルを順を追って解説します。最後まで読めば、フォルダ全体を一括で処理できる再利用可能なスクリプトが手に入ります。 + +必要なライブラリ、各ステップの重要性、エッジケースの扱い、トラブルシューティングまで網羅しています。外部ドキュメントを追いかける必要はありません。以下のコードは自己完結しており、解説は「どうやって」だけでなく「なぜ」も説明しています。お気に入りのIDEを開いて、さっそく始めましょう。 + +--- + +## 作成するもの + +- OCRエンジンを初期化する(例として `ocr` パッケージを使用)。 +- ディレクトリを走査し、**list image files python**スタイルで PNG、JPG、TIFF をフィルタリングして列挙。 +- 見つかったすべての画像に対して**バッチ OCR**を実行。 +- 各ファイルの抽出テキストを明示的にラベル付けして出力。 + +> **プロのコツ:** `ocr` ライブラリがインストールされていない場合は、`pytesseract` に差し替えてもほぼ同じロジックで動作します。 + +--- + +## 前提条件 + +- Python 3.8+(スクリプトは f‑string と型ヒントを使用)。 +- `OcrEngine` と `recognize_batch` を提供する OCR ライブラリ。ここでは架空の `ocr` パッケージを例にしていますが、実際のライブラリでも同様のパターンが使えます。 +- 処理したい画像ファイルが入っているフォルダ(`.png`、`.jpg`、`.tif`)。 + +--- + +## Step 1 – 必要なモジュールのインストールとインポート + +まず、OCR パッケージが利用可能か確認してください。実際のライブラリ(例: `pytesseract`)を使う場合はインポート文を置き換えます。 + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **重要性:** `os` をインポートするとクロスプラットフォームのパス操作が可能になり、`typing.List` は IDE の補完や将来の拡張性に役立ちます。 + +--- + +## Step 2 – **Extract Text from Images**: OCR エンジンの初期化 + +エンジンを作成することが OCR 作業の第一歩です。言語は自動検出に設定し、混在言語の文書にも対応できるようにします。 + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **解説:** エンジン生成を関数に切り出すことでコードをモジュール化しています。後で DPI や OCR モードを変更したい場合は、この関数だけを修正すれば済みます。 + +--- + +## Step 3 – **List Image Files Python**: ディレクトリからファイルを取得 + +次に、処理対象となるすべての画像を見つける必要があります。以下のリスト内包表記は一般的な **list image files python** パターンを模倣しています。 + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **エッジケース処理:** この関数はサブフォルダを無視します(必要なら再帰処理を追加可能)し、隠しファイルは自動的に除外されます。隠しファイルは通常、サポート対象の拡張子で終わらないためです。 + +--- + +## Step 4 – **Convert Scanned Images to Text**: バッチ OCR の実行 + +多くの OCR ライブラリはバッチメソッドを提供しており、1枚ずつ処理するよりもはるかに高速です。以下が呼び出し例です。 + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **なぜバッチ処理か?** すべての画像を一度に送ることで、OCR モデルのロードオーバーヘッドが削減され、CPU/GPU の利用効率が向上します。 + +--- + +## Step 5 – **Recognize Text from Pictures**: 結果の表示 + +最後に、ファイル名と OCR 結果をペアにしてイテレートし、各画像ごとに見やすいヘッダーを出力します。 + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **ヒント:** `strip()` は OCR が付与しがちな前後の空白を除去します。 + +--- + +## 完全スクリプト – すべてをまとめる + +以下が実行可能な完全プログラムです。`batch_ocr.py` として保存し、`python batch_ocr.py ` で実行してください。 + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### 期待される出力 + +フォルダに `invoice1.png` と `receipt.jpg` があると仮定すると、次のような出力が得られます。 + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +各ブロックは明確にラベル付けされているため、データベースへの保存など、下流処理がシンプルになります。 + +--- + +## よくある落とし穴の対処法 + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **No text appears** | OCR の言語が検出されない、または画像のコントラストが低すぎる。 | 言語を強制指定(`engine.language = ocr.Language.English`)するか、画像のコントラストを上げて前処理する。 | +| **Memory error on large batches** | エンジンがすべての画像を一度に読み込もうとする。 | `image_files` をチャンクに分割(例: `batch_size = 20`)し、`recognize_batch` を複数回呼び出す。 | +| **Unsupported file format** | `.gif` や `.bmp` を追加した。 | `supported_exts` タプルに拡張子を追加するか、事前に PNG/JPG に変換する。 | +| **Unicode garbling** | OCR がバイト列を返している。 | OCR ライブラリが Unicode を出力するように設定(必要なら `result.text.decode('utf‑8')`)する。 | + +--- + +## ワークフローの拡張 + +**画像からテキストを抽出**できたので、次のステップを検討してください。 + +- **CSV へのエクスポート** – ファイル名と抽出テキストをスプレッドシートに書き出し、分析に活用。 +- **並列処理** – `concurrent.futures.ThreadPoolExecutor` を使って複数バッチを同時に処理。 +- **クラウド OCR との統合** – ローカルエンジンを Google Vision や Azure OCR に置き換えて、複雑なレイアウトでも高精度に。 +- **画像前処理の追加** – Pillow や OpenCV で画像の傾き補正、ノイズ除去、二値化を行い、OCR 精度を向上。 + +これらのアイデアはすべて、ここで構築したコア関数をそのまま利用できるため、ゼロから始める必要はありません。 + +--- + +## 結論 + +Python で **画像からテキストを抽出**するための完全なソリューションを一通り解説しました。**list image files python** から **recognize text from pictures**、そして **convert scanned images to text** までをバッチ処理で実装し、シンプルながら拡張性の高いスクリプトが完成しました。領収書のデジタル化、検索可能なアーカイブ構築、データ抽出パイプラインの構築など、さまざまなプロジェクトの土台として活用できます。 + +ぜひ実行してみて、前処理を調整しながら OCR 精度の向上を体感してください。問題が発生したら「よくある落とし穴」表を参照すれば、ほとんどのケースは小さな設定変更で解決できます。 + +次のチャレンジはどうですか?`pdf2image` を使って PDF を画像に変換し、同じパイプラインに流し込んでみましょう。OCR と Python の豊富なエコシステムを組み合わせれば、可能性は無限です。 + +Happy coding, and may your text be ever legible! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全なコード例とステップバイステップの解説が含まれており、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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/japanese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..6e249d0ed --- /dev/null +++ b/ocr/japanese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR を使用して画像からテキストを抽出します。自動言語検出、並列処理、バッチ認識を簡潔なチュートリアルで学びましょう。 +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: ja +og_description: Python OCRで画像からテキストを抽出します。このガイドでは、自動言語検出、並列処理、バッチ認識を1つのチュートリアルで紹介しています。 +og_title: Pythonで画像からテキストを抽出する – 完全OCRガイド +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Pythonで画像からテキストを抽出する – 完全OCRガイド +url: /ja/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonで画像からテキストを抽出 – 完全OCRガイド + +画像の文字を手で入力せずに **画像からテキストを抽出** できたらと思ったことはありませんか? あなただけではありません。古いレシートをデジタル化したり、検索可能な文書アーカイブを構築したり、単にクールなAIトリックで遊んだりする場合でも、画像から文字を取り出す能力は、今日のPython開発者にとって必須のスキルです。 + +このチュートリアルでは、人気のOCRエンジンを使って **画像からテキストを抽出** する、実行可能な完全なサンプルを順に解説します。自動言語検出、速度向上のための並列処理、バッチ画像認識をカバーし、数十ファイルを数秒で処理できるようにします。必要な内容ですか? それでは始めましょう。 + +## 学べること + +- `ocr.OcrEngine` で OCR エンジンをインスタンス化する方法 +- **自動言語検出** を有効にして、エンジンが自動で適切な言語を選択する方法 +- カスタムスレッドプールで **並列処理 OCR** を設定する方法 +- ファイルリストに対して **バッチ画像認識** を実行する方法 +- 各画像の認識結果テキストを出力し、保存やインデックス作成に利用できる形で表示する方法 + +外部ドキュメントは不要です。必要なものはすべてここにあり、`ocr` パッケージ(`pip install ocr` でインストール)だけで動作します。 + +## 前提条件 + +開始する前に、以下が揃っていることを確認してください。 + +1. Python 3.8 以降がインストールされていること。 +2. `ocr` パッケージ(`pip install ocr`)。 +3. 処理したい PNG(または JPG)画像が入ったフォルダー。 +4. Python の関数とループに関する基本的な知識。 + +以上です—重い依存関係も GPU も不要で、純粋な Python だけです。 + +![画像からテキストを抽出する例](https://example.com/ocr-demo.png "画像からテキストを抽出する出力のスクリーンショット") + +*Alt text: 画像からテキストを抽出するデモスクリーンショット* + +## Step 1 – OCR エンジンのセットアップ(Primary Keyword in Action) + +まず最初に OCR エンジンのインスタンスを作成します。`ocr.OcrEngine()` は操作の中枢で、文字・行・段落を読む方法を知っています。 + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +なぜ明示的にエンジンが必要なのか? **ocr.OcrEngine の使用** により、言語設定やスレッド管理などを細かく制御できるからです。ワンライナーのヘルパーに比べ、**画像からテキストを抽出** する最も柔軟な方法です。 + +## Step 2 – エンジンに自動言語検出を任せる + +多くの OCR ライブラリは対象言語を手動で指定する必要があります。単一言語のプロジェクトでは問題ありませんが、混在言語のバッチ処理では面倒です。幸い、`ocr` パッケージは **自動言語検出** をサポートしています。 + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +`engine.language` に `ocr.Language.Auto` を設定すると、エンジンは各画像を解析して適切な言語モデルを自動で選択します。この一行で、国際文書を扱う際の手動設定作業を何時間も削減できます。 + +## Step 3 – 並列処理 OCR で速度アップ + +CPU コアが4つ以上あるなら、活用しませんか? エンジンはスレッドプールを立ち上げ、複数画像を同時に処理できます。ここが **並列処理 OCR** の威力です。 + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +マシンに合わせて `4` の数値は自由に調整してください。スレッド数を増やすほどバッチ実行は速くなりますが、各スレッドはメモリを消費するので、環境に合ったバランスを見つけましょう。 + +## Step 4 – 処理したい画像を集める + +次にファイルパスのリストが必要です。手動で作成したり、CSV から読み込んだり、`glob` を使ったりできます。ここでは簡潔さのためにハードコードした短いリストを示します。 + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +`YOUR_DIRECTORY` を実際のパスに置き換えてください。数十ファイルがある場合は、`glob.glob("*.png")` で一括取得できます。 + +## Step 5 – バッチ画像認識を実行 + +チュートリアルの核心です。`files` に含まれるすべての画像を処理し、結果オブジェクトのリストを返す単一呼び出しです。これが **バッチ画像認識** 機能で、大規模 OCR を実用的にします。 + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +内部では、先ほど設定した4つのワーカースレッドに各ファイルが分配され、同時に自動言語検出も行われます。メソッドは、認識されたテキストとメタデータを保持した要素のリストを返します。 + +## Step 6 – 抽出したテキストを出力(または保存) + +最後に結果をループしてテキストを出力します。実際のプロジェクトではデータベースや CSV に書き込むことが多いですが、ここではシンプルにコンソールへ表示します。 + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**期待される出力**(簡略化): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +各ブロックはファイル名と OCR で取得した文字列を示します。画像に複数言語が混在している場合は、前述の **自動言語検出** ステップのおかげで適切な文字が表示されます。 + +## プロのコツ & よくある落とし穴 + +- **画像品質が重要** – ぼやけた画像やコントラストが低い画像はゴミデータになります。必要に応じて OpenCV(`cv2.threshold`、`cv2.resize`)で前処理してください。 +- **スレッド数 vs I/O** – 画像が遅いネットワークドライブ上にある場合、スレッドを増やしても効果が薄いことがあります。`top` や `Task Manager` で CPU 使用率を監視しましょう。 +- **Unicode の取り扱い** – `result.text` は Unicode 文字列です。ファイルに書き込む際は `encoding="utf-8"` で開き、`UnicodeEncodeError` を回避してください。 +- **メモリ使用量** – 大きな PDF を処理すると RAM を大量に消費します。`MemoryError` が出たらスレッドプールサイズを減らすか、画像を小さなチャンクに分割して処理してください。 + +## 完全動作スクリプト + +以下は、ここまで説明したすべての手順を組み込んだ、コピー&ペースト可能なスクリプトです。`batch_ocr.py` として保存し、`python batch_ocr.py` を実行してください。 + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +実行例: + +```bash +python batch_ocr.py ./my_images 4 +``` + +各画像に対して整形されたテキストブロックが表示され、**画像からテキストを抽出** がスケールで可能であることが証明されます。 + +## 次にやるべきこと + +Python で **画像からテキストを抽出** する基本をマスターしたら、以下のテーマを検討してみてください。 + +- **ポストプロセッシング**: 正規表現や自然言語処理ライブラリで OCR 出力をクリーンアップ +- **PDF 変換**: 抽出した文字列を PDF ジェネレータに渡し、検索可能な PDF を作成 +- **クラウド OCR サービス**: オンプレミスの `ocr` 結果を Google Vision や Azure OCR と比較し、エッジケースの精度を検証 +- **GUI フロントエンド**: 小さな Flask や FastAPI アプリを作り、ユーザーが画像をアップロードして即座にテキストを取得できるようにする + +これらすべてが、今回構築した **Python OCR ライブラリ** の基盤と、ここで使った **並列処理 OCR** のテクニックから恩恵を受けます。 + +--- + +*Happy coding! If you hit any snags, drop a comment below—I'm always up for troubleshooting OCR quirks.* + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を応用した関連トピックを扱っています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/japanese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..b8a321d55 --- /dev/null +++ b/ocr/japanese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-19 +description: PythonでOCRを使用してPDFを抽出する方法 – PDFからテキストを抽出し、画像からテキストを認識し、OCRのPython例を含むステップバイステップチュートリアル。 +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: ja +og_description: PythonでOCRを使用してPDFを抽出する方法。PDFからテキストを抽出し、画像から文字を認識し、完全なOCR Python例をご覧ください。 +og_title: PythonでOCRを使ってPDFテキストを抽出する方法 – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: PythonでOCRを使ってPDFテキストを抽出する方法 – 完全ガイド +url: /ja/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PythonでOCRを使用してPDFテキストを抽出する方法 – 完全ガイド + +スキャン画像だけのPDFから**PDFを抽出する方法**を考えたことがありますか? あなただけではありません。実際のプロジェクトでは、契約書、請求書、歴史的アーカイブなど、受け取ったPDFに選択可能なテキストがないことがよくあります。良いニュースは、数行のPythonコードで画像のみのページを検索可能で編集可能なテキストに変換できることです。 + +このチュートリアルでは、PDFを読み取り、最初のページを画像としてレンダリングし、OCRエンジンを使用して**PDFからテキストを抽出**する実用的な**OCR Python example**を順に解説します。最後まで読むと、**OCRでPDFを読む**方法、各ステップの重要性、マルチページ文書や異なる言語へのコードの適応方法が正確に分かります。 + +## 学べること + +- 信頼できるOCRライブラリをPythonにインストールし設定する方法。 +- OCRに適した画像へPDFページを変換する方法。 +- **画像からテキストを認識**し、クリーンなUnicode文字列を取得する方法。 +- よくある落とし穴(低解像度PDF、回転ページ)と回避策。 +- スクリプトを拡張して複数ページやバッチ処理に対応させる方法。 + +**Prerequisites**: Python 3.8以上、pip、仮想環境の基本的な理解。OCRの事前経験は不要です—手順に従うだけです。 + +--- + +## ## PythonでOCRを使用してPDFテキストを抽出する方法 + +このH2ヘッダーは、検索エンジンが好む主要キーワードをちょうどそこに入れています。さっそくコードに入りましょう。 + +### Step 1 – 必要なパッケージをインストール + +まず、OCRエンジンが必要です。以下の例では、Tesseract の薄いラッパーである人気の **ocr** パッケージを使用しています。別のバックエンドを好む場合でも、概念は同じです。 + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro tip:** Linux では Tesseract バイナリも必要です: `sudo apt-get install tesseract-ocr`。macOS ユーザーは Homebrew で取得できます: `brew install tesseract`。 + +### Step 2 – OCRエンジンを初期化し言語を設定 + +エンジンを起動し、英字文字を対象にするよう指示します。`ocr.Language.English` を任意のサポート言語コードに置き換えることができます。 + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Why this matters:** 言語を指定すると、エンジンが言語固有の辞書や文字モデルを適用できるため、精度が劇的に向上します。 + +### Step 3 – PDFページを画像として読み込む + +OCR はラスタ画像で動作し、PDF オブジェクトでは動作しません。`ocr.Image.from_pdf` ヘルパーは選択したページをビットマップにレンダリングします。他のページを処理する場合は `page_number` を調整してください(0 ベースインデックス)。 + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** PDF にベクターグラフィックが含まれている場合、鮮明なレンダリングが得られることがあります。低解像度スキャンの場合は DPI を上げてください: `ocr.Image.from_pdf(..., dpi=300)`。 + +### Step 4 – レンダリングされた画像からテキストを認識 + +ここが **ocr python example** の核心です。エンジンがビットマップを処理し、抽出された文字列を含むオブジェクトを返します。 + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +`ocr_result.text` 属性にプレーンテキスト出力が格納され、可能な限り改行が保持されます。 + +### Step 5 – 抽出したテキストを表示または保存 + +最後に結果を出力します。実際のアプリケーションではファイルやデータベースに書き込むことが多いでしょう。 + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +スクリプトを実行すると、次のような出力が表示されます: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +これが OCR を使用した **extract text from pdf** ワークフローの全体です。 + +--- + +## ## 画像からテキストを認識 – 精度調整 + +**画像からテキストを認識**(例: レシートの JPEG)のみが目的の場合、PDF 変換ステップをスキップできます: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips for better results:** + +- **Pre‑process** 画像: グレースケールに変換し、しきい値処理やデスケューを行う。Pillow で簡単に実装可能です。 +- PDF レンダリング時に **DPI を上げる**: 高解像度ほど OCR エンジンに詳細が提供されます。 +- OCR エンジンのページ分割設定を有効にする: `ocr_engine.config = "--psm 6"`(均一ブロック用)。 + +--- + +## ## OCRでPDFを読む – 複数ページの処理 + +多くの契約書は数ページにわたります。各ページをループ処理するのは簡単です: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +この関数は **read PDF with OCR** を実行し、出力を連結して明確なページ区切りマーカーを挿入します。その後 `full_text` を検索インデックスに投入したり、`.txt` ファイルとして保存したりできます。 + +--- + +## ## よくある落とし穴と対策 + +| 症状 | 考えられる原因 | 対策 | +|---------|--------------|-----| +| 文字化け、`?` が多数 | 言語設定が間違っている、または言語データファイルが欠如している | 正しいTesseract言語パック(`tesseract-ocr-`)をインストールし、`ocr_engine.language` を設定する。 | +| 行が欠落または単語が切り捨てられる | DPIが低い(150未満) | PDFを300 DPI以上でレンダリングする(`dpi=300`)。 | +| テキストが回転または逆さま | スキャンページが正しくない向き | 認識前に `ocr.Image.deskew(page_image)` を使用する。 | +| 大きなPDFで処理が遅い | ページを単一スレッドで順次処理している | `concurrent.futures.ThreadPoolExecutor` で並列化する。 | + +--- + +## ## OCR Python Example の拡張 + +- **Export to PDF/A**: 抽出後、`reportlab` や `pypdf2` を使ってテキストを検索可能な PDF に埋め込めます。 +- **Language detection**: OCR 出力に `langdetect` を使用し、`ocr_engine.language` を動的に切り替えます。 +- **Batch processing**: `os.listdir` でディレクトリを走査し、`extract_all_pages` をすべてのファイルに適用します。 + +--- + +## ## 期待される出力と検証 + +クリアな英語スキャンに対してスクリプトを実行すると、適切な句読点が付いたクリーンなテキストブロックが得られるはずです。検証手順: + +1. 数行を元のスキャン画像と比較する。 +2. 簡単な単語数カウント (`len(ocr_result.text.split())`) を実行し、出力が空でないことを確認する。 +3. 必要に応じて `pyspellchecker` などのスペルチェッカーに結果を渡し、OCR エラーを検出する。 + +--- + +## Conclusion + +従来のパースが失敗するケースで**PDFを抽出する方法**をカバーし、完全な **ocr python example** を実演し、**画像からテキストを認識** と **OCRでPDFを読む** を単一ページ・マルチページシナリオの両方で説明しました。上記のコードスニペットを使えば、スキャンされた PDF を検索可能で編集可能なテキストに変換でき、手動での再入力は不要です。 + +次のステップは? 言語をスペイン語(`ocr.Language.Spanish`)に変更したり、画像前処理技術を試して精度を向上させたりしてください。ドキュメント管理システムを構築している場合は、抽出テキストを Elasticsearch にインデックス化して超高速検索を実現しましょう。 + +質問や変わった PDF に遭遇したらコメントを残してください。Happy coding! + +![PythonでOCRを使用してPDFを抽出する方法](image.png "PythonでOCRを使用してPDFを抽出する方法") + + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示した手法を基にした関連トピックを扱っています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得したり、独自プロジェクトで代替実装アプローチを探求したりするのに役立ちます。 + +- [Aspose OCRで画像からテキストを抽出 – ステップバイステップガイド](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [PDFテキストを認識 – Aspose.OCR for JavaによるOCR操作](/ocr/english/java/ocr-operations/) +- [Aspose.OCRを使用したC#での画像テキスト抽出(言語選択)](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/japanese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..879267e19 --- /dev/null +++ b/ocr/japanese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-06-19 +description: Aspose を使って Java で OCR を利用する方法を学びましょう。このステップバイステップガイドでは、画像の自動デスキュー、言語の自動検出、テキスト抽出を簡単に行う方法をカバーしています。 +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: ja +og_description: Asposeを使用したJavaでのOCRの使い方:画像の自動デスキュー、言語の自動検出、画像からテキスト抽出を網羅した完全ガイド +og_title: Aspose を使用した Java の OCR の使い方 – 完全ガイド +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Aspose を使って Java で OCR を利用する方法 – 完全ガイド +url: /ja/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# JavaでAsposeを使用したOCRの使い方 – 完全ガイド + +Javaプロジェクトで設定に頭を抱えずに **OCRの使い方** を知りたくありませんか? あなただけではありません。ソースのスキャンが歪んでいたり、未知の言語で書かれていたりすると、特に **画像からテキストを抽出** する必要があるときに、多くの開発者が壁にぶつかります。 + +このチュートリアルでは、Asposeを使用したOCRの具体的な使い方をハンズオンで示します。**auto deskew images**、**auto language detection**、そして完全な **ocr image preprocessing** パイプラインを含みます。最後まで読むと、認識されたテキストをコンソールに出力する実行可能なコードスニペットが手に入り、各設定がなぜ重要かが理解できるようになります。 + +> **得られるもの:** 完全な実行可能Javaプログラム、各行の解説、エッジケースへの対処ヒント、バッチ処理やPDFへの拡張アイデア。 + +--- + +## 前提条件 + +- Java 17(または任意の最新JDK)がインストールされ、設定されていること。 +- 依存関係管理のためのMavenまたはGradle(Mavenの座標を示します)。 +- Aspose OCR for Java のライセンスファイル(`Aspose.OCR.Java.lic`)。テストだけの場合はライセンス手順を省略できますが、無料トライアルは透かしが入ります。 +- サンプル画像(`your_image.png`)をコードからアクセス可能な場所に配置すること。 + +> **プロのコツ:** 画像は専用の `resources` フォルダーに入れ、クラスパス経由でロードしましょう。これにより、OS間のパス関連の問題を回避できます。 + +## 手順 1: プロジェクトのセットアップと Aspose OCR 依存関係の追加 + +新しいMavenプロジェクトを作成(または既存のものを使用)し、`pom.xml` に以下を追加します。 + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn clean install` を実行してライブラリを取得します。Gradleを使用する場合は、同等のコマンドは次のとおりです。 + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +これでクラスパスに **ocr image preprocessing** クラスが追加されました。 + +## 手順 2: Aspose OCR ライセンスの適用(任意だが推奨) + +ライセンスを所有している場合は、`main` メソッドの冒頭で適用してください。この手順を省略しても動作しますが、無料版は出力に「Demo」透かしを付加します。 + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **重要な理由:** ライセンス版は使用制限を解除し、透かしを無効にするため、クリーンで本番環境向けの結果が得られます。 + +## 手順 3: OCR エンジンインスタンスの作成 + +エンジンはプロセスの中心です。インスタンス化することで、すべての **ocr image preprocessing** オプションにアクセスできます。 + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +この時点でエンジンは準備完了ですが、デフォルト設定はスキャン文書には最適でない場合があります。いくつか調整しましょう。 + +## 手順 4: Auto Deskew Images を有効にしてスキャンをクリアにする + +傾いたスキャンは一般的な問題です。Asposeは認識前に画像を自動で水平にする **auto deskew images** 機能を提供します。 + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **動作概要:** アルゴリズムはテキストのベースライン角度を解析し、最も確からしい正立方向に画像を回転させます。これにより、スマートフォンで撮影した写真の精度が大幅に向上します。 + +## 手順 5: Auto Language Detection を有効にする + +ソース画像の言語が不明な場合は、エンジンに自動で判別させましょう。これが **auto language detection** 設定です。 + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +これを有効にすると、Asposeは文字形状をスキャンし、最も可能性の高い言語モデルを選択します。標準で30以上の言語をサポートしています。 + +## 手順 6: 認識したい画像をロードする + +画像はディスク、URL、またはバイト配列からロードできます。簡単のため、ローカルファイルから読み込みます。 + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **ヒント:** 大きな画像を扱う場合は、`engine.getImagePreprocessing().setResizeFactor(0.5)` で先にダウンサンプリングすると、詳細をほとんど失わずに処理速度が向上します。 + +## 手順 7: OCR 認識を実行し、画像からテキストを抽出する + +これでエンジンが処理を行います。`recognize` メソッドは認識されたテキストや信頼度スコアなどを含む `OcrResult` オブジェクトを返します。 + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +コンソールには画像から抽出されたプレーンテキストが表示されます。これが目指した核心の **extract text image** 結果です。 + +## 完全動作例 + +以下はすべてを結びつけた完全な Java クラスです。`src/main/java/com/example/OcrDemo.java` にコピー&ペーストして実行してください。 + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### 期待される出力 + +画像にクリーンなスキャンで “Hello World” というフレーズが含まれていれば、次のように表示されます。 + +``` +=== Recognized Text === +Hello World +``` + +より複雑な文書(例: 多言語レシート)の場合、出力には改行と検出された言語コードが含まれます。 + +## よくある落とし穴とプロのコツ + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **文字化け** | 画像が暗すぎるかノイズが多い。 | `engine.getImagePreprocessing().setBinarization(true)` を有効にするか、手動でコントラストを調整してください。 | +| **誤った言語** | 混在言語のページで自動検出が失敗する。 | `engine.setLanguage(Language.English)`(または適切な enum)を設定して特定の言語を強制してください。 | +| **処理が遅い** | 非常に高解像度の画像。 | `engine.getImagePreprocessing().setResizeFactor(0.5)` でダウンサンプルしてください。 | +| **メモリ不足エラー** | 大量の画像を一度にロードした場合。 | 画像を順次処理し、各実行後に `engine.dispose()` を呼び出してください。 | + +> **覚えておくべきこと:** OCR エンジンは読み取り専用操作に対してスレッドセーフですが、スレッドごとに新しいインスタンスを作成すると隠れた状態バグを回避できます。 + +## ソリューションの拡張 + +Asposeで **OCRの使い方** が分かったので、次のことを検討できるでしょう。 + +1. **PDFを処理する** – 各 PDF ページを画像(`PdfConverter`)に変換し、同じパイプラインに渡す。 +2. **フォルダーをバッチ処理** – ディレクトリ内のファイルをループし、同じ手順を適用して結果を CSV に書き出す。 +3. **Webサービスと統合** – マルチパートアップロードを受け付ける Spring Boot の `@RestController` を通じて OCR ロジックを公開する。 + +これらすべてのシナリオは、ここで構築した同じ **ocr image preprocessing** 設定を再利用します。 + +## 結論 + +Javaで Aspose を使用した **OCRの使い方** を最初から最後までカバーしました:ライセンスの適用、エンジンの作成、**auto deskew images** の有効化、**auto language detection** の有効化、画像のロード、そして最終的に `System.out.println` で **extract text image** を実行します。コードは完全に自己完結しており、最新の JDK で動作し、精度とパフォーマンスのベストプラクティスを示しています。 + +自分の画像(例えばスキャンした契約書やレシートのスクリーンショット)で試してみてください。前処理フラグを調整し、異なる言語で実験すれば、Aspose の OCR ライブラリが本番レベルのテキスト抽出に最適な選択肢である理由がすぐに分かります。 + +質問や結果の共有があれば、下のコメント欄に書くか、GitHub で私にメッセージしてください。コーディングを楽しんで! + +--- + +![JavaでOCRを使用する例](/images/ocr-java-example.png "JavaでOCRを使用する方法 – Aspose デモスクリーンショット") + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説付きの完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [Aspose.OCR を使用した言語付き画像テキストの OCR 方法](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR の検出領域モードで画像からテキストを抽出(Java)](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [OCR の使い方 - Aspose.OCR for Java による高度なテクニック](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/japanese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..52da75a37 --- /dev/null +++ b/ocr/japanese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR を使用して Python で OCR の精度を向上させましょう。OCR 言語の設定方法、OCR 用に画像を読み込む方法、カスタム辞書を使用して画像からテキストを抽出する方法を学びます。 +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: ja +og_description: OCR言語を設定し、OCR用に画像を読み込み、カスタム辞書を使用して画像からテキストを抽出することで、PythonのOCR精度を向上させます。 +og_title: PythonでOCR精度を向上させる – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: PythonでOCR精度を向上させる – 完全ガイド +url: /ja/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python で OCR 精度を向上させる – 完全ガイド + +スキャンしたテキストに奇妙な記号や製品コード、ブランド名が含まれているとき、**OCR 精度を向上させる** 方法を考えたことはありませんか? あなたは一人ではありません。多くのプロジェクトでデフォルトエンジンは意味不明な文字列を出力し、生産性を大きく低下させます。 + +このチュートリアルでは、実践的なエンドツーエンドの例を通じて、**OCR 言語の設定**、**画像の読み込み**、**画像に対する OCR の実行**、そして認識率を高めるカスタム辞書を用いた **画像からテキストを抽出** の手順を解説します。最後まで読めば、任意の Python コードベースにすぐ組み込めるスクリプトが手に入ります。 + +## 学べること + +- Aspose OCR を使用して PNG ファイルを読み取る完全動作する Python スクリプト +- 言語設定とカスタム単語リストで **OCR 精度を向上させる** 方法 +- 各設定が重要な理由の明確な説明と、ラテン文字以外の文字に対する対処法のヒント +- 一般的な OCR の落とし穴をトラブルシューティングするための簡易チェックリスト + +### 前提条件 + +- Python 3.8 以上がインストールされていること +- `aspose-ocr` パッケージ(`pip install aspose-ocr` でインストール) +- 読み取り対象のテキストが含まれるサンプル画像(`technical_doc.png`) +- Python の基本的な知識 – 特別なスキルは不要です + +> **プロのコツ:** 仮想環境で作業している場合は、パッケージをインストールする前に環境をアクティベートしてください。依存関係が整理され、バージョン衝突を防げます。 + +--- + +## 手順 1: Aspose OCR をインストールしてインポート + +まずはライブラリを環境に導入し、必要な要素をインポートします。 + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr` 名前空間から `OcrEngine` クラスにアクセスでき、これが OCR プロセスの中心です。ここでインポートしておくことで、スクリプト全体がすっきり読みやすくなります。 + +--- + +## 手順 2: OCR エンジンを作成し **OCR 言語を設定** + +言語が重要なのはなぜでしょうか? OCR エンジンは言語固有のモデルを使って文字形状や単語パターンを認識します。英語テキストをスキャンすると伝えると、キリル文字は無視され、ラテン文字に集中するため、**OCR 精度が大幅に向上**します。 + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **注:** Aspose OCR は 50 以上の言語に対応しています。ドキュメントが英語でない場合は `ocr.Language.English` を `ocr.Language.Spanish`、`ocr.Language.French` などに置き換えてください。 + +--- + +## 手順 3: **カスタム辞書** を定義して精度をブースト + +請求書に「AsposeOCR」や「SKU12345」のような製品コードが含まれていると想像してください。エンジンはこれらの語を知らないため誤認識します。カスタム単語リストを提供すると、エンジンに対して「これらは正しい文字列なので修正しないで」と指示できます。これが **OCR 精度を向上させる** 簡単な方法です。 + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +エントリが数百件ある場合はファイルやデータベースから読み込んでも構いませんが、ここではシンプルに Python のリストに保持しています。 + +--- + +## 手順 4: **画像を OCR 用に読み込む** + +次に画像が必要です。`Image.load` メソッドは PNG、JPEG、BMP などのサポートされているラスタ形式のパスを受け取ります。ファイルが見つからないと例外がスローされるため、例外処理で保護します。 + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **このステップが重要な理由:** 画像を正しく読み込むことで、エンジンは意図したピクセルデータに基づいて解析できます。破損したファイルやパスミスはフラストレーションの原因となります。 + +--- + +## 手順 5: **画像に対して OCR を実行** し結果を取得 + +エンジンの設定と画像の準備が整ったら、認識はたった一つのメソッド呼び出しで完了します。結果オブジェクトには生テキスト、信頼度スコア、必要に応じてレイアウト情報も含まれます。 + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +画像から **テキストを抽出** したい場合は、改行文字で分割すれば行単位で取得できます。 + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## 手順 6: 出力を検証 – 本当に **OCR 精度が向上** したか? + +結果を出力して、カスタム辞書が効果を発揮したか確認しましょう。 + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +サンプル画像に対する典型的な出力例は次のようになります。 + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +ブランド名、ギリシャ文字、製品コードが定義どおりに表示されていることに注目してください。カスタム辞書がなければ、エンジンは「Aspose OCR」や「SKU 1234」のように「修正」しようとしてしまいます。 + +--- + +## よくある落とし穴と対処法 + +| 問題 | 発生理由 | 対策 | +|------|----------|------| +| **文字化け** | 言語設定が間違っている、または解像度が低い画像 | `engine.language` がソース言語と一致しているか確認し、300 dpi 以上の高解像度でスキャンする | +| **カスタム単語が無視される** | 辞書がエンジンに紐付いていない、またはプロパティ名のタイプミス | `engine.text_processing.custom_dictionary = …` を再確認 | +| **ファイルが見つからない** | パスが誤っている、またはアクセス権が不足している | `os.path.abspath()` で絶対パスを確認し、適切な権限でスクリプトを実行 | +| **処理が遅い** | 画像が大きすぎる、ページ数が多い | 画像を事前にトリミング・リサイズするか、`engine.recognize(image, max_threads=4)` で並列化 | + +--- + +## さらに踏み込む: **OCR 精度を向上** させる高度な調整 + +1. **前処理** – Pillow でコントラスト強調や二値化を行ってから Aspose OCR に渡す +2. **複数言語** – `engine.language = ocr.Language.English | ocr.Language.French` でバイリンガル認識を有効化 +3. **領域限定 OCR** – テーブルなど特定エリアだけが必要な場合は、先に画像をトリミングしてノイズを減らす +4. **信頼度フィルタ** – `result.confidence` で文字ごとのスコアが取得できるので、低信頼度の結果はプログラムで除外可能 + +--- + +## 完全動作スクリプト + +以下は本チュートリアルで説明したすべての手順を組み込んだ、コピー&ペースト可能なスクリプトです。`improve_ocr_accuracy.py` として保存し、コマンドラインから実行してください。 + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +実行例: + +```bash +python improve_ocr_accuracy.py +``` + +先ほど示した整形済みの出力が表示されるはずです。 + +--- + +## 結論 + +本稿では、Python で **OCR 精度を向上** させるシンプルな手順を次のようにまとめました。 + +1. ドキュメントに合わせて **OCR 言語を設定** +2. エンジンが正しいピクセルを認識できるよう **画像を正しく読み込む** +3. **画像に対して OCR を実行** し、1 行のメソッド呼び出しで結果を取得 +4. **画像からテキストを抽出** し、結果を検証 +5. ドメイン固有の用語を固定する **カスタム辞書** を追加 + +これで、未加工の画像からクリーンで検索可能なテキストへ変換するワークフローが完成です。次のステップとして、画像前処理(コントラスト調整、デスケュー)に挑戦したり、`ocr.Language.English | ocr.Language.German` のように多言語設定に切り替えてみてください。同じ原則で **OCR 精度を向上** させ続けられます。 + +質問や特殊ケースがあればコメントで教えてください。Happy coding! + +![improve OCR accuracy + + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全動作コード例が含まれており、API の追加機能を習得したり、別の実装アプローチを自分のプロジェクトに取り入れるのに役立ちます。 + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/japanese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..f37d281b7 --- /dev/null +++ b/ocr/japanese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-19 +description: Python の OCR ライブラリを使用して画像で OCR を実行します。画像からテキストを検出し、JPEG からテキストを認識し、スキャンした画像からテキストを効率的に抽出する方法を学びましょう。 +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: ja +og_description: Pythonで画像のOCRを実行し、スキャンしたファイルからテキストを抽出します。このガイドでは、画像の読み込み、傾き補正、テキスト認識をステップバイステップで解説します。 +og_title: Pythonで画像のOCRを実行する – 完全テキスト抽出ガイド +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Pythonで画像のOCRを実行する – 完全テキスト抽出ガイド +url: /ja/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python で画像の OCR を実行する – 完全テキスト抽出ガイド + +画像ファイルに対して **OCR を実行** したいけど、コードが暗号のようで壁にぶつかっていませんか? あなただけではありません。スキャンした領収書の山を検索可能な PDF に変換したり、データサイエンスプロジェクトのために JPEG からキャプションを抽出したりする際、JPEG などのフォーマットからテキストを認識できることは、今日の開発者にとって必須スキルです。 + +このチュートリアルでは、**画像からテキストを検出** し、**スキャン画像からテキストを抽出** し、さらに **OCR 用に画像をロード** する方法を、数行のコードで実演する完全な実行可能サンプルを順を追って解説します。最後まで読めば、インポート忘れや「ドキュメント参照」的な曖昧さのない、実運用可能なスニペットを自分のプロジェクトにすぐ組み込めます。 + +## 作成するもの + +- OCR エンジンを作成し、auto‑deskew を有効化し、JPEG(または任意のサポート形式)をロードして認識結果を出力する小さな Python スクリプト +- 各設定が **なぜ** 必要かを説明する解説(**どうやって** だけでなく) +- マルチページ PDF、非英語言語、ぼやけたスキャンなどの一般的な落とし穴への対処法 + +### 前提条件 + +- Python 3.8+ がインストール済み(例では `pip install ocr-lib` で入手できる `ocr` パッケージを使用しています – 実際のライブラリ名に置き換えてください) +- Python の関数と仮想環境に関する基本的な知識 +- 処理したい画像ファイル(JPEG、PNG、TIFF)。ここでは `skewed_page.jpg` を例として使用します + +> **プロのコツ:** Windows 環境で OCR ライブラリをインストールする際は、権限の問題を回避するためにターミナルを管理者として実行してください。 + +--- + +## Perform OCR on Image – Setup and Configuration + +最初に必要なのは、クリーンな OCR エンジンインスタンスです。これは処理全体の「脳」に相当し、適切に構成しなければ、どんなに鮮明な画像でも意味不明な文字列が返ってきます。 + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**重要性:** +`engine.language` を設定すると、OCR エンジンが期待する文字セットが絞り込まれ、精度が大幅に向上します。この設定を省略すると、エンジンは推測に頼り、単純な単語すら誤認識しがちです。 + +--- + +## Enable Automatic Deskew – Fix Tilted Scans + +スキャンしたページはほとんどが完全に平坦ではありません。わずかな傾きでも文字の分割が乱れ、「Hello」が「H3llo」になることがあります。`auto_deskew` フラグはこの処理を自動で行います。 + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**エッジケース:** 画像がすでに真っ直ぐであることが分かっている場合、デスクューを無効にすると数ミリ秒の処理時間短縮が期待できます – 大量ページをバッチ処理する際に有用です。 + +--- + +## Load Image for OCR – Supporting JPEG, PNG, TIFF + +ここで実際に **OCR 用に画像をロード** します。`ocr.Image.load` メソッドは柔軟で、サポートされているラスタ形式へのパスを受け取ります。 + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **このステップが重要な理由:** ライブラリはファイルを内部ビットマップに読み込み、必要に応じてカラースペース変換を行います。生のバイトストリームを直接渡すと `FileNotFoundError` が発生するか、最悪の場合空の結果が黙って返ります。 + +**JPEG からテキストを認識** したい場合は、拡張子が `.jpeg` または `.jpg` であることを確認してください。同じ呼び出しで PNG(`.png`)や TIFF(`.tif`)も問題なく扱えます。 + +--- + +## Perform OCR on Image – Running the Engine + +エンジンが準備でき、画像がメモリ上にある状態で、いよいよ **画像に対して OCR を実行** します。この一行で前処理、セグメンテーション、分類、テキスト組み立てが行われます。 + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**内部で何が起きているか?** +- デスクューが有効なら変換を適用 +- ニューラルネットワークまたは Tesseract バックエンドで文字を識別 +- 文字を単語・行に結合し、リッチな `result` オブジェクトを返す + +--- + +## Extract Text from Scanned Image – Output the Results + +最後に **スキャン画像からテキストを抽出** し、結果を表示します。`result.text` 属性にプレーンテキストが格納されています。 + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +典型的な出力例: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +OCR エンジンが文字を検出できなかった場合、`result.text` は空文字列になります。その際は画像品質を再確認するか、`engine.confidence_threshold`(ライブラリがサポートしていれば)を調整してください。 + +--- + +## Handling Common Variations + +### Recognize Text from JPEG vs PNG + +両形式ともサポートされていますが、JPEG の圧縮アーティファクトがエンジンを混乱させることがあります。誤認識が頻発する場合は、まず JPEG を PNG に変換してみてください。 + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detect Text from Image with Multiple Languages + +文書に英語とスペイン語が混在している場合は、多言語モードを設定します。 + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +これにより、認識時に両方のアルファベットが考慮されます。 + +### Extract Text from Scanned PDFs + +PDF の場合は、まず各ページを画像にラスタライズする必要があります。`pdf2image` などのライブラリを使えば簡単です。 + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Full Working Example + +以下は `ocr_demo.py` にコピペできる完全なスクリプトです。エラーハンドリングと実行時間測定用の小さなヘルパーが含まれています。 + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**期待される出力**(クリアなスキャンを想定): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Frequently Asked Questions + +**Q: ヘッドレスサーバーで実行できますか?** +A: もちろんです。ライブラリは GUI がなくても動作します。サーバーに必要なネイティブバイナリ(例: Tesseract)をインストールしておくだけです。 + +**Q: 画像がぼやけている場合は?** +A: `engine.recognize` の前にシャープ化フィルタを追加すると効果的です。多くの OCR ライブラリは `image_preprocessing.sharpen = True` を提供しているか、OpenCV の `cv2.GaussianBlur` を逆に使うことで実装できます。 + +**Q: バッチ処理はサポートされていますか?** +A: はい。ファイルパスのリストに対して `perform_ocr` をループで呼び出すだけで対応できます。 + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/japanese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..d977183a6 --- /dev/null +++ b/ocr/japanese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR Java を使用して画像の OCR を実行します。OCR 用に画像を読み込む方法、Aspose ライセンスの使用方法、数分で画像からテキストを抽出する方法を学びましょう。 +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: ja +og_description: Aspose OCR Javaで画像のOCRを実行します。このガイドでは、Asposeライセンスの使用方法、OCR用に画像を読み込む方法、そして画像からテキストを効率的に抽出する方法を示します。 +og_title: Aspose OCR Javaで画像のOCRを実行する – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Aspose OCR Javaで画像のOCRを実行する – 完全ステップバイステップガイド +url: /ja/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Java で画像の OCR を実行する – 完全ステップバイステップガイド + +画像ファイルに **OCR を実行** したいけど、設定が多くて信頼できる結果が得られるライブラリが分からない…という経験はありませんか?実際のプロジェクトでは、パスポートのスキャン、請求書のデジタル化、スクリーンショットからのテキスト抽出など、画像データからテキストを素早く認識できることが大きな差別化要因になります。 + +このチュートリアルでは、Aspose OCR for Java を使って **画像の OCR を実行** するハンズオン例を詳しく解説します。Aspose ライセンスの適用方法から画像の読み込み、エンジンの実行、最終的に **画像からテキストを抽出** して下流処理に利用するまでを網羅します。余計な説明は省き、すぐにコピーペーストできる実装例をご提供します。 + +## 学べること + +- Java プロジェクトで **Aspose ライセンスを使用** する方法が明確に分かります。 +- **OCR 用に画像をロード** し、エンジンに言語自動検出させるための正確なコードが手に入ります。 +- **画像のテキストを認識** し、**画像からテキストを抽出** する手順を段階的に学べます。 +- 空結果、未対応フォーマット、メモリ問題といった一般的な落とし穴への対処法も紹介します。 + +> **前提条件** – Java 8 以上、依存管理のための Maven または Gradle、そして Aspose OCR for Java のライセンスファイル(評価モードでも実行可能)。 + +--- + +## Aspose OCR Java で画像の OCR を実行する方法 + +以下は、フロー全体を示す実行可能な Java プログラムです。`AsposeOcrDemo.java` という名前で保存し、IDE もしくはコマンドラインから実行してください。 + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### 期待されるコンソール出力 + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +ライセンスファイルがない状態で実行すると、最初の行に評価モードである旨が表示されますが、OCR 自体は動作します。 + +--- + +## Aspose ライセンスの設定と使用 + +### ライセンスが重要な理由 + +評価モードでもテストは可能ですが、出力に透かしが入ったり、1 回の実行で処理できるページ数が制限されたりします。**use aspose license** 手順を踏むことで、これらの制限が解除され、Aspose に対して有料ユーザーであることを示すことができます。 + +### ライセンスの取得と適用手順 + +1. Aspose ストアでライセンスを購入します。 +2. `Aspose.OCR.Java.lic` ファイルをダウンロードします。 +3. アプリケーションから参照できる場所(例: `src/main/resources` フォルダ)に配置します。 +4. 上記コードのように、OCR 処理を行う前に `new License().setLicense("Aspose.OCR.Java.lic");` を呼び出します。 + +> **プロのコツ**: サーバーにデプロイする場合は、`FileNotFoundException` を防ぐために絶対パスまたはクラスパスリソースローダーを使用してください。 + +--- + +## OCR 処理用に画像をロードする + +`Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` は **画像を OCR 用にロード** する中心的な行です。Aspose OCR は PNG、JPEG、BMP、TIFF だけでなく、Aspose.Pdf と組み合わせることでマルチページ PDF もサポートします。 + +### よくある落とし穴 + +| Issue | Symptom | Fix | +|-------|---------|-----| +| Wrong file path | `FileNotFoundException` | パスを再確認し、OS 非依存の区切り文字を使うために `Paths.get(...)` を利用してください。 | +| Unsupported format | `UnsupportedOperationException` | 画像を PNG または JPEG に変換してからロードしてください。 | +| Huge image ( > 10 MP) | Out‑of‑memory errors | `java.awt.Image` で画像を縮小してから Aspose に渡してください。 | + +--- + +## 画像からテキストを抽出し結果を処理する + +OCR エンジンが完了すると、`OcrResult` オブジェクトに認識された文字列が格納されます。ここで **画像からテキストを抽出** し、データベース保存や検索インデックスへの投入、下流の NLP パイプラインへの入力など、次の処理に渡します。 + +### 複数言語への対応 + +`engine.setLanguage(Language.Auto)` と設定しているため、Aspose は実行時に言語を自動検出します。事前に言語が分かっている場合(例: すべてロシア語文書)には、`Language.Auto` を `Language.Russian` に置き換えることでパフォーマンスが向上します。 + +### 後処理のヒント + +- **空白文字のトリム**: `result.getText().trim()`。 +- **改行コードの正規化**: `result.getText().replace("\r\n", "\n")`。 +- **非印字文字の除去**: 正規表現 `result.getText().replaceAll("[^\\p{Print}]", "")` を使用。 + +--- + +## 高度なオプションで画像テキストを認識 (任意) + +より細かい制御が必要な場合、Aspose OCR には追加プロパティが用意されています。 + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +これらの調整は、傾きやコントラストが低いスキャン文書を扱う際に便利です。 + +--- + +## 完全動作サンプルのまとめ + +全体を組み合わせると、最終プログラムは以下の順序で実行されます。 + +1. **画像の OCR を実行** – `OcrEngine` を作成。 +2. **Aspose ライセンスを使用** – 任意だが推奨。 +3. **OCR 用に画像をロード** – `Image.load` を呼び出す。 +4. **言語検出を設定** – `Language.Auto` で **画像テキストを認識**。 +5. **画像からテキストを抽出** – 結果を出力し、空応答に対しては安全に処理。 + +以下の依存関係を持つ Maven プロジェクトにコードブロックを貼り付ければすぐに動作します。 + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` を実行すると、コンソールに認識されたテキストが表示されます。 + +--- + +## まとめ + +本稿では、Aspose OCR for Java を使って **画像の OCR を実行** し、ライセンスの適用、**OCR 用に画像をロード**、**画像テキストを認識**、そして最終的に **画像からテキストを抽出** する手順を一通り解説しました。シンプルで多言語対応が標準装備されており、必要に応じて高度な前処理オプションも利用可能です。 + +次のステップは? OCR 結果を検索インデックスに流し込んだり、抽出テキストで PDF を生成したり、さまざまな画像フォーマットで実験してみたりしてください。Aspose の堅牢な API なら、OCR の細かな調整に時間を取られることなく、機能開発に集中できます。 + +質問や特殊ケースに遭遇したら、下のコメント欄にどうぞ—ハッピーコーディング! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを踏まえてさらに応用できる内容です。各リソースには、完全なコード例とステップバイステップの解説が含まれているので、API の追加機能習得や別実装アプローチの探索に役立ちます。 + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/korean/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..29646c265 --- /dev/null +++ b/ocr/korean/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR을 사용하여 이미지에서 검색 가능한 PDF를 만들기. OCR을 PDF로 변환하고, 이미지에서 텍스트를 추출하며, + 이미지를 빠르게 OCR하는 방법을 배워보세요. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: ko +og_description: Python OCR을 사용하여 이미지에서 검색 가능한 PDF 만들기. 이 가이드는 OCR을 PDF로 변환하고, 이미지에서 + 텍스트를 추출하며, 이미지에 OCR을 수행하는 방법을 보여줍니다. +og_title: Python으로 검색 가능한 PDF 만들기 – 전체 프로그래밍 안내 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Python으로 검색 가능한 PDF 만들기 – 완전 단계별 가이드 +url: /ko/python-java/general/create-searchable-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 만들기 – 완전 단계별 가이드 + +스캔한 영수증에서 **create searchable PDF**를 만들어야 할 때, 어디서 시작해야 할지 몰라 고민한 적 있나요? 당신만 그런 것이 아닙니다—많은 개발자들이 텍스트 사진을 실제로 검색 가능한 PDF로 바꾸려 할 때 같은 장벽에 부딪힙니다. + +이 튜토리얼에서는 **perform OCR on image**를 수행하고, OCR 결과를 **searchable PDF**로 변환하며, 필요하다면 원시 텍스트를 추출하는 실용적인 솔루션을 단계별로 안내합니다. 불필요한 내용 없이 바로 프로젝트에 복사‑붙여넣기 할 수 있는 작동 예제만 제공합니다. + +## 배울 내용 + +- Python에서 가벼운 OCR 엔진을 설정하는 방법 +- **convert OCR to PDF**의 정확한 단계와 이를 검색 가능한 문서로 저장하는 방법 +- 후속 분석을 위한 **extract text from image** 방법 +- 이미지 방향 및 대용량 파일과 같은 일반적인 함정을 처리하기 위한 팁 +- 자신의 사용 사례에 맞게 조정할 수 있는 완전하고 실행 가능한 스크립트 + +### 사전 요구 사항 + +- Python 3.8+가 설치된 환경 +- pip 및 가상 환경에 대한 기본적인 이해 (선택 사항이지만 권장) +- 명확하고 기계가 읽을 수 있는 텍스트가 포함된 이미지 파일(PNG, JPEG 등) + +위 조건을 갖추셨다면, 시작해봅시다. + +## 1단계: 필요한 라이브러리 설치 + +앞서 본 코드 스니펫은 가상의 `ocr` 패키지를 사용했지만, 동일한 아이디어는 **EasyOCR**, **pytesseract**, **pdfminer.six**와 같은 실제 라이브러리에도 적용됩니다. 이 가이드에서는 순수 Python이며 다국어를 지원하고 보조 헬퍼를 통해 편리한 PDF 변환 메서드를 제공하는 **EasyOCR**를 사용합니다. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** 가상 환경(`python -m venv venv && source venv/bin/activate`) 안에 설치하여 의존성을 깔끔하게 관리하세요. + +## 2단계: OCR 엔진 초기화 – Perform OCR on Image + +라이브러리가 준비되었으니 OCR 엔진을 생성하고 영어 텍스트를 처리하도록 지정합니다. 여기서 처음으로 **perform OCR on image**를 수행합니다. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +왜 전용 리더 객체가 필요할까요? EasyOCR는 언어 모델을 미리 로드하므로, 여러 이미지에 대해 동일한 `reader`를 재사용하는 것이 매번 다시 초기화하는 것보다 훨씬 효율적입니다. + +## 3단계: 이미지 로드 – Extract Text from Image + +이미지를 메모리로 불러옵니다. 이 단계가 나중에 **extract text from image**를 수행하는 단계이지만, 우선 이미지를 로드합니다. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +이미지가 뒤집히거나 기울어져 있다면 OCR 엔진에 전달하기 전에 Pillow의 `rotate` 또는 `transpose` 메서드를 사용해 보세요. 간단한 시각적 확인만으로도 나중에 디버깅에 소요되는 시간을 크게 절약할 수 있습니다. + +## 4단계: OCR 엔진 실행 및 결과 캡처 + +프로세스의 핵심—이미지를 OCR 엔진에 전달하고 구조화된 데이터를 반환받는 단계입니다. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +`detail=1` 플래그는 바운딩 박스를 제공하며, 이는 나중에 **convert OCR to PDF**할 때 필요합니다. 순수 문자열만 원한다면 `detail=0`으로 설정하세요. + +## 5단계: OCR 결과를 검색 가능한 PDF로 변환 – Convert OCR to PDF + +EasyOCR는 직접적인 PDF 작성기를 제공하지 않지만, Pillow와 `reportlab` 라이브러리를 사용해 PDF를 직접 만들 수 있습니다. 튜토리얼을 가볍게 유지하기 위해 원본 이미지를 삽입하고 보이지 않는 텍스트를 오버레이할 수 있는 `fpdf2`를 사용합니다. + +```bash +pip install fpdf2 +``` +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +무슨 일이 일어난 걸까요? 스캔한 이미지를 보이는 레이어로 배치하고, 인식된 단어들을 흰색 텍스트로 위에 써서 흰 배경과 섞이게 했습니다. 검색 도구는 여전히 숨겨진 레이어를 읽기 때문에, 시각적 모습은 그대로이면서 PDF가 **searchable**하게 됩니다. + +## 6단계: PDF 바이트 저장 – Convert Image to PDF + +PDF를 메모리에서 처리하고 싶다면(예: API로 전송) 디스크에 직접 쓰는 대신 바이트를 캡처할 수 있습니다. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +해당 코드는 고전적인 **convert image to PDF** 워크플로를 보여줍니다: 이미지로 시작해 OCR을 실행하고, 텍스트를 오버레이한 뒤 최종적으로 PDF 스트림을 출력합니다. + +## 7단계: 결과 검증 – 빠른 확인 + +스크립트를 실행한 뒤, 任意의 PDF 뷰어에서 `receipt_searchable.pdf`를 열고 검색창(Ctrl + F)을 사용해 보세요. 영수증에 있는 단어를 입력했을 때 정확한 위치로 이동한다면 **create searchable pdf**에 성공한 것입니다! + +검색이 실패한다면, 다음을 다시 확인하세요: + +1. OCR 신뢰도 점수(`conf` 값). 낮은 신뢰도는 이미지가 흐릿함을 의미할 수 있습니다. +2. 바운딩 박스 좌표—때때로 EasyOCR가 다른 방향으로 보고할 수 있습니다. +3. PDF 뷰어가 “이미지 전용” 모드로 설정되어 있지 않은지 확인하세요(드물지만 일부 뷰어에 해당 옵션이 있습니다). + +## 전체 작동 스크립트 + +모든 과정을 종합한 완전하고 바로 실행 가능한 파이썬 파일은 다음과 같습니다: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +`searchable_pdf.py`로 저장하고, `YOUR_DIRECTORY` 자리표시자를 실제 경로로 교체한 뒤 실행하세요: + +```bash +python searchable_pdf.py +``` + +확인 메시지가 표시되고 새로 만든 검색 가능한 PDF가 폴더에 생성될 것입니다. + +## 흔히 묻는 질문 및 예외 상황 + +**이미지가 컬러인 경우는?** +EasyOCR는 흑백 및 컬러 이미지 모두에서 작동하지만, 그레이스케일(`pil_image.convert("L")`)로 변환하면 잡음이 많은 스캔에서 정확도가 향상될 수 있습니다. + +**다중 페이지 PDF를 처리할 수 있나요?** +네—각 페이지 이미지를 순회하면서 OCR 단계를 수행하고, 각 페이지를 동일한 `FPDF` 객체에 추가하면 됩니다. 새 이미지마다 커서를 초기화(`self.add_page()`)하는 것을 잊지 마세요. + +**보이지 않는 흰색 텍스트 대신 원본 텍스트 레이어를 유지할 수 있나요?** +진정한 “텍스트‑이미지 아래” PDF(예: 접근성을 위해)가 필요하다면 `pdfminer` 또는 `pikepdf`를 사용해 적절한 PDF 태그와 함께 숨겨진 텍스트 레이어를 삽입하는 것을 고려하세요. 좀 더 고급 기술이지만 원리는 동일합니다: 배경 이미지 + 텍스트 오버레이. + +**OCR 신뢰도가 낮은 경우는?** +신뢰도가 낮은 단어를 필터링할 수 있습니다: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## 마무리 – 우리가 달성한 것 + +우리는 간단한 영수증 이미지를 시작점으로, **perform OCR on image**를 수행하고 인식된 문자열을 추출한 뒤, 최종적으로 **create searchable pdf**를 만들어 전문 스캔 문서와 동일하게 동작하도록 했습니다. 이 과정은 **convert OCR to PDF**, **extract text from image**, **convert image to PDF**, **perform OCR on image**와 같은 모든 보조 키워드를 다루었으므로, 이제 유사한 프로젝트에 재사용 가능한 도구 상자를 갖게 되었습니다. + +### 다음 단계 + +- `easyocr.Reader(['en', 'es'])`와 같이 ISO 코드를 전달해 다른 언어를 실험해 보세요. +- 완전 오프라인 솔루션이 필요하면 EasyOCR를 Tesseract로 교체하세요; 나머지 파이프라인은 동일합니다. +- 문제 스캔을 디버깅하기 위해 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/korean/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/korean/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..b98fe3b7c --- /dev/null +++ b/ocr/korean/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-19 +description: 간단한 OCR 엔진을 사용해 파이썬으로 이미지에서 텍스트를 추출합니다. 스캔한 이미지를 텍스트로 변환하고, 사진에서 텍스트를 + 인식하며, 파이썬으로 이미지 파일을 효율적으로 나열하는 방법을 배워보세요. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: ko +og_description: 가벼운 OCR 엔진을 사용해 Python에서 이미지의 텍스트를 추출합니다. 이 가이드는 스캔한 이미지를 텍스트로 변환하고, + 사진에서 텍스트를 인식하며, 몇 단계만에 파이썬으로 이미지 파일을 나열하는 방법을 보여줍니다. +og_title: Python으로 이미지에서 텍스트 추출 – 전체 배치 OCR 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Python으로 이미지에서 텍스트 추출 – 전체 배치 OCR 가이드 +url: /ko/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 텍스트 추출하기 (Python) – 전체 배치 OCR 가이드 + +이미지를 **텍스트로 추출**해야 하는데 어디서 시작해야 할지 몰라 고민한 적 있나요? 여러분만 그런 것이 아닙니다—개발자들은 스캔한 PDF, 사진으로 찍은 영수증, 스크린샷 등을 검색 가능한 텍스트로 변환하는 문제에 끊임없이 직면합니다. 이번 튜토리얼에서는 **스캔한 이미지를 텍스트로 변환**하고, 사진에서 텍스트를 인식하며, **list image files python** 스타일로 이미지 파일을 나열하는 완전한 실행 예제를 단계별로 살펴보겠습니다. 최종적으로 전체 폴더를 한 번에 처리할 수 있는 재사용 가능한 스크립트를 얻게 됩니다. + +필요한 라이브러리, 각 단계가 왜 중요한지, 엣지 케이스 처리, 그리고 약간의 트러블슈팅까지 모두 다룹니다. 외부 문서를 찾아볼 필요 없이 아래 코드는 자체적으로 완전하며, 설명은 “어떻게”와 “왜”를 모두 답합니다. 좋아하는 IDE를 열고 바로 시작해 보세요. + +--- + +## 만들게 될 것 + +- OCR 엔진 초기화 (`ocr` 패키지를 예시로 사용) +- 디렉터리를 스캔하고 **list image files python** 스타일로 PNG, JPG, TIFF 파일을 필터링 +- 찾은 모든 사진에 대해 **배치 OCR** 수행 +- 각 파일별로 추출된 텍스트를 명확히 라벨링하여 출력 + +> **Pro tip:** `ocr` 라이브러리가 설치되어 있지 않다면, 몇 가지 작은 수정만으로 `pytesseract` 로 교체할 수 있습니다—핵심 로직은 동일합니다. + +--- + +## 사전 준비 + +- Python 3.8+ (스크립트가 f‑string 및 타입 힌트를 사용합니다) +- `OcrEngine` 과 `recognize_batch` 를 제공하는 OCR 라이브러리. 여기서는 가상의 `ocr` 패키지를 가정하지만, 실제 라이브러리에도 동일한 패턴을 적용할 수 있습니다. +- 처리하고자 하는 이미지 파일이 들어 있는 폴더 (`.png`, `.jpg`, `.tif`) + +--- + +## Step 1 – Install & Import Required Modules + +먼저 OCR 패키지가 사용 가능한지 확인합니다. 실제 라이브러리(`pytesseract` 등)를 사용할 경우 import 문을 해당 라이브러리로 교체하면 됩니다. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Why this matters:** `os` 를 import 하면 플랫폼에 관계없이 경로를 다룰 수 있고, `typing.List` 는 IDE 자동완성과 향후 확장성을 돕습니다. + +--- + +## Step 2 – **Extract Text from Images**: Initialize the OCR Engine + +엔진을 생성하는 것은 모든 OCR 작업의 첫 단계입니다. 여기서는 언어를 자동 감지하도록 설정해 혼합 언어 문서도 처리할 수 있게 합니다. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explanation:** 엔진 생성을 함수로 캡슐화하면 코드가 모듈화됩니다. 나중에 DPI나 OCR 모드를 조정해야 할 경우 이 한 곳만 수정하면 됩니다. + +--- + +## Step 3 – **List Image Files Python**: Gather Files from a Directory + +이제 처리할 모든 사진을 찾아야 합니다. 아래 리스트 컴프리헨션은 흔히 쓰이는 “list image files python” 패턴을 그대로 구현합니다. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Edge case handling:** 이 함수는 하위 폴더를 무시합니다(필요하면 재귀적으로 확장 가능) 그리고 숨김 파일은 지원되는 확장자로 끝나지 않기 때문에 자동으로 필터링됩니다. + +--- + +## Step 4 – **Convert Scanned Images to Text**: Run Batch OCR + +대부분의 OCR 라이브러리는 한 번에 여러 이미지를 처리하는 배치 메서드를 제공하며, 개별 처리보다 훨씬 빠릅니다. 아래와 같이 호출합니다. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Why batch?** 모든 이미지를 한 번에 전달하면 모델 로딩 같은 오버헤드가 감소하고 CPU/GPU 활용 효율이 높아집니다. + +--- + +## Step 5 – **Recognize Text from Pictures**: Display the Results + +마지막으로 파일명과 OCR 결과를 짝지어 순회하면서 각 이미지마다 깔끔한 헤더를 출력합니다. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tip:** `strip()` 은 OCR이 자주 추가하는 앞뒤 공백을 제거해 줍니다. + +--- + +## Full Script – Put It All Together + +아래는 완전하고 실행 가능한 전체 프로그램입니다. `batch_ocr.py` 로 저장한 뒤 `python batch_ocr.py ` 로 실행하세요. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Expected Output + +폴더에 `invoice1.png` 와 `receipt.jpg` 가 들어 있다고 가정하면 다음과 같은 출력이 나타날 수 있습니다. + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +각 블록이 명확히 라벨링돼 있어, 이후 데이터베이스 저장 등 다운스트림 처리도 간편합니다. + +--- + +## Handling Common Pitfalls + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **No text appears** | OCR 언어가 감지되지 않았거나 이미지가 저대비인 경우 | 언어를 강제 지정 (`engine.language = ocr.Language.English`)하거나 이미지 전처리(대비 증가)를 수행 | +| **Memory error on large batches** | 엔진이 모든 이미지를 한 번에 로드하려 하기 때문 | `image_files` 를 청크로 나누어 (`batch_size = 20`) `recognize_batch` 를 반복 호출 | +| **Unsupported file format** | `.gif` 혹은 `.bmp` 와 같은 형식을 추가했을 경우 | `supported_exts` 튜플에 형식을 추가하거나 PNG/JPG 로 변환 | +| **Unicode garbling** | OCR이 문자열 대신 바이트를 반환 | OCR 라이브러리가 Unicode 를 출력하도록 설정 (`result.text.decode('utf‑8')` 등) | + +--- + +## Extending the Workflow + +이제 **이미지에서 텍스트를 추출**할 수 있게 되었으니, 다음 단계도 고려해 보세요: + +- **Export to CSV** – 파일명과 추출된 텍스트를 스프레드시트에 기록해 분석에 활용 +- **Parallel processing** – `concurrent.futures.ThreadPoolExecutor` 로 여러 배치를 동시에 처리 +- **Integrate with cloud OCR** – 로컬 엔진을 Google Vision 혹은 Azure OCR 로 교체해 복잡한 레이아웃에서도 높은 정확도 확보 +- **Add image preprocessing** – Pillow 혹은 OpenCV 로 이미지 기울기 보정, 노이즈 제거, 임계값 적용 등 전처리를 하면 OCR 결과가 크게 개선 + +위 아이디어들은 모두 앞서 만든 핵심 함수들을 그대로 활용하므로, 처음부터 다시 코딩할 필요가 없습니다. + +--- + +## Conclusion + +우리는 Python에서 **이미지에서 텍스트를 추출**하는 전체 솔루션을 단계별로 살펴보았습니다. 여기에는 **list image files python** 부터 **recognize text from pictures**, 그리고 **convert scanned images to text** 까지의 배치 흐름이 포함됩니다. 스크립트는 의도적으로 간단하면서도 확장성을 염두에 두었으니, 영수증 디지털화, 검색 가능한 아카이브 구축, 데이터 추출 파이프라인 등 다양한 프로젝트의 기반으로 활용할 수 있습니다. + +코드를 직접 실행해 보고 전처리 단계를 조정해 보면서 OCR 정확도가 어떻게 상승하는지 확인해 보세요. 문제가 발생하면 “Handling Common Pitfalls” 표를 다시 참고하면 대부분 작은 설정 변경만으로 해결됩니다. + +다음 도전 과제가 준비됐나요? `pdf2image` 로 PDF‑to‑image 변환 단계를 추가하고, 동일 파이프라인에 바로 연결해 보세요. OCR과 Python 생태계를 결합하면 가능성은 무한합니다. + +Happy coding, and may your text be ever legible! + +## What Should You Learn Next? + +다음 튜토리얼들은 이번 가이드에서 다룬 기술을 확장·심화할 수 있는 관련 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공해 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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/korean/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..8c459ae1f --- /dev/null +++ b/ocr/korean/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR을 사용해 이미지에서 텍스트를 추출합니다. 자동 언어 감지, 병렬 처리 및 배치 인식을 간결한 튜토리얼에서 + 배워보세요. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: ko +og_description: Python OCR로 이미지에서 텍스트를 추출하세요. 이 가이드는 자동 언어 감지, 병렬 처리 및 배치 인식을 하나의 + 튜토리얼에서 보여줍니다. +og_title: Python에서 이미지에서 텍스트 추출 – 전체 OCR 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python에서 이미지에서 텍스트 추출 – 전체 OCR 가이드 +url: /ko/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 텍스트 추출하기 – 전체 OCR 가이드 + +이미지를 **텍스트로 추출**하는 방법을 고민해 본 적 있나요? 직접 타이핑하지 않아도 되는 편리함을 원한다면 당신만 그런 것이 아닙니다. 오래된 영수증을 디지털화하거나, 검색 가능한 문서 아카이브를 구축하거나, 멋진 AI 트릭을 즐기고 싶을 때, 사진에서 텍스트를 뽑아내는 능력은 오늘날 모든 Python 개발자에게 필수 스킬입니다. + +이 튜토리얼에서는 인기 있는 OCR 엔진을 사용해 **이미지에서 텍스트를 추출**하는 완전한 실행 예제를 단계별로 살펴봅니다. 자동 언어 감지, 속도 향상을 위한 병렬 처리, 배치 이미지 인식까지 다루어 수십 개 파일을 몇 초 만에 처리할 수 있습니다. 필요하신 내용인가요? 바로 시작해 보겠습니다. + +## 배울 내용 + +- `ocr.OcrEngine`으로 OCR 엔진 인스턴스 생성하기 +- **자동 언어 감지**를 활성화해 엔진이 스스로 언어를 선택하도록 하기 +- 커스텀 스레드 풀을 이용한 **병렬 처리 OCR** 설정하기 +- 파일 리스트에 대한 **배치 이미지 인식** 실행하기 +- 각 이미지에 대해 인식된 텍스트를 출력하고, 저장하거나 색인할 준비하기 + +외부 문서는 필요 없습니다—여기서 바로 `ocr` 패키지(`pip install ocr`)만 있으면 코드를 바로 실행할 수 있습니다. + +## 사전 준비 + +시작하기 전에 다음을 준비하세요: + +1. Python 3.8 이상 설치 +2. `ocr` 패키지 (`pip install ocr`) +3. 처리하려는 PNG(또는 JPG) 이미지가 들어 있는 폴더 +4. Python 함수와 루프에 대한 기본 지식 + +그게 전부입니다—무거운 의존성도, GPU도 필요 없고 순수 Python만 있으면 됩니다. + +![extract text from images example](https://example.com/ocr-demo.png "Screenshot showing extract text from images output") + +*대체 텍스트: extract text from images demo screenshot* + +## Step 1 – OCR 엔진 설정하기 (Primary Keyword in Action) + +먼저 OCR 엔진 인스턴스를 생성합니다. `ocr.OcrEngine()`은 작업의 두뇌와 같으며, 문자, 줄, 단락을 읽는 방법을 알고 있습니다. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +왜 명시적으로 엔진을 만들어야 할까요? **ocr.OcrEngine 사용**은 언어 설정, 스레딩 등 세부 제어를 가능하게 해 주며, 한 줄 헬퍼보다 **이미지에서 텍스트를 추출**하는 가장 유연한 방법입니다. + +## Step 2 – 엔진에 자동 언어 감지 시키기 + +대부분의 OCR 라이브러리는 어떤 언어를 인식할지 지정해야 합니다. 단일 언어 프로젝트에는 괜찮지만, 혼합 언어 배치에서는 번거롭습니다. 다행히 `ocr` 패키지는 **자동 언어 감지**를 지원합니다. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +`engine.language`를 `ocr.Language.Auto`로 설정하면 엔진이 각 이미지를 살펴보고 적절한 언어 모델을 자동으로 선택합니다. 이 한 줄만으로 국제 문서를 다룰 때 수시간의 수작업 설정을 절감할 수 있습니다. + +## Step 3 – 병렬 처리 OCR으로 속도 올리기 + +CPU 코어가 4개 이상이라면 활용해 보세요. 엔진은 스레드 풀을 생성해 여러 이미지를 동시에 처리할 수 있습니다. 여기서 **병렬 처리 OCR**의 진가가 발휘됩니다. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +머신에 맞게 숫자 `4`를 조정하면 됩니다. 스레드 수가 많을수록 배치 실행이 빨라지지만, 각 스레드가 메모리를 차지하니 환경에 맞는 최적점을 찾아야 합니다. + +## Step 4 – 처리할 이미지 모으기 + +이제 파일 경로 리스트가 필요합니다. 리스트를 직접 작성하거나 CSV에서 읽어오거나 `glob`을 사용할 수 있습니다. 여기서는 간단히 짧은 리스트를 하드코딩합니다: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +`YOUR_DIRECTORY`를 실제 경로로 교체하세요. 파일이 수십 개라면 `glob.glob("*.png")` 같은 한 줄이 작업을 대신해 줍니다. + +## Step 5 – 배치 이미지 인식 실행하기 + +튜토리얼의 핵심 부분입니다. `files`에 있는 모든 이미지를 한 번에 처리하고 결과 객체 리스트를 반환합니다. 바로 **배치 이미지 인식** 기능으로 대규모 OCR이 실용화됩니다. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +엔진은 앞서 설정한 네 개의 워커 스레드에 파일을 분배하고, 동시에 각 이미지에 대해 자동 언어 감지를 수행합니다. 반환된 리스트의 각 요소는 인식된 텍스트와 메타데이터를 담고 있습니다. + +## Step 6 – 추출된 텍스트 출력(또는 저장)하기 + +마지막으로 결과를 순회하며 텍스트를 출력합니다. 실제 프로젝트에서는 데이터베이스나 CSV 파일에 저장하겠지만, 예제는 출력으로 간단히 보여줍니다. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**예상 출력**(요약): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +각 블록은 파일명 뒤에 OCR이 만든 문자열을 보여줍니다. 이미지에 여러 언어가 섞여 있으면 앞서 설정한 **자동 언어 감지** 덕분에 해당 문자들이 올바르게 표시됩니다. + +## 팁 & 흔히 겪는 문제 + +- **이미지 품질** – 흐리거나 대비가 낮은 사진은 쓰레기 결과를 낳습니다. 필요하면 OpenCV(`cv2.threshold`, `cv2.resize`)로 전처리하세요. +- **스레드 수 vs I/O** – 이미지가 느린 네트워크 드라이브에 있다면 스레드 수를 늘려도 도움이 되지 않을 수 있습니다. `top`이나 `Task Manager`로 CPU 사용량을 확인하세요. +- **Unicode 처리** – `result.text`는 Unicode 문자열입니다. 파일에 쓸 때는 `encoding="utf-8"` 옵션을 사용해 `UnicodeEncodeError`를 방지하세요. +- **메모리 사용량** – 큰 PDF를 처리하면 RAM이 많이 잡힐 수 있습니다. `MemoryError`가 발생하면 스레드 풀 크기를 줄이거나 작은 청크로 나눠 처리하세요. + +## 전체 작동 스크립트 + +아래는 지금까지 설명한 모든 단계를 포함한 복사‑붙여넣기용 완전한 스크립트입니다. `batch_ocr.py`라는 파일명으로 저장하고 `python batch_ocr.py`를 실행하세요. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +실행 방법: + +```bash +python batch_ocr.py ./my_images 4 +``` + +각 이미지마다 깔끔하게 포맷된 텍스트 블록이 출력되어 **이미지에서 텍스트를 추출**할 수 있음을 확인할 수 있습니다. + +## 다음 단계는? + +Python으로 **이미지에서 텍스트를 추출**하는 기본을 마스터했으니, 다음 주제들을 탐색해 보세요: + +- **후처리**: 정규식이나 자연어 처리 라이브러리로 OCR 결과 정리 +- **PDF 변환**: 추출한 문자열을 PDF 생성기로 보내 검색 가능한 PDF 만들기 +- **클라우드 OCR 서비스**: 온프레미스 `ocr` 결과를 Google Vision이나 Azure OCR과 비교해 정확도 확인 +- **GUI 프론트엔드**: Flask 또는 FastAPI 앱을 만들어 사용자가 이미지를 업로드하고 즉시 텍스트를 확인하도록 구현 + +이 모든 주제는 방금 설정한 **Python OCR 라이브러리** 기반 위에 쌓이며, 여기서 사용한 **병렬 처리 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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/korean/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..e4a874b8f --- /dev/null +++ b/ocr/korean/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-19 +description: Python에서 OCR을 사용하여 PDF 추출하는 방법 – PDF에서 텍스트 추출, 이미지에서 텍스트 인식, OCR Python + 예제를 포함한 단계별 튜토리얼. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: ko +og_description: Python에서 OCR을 사용해 PDF를 추출하는 방법. PDF에서 텍스트를 추출하고 이미지에서 텍스트를 인식하며, 완전한 + OCR Python 예제를 확인하세요. +og_title: Python에서 OCR을 사용해 PDF 텍스트 추출하는 방법 – 전체 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Python에서 OCR로 PDF 텍스트 추출하는 방법 – 완전 가이드 +url: /ko/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 파이썬에서 OCR을 사용해 PDF 텍스트 추출하기 – 완전 가이드 + +스캔된 이미지일 뿐인 파일에서 **PDF를 추출하는 방법**을 궁금해 본 적 있나요? 당신만 그런 것이 아닙니다. 실제 프로젝트에서는 계약서, 청구서, 혹은 역사적 기록과 같이 PDF가 선택 가능한 텍스트를 전혀 포함하지 않을 때가 많습니다. 좋은 소식은? 파이썬 몇 줄만으로 이미지 전용 페이지를 검색 가능하고 편집 가능한 텍스트로 변환할 수 있다는 것입니다. + +이 튜토리얼에서는 PDF를 읽고 첫 페이지를 이미지로 렌더링한 뒤 OCR 엔진을 사용해 **PDF에서 텍스트를 추출**하는 실용적인 **OCR 파이썬 예제**를 단계별로 살펴보겠습니다. 마지막까지 하면 **OCR로 PDF 읽기** 방법, 각 단계가 중요한 이유, 그리고 다중 페이지 문서나 다른 언어에 맞게 코드를 정확히 알게 됩니다. + +## 배울 내용 + +- 파이썬용 신뢰할 수 있는 OCR 라이브러리를 설치하고 설정합니다. +- OCR에 적합한 이미지로 PDF 페이지를 변환합니다. +- **이미지에서 텍스트 인식**하고 깨끗한 유니코드 문자열을 가져옵니다. +- 일반적인 함정(저해상도 PDF, 회전된 페이지)과 이를 피하는 방법. +- 스크립트를 확장하여 다중 페이지 또는 배치 처리에 대응합니다. + +**전제 조건**: Python 3.8 이상, pip, 그리고 가상 환경에 대한 기본 이해. 사전 OCR 경험은 필요 없으며, 따라하기만 하면 됩니다. + +--- + +## ## 파이썬에서 OCR을 사용해 PDF 텍스트 추출하기 + +이 H2 헤더는 주요 키워드를 검색 엔진이 선호하는 위치에 포함하고 있습니다. 바로 코드로 들어가 보겠습니다. + +### Step 1 – 필요한 패키지 설치 + +먼저 OCR 엔진이 필요합니다. 아래 예제는 Tesseract를 감싸는 가벼운 래퍼인 인기 **ocr** 패키지를 사용합니다. 다른 백엔드를 선호한다면 개념은 동일합니다. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **팁:** Linux에서는 Tesseract 바이너리도 필요합니다: `sudo apt-get install tesseract-ocr`. macOS 사용자는 Homebrew를 통해 설치할 수 있습니다: `brew install tesseract`. + +### Step 2 – OCR 엔진 초기화 및 언어 설정 + +이제 엔진을 시작하고 영어 문자를 찾도록 설정합니다. `ocr.Language.English`를 지원되는 다른 언어 코드로 교체할 수 있습니다. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**왜 중요한가:** 언어를 지정하면 엔진이 해당 언어 전용 사전과 문자 모델을 적용할 수 있어 정확도가 크게 향상됩니다. + +### Step 3 – PDF 페이지를 이미지로 로드 + +OCR은 PDF 객체가 아니라 래스터 이미지에서 작동합니다. `ocr.Image.from_pdf` 헬퍼는 선택한 페이지를 비트맵으로 렌더링합니다. 다른 페이지를 사용하려면 `page_number`를 조정하세요(0부터 시작하는 인덱스). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **예외 상황:** PDF에 스캔된 이미지가 아닌 벡터 그래픽이 포함된 경우 선명한 렌더링을 얻을 수 있습니다. 저해상도 스캔의 경우 DPI를 높이는 것을 고려하세요: `ocr.Image.from_pdf(..., dpi=300)`. + +### Step 4 – 렌더링된 이미지에서 텍스트 인식 + +이것이 **ocr 파이썬 예제**의 핵심입니다. 엔진은 비트맵을 처리하고 추출된 문자열을 포함한 객체를 반환합니다. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +`ocr_result.text` 속성은 가능한 경우 줄 바꿈을 유지한 순수 텍스트 출력을 담고 있습니다. + +### Step 5 – 추출된 텍스트 출력 또는 저장 + +마지막으로 결과를 출력합니다. 실제 애플리케이션에서는 파일이나 데이터베이스에 저장할 가능성이 높습니다. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +스크립트를 실행하면 다음과 같은 출력이 나타납니다: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +이것이 OCR을 사용한 완전한 **PDF에서 텍스트 추출** 워크플로우입니다. + +--- + +## ## 이미지에서 텍스트 인식 – 정확도 조정 + +**이미지에서 텍스트 인식**(예: 영수증 JPEG)만 필요하다면 PDF 변환 단계를 건너뛸 수 있습니다: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +더 나은 결과를 위한 팁: + +- **전처리**: 이미지를 그레이스케일로 변환하고, 임계값 적용 또는 기울기 보정(deskew). Pillow를 사용하면 쉽게 할 수 있습니다. +- PDF 렌더링 시 **DPI 증가**: 높은 해상도가 OCR 엔진에 더 많은 세부 정보를 제공합니다. +- 페이지 구분을 위한 OCR 엔진 **설정 활성화** (`ocr_engine.config = "--psm 6"`은 균일 블록용). + +## ## OCR로 PDF 읽기 – 다중 페이지 처리 + +대부분의 계약서는 여러 페이지에 걸쳐 있습니다. 각 페이지를 순회하는 것은 간단합니다: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +이 함수는 **OCR로 PDF를 읽고**, 출력 결과를 연결한 뒤 명확한 페이지 구분자를 삽입합니다. 이후 `full_text`를 검색 인덱스에 넣거나 `.txt` 파일로 저장할 수 있습니다. + +## ## 일반적인 함정과 해결 방법 + +| 증상 | 가능한 원인 | 해결 방법 | +|---------|--------------|-----| +| 문자가 깨지거나 `?`가 많이 표시됨 | 잘못된 언어 설정 또는 언어 데이터 파일 누락 | 올바른 Tesseract 언어 팩(`tesseract-ocr-`)을 설치하고 `ocr_engine.language`를 설정합니다. | +| 줄이 누락되거나 단어가 잘려 나옴 | DPI가 낮음(150 이하) | PDF를 300 DPI 이상(`dpi=300`)으로 렌더링합니다. | +| 텍스트가 회전되었거나 뒤집혀 있음 | 스캔된 페이지가 올바른 방향이 아님 | 인식 전에 `ocr.Image.deskew(page_image)`를 사용합니다. | +| 대용량 PDF 처리 시 속도가 느림 | 단일 스레드에서 페이지를 순차적으로 처리 | `concurrent.futures.ThreadPoolExecutor`를 사용해 병렬 처리합니다. | + +## ## OCR 파이썬 예제 확장 + +- **PDF/A로 내보내기**: 추출 후 `reportlab` 또는 `pypdf2`를 사용해 텍스트를 검색 가능한 PDF에 다시 삽입할 수 있습니다. +- **언어 감지**: OCR 출력에 `langdetect`를 적용해 `ocr_engine.language`를 동적으로 전환합니다. +- **배치 처리**: `os.listdir`로 디렉터리를 순회하고 `extract_all_pages`를 모든 파일에 적용합니다. + +## ## 예상 출력 및 검증 + +명확한 영어 스캔에 대해 스크립트를 실행하면 적절한 구두점이 포함된 깔끔한 텍스트 블록이 표시됩니다. 검증 방법: + +1. 몇 줄을 원본 스캔 이미지와 비교합니다. +2. 간단한 단어 수(`len(ocr_result.text.split())`)를 실행해 출력이 비어 있지 않은지 확인합니다. +3. 선택적으로 결과를 `pyspellchecker`와 같은 맞춤법 검사기에 입력해 OCR 오류를 찾아봅니다. + +## 결론 + +전통적인 파싱이 실패할 때 **PDF를 추출하는 방법**을 다루었고, 전체 **ocr 파이썬 예제**를 시연했으며, **이미지에서 텍스트 인식** 및 **OCR로 PDF 읽기**를 단일 페이지와 다중 페이지 상황 모두에 적용하는 방법을 설명했습니다. 위 코드 스니펫을 사용하면 이제 스캔된 PDF를 검색 가능하고 편집 가능한 텍스트로 변환할 수 있어 수동 재입력이 필요 없습니다. + +다음 단계는? 언어를 스페인어(`ocr.Language.Spanish`)로 바꾸어 보거나 이미지 전처리 기법을 실험해 정확도를 높여보세요. 문서 관리 시스템을 구축 중이라면 추출된 텍스트를 Elasticsearch에 색인하여 초고속 검색을 구현하는 것을 고려해 보세요. + +질문이 있거나 특이한 PDF에 부딪혔다면 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +![파이썬에서 OCR을 사용해 PDF 추출하기](image.png "파이썬에서 OCR을 사용해 PDF 추출하기") + +## 다음에 배울 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 숙달하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [Aspose OCR을 사용해 이미지에서 텍스트 추출 – 단계별 가이드](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [PDF 텍스트 인식 – Aspose.OCR for Java를 사용한 OCR 작업](/ocr/english/java/ocr-operations/) +- [Aspose.OCR을 사용한 언어 선택이 가능한 C# 이미지 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/korean/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..3b65f41f1 --- /dev/null +++ b/ocr/korean/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,283 @@ +--- +category: general +date: 2026-06-19 +description: Aspose를 사용하여 Java에서 OCR을 활용하는 방법을 배워보세요. 이 단계별 가이드는 이미지 자동 교정, 자동 언어 + 감지 및 텍스트 이미지 추출을 쉽게 다룹니다. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: ko +og_description: 'Aspose를 사용한 Java에서 OCR 활용 방법: 자동 이미지 교정, 자동 언어 감지 및 사진에서 텍스트 이미지 + 추출을 포함한 전체 가이드.' +og_title: Aspose와 함께 Java에서 OCR 사용 방법 – 완전 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Aspose와 함께 Java에서 OCR을 사용하는 방법 – 완전 가이드 +url: /ko/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java에서 Aspose를 사용한 OCR 활용 방법 – 완전 가이드 + +프로젝트에서 **OCR을 어떻게 사용**해야 할지 고민하면서 설정에 머리를 싸매본 적 있나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 스캔본이 비뚤어졌거나 알 수 없는 언어로 되어 있을 때 **이미지에서 텍스트 추출**을 빠르게 해야 하는 상황에서 벽에 부딪히곤 합니다. + +이 튜토리얼에서는 Aspose와 함께 OCR을 사용하는 방법을 실제 예제로 단계별로 보여드리며, **자동 이미지 디스큐**(auto deskew images), **자동 언어 감지**(auto language detection), 그리고 전체 **ocr 이미지 전처리**(ocr image preprocessing) 파이프라인을 포함합니다. 마지막에는 인식된 텍스트를 콘솔에 출력하는 실행 가능한 코드 스니펫을 제공하고, 각 설정이 왜 중요한지도 설명합니다. + +> **얻을 수 있는 것:** 완전한 실행 가능한 Java 프로그램, 각 라인에 대한 설명, 엣지 케이스 처리 팁, 배치 처리나 PDF로 확장하는 아이디어. + +--- + +## Prerequisites + +- Java 17(또는 최신 JDK) 설치 및 설정 +- Maven 또는 Gradle을 통한 의존성 관리(우리는 Maven 좌표를 보여드립니다) +- Aspose OCR for Java 라이선스 파일(`Aspose.OCR.Java.lic`). 테스트만 할 경우 라이선스 단계를 건너뛸 수 있지만, 무료 체험판은 워터마크를 추가합니다. +- 코드에서 접근 가능한 위치에 두어진 샘플 이미지(`your_image.png`) + +> **Pro tip:** 이미지를 전용 `resources` 폴더에 보관하고 클래스패스를 통해 로드하면 OS마다 달라지는 경로 문제를 피할 수 있습니다. + +--- + +## Step 1: Set Up the Project and Add Aspose OCR Dependency + +새 Maven 프로젝트를 만들거나 기존 프로젝트에 아래 내용을 `pom.xml`에 추가하세요: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn clean install`을 실행해 라이브러리를 받아옵니다. Gradle을 선호한다면 동등한 내용은 다음과 같습니다: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +이제 **ocr 이미지 전처리** 클래스가 클래스패스에 포함되었습니다. + +--- + +## Step 2: Apply Your Aspose OCR License (Optional but Recommended) + +라이선스가 있다면 `main` 메서드 시작 부분에 바로 적용하세요. 이 단계를 건너뛰면 무료 버전이 출력에 “Demo” 워터마크를 삽입합니다. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Why this matters:** 라이선스 버전은 사용 제한을 없애고 워터마크를 비활성화해 깔끔하고 프로덕션에 바로 사용할 수 있는 결과를 제공합니다. + +--- + +## Step 3: Create the OCR Engine Instance + +엔진은 전체 프로세스의 핵심입니다. 인스턴스를 생성하면 모든 **ocr 이미지 전처리** 옵션에 접근할 수 있습니다. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +이 시점에서 엔진은 기본 설정으로 준비되지만, 스캔 문서에 최적화되지 않을 수 있습니다. 몇 가지를 조정해 보겠습니다. + +--- + +## Step 4: Enable Auto Deskew Images for Cleaner Scans + +기울어진 스캔은 흔한 문제입니다. Aspose는 **auto deskew images** 기능을 제공해 인식 전에 자동으로 이미지를 바로 잡아줍니다. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **How it works:** 알고리즘이 텍스트 기준선 각도를 분석하고 가장 가능성이 높은 수직 방향으로 이미지를 회전합니다. 휴대폰으로 촬영한 사진의 정확도가 크게 향상됩니다. + +--- + +## Step 5: Turn On Auto Language Detection + +소스 이미지의 언어를 모를 경우 엔진에게 판단하게 하세요. 이것이 **auto language detection** 설정입니다. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +이 옵션을 켜면 Aspose가 글리프를 스캔해 30개가 넘는 언어 모델 중 가장 가능성이 높은 언어를 자동으로 선택합니다. + +--- + +## Step 6: Load the Image You Want to Recognize + +이미지는 디스크, URL, 혹은 바이트 배열에서 로드할 수 있습니다. 여기서는 로컬 파일을 읽는 가장 간단한 방법을 보여드립니다. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** 큰 이미지를 다룰 경우 `engine.getImagePreprocessing().setResizeFactor(0.5)` 로 먼저 다운샘플링하면 디테일 손실 없이 처리 속도를 높일 수 있습니다. + +--- + +## Step 7: Perform OCR Recognition and Extract Text Image + +이제 엔진이 마법을 부립니다. `recognize` 메서드는 인식된 텍스트와 신뢰도 점수 등을 포함한 `OcrResult` 객체를 반환합니다. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +콘솔에 사진에서 추출된 순수 텍스트가 표시됩니다—우리가 목표로 했던 **extract text image** 결과가 바로 여기입니다. + +--- + +## Full Working Example + +아래는 모든 과정을 하나로 묶은 완전한 Java 클래스입니다. `src/main/java/com/example/OcrDemo.java`에 복사‑붙여넣기하고 실행해 보세요. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Expected Output + +이미지에 깨끗한 스캔 상태로 “Hello World”라는 문구가 포함되어 있다면 다음과 같은 결과가 출력됩니다: + +``` +=== Recognized Text === +Hello World +``` + +다국어 영수증 같은 복잡한 문서의 경우 줄 바꿈과 감지된 언어 코드가 함께 표시됩니다. + +--- + +## Common Pitfalls & Pro Tips + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | 이미지가 너무 어둡거나 노이즈가 많음 | `engine.getImagePreprocessing().setBinarization(true)` 를 활성화하거나 대비를 수동으로 조정 | +| **Wrong language** | 혼합 언어 페이지에서 자동 감지가 실패 | `engine.setLanguage(Language.English)`(또는 해당 enum) 로 특정 언어 강제 지정 | +| **Slow processing** | 매우 고해상도 이미지 | `engine.getImagePreprocessing().setResizeFactor(0.5)` 로 다운스케일 | +| **Out‑of‑memory errors** | 한 번에 많은 이미지 로드 | 이미지를 순차적으로 처리하고 각 실행 후 `engine.dispose()` 호출 | + +> **Remember:** OCR 엔진은 읽기 전용 작업에 대해 스레드‑안전하지만, 스레드당 새 인스턴스를 생성하면 숨겨진 상태 버그를 방지할 수 있습니다. + +--- + +## Extending the Solution + +이제 **OCR을 어떻게 사용**하는지 알았으니 다음과 같이 확장해 볼 수 있습니다: + +1. **PDF 처리** – 각 PDF 페이지를 이미지(`PdfConverter`)로 변환한 뒤 동일 파이프라인에 전달 +2. **폴더 일괄 처리** – 디렉터리 내 파일을 순회하면서 동일 단계 적용, 결과를 CSV에 기록 +3. **웹 서비스와 통합** – Spring Boot `@RestController` 로 OCR 로직을 노출하고 multipart 업로드를 받아 처리 + +위 모든 시나리오는 여기서 만든 **ocr 이미지 전처리** 구성을 그대로 재사용합니다. + +--- + +## Conclusion + +Java에서 Aspose를 이용한 **OCR 사용법**을 처음부터 끝까지 다뤘습니다: 라이선스 적용, 엔진 생성, **auto deskew images** 활성화, **auto language detection** 켜기, 이미지 로드, 그리고 최종적으로 `System.out.println` 으로 **extract text image** 수행까지. 코드는 완전 자립형이며 최신 JDK에서 실행 가능하고, 정확도와 성능을 위한 모범 사례를 보여줍니다. + +직접 사진을 가지고 실행해 보세요—예를 들어 스캔된 계약서나 영수증 스크린샷 등. 전처리 플래그를 조정하고 다양한 언어를 실험하면 Aspose OCR 라이브러리가 왜 프로덕션 급 텍스트 추출에 적합한 선택인지 빠르게 체감할 수 있을 겁니다. + +질문이 있거나 결과를 공유하고 싶다면 아래 댓글을 남기거나 GitHub에서 저에게 ping 주세요. Happy coding! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## 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 Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/korean/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..d34aeceab --- /dev/null +++ b/ocr/korean/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,317 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR를 사용하여 Python에서 OCR 정확도를 향상시키세요. OCR 언어 설정 방법, OCR을 위한 이미지 + 로드 방법, 그리고 사용자 정의 사전을 사용해 이미지에서 텍스트를 추출하는 방법을 배워보세요. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: ko +og_description: OCR 언어를 설정하고, OCR용 이미지를 로드하며, 사용자 정의 사전을 사용해 이미지에서 텍스트를 추출하여 Python에서 + OCR 정확도를 향상시킵니다. +og_title: Python에서 OCR 정확도 향상 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Python에서 OCR 정확도 향상 – 완전 가이드 +url: /ko/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 OCR 정확도 향상 – 완전 가이드 + +스캔하는 텍스트에 특수 기호, 제품 코드, 브랜드명이 섞여 있을 때 **OCR 정확도를 향상**시키는 방법이 궁금하셨나요? 혼자만 그런 것이 아닙니다. 많은 프로젝트에서 기본 엔진이 엉뚱한 결과를 내놓아 생산성이 크게 떨어집니다. + +이 튜토리얼에서는 **OCR 언어 설정**, **이미지 로드**, **이미지에 대한 OCR 수행**, 그리고 인식률을 높여주는 **맞춤 사전**을 이용해 텍스트를 추출하는 실전 엔드‑투‑엔드 예제를 단계별로 살펴봅니다. 마지막에는 어떤 Python 코드베이스에도 바로 넣어 실행할 수 있는 스크립트를 제공할 것입니다. + +## 이번 튜토리얼을 통해 얻을 수 있는 것 + +- PNG 파일을 읽는 Aspose OCR을 활용한 완전한 Python 스크립트 +- 언어와 맞춤 단어 목록을 설정하여 **OCR 정확도 향상**하는 방법 +- 각 설정이 중요한 이유에 대한 명확한 설명과 비라틴 문자 처리 팁 +- 일반적인 OCR 문제를 해결하기 위한 빠른 체크리스트 + +### 사전 요구 사항 + +- Python 3.8 이상 설치 +- `aspose-ocr` 패키지 (`pip install aspose-ocr` 로 설치) +- 읽고자 하는 텍스트가 포함된 샘플 이미지 (`technical_doc.png`) +- Python에 대한 기본 지식 – 별다른 사전 지식은 필요 없습니다. + +> **Pro tip:** 가상 환경에서 작업한다면 패키지를 설치하기 전에 환경을 활성화하세요. 이렇게 하면 의존성을 깔끔하게 관리하고 버전 충돌을 방지할 수 있습니다. + +--- + +## Step 1: Install and Import Aspose OCR + +먼저 라이브러리를 환경에 설치하고 필요한 요소를 가져옵니다. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr` 네임스페이스를 통해 `OcrEngine` 클래스를 사용할 수 있습니다. 이 클래스를 여기서 가져오면 스크립트의 나머지 부분을 깔끔하고 읽기 쉽게 유지할 수 있습니다. + +--- + +## Step 2: Create an OCR Engine and **Set OCR Language** + +언어 설정이 왜 중요한가요? OCR 엔진은 언어별 모델을 사용해 문자 형태와 단어 패턴을 인식합니다. 엔진에 영어 텍스트를 스캔한다고 알려주면 키릴 문자 등을 무시하고 라틴 알파벳에 집중해 **OCR 정확도**가 크게 **향상**됩니다. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Note:** Aspose OCR은 50개 이상의 언어를 지원합니다. 문서가 영어가 아니라면 `ocr.Language.English` 대신 `ocr.Language.Spanish`, `ocr.Language.French` 등을 사용하세요. + +--- + +## Step 3: Define a **Custom Dictionary** to Boost Accuracy + +예를 들어 인보이스에 “AsposeOCR” 혹은 “SKU12345” 같은 단어가 자주 등장한다면, 엔진은 이 용어들을 알지 못해 잘못 추측합니다. 맞춤 단어 목록을 제공하면 엔진에 *“이 문자열은 올바른 것이니 교정하지 말라”*고 알려주는 효과가 있어 **OCR 정확도 향상**에 즉각적인 도움이 됩니다. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +수백 개의 항목이 있다면 파일이나 데이터베이스에서 로드할 수 있지만, 여기서는 간단히 Python 리스트에 담아 사용합니다. + +--- + +## Step 4: **Load Image for OCR** + +이제 이미지를 준비합니다. `Image.load` 메서드는 PNG, JPEG, BMP 등 지원되는 래스터 포맷의 경로를 받아들입니다. 파일을 찾을 수 없으면 엔진이 예외를 발생시키므로 이를 방지하도록 코드를 작성합니다. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Why this step matters:** 이미지를 올바르게 로드해야 엔진이 분석하려는 정확한 픽셀 데이터를 사용할 수 있습니다. 파일이 손상되었거나 경로가 잘못되면 흔히 겪는 좌절의 원인이 됩니다. + +--- + +## Step 5: **Perform OCR on Image** and Extract Results + +엔진 설정과 이미지 준비가 끝났다면 실제 인식은 단 한 줄의 메서드 호출로 완료됩니다. 결과 객체에는 원시 텍스트, 신뢰도 점수, 필요 시 레이아웃 정보까지 포함됩니다. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +이미지에서 **텍스트를 라인 단위로 추출**하려면 개행 문자(`\n`)를 기준으로 문자열을 분할하면 됩니다. + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Step 6: Verify the Output – Does It Really **Improve OCR Accuracy**? + +결과를 출력해 맞춤 사전이 실제로 차이를 만들었는지 확인해 보세요. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +샘플 이미지에 대한 일반적인 출력 예시는 다음과 같습니다: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +브랜드명, 그리스 문자, 제품 코드가 우리가 정의한 대로 정확히 나타나는 것을 확인할 수 있습니다. 맞춤 사전이 없었다면 엔진은 이를 “Aspose OCR” 혹은 “SKU 1234”와 같이 교정하려 했을 것입니다. + +--- + +## Common Pitfalls & How to Tackle Them + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | 잘못된 언어 설정 또는 저해상도 이미지 | `engine.language`가 원본 언어와 일치하는지 확인하고, 300 dpi 이상의 고해상도 스캔을 사용하세요. | +| **Custom words ignored** | 사전이 연결되지 않았거나 속성 이름에 오타 | `engine.text_processing.custom_dictionary = …` 를 다시 확인하세요. | +| **File not found** | 경로 오류 또는 파일 접근 권한 부족 | `os.path.abspath()` 로 절대 경로를 확인하고, 적절한 권한으로 스크립트를 실행하세요. | +| **Slow processing** | 이미지가 크거나 페이지가 많음 | 이미지 전처리(자르기, 리사이즈)하거나 `engine.recognize(image, max_threads=4)` 로 병렬 처리하세요. | + +--- + +## Going Further: Advanced Tweaks for **Improve OCR Accuracy** + +1. **Pre‑processing** – Pillow를 사용해 대비 강화 또는 이진화를 적용한 뒤 Aspose OCR에 전달합니다. +2. **Multiple Languages** – `engine.language = ocr.Language.English | ocr.Language.French` 와 같이 설정하면 이중 언어 인식이 가능합니다. +3. **Region‑Based OCR** – 표와 같이 특정 영역만 필요하다면 먼저 해당 영역을 잘라내어 노이즈를 줄입니다. +4. **Confidence Filtering** – `result.confidence` 로 문자별 신뢰도 점수를 확인하고, 낮은 신뢰도의 결과는 프로그램적으로 제외할 수 있습니다. + +--- + +## Full Working Script + +아래는 앞서 설명한 모든 단계를 포함한 완전 복사‑붙여넣기 가능한 스크립트입니다. `improve_ocr_accuracy.py` 라는 파일명으로 저장한 뒤 커맨드 라인에서 실행하세요. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +실행 방법: + +```bash +python improve_ocr_accuracy.py +``` + +앞서 보여드린 깔끔한 출력이 화면에 표시될 것입니다. + +--- + +## Conclusion + +이번 튜토리얼에서는 Python에서 **OCR 정확도 향상**을 위한 간단하면서도 효과적인 방법을 다루었습니다. + +1. **문서에 맞는 OCR 언어 설정** +2. **이미지를 올바르게 로드**하여 엔진이 정확한 픽셀을 보게 함 +3. **이미지에 OCR 수행**을 한 번의 메서드 호출로 실행 +4. **이미지에서 텍스트 추출** 후 결과 확인 +5. **맞춤 사전 추가**로 도메인 특화 용어를 고정 + +이렇게 하면 원본 사진에서 깨끗하고 검색 가능한 텍스트로 변환하는 전체 흐름을 깔끔한 재사용 가능한 스크립트 하나에 담을 수 있습니다. + +다음 단계로는 이미지 전처리(대비 조정, 기울기 보정)를 실험하거나 `ocr.Language.English | ocr.Language.German` 와 같이 다국어 설정을 시도해 보세요. 동일한 원칙을 적용하면 다양한 문서에서도 **OCR 정확도 향상**을 지속적으로 이룰 수 있습니다. + +궁금한 점이나 특이 케이스가 있나요? 아래 댓글에 남겨 주세요. Happy coding! + +![improve OCR accuracy + + +## What Should You Learn Next? + +다음 튜토리얼들은 이번 가이드에서 다룬 기술을 확장·심화할 수 있는 관련 주제들을 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [이미지에서 텍스트 추출 – Aspose.OCR for .NET을 활용한 OCR 최적화](/ocr/english/net/ocr-optimization/) +- [다중 언어 이미지 텍스트 인식 – Aspose OCR for .NET](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [OCR 이미지 인식에서 임계값 설정 방법](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/korean/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..91109ceca --- /dev/null +++ b/ocr/korean/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-19 +description: Python의 OCR 라이브러리를 사용하여 이미지에서 OCR을 수행합니다. 이미지에서 텍스트를 감지하고, JPEG에서 텍스트를 + 인식하며, 스캔한 이미지에서 텍스트를 효율적으로 추출하는 방법을 배웁니다. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: ko +og_description: Python으로 이미지에 OCR을 수행하고 스캔 파일에서 텍스트를 추출합니다. 이 가이드는 이미지를 로드하고, 기울기를 + 보정하며, 텍스트를 단계별로 인식하는 과정을 안내합니다. +og_title: Python에서 이미지 OCR 수행 – 전체 텍스트 추출 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Python에서 이미지 OCR 수행 – 전체 텍스트 추출 가이드 +url: /ko/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 OCR 수행 (Python) – 전체 텍스트 추출 가이드 + +이미지 파일에 **OCR을 수행**하려고 했지만 코드가 난해해서 막혔던 적 있나요? 당신만 그런 것이 아닙니다. 스캔한 영수증을 검색 가능한 PDF로 변환하거나 데이터‑사이언스 프로젝트를 위해 JPEG에서 캡션을 추출하든, JPEG 및 기타 포맷에서 텍스트를 인식하는 능력은 오늘날 모든 개발자에게 필수적인 스킬입니다. + +이 튜토리얼에서는 **이미지 파일에서 텍스트를 감지**하고, **스캔한 이미지 문서에서 텍스트를 추출**하며, **OCR용 이미지 로드**까지 몇 줄의 코드만으로 보여주는 완전하고 실행 가능한 예제를 단계별로 살펴봅니다. 끝까지 따라오면, 누락된 import 없이 바로 프로젝트에 삽입할 수 있는 견고하고 프로덕션‑레디 스니펫을 얻게 됩니다. + +## 만들게 될 것 + +- OCR 엔진을 생성하고 자동 디스큐를 활성화하며 JPEG(또는 지원되는 형식)를 로드하고 인식된 텍스트를 출력하는 작은 Python 스크립트 +- **왜** 각 설정이 중요한지에 대한 설명과 **어떻게** 입력하는지에 대한 안내 +- 다중 페이지 PDF, 비영어권 언어, 흐릿한 스캔과 같은 일반적인 함정에 대한 팁 + +### 사전 요구 사항 + +- Python 3.8+ 설치 (예제에서는 `pip install ocr-lib` 로 설치 가능한 `ocr` 패키지를 사용합니다 – 실제 라이브러리 이름으로 교체하세요) +- Python 함수와 가상 환경에 대한 기본 지식 +- 처리하고자 하는 이미지 파일(JPEG, PNG, TIFF) – 여기서는 `skewed_page.jpg` 를 예시로 사용합니다 + +> **프로 팁:** Windows 환경이라면 OCR 라이브러리를 설치할 때 권한 문제를 피하기 위해 터미널을 관리자 권한으로 실행하세요. + +--- + +## 이미지에서 OCR 수행 – 설정 및 구성 + +가장 먼저 필요한 것은 깨끗한 OCR 엔진 인스턴스입니다. 이는 작업의 두뇌와도 같으며, 올바른 구성이 없으면 가장 선명한 이미지조차도 의미 없는 결과를 반환합니다. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**왜 중요한가:** +`engine.language` 를 설정하면 OCR 엔진이 기대하는 문자 집합을 제한하여 정확도가 크게 향상됩니다. 이를 생략하면 엔진이 추측하게 되어 간단한 단어조차 잘못 인식할 수 있습니다. + +--- + +## 자동 디스큐 활성화 – 기울어진 스캔 보정 + +스캔한 페이지는 거의 완벽하게 평평하지 않습니다. 약간의 기울기만 있어도 문자 구분이 흐트러져 “Hello”가 “H3llo”처럼 변할 수 있습니다. `auto_deskew` 플래그가 이 작업을 대신해 줍니다. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**예외 상황:** 이미지가 이미 똑바로 정렬되어 있다는 것을 확신한다면 디스큐를 비활성화하여 처리 시간을 몇 밀리초 절감할 수 있습니다—수천 페이지를 배치 작업으로 처리할 때 유용합니다. + +--- + +## OCR용 이미지 로드 – JPEG, PNG, TIFF 지원 + +이제 실제로 **OCR용 이미지 로드**를 수행합니다. `ocr.Image.load` 메서드는 유연하며, 지원되는 래스터 포맷이면 어떤 경로든 받아들입니다. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **왜 중요한 단계인가:** 라이브러리는 파일을 내부 비트맵으로 읽어들여 필요한 색 공간 변환을 수행합니다. 이 과정을 건너뛰고 원시 바이트 스트림을 전달하면 `FileNotFoundError`가 발생하거나, 더 나쁘게는 빈 결과가 조용히 반환될 수 있습니다. + +특히 **JPEG 파일에서 텍스트를 인식**하려면 파일 확장자가 `.jpeg` 혹은 `.jpg` 인지 확인하면 됩니다. 동일한 호출이 PNG(`.png`)나 TIFF(`.tif`)에도 별도 수정 없이 동작합니다. + +--- + +## 이미지에서 OCR 수행 – 엔진 실행 + +엔진이 준비되고 이미지가 메모리에 로드되었으니 **이미지에서 OCR 수행**을 할 차례입니다. 아래 한 줄이 전 과정을 담당합니다: 전처리, 세그멘테이션, 분류, 텍스트 조합. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**내부에서 무슨 일이 일어나나요?** +- 엔진이 디스큐 변환을 적용합니다(활성화된 경우). +- 신경망 또는 Tesseract 백엔드를 사용해 문자를 식별합니다. +- 마지막으로 문자를 단어와 줄로 연결해 풍부한 `result` 객체를 반환합니다. + +--- + +## 스캔 이미지에서 텍스트 추출 – 결과 출력 + +마지막 단계는 **스캔 이미지에서 텍스트 추출**하고 이를 표시하는 것입니다. `result.text` 속성에 순수 텍스트가 들어 있습니다. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +전형적인 출력 예시: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +OCR 엔진이 어떤 문자도 찾지 못하면 `result.text` 는 빈 문자열이 됩니다. 이 경우 이미지 품질을 재검토하거나 `engine.confidence_threshold` 속성을 조정해 보세요(라이브러리에서 지원한다면). + +--- + +## 일반적인 변형 처리 + +### JPEG vs PNG 텍스트 인식 + +두 포맷 모두 지원되지만 JPEG 압축은 엔진을 혼란스럽게 하는 아티팩트를 만들 수 있습니다. 오인식이 빈번하다면 JPEG를 먼저 PNG로 변환해 보세요: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### 다중 언어 이미지 텍스트 감지 + +문서에 영어와 스페인어가 섞여 있다면 다국어 모드를 설정합니다: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +엔진은 이제 두 알파벳을 모두 고려해 인식합니다. + +### 스캔 PDF에서 텍스트 추출 + +PDF의 경우 각 페이지를 먼저 이미지로 래스터화해야 합니다. `pdf2image` 같은 라이브러리를 사용하면 손쉽게 처리할 수 있습니다: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## 전체 작업 예제 + +아래는 `ocr_demo.py` 파일에 복사‑붙여넣기 할 수 있는 완전한 스크립트입니다. 오류 처리와 실행 시간을 측정하는 작은 헬퍼 함수도 포함되어 있습니다. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**예상 출력**(깨끗한 스캔을 가정): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## 자주 묻는 질문 + +**Q: 헤드리스 서버에서도 실행할 수 있나요?** +A: 물론 가능합니다. 라이브러리는 GUI 없이 동작하므로 서버에 필요한 네이티브 바이너리(예: Tesseract)만 설치하면 됩니다. + +**Q: 이미지가 흐릿하면 어떻게 해야 하나요?** +A: `engine.recognize` 전에 샤프닝 필터를 적용해 보세요. 많은 OCR 라이브러리는 `image_preprocessing.sharpen = True` 옵션을 제공하거나 OpenCV의 `cv2.GaussianBlur` 를 역으로 사용해 샤프닝을 구현할 수 있습니다. + +**Q: 스크립트가 배치 처리도 지원하나요?** +A: 예. 파일 경로 리스트에 대해 `perform_ocr` 를 루프 안에서 호출하면 됩니다. + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/korean/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..427596b77 --- /dev/null +++ b/ocr/korean/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR Java를 사용하여 이미지에서 OCR을 수행합니다. OCR을 위해 이미지를 로드하는 방법, Aspose + 라이선스를 사용하는 방법, 그리고 몇 분 안에 이미지에서 텍스트를 추출하는 방법을 배워보세요. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: ko +og_description: Aspose OCR Java를 사용하여 이미지에서 OCR을 수행합니다. 이 가이드는 Aspose 라이선스를 사용하는 방법, + OCR을 위한 이미지를 로드하는 방법, 그리고 이미지를 효율적으로 텍스트로 추출하는 방법을 보여줍니다. +og_title: Aspose OCR Java로 이미지에서 OCR 수행 – 전체 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Aspose OCR Java를 사용하여 이미지에서 OCR 수행 – 완전한 단계별 가이드 +url: /ko/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에 대한 OCR 수행 (Aspose OCR Java) – 완전한 단계별 가이드 + +이미지 파일에 **perform OCR on image** 를 해야 하는 상황을 겪어본 적이 있지만, 많은 설정 없이도 신뢰할 수 있는 결과를 제공하는 라이브러리를 찾기 어려웠나요? 당신만 그런 것이 아닙니다. 실제 프로젝트에서는 여권 스캔, 청구서 디지털화, 스크린샷에서 텍스트 추출 등과 같이 텍스트 이미지 데이터를 빠르게 인식하는 능력이 큰 변화를 가져옵니다. + +이 튜토리얼에서는 Aspose OCR for Java 를 사용해 **perform OCR on image** 하는 방법을 직접 보여줍니다. Aspose 라이선스 적용부터 이미지 로드, 엔진 실행, 최종적으로 **extract text from image** 하는 전체 과정을 다룹니다. 불필요한 내용은 없으며, 바로 복사‑붙여넣기 할 수 있는 실전 솔루션을 제공합니다. + +## 배울 수 있는 내용 + +- Java 프로젝트에서 **use Aspose license** 하는 방법을 명확히 이해합니다. +- **load image for OCR** 하고 엔진이 언어를 자동 감지하도록 하는 정확한 코드를 제공합니다. +- **recognize text image** 내용과 **extract text from image** 를 안전하게 수행하는 단계별 지침을 제공합니다. +- 일반적인 함정(빈 결과, 지원되지 않는 포맷, 메모리 문제) 처리 팁을 제공합니다. + +> **전제 조건** – Java 8 이상, Maven 또는 Gradle을 이용한 의존성 관리, 그리고 Aspose OCR for Java 라이선스 파일(또는 평가 모드 사용 가능). + +--- + +## Aspose OCR Java 로 이미지에 대한 OCR 수행 방법 + +아래는 전체 흐름을 보여주는 실행 가능한 Java 프로그램입니다. `AsposeOcrDemo.java` 로 저장한 뒤 IDE 또는 명령줄에서 실행하세요. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### 예상 콘솔 출력 + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +라이선스 파일 없이 프로그램을 실행하면 첫 번째 줄에 평가 모드라는 메시지만 표시되지만 OCR은 정상적으로 작동합니다. + +--- + +## Aspose 라이선스 설정 및 사용 + +### 라이선스가 중요한 이유 + +평가 모드로 라이브러리를 사용해도 간단한 테스트는 가능하지만, 출력에 워터마크가 삽입되고 한 번에 처리할 수 있는 페이지 수가 제한됩니다. **use aspose license** 단계를 수행하면 이러한 제한이 사라지고, Aspose에 유료 고객임을 알릴 수 있습니다. + +### 라이선스 획득 및 적용 방법 + +1. Aspose 스토어에서 라이선스를 구매합니다. +2. `Aspose.OCR.Java.lic` 파일을 다운로드합니다. +3. 애플리케이션이 읽을 수 있는 위치에 배치합니다—보통 `src/main/resources` 폴더가 일반적입니다. +4. 위 코드와 같이 OCR 작업을 시작하기 전에 `new License().setLicense("Aspose.OCR.Java.lic");` 를 호출합니다. + +> **프로 팁:** 서버에 배포할 경우 절대 경로나 클래스패스 리소스 로더를 사용해 `FileNotFoundException` 을 방지하세요. + +--- + +## OCR 처리를 위한 이미지 로드 + +`Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` 라인은 **load image for OCR** 단계의 핵심입니다. Aspose OCR 은 PNG, JPEG, BMP, TIFF 등 다양한 포맷을 지원하며, Aspose.Pdf 와 결합하면 다중 페이지 PDF 도 처리할 수 있습니다. + +### 흔히 발생하는 문제 + +| Issue | Symptom | Fix | +|-------|---------|-----| +| 잘못된 파일 경로 | `FileNotFoundException` | 경로를 다시 확인하고 OS‑독립적인 구분자를 위해 `Paths.get(...)` 를 사용합니다. | +| 지원되지 않는 포맷 | `UnsupportedOperationException` | 이미지를 PNG 또는 JPEG 로 변환한 뒤 로드합니다. | +| 매우 큰 이미지 ( > 10 MP) | 메모리 부족 오류 | `java.awt.Image` 를 이용해 이미지 크기를 축소한 뒤 Aspose에 전달합니다. | + +--- + +## 이미지에서 텍스트 추출 및 결과 처리 + +OCR 엔진이 작업을 마치면 `OcrResult` 객체에 인식된 문자열이 들어 있습니다. 여기서 **extract text from image** 를 수행해 데이터베이스 저장, 검색 인덱스 입력, 혹은 다운스트림 NLP 파이프라인에 활용할 수 있습니다. + +### 다중 언어 처리 + +`engine.setLanguage(Language.Auto)` 로 설정했기 때문에 Aspose 가 실행 중에 언어를 자동 감지합니다. 사전에 언어가 확정돼 있다면(예: 모든 문서가 러시아어) `Language.Auto` 대신 `Language.Russian` 으로 교체해 성능을 높일 수 있습니다. + +### 후처리 팁 + +- **공백 제거**: `result.getText().trim()` +- **줄 바꿈 정규화**: `result.getText().replace("\r\n", "\n")` +- **비인쇄 문자 제거**: `result.getText().replaceAll("[^\\p{Print}]", "")` 와 같은 정규식 사용 + +--- + +## 고급 옵션으로 텍스트 이미지 인식 (선택 사항) + +보다 세밀한 제어가 필요하다면 Aspose OCR 은 추가 속성을 제공합니다: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +이러한 조정은 스캔 문서가 기울어졌거나 대비가 낮은 경우에 유용합니다. + +--- + +## 전체 작업 예제 요약 + +전체 코드를 한 번에 정리하면 다음 순서대로 진행됩니다: + +1. **Perform OCR on image** – `OcrEngine` 생성 +2. **Use Aspose license** – 선택 사항이지만 권장 +3. **Load image for OCR** – `Image.load` 사용 +4. **Set language detection** – `Language.Auto` 로 **recognize text image** 자동 감지 +5. **Extract text from image** – 결과를 출력하고 빈 응답을 우아하게 처리 + +아래 의존성을 포함한 Maven 프로젝트에 위 코드 블록을 그대로 복사하면 됩니다: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` 를 실행하면 콘솔에 인식된 텍스트가 표시됩니다. + +--- + +## 결론 + +Aspose OCR for Java 을 사용해 **perform OCR on image** 파일을 처리하는 전체 과정을 살펴보았습니다. 라이선스 적용부터 **loading the image for OCR**, **recognize text image** 내용, 그리고 최종 **extract text from image** 까지 단계별로 구현했습니다. 이 방법은 여러 언어를 즉시 지원하며, 필요 시 고급 전처리 옵션으로 확장할 수 있습니다. + +다음 단계는 무엇일까요? OCR 결과를 검색 인덱스에 넣어 보거나, 추출된 텍스트로 PDF 를 생성하거나, 다양한 이미지 포맷을 실험해 보세요. 가능성은 무궁무진하며, Aspose 의 강력한 API 덕분에 OCR 문제에 머무는 시간보다 실제 기능 구현에 더 많은 시간을 할애할 수 있습니다. + +궁금한 점이나 특수 케이스가 있으면 아래 댓글에 남겨 주세요—행복한 코딩 되세요! + +## 다음에 배울 내용 + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 확장하거나 변형하는 데 도움이 되는 관련 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공하여 추가 API 기능을 마스터하고 프로젝트에 적용할 수 있도록 돕습니다. + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/polish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7acd74634 --- /dev/null +++ b/ocr/polish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Utwórz przeszukiwalny PDF z obrazu przy użyciu OCR w Pythonie. Dowiedz + się, jak konwertować OCR na PDF, wyodrębniać tekst z obrazu i szybko przeprowadzać + OCR na obrazie. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: pl +og_description: Utwórz przeszukiwalny PDF z obrazu przy użyciu OCR w Pythonie. Ten + przewodnik pokazuje, jak przekonwertować OCR na PDF, wyodrębnić tekst z obrazu i + wykonać OCR na obrazie. +og_title: Utwórz przeszukiwalny PDF w Pythonie – Pełny przewodnik programistyczny +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Tworzenie przeszukiwalnego PDF w Pythonie – Kompletny przewodnik krok po kroku +url: /pl/python-java/general/create-searchable-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 >}} + +# Utwórz przeszukiwalny PDF w Pythonie – Kompletny przewodnik krok po kroku + +Kiedykolwiek potrzebowałeś **utworzyć przeszukiwalny PDF** ze zeskanowanego paragonu, ale nie wiedziałeś od czego zacząć? Nie jesteś sam — wielu programistów napotyka tę samą przeszkodę, gdy po raz pierwszy próbują zamienić zdjęcie tekstu w PDF, który naprawdę można przeszukiwać. + +W tym samouczku przeprowadzimy Cię przez praktyczne rozwiązanie, które pozwala **wykonać OCR na obrazie**, przekształcić wynik OCR w **przeszukiwalny PDF**, a nawet wyciągnąć surowy tekst, jeśli potrzebujesz go do dalszego przetwarzania. Bez zbędnych ozdobników, tylko działający przykład, który możesz skopiować i wkleić do swojego projektu już dziś. + +## Co się nauczysz + +- Jak skonfigurować lekki silnik OCR w Pythonie +- Dokładne kroki, aby **przekształcić OCR do PDF** i zapisać go jako przeszukiwalny dokument +- Sposoby na **wyodrębnienie tekstu z obrazu** do dalszej analizy +- Wskazówki dotyczące radzenia sobie z typowymi problemami, takimi jak orientacja obrazu i duże pliki +- Kompletny, gotowy do uruchomienia skrypt, który możesz dostosować do własnego przypadku użycia + +### Wymagania wstępne + +- Python 3.8+ zainstalowany na Twoim komputerze +- Podstawowa znajomość pip i środowisk wirtualnych (opcjonalnie, ale zalecane) +- Plik obrazu (PNG, JPEG itp.) zawierający wyraźny, maszynowo‑czytelny tekst + +Jeśli masz to wszystko, zanurzmy się. + +## Krok 1: Zainstaluj wymaganą bibliotekę + +The code snippet you saw earlier uses a fictional `ocr` package, but the same ideas apply to real‑world libraries such as **EasyOCR**, **pytesseract**, or **pdfminer.six**. For this guide we’ll use **EasyOCR** because it’s pure Python, supports many languages, and returns a handy PDF conversion method via an auxiliary helper. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Zainstaluj w środowisku wirtualnym (`python -m venv venv && source venv/bin/activate`), aby utrzymać porządek w zależnościach. + +## Krok 2: Zainicjalizuj silnik OCR – Wykonaj OCR na obrazie + +Now that the library is ready, we create an OCR engine and tell it to work with English text. This is the first place where we **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Why do we need a dedicated reader object? EasyOCR pre‑loads language models, so re‑using the same `reader` for multiple images is far more efficient than re‑initializing it each time. + +## Krok 3: Załaduj obraz – Wyodrębnij tekst z obrazu + +Let’s bring the picture into memory. This step is where we **extract text from image** later, but first we just load it. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +If your image is upside‑down or skewed, consider using Pillow’s `rotate` or `transpose` methods before feeding it to the OCR engine. A quick visual check can save you hours of debugging later. + +## Krok 4: Uruchom silnik OCR i przechwyć wyniki + +Here’s the core of the process—sending the image to the OCR engine and getting back structured data. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +The `detail=1` flag gives us bounding boxes, which we’ll need when we later **convert OCR to PDF**. If you only care about raw strings, set `detail=0`. + +## Krok 5: Przekształć wynik OCR w przeszukiwalny PDF – Convert OCR to PDF + +EasyOCR doesn’t provide a direct PDF writer, but we can stitch together the PDF ourselves using Pillow and the `reportlab` library. To keep the tutorial lightweight, we’ll use `fpdf2`, which lets us embed the original image and overlay invisible text. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +What just happened? We placed the scanned image as the visible layer, then wrote the recognized words on top using white text that blends into the white background. Search tools still read the hidden layer, so the PDF becomes **searchable** without altering the visual appearance. + +## Krok 6: Zapisz bajty PDF – Convert Image to PDF + +If you prefer to handle the PDF in memory (e.g., sending it over an API), you can capture the bytes instead of writing directly to disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +That line demonstrates the classic **convert image to PDF** workflow: you start with an image, run OCR, overlay text, and finally emit a PDF stream. + +## Krok 7: Zweryfikuj wynik – Szybkie kontrole + +After you run the script, open `receipt_searchable.pdf` in any PDF viewer and try the search box (Ctrl + F). Type a word you know appears in the receipt—if it jumps to the right spot, you’ve successfully **create searchable pdf**! + +If the search fails, double‑check: + +1. Wyniki pewności OCR (`conf`). Niska pewność może oznaczać, że obraz jest rozmazany. +2. Współrzędne ramki ograniczającej — czasami EasyOCR podaje je w innej orientacji. +3. Czy przeglądarka PDF nie jest ustawiona w tryb „tylko obraz” (rzadko, ale niektóre przeglądarki mają taką opcję). + +## Pełny działający skrypt + +Putting everything together, here’s the complete, ready‑to‑run Python file: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Save this as `searchable_pdf.py`, replace the `YOUR_DIRECTORY` placeholders with real paths, and run: + +```bash +python searchable_pdf.py +``` + +You should see a confirmation message and a brand‑new searchable PDF sitting in your folder. + +## Często zadawane pytania i przypadki brzegowe + +**Co zrobić, jeśli obraz jest kolorowy?** +EasyOCR works with both grayscale and color images, but converting to grayscale (`pil_image.convert("L")`) can sometimes improve accuracy on noisy scans. + +**Czy mogę obsługiwać wielostronicowe PDFy?** +Yes—loop over each page image, run the OCR steps, and append each page to the same `FPDF` object. Just remember to reset the cursor (`self.add_page()`) for each new image. + +**Czy istnieje sposób, aby zachować oryginalną warstwę tekstową zamiast niewidocznego białego tekstu?** +If you need a true “text‑under‑image” PDF (e.g., for accessibility), consider using `pdfminer` or `pikepdf` to embed a hidden text layer with proper PDF tags. That’s more advanced, but the principle remains the same: background image + overlay text. + +**Co zrobić, gdy pewność OCR jest niska?** +You can filter out low‑confidence words: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Podsumowanie – Co osiągnęliśmy + +We started with a simple image of a receipt, **performed OCR on image**, extracted the recognized strings, and finally **create searchable pdf** that behaves like any professionally scanned document. The process covered every secondary keyword—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, and **perform OCR on image**—so you now have a reusable toolbox for any similar project. + +### Kolejne kroki + +- Eksperymentuj z innymi językami, przekazując ich kody ISO do `easyocr.Reader(['en', 'es'])`. +- Zamień EasyOCR na Tesseract, jeśli potrzebujesz w pełni offline'owego rozwiązania; reszta pipeline pozostaje taka sama. +- Dodaj wizualizację pewności OCR (rysowanie ramek na obrazie), aby debugować problematyczne skany. + +Masz własny pomysł, którym chciałbyś się podzielić? Dodaj komentarz, fork + +## Co powinieneś 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. + +- [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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/polish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/polish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..6a0c729de --- /dev/null +++ b/ocr/polish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Wyodrębnij tekst z obrazów w Pythonie za pomocą prostego silnika OCR. + Dowiedz się, jak konwertować zeskanowane obrazy na tekst, rozpoznawać tekst na zdjęciach + oraz efektywnie wyświetlać pliki graficzne w Pythonie. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: pl +og_description: Wyodrębnij tekst z obrazów w Pythonie przy użyciu lekkiego silnika + OCR. Ten przewodnik pokazuje, jak przekształcić zeskanowane obrazy w tekst, rozpoznać + tekst na zdjęciach oraz wypisać pliki graficzne w Pythonie w kilku krokach. +og_title: Wyodrębnianie tekstu z obrazów w Pythonie – Pełny przewodnik po wsadowym + OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Wyodrębnianie tekstu z obrazów w Pythonie – Pełny przewodnik po OCR wsadowym +url: /pl/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wyodrębnianie tekstu z obrazów w Pythonie – Kompletny przewodnik po OCR wsadowym + +Kiedykolwiek potrzebowałeś **wyodrębnić tekst z obrazów**, ale nie wiedziałeś, od czego zacząć? Nie jesteś sam — programiści stale stają przed wyzwaniem przekształcania zeskanowanych PDF‑ów, sfotografowanych paragonów czy zrzutów ekranu w tekst możliwy do przeszukiwania. W tym tutorialu przeprowadzimy Cię przez kompletny, gotowy do uruchomienia przykład, który pokazuje, jak **zamienić zeskanowane obrazy na tekst**, rozpoznać tekst ze zdjęć oraz **list image files python**‑style. Po zakończeniu będziesz mieć wielokrotnego użytku skrypt, który przetwarza cały folder jednorazowo. + +Omówimy wszystko, co potrzebne: wymagane biblioteki, dlaczego każdy krok ma znaczenie, obsługę przypadków brzegowych i trochę rozwiązywania problemów. Nie musisz przeszukiwać zewnętrznych dokumentacji; kod poniżej jest samodzielny, a wyjaśnienia odpowiadają zarówno na „jak”, jak i „dlaczego”. Otwórz ulubione IDE i zaczynamy. + +--- + +## Co zbudujesz + +- Zainicjalizujesz silnik OCR (do ilustracji użyjemy pakietu `ocr`). +- Przeskanujesz katalog i **list image files python**‑style, filtrując PNG, JPG i TIFF. +- Wykonasz operację **batch OCR** na wszystkich znalezionych obrazach. +- Wydrukujesz wyodrębniony tekst dla każdego pliku, wyraźnie oznaczony. + +> **Pro tip:** Jeśli nie masz zainstalowanej biblioteki `ocr`, możesz zamienić ją na `pytesseract` przy kilku drobnych zmianach — logika pozostaje ta sama. + +--- + +## Wymagania wstępne + +- Python 3.8+ (skrypt używa f‑stringów i adnotacji typów). +- Biblioteka OCR udostępniająca `OcrEngine` z metodą `recognize_batch`. W tym przewodniku zakładamy fikcyjny pakiet `ocr`, ale wzorzec działa z prawdziwymi bibliotekami. +- Folder zawierający pliki graficzne, które chcesz przetworzyć (`.png`, `.jpg`, `.tif`). + +--- + +## Krok 1 – Instalacja i import wymaganych modułów + +Najpierw upewnij się, że pakiet OCR jest dostępny. Jeśli używasz prawdziwej biblioteki, takiej jak `pytesseract`, zamień import odpowiednio. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Dlaczego to ważne:** Importowanie `os` zapewnia obsługę ścieżek niezależną od platformy, a `typing.List` pomaga w autouzupełnianiu w IDE i przyszłej rozbudowie. + +--- + +## Krok 2 – **Extract Text from Images**: Inicjalizacja silnika OCR + +Utworzenie silnika to pierwszy krok w każdej pracy z OCR. Ustawiamy także język na automatyczne wykrywanie, aby silnik mógł radzić sobie z dokumentami wielojęzycznymi. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Wyjaśnienie:** Dzięki umieszczeniu tworzenia silnika w funkcji kod pozostaje modularny. Jeśli później będziesz musiał dostosować DPI lub tryb OCR, zmienisz to tylko w jednym miejscu. + +--- + +## Krok 3 – **List Image Files Python**: Zbieranie plików z katalogu + +Teraz musimy zlokalizować każde zdjęcie, które chcemy przetworzyć. Poniższe wyrażenie listowe odzwierciedla typowy wzorzec „list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Obsługa przypadków brzegowych:** Funkcja ignoruje podkatalogi (możesz dodać rekurencję później) i automatycznie odrzuca ukryte pliki, ponieważ zazwyczaj nie kończą się one obsługiwanymi rozszerzeniami. + +--- + +## Krok 4 – **Convert Scanned Images to Text**: Uruchomienie batch OCR + +Większość bibliotek OCR oferuje metodę wsadową, która jest znacznie szybsza niż przetwarzanie pojedynczych obrazów. Oto jak ją wywołać. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Dlaczego batch?** Przesyłanie wszystkich obrazów naraz zmniejsza narzut (np. wielokrotne ładowanie modelu OCR) i często zapewnia lepsze wykorzystanie CPU/GPU. + +--- + +## Krok 5 – **Recognize Text from Pictures**: Wyświetlenie wyników + +Na koniec iterujemy po sparowanych nazwach plików i wynikach OCR, wypisując przejrzysty nagłówek dla każdego obrazu. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Wskazówka:** `strip()` usuwa białe znaki na początku i końcu, które OCR często dodaje. + +--- + +## Pełny skrypt – Połącz wszystko razem + +Poniżej znajduje się kompletny, gotowy do uruchomienia program. Zapisz go jako `batch_ocr.py` i uruchom `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Oczekiwany wynik + +Zakładając, że w folderze znajdują się `invoice1.png` i `receipt.jpg`, możesz zobaczyć: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Każdy blok jest wyraźnie oznaczony, co ułatwia dalsze przetwarzanie (np. zapisywanie do bazy danych). + +--- + +## Rozwiązywanie typowych problemów + +| Problem | Dlaczego się pojawia | Szybka naprawa | +|---------|----------------------|---------------| +| **Brak wyświetlanego tekstu** | Język OCR nie został wykryty lub obraz ma zbyt niski kontrast. | Wymuś język (`engine.language = ocr.Language.English`) lub wstępnie przetwórz obrazy (zwiększ kontrast). | +| **Błąd pamięci przy dużych partiach** | Silnik próbuje załadować wszystkie obrazy jednocześnie. | Podziel `image_files` na fragmenty (`batch_size = 20`) i wywołuj `recognize_batch` wielokrotnie. | +| **Nieobsługiwany format pliku** | Dodałeś `.gif` lub `.bmp`. | Rozszerz krotkę `supported_exts` lub skonwertuj obrazy do PNG/JPG wcześniej. | +| **Zniekształcone znaki Unicode** | OCR zwraca bajty zamiast łańcuchów. | Upewnij się, że biblioteka OCR zwraca Unicode (`result.text.decode('utf‑8')` w razie potrzeby). | + +--- + +## Rozszerzanie przepływu pracy + +Teraz, gdy potrafisz **extract text from images**, rozważ następujące kolejne kroki: + +- **Eksport do CSV** – Zapisz każdą nazwę pliku i wyodrębniony tekst w arkuszu kalkulacyjnym do dalszej analizy. +- **Przetwarzanie równoległe** – Użyj `concurrent.futures.ThreadPoolExecutor`, aby obsługiwać wiele partii jednocześnie. +- **Integracja z chmurowym OCR** – Zamień lokalny silnik na Google Vision lub Azure OCR, aby uzyskać wyższą dokładność przy skomplikowanych układach. +- **Dodaj wstępne przetwarzanie obrazu** – Biblioteki takie jak Pillow lub OpenCV mogą prostować, odszumiewać lub progować obrazy przed OCR, zwiększając wyniki. + +Wszystkie te pomysły naturalnie wykorzystują te same podstawowe funkcje, które zbudowaliśmy, więc nie musisz zaczynać od zera. + +--- + +## Zakończenie + +Przeszliśmy razem przez kompletną metodę **extract text from images** w Pythonie, obejmując wszystko od **list image files python** po **recognize text from pictures** i w końcu **convert scanned images to text** w schludnym trybie wsadowym. Skrypt jest celowo prosty, a jednocześnie na tyle elastyczny, że może służyć jako podstawa większych projektów — czy to digitalizujesz paragony, budujesz przeszukiwalne archiwum, czy tworzysz potok ekstrakcji danych. + +Wypróbuj go, dopasuj kroki wstępnego przetwarzania i obserwuj, jak rośnie dokładność OCR. Jeśli napotkasz problemy, wróć do tabeli „Rozwiązywanie typowych problemów” — większość z nich rozwiązuje się drobną zmianą konfiguracji. + +Gotowy na kolejny wyzwanie? Spróbuj dodać krok konwersji PDF‑na‑obraz przy użyciu `pdf2image`, a następnie podaj te obrazy bezpośrednio do tego samego potoku. Nie ma granic, gdy łączysz OCR z bogatym ekosystemem Pythona. + +Miłego kodowania i niech Twój tekst zawsze będzie czytelny! + +## 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 wyczerpujące wyjaśnienia krok po kroku, pomagające opanować dodatkowe funkcje API i odkrywać alternatywne podejścia 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/) +- [Extract Text Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/polish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..04c0f5bc3 --- /dev/null +++ b/ocr/polish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-19 +description: Wyodrębnij tekst z obrazów przy użyciu Python OCR. Poznaj automatyczne + wykrywanie języka, przetwarzanie równoległe i rozpoznawanie wsadowe w zwięzłym tutorialu. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: pl +og_description: Wyodrębniaj tekst z obrazów przy użyciu OCR w Pythonie. Ten przewodnik + pokazuje automatyczne wykrywanie języka, przetwarzanie równoległe oraz rozpoznawanie + wsadowe w jednym samouczku. +og_title: Wyodrębnianie tekstu z obrazów w Pythonie – pełny przewodnik OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Wyodrębnianie tekstu z obrazów w Pythonie – pełny przewodnik OCR +url: /pl/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# wyodrębnianie tekstu z obrazów w Pythonie – Pełny przewodnik OCR + +Zastanawiałeś się kiedyś, jak **wyodrębnić tekst z obrazów** bez ręcznego przepisywania każdego słowa? Nie jesteś jedyny. Niezależnie od tego, czy digitalizujesz stare paragony, tworzysz przeszukiwalne archiwum dokumentów, czy po prostu bawisz się ciekawymi sztucznymi inteligencjami, umiejętność wyciągania tekstu ze zdjęć jest niezbędna dla każdego programisty Pythona współcześnie. + +W tym samouczku przeprowadzimy Cię przez kompletny, gotowy do uruchomienia przykład, który **wyodrębnia tekst z obrazów** przy użyciu popularnego silnika OCR. Omówimy automatyczne wykrywanie języka, równoległe przetwarzanie dla zwiększenia szybkości oraz rozpoznawanie obrazów w partiach, abyś mógł obsłużyć dziesiątki plików w kilka sekund. Brzmi jak to, czego potrzebujesz? Zanurzmy się. + +## Czego się nauczysz + +- Jak utworzyć instancję silnika OCR za pomocą `ocr.OcrEngine`. +- Włączenie **automatycznego wykrywania języka**, aby silnik sam wybierał odpowiedni język. +- Konfigurowanie **OCR z równoległym przetwarzaniem** przy użyciu własnej puli wątków. +- Uruchamianie **rozpoznawania obrazów w partiach** na liście plików. +- Wyświetlanie rozpoznanego tekstu dla każdego obrazu, gotowego do zapisania lub indeksacji. + +Nie potrzebujesz żadnej zewnętrznej dokumentacji — wszystko, czego potrzebujesz, znajduje się tutaj, a kod działa od razu po zainstalowaniu pakietu `ocr` (zainstaluj go poleceniem `pip install ocr`). + +## Wymagania wstępne + +1. Python 3.8 lub nowszy zainstalowany. +2. Pakiet `ocr` (`pip install ocr`). +3. Folder z obrazami PNG (lub JPG), które chcesz przetworzyć. +4. Podstawowa znajomość funkcji i pętli w Pythonie. + +To wszystko — brak ciężkich zależności, żadnej magii GPU, po prostu czysty Python. + +![przykład wyodrębniania tekstu z obrazów](https://example.com/ocr-demo.png "Zrzut ekranu pokazujący wynik wyodrębniania tekstu z obrazów") + +*Alt text: zrzut ekranu demonstracji wyodrębniania tekstu z obrazów* + +## Krok 1 – Konfiguracja silnika OCR (Główne słowo kluczowe w akcji) + +Na początek: utwórz instancję silnika OCR. `ocr.OcrEngine()` to mózg całej operacji; wie, jak odczytywać znaki, linie i akapity. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Dlaczego potrzebujemy wyraźnego silnika? Ponieważ **użycie ocr.OcrEngine** daje Ci precyzyjną kontrolę nad ustawieniami języka, wątkami i nie tylko. To najelastyczniejszy sposób na **wyodrębnianie tekstu z obrazów** w porównaniu do jednowierszowych pomocników. + +## Krok 2 – Niech silnik automatycznie wykrywa języki + +Większość bibliotek OCR wymaga podania języka, którego mają szukać. To w porządku przy projekcie jednojęzycznym, ale uciążliwe przy mieszanej partii językowej. Na szczęście pakiet `ocr` obsługuje **automatyczne wykrywanie języka**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Ustawienie `engine.language` na `ocr.Language.Auto` mówi silnikowi, aby „powąchał” każdy obraz i wybrał odpowiedni model językowy. Ten krótki wiersz oszczędza godziny ręcznej konfiguracji przy pracy z dokumentami międzynarodowymi. + +## Krok 3 – Przyspiesz działanie dzięki równoległemu przetwarzaniu OCR + +Masz cztery lub więcej rdzeni CPU? Dlaczego ich nie wykorzystać? Silnik może uruchomić pulę wątków, pozwalając na jednoczesne przetwarzanie wielu obrazów. To właśnie **równoległe przetwarzanie OCR** pokazuje swoją moc. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Śmiało dostosuj liczbę `4` do możliwości swojego komputera. Więcej wątków → szybsze przetwarzanie partii, ale pamiętaj, że każdy wątek zużywa pamięć, więc znajdź optymalny punkt dla swojego środowiska. + +## Krok 4 – Zbierz obrazy, które chcesz przetworzyć + +Teraz potrzebujemy listy ścieżek do plików. Możesz zbudować tę listę ręcznie, odczytać ją z CSV lub użyć `glob`. Dla przejrzystości zakodujemy krótką listę na stałe: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Zastąp `YOUR_DIRECTORY` rzeczywistą ścieżką w swoim systemie. Jeśli masz dziesiątki plików, szybkie `glob.glob("*.png")` wykona ciężką pracę. + +## Krok 5 – Uruchom rozpoznawanie obrazów w partiach + +Oto serce samouczka: jedno wywołanie, które przetwarza każdy obraz w `files` i zwraca listę obiektów wynikowych. To funkcja **rozpoznawania obrazów w partiach**, która czyni OCR na dużą skalę praktycznym. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +W tle silnik rozdziela każdy plik na cztery wątki robocze, które skonfigurowaliśmy wcześniej, jednocześnie automatycznie wykrywając język dla każdego obrazu. Metoda zwraca listę, w której każdy element zawiera rozpoznany tekst oraz metadane. + +## Krok 6 – Wyświetl (lub zapisz) wyodrębniony tekst + +Na koniec przechodzimy po wynikach i drukujemy tekst. W prawdziwym projekcie prawdopodobnie zapiszesz to do bazy danych lub pliku CSV, ale wyświetlanie utrzymuje przykład prostym. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Oczekiwany wynik** (skrócony dla przejrzystości): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Każdy blok pokazuje nazwę pliku, po której następuje ciąg znaków wygenerowany przez OCR. Jeśli obraz zawiera wiele języków, zobaczysz odpowiednie znaki dzięki wcześniejszemu krokowi **automatycznego wykrywania języka**. + +## Profesjonalne wskazówki i typowe pułapki + +- **Jakość obrazu ma znaczenie** – rozmyte lub niskokontrastowe zdjęcia wygenerują śmieci. W razie potrzeby wstępnie przetwórz je za pomocą OpenCV (`cv2.threshold`, `cv2.resize`). +- **Liczba wątków vs. I/O** – jeśli Twoje obrazy znajdują się na wolnym dysku sieciowym, więcej wątków może nie pomóc. Monitoruj użycie CPU przy pomocy `top` lub `Task Manager`. +- **Obsługa Unicode** – `result.text` jest ciągiem Unicode. Przy zapisie do plików otwieraj je z `encoding="utf‑8"`, aby uniknąć `UnicodeEncodeError`. +- **Zużycie pamięci** – duże pliki PDF mogą pochłaniać dużo RAMu. Jeśli napotkasz `MemoryError`, zmniejsz rozmiar puli wątków lub przetwarzaj obrazy w mniejszych partiach. + +## Pełny działający skrypt + +Poniżej znajduje się kompletny, gotowy do skopiowania i wklejenia skrypt, który zawiera wszystkie omówione kroki. Zapisz go jako `batch_ocr.py` i uruchom `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Uruchom go w ten sposób: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Zobaczysz ładnie sformatowany blok tekstu dla każdego obrazu, co dowodzi, że możesz **wyodrębniać tekst z obrazów** na dużą skalę. + +## Co dalej? + +Teraz, gdy opanowałeś podstawy **wyodrębniania tekstu z obrazów** w Pythonie, rozważ dalsze eksploracje: + +- **Post‑processing**: oczyszczanie wyników OCR przy użyciu wyrażeń regularnych lub bibliotek przetwarzania języka naturalnego. +- **Konwersja do PDF**: wprowadź wyodrębnione ciągi do generatora PDF, aby uzyskać przeszukiwalne dokumenty. +- **Usługi OCR w chmurze**: porównaj wyniki `ocr` lokalnie z Google Vision lub Azure OCR pod kątem dokładności w trudnych przypadkach. +- **Interfejs GUI**: zbuduj małą aplikację Flask lub FastAPI, która pozwoli użytkownikom wgrywać obrazy i natychmiast widzieć wyodrębniony tekst. + +Wszystkie te tematy opierają się na fundamencie **biblioteki OCR dla Pythona**, którą właśnie skonfigurowałeś, i korzystają z tych samych **trików równoległego przetwarzania OCR**, które zastosowaliśmy tutaj. + +--- + +*Miłego kodowania! Jeśli napotkasz problemy, zostaw komentarz poniżej — zawsze chętnie pomogę rozwiązać trudności związane z OCR.* + +## 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 wraz z wyjaśnieniami 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 obrazu – Optymalizacja OCR z Aspose.OCR dla .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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/polish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..24d1ba5d3 --- /dev/null +++ b/ocr/polish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-06-19 +description: Jak wyodrębnić PDF za pomocą OCR w Pythonie – krok po kroku tutorial + obejmujący wyodrębnianie tekstu z PDF, rozpoznawanie tekstu z obrazu oraz przykład + OCR w Pythonie. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: pl +og_description: Jak wyodrębnić PDF za pomocą OCR w Pythonie. Dowiedz się, jak wyodrębnić + tekst z PDF, rozpoznać tekst z obrazu i zobacz kompletny przykład OCR w Pythonie. +og_title: Jak wyodrębnić tekst z PDF przy użyciu OCR w Pythonie – pełny poradnik +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Jak wyodrębnić tekst z PDF przy użyciu OCR w Pythonie – Kompletny przewodnik +url: /pl/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak wyodrębnić tekst z PDF przy użyciu OCR w Pythonie – Kompletny przewodnik + +Zastanawiałeś się kiedyś **jak wyodrębnić PDF** zawartość, gdy plik jest jedynie zeskanowanym obrazem? Nie jesteś jedyny. W wielu rzeczywistych projektach — myśl o umowach, fakturach czy archiwach historycznych — otrzymany PDF nie zawiera tekstu, który można zaznaczyć. Dobra wiadomość? Kilka linijek Pythona może zamienić te jedynie obrazowe strony w przeszukiwalny, edytowalny tekst. + +W tym tutorialu przeprowadzimy praktyczny **przykład OCR w Pythonie**, który odczytuje PDF, renderuje jego pierwszą stronę jako obraz, a następnie **wyodrębnia tekst z PDF** przy użyciu silnika OCR. Po zakończeniu dokładnie będziesz wiedział, jak **czytać PDF z OCR**, dlaczego każdy krok ma znaczenie i jak dostosować kod do dokumentów wielostronicowych lub różnych języków. + +## Co się nauczysz + +- Zainstaluj i skonfiguruj niezawodną bibliotekę OCR dla Pythona. +- Konwertuj strony PDF na obrazy odpowiednie dla OCR. +- **Rozpoznawaj tekst z obrazu** i uzyskaj czyste ciągi Unicode. +- Typowe pułapki (PDF o niskiej rozdzielczości, obrócone strony) i jak ich unikać. +- Rozszerz skrypt, aby obsługiwał wiele stron lub przetwarzanie wsadowe. + +**Wymagania wstępne**: Python 3.8+, pip oraz podstawowa znajomość środowisk wirtualnych. Nie wymagana wcześniejsza znajomość OCR — po prostu podążaj za instrukcjami. + +--- + +## ## Jak wyodrębnić tekst z PDF przy użyciu OCR w Pythonie + +Ten nagłówek H2 zawiera nasze główne słowo kluczowe dokładnie tam, gdzie wyszukiwarki go uwielbiają. Zanurzmy się od razu w kod. + +### Krok 1 – Zainstaluj wymagane pakiety + +Najpierw potrzebujemy silnika OCR. Poniższy przykład używa popularnego pakietu **ocr** (cienka nakładka na Tesseract). Jeśli wolisz inny backend, koncepcje pozostają takie same. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Porada:** Na Linuksie będziesz także potrzebował binarki Tesseract: `sudo apt-get install tesseract-ocr`. Użytkownicy macOS mogą ją pobrać przez Homebrew: `brew install tesseract`. + +### Krok 2 – Zainicjalizuj silnik OCR i ustaw język + +Teraz uruchamiamy silnik i instruujemy go, aby szukał angielskich znaków. Możesz zamienić `ocr.Language.English` na dowolny obsługiwany kod języka. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Dlaczego to ważne:** Określenie języka znacząco zwiększa dokładność, ponieważ silnik może zastosować słowniki i modele znaków specyficzne dla języka. + +### Krok 3 – Wczytaj stronę PDF jako obraz + +OCR działa na obrazach rastrowych, nie na obiektach PDF. Pomocnicza funkcja `ocr.Image.from_pdf` renderuje wybraną stronę do bitmapy. Dostosuj `page_number` dla innych stron (indeksowanie od 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Przypadek brzegowy:** Jeśli PDF zawiera grafikę wektorową zamiast zeskanowanych obrazów, możesz uzyskać wyraźne renderowanie. Dla skanów o niskiej rozdzielczości rozważ zwiększenie DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Krok 4 – Rozpoznaj tekst z wyrenderowanego obrazu + +Oto serce **przykładu ocr w Pythonie**. Silnik przetwarza bitmapę i zwraca obiekt zawierający wyodrębniony ciąg znaków. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Atrybut `ocr_result.text` zawiera wynik w postaci zwykłego tekstu, zachowując podziały linii, gdy to możliwe. + +### Krok 5 – Wydrukuj lub zapisz wyodrębniony tekst + +Na koniec wypisujemy wynik. W rzeczywistej aplikacji prawdopodobnie zapisałbyś go do pliku lub bazy danych. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Uruchomienie skryptu powinno wyświetlić coś podobnego do: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +To kompletny **wyodrębnianie tekstu z pdf** przy użyciu OCR. + +--- + +## ## Rozpoznawanie tekstu z obrazu – Dostosowywanie dokładności + +Jeśli interesuje Cię tylko **rozpoznawanie tekstu z obrazu** (np. JPEG paragonu), możesz pominąć krok konwersji PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Wskazówki dla lepszych wyników:** + +- **Wstępne przetwarzanie** obrazu: konwersja do odcieni szarości, zastosowanie progowania lub prostowanie (deskew). Pillow ułatwia to. +- **Zwiększ DPI** podczas renderowania PDF: wyższa rozdzielczość dostarcza silnikowi OCR więcej szczegółów. +- **Włącz konfigurację silnika OCR** dla segmentacji stron (`ocr_engine.config = "--psm 6"` dla jednolitych bloków). + +## ## Czytanie PDF z OCR – Obsługa wielu stron + +Większość umów rozciąga się na kilka stron. Iterowanie po każdej stronie jest proste: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Ta funkcja **czyta PDF z OCR**, konkatenatuje wynik i wstawia wyraźny znacznik podziału strony. Następnie możesz przekazać `full_text` do indeksu wyszukiwania lub zapisać jako plik `.txt`. + +## ## Typowe problemy i jak je naprawić + +| Objaw | Prawdopodobna przyczyna | Rozwiązanie | +|---------|--------------|-----| +| Zniekształcone znaki, dużo `?` | Nieprawidłowy język lub brak plików danych językowych | Zainstaluj właściwy pakiet językowy Tesseract (`tesseract-ocr-`) i ustaw `ocr_engine.language`. | +| Brakujące linie lub przycięte słowa | Niska rozdzielczość DPI (poniżej 150) | Renderuj PDF w 300 DPI lub wyżej (`dpi=300`). | +| Tekst jest obrócony lub do góry nogami | Zeskanowana strona nie jest prawidłowo ustawiona | Użyj `ocr.Image.deskew(page_image)` przed rozpoznaniem. | +| Wolne przetwarzanie dużych PDF‑ów | Przetwarzanie stron kolejno w jednym wątku | Zrównoleglij przy użyciu `concurrent.futures.ThreadPoolExecutor`. | + +## ## Rozszerzanie przykładu OCR w Pythonie + +- **Eksport do PDF/A**: Po wyodrębnieniu możesz osadzić tekst z powrotem w przeszukiwalnym PDF przy użyciu `reportlab` lub `pypdf2`. +- **Wykrywanie języka**: Użyj `langdetect` na wyniku OCR, aby dynamicznie przełączać `ocr_engine.language`. +- **Przetwarzanie wsadowe**: Przejdź po katalogu za pomocą `os.listdir` i zastosuj `extract_all_pages` do każdego pliku. + +## ## Oczekiwany wynik i weryfikacja + +Gdy uruchomisz skrypt na wyraźnym skanie w języku angielskim, powinieneś zobaczyć czysty blok tekstu z prawidłową interpunkcją. Zweryfikuj przez: + +1. Porównanie kilku linii z oryginalnym zeskanowanym obrazem. +2. Uruchomienie prostego liczenia słów (`len(ocr_result.text.split())`), aby upewnić się, że wynik nie jest pusty. +3. Opcjonalnie, przekazanie wyniku do sprawdzania pisowni, np. `pyspellchecker`, aby wykryć błędy OCR. + +## Podsumowanie + +Omówiliśmy **jak wyodrębnić PDF** zawartość, gdy tradycyjne parsowanie zawodzi, przedstawiliśmy pełny **przykład ocr w Pythonie** i wyjaśniliśmy, jak **rozpoznawać tekst z obrazu** oraz **czytać PDF z OCR** zarówno dla pojedynczych, jak i wielostronicowych scenariuszy. Dzięki powyższym fragmentom kodu możesz teraz zamienić dowolny zeskanowany PDF w przeszukiwalny, edytowalny tekst — bez ręcznego przepisywania. + +Kolejne kroki? Spróbuj zamienić język na hiszpański (`ocr.Language.Spanish`) lub eksperymentuj z technikami wstępnego przetwarzania obrazu, aby zwiększyć dokładność. Jeśli budujesz system zarządzania dokumentami, rozważ indeksowanie wyodrębnionego tekstu w Elasticsearch dla błyskawicznego wyszukiwania. + +Masz pytania lub napotkałeś dziwny PDF? zostaw komentarz i szczęśliwego kodowania! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletny działający kod 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/) +- [Rozpoznaj tekst PDF – operacje OCR z Aspose.OCR dla Java](/ocr/english/java/ocr-operations/) +- [Wyodrębnij tekst z obrazu w C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/polish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..b2886e3b8 --- /dev/null +++ b/ocr/polish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-06-19 +description: Dowiedz się, jak używać OCR w Javie z Aspose. Ten przewodnik krok po + kroku obejmuje automatyczne prostowanie obrazów, automatyczne wykrywanie języka + oraz łatwe wyodrębnianie tekstu z obrazu. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: pl +og_description: 'Jak używać OCR w Javie z Aspose: pełny przewodnik obejmujący automatyczne + prostowanie obrazów, automatyczne wykrywanie języka oraz wyodrębnianie tekstu z + obrazów.' +og_title: Jak korzystać z OCR w Javie z Aspose – Kompletny przewodnik +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Jak używać OCR w Javie z Aspose – kompletny przewodnik +url: /pl/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak używać OCR w Javie z Aspose – Kompletny przewodnik + +Zastanawiałeś się kiedyś **jak używać OCR** w projekcie Java, nie tracąc włosów z powodu konfiguracji? Nie jesteś jedyny. Wielu programistów napotyka problem, gdy muszą szybko **wyodrębnić tekst z obrazu**, szczególnie gdy skany źródłowe są krzywe lub napisane w nieznanym języku. + +W tym samouczku przeprowadzimy Cię przez praktyczny przykład, który pokaże dokładnie, jak używać OCR z Aspose, w tym **auto deskew images**, **auto language detection** oraz pełną **ocr image preprocessing** pipeline. Po zakończeniu będziesz mieć gotowy do uruchomienia fragment kodu, który wypisuje rozpoznany tekst w konsoli, i zrozumiesz, dlaczego każde ustawienie ma znaczenie. + +> **Co otrzymasz:** kompletny, uruchamialny program w Javie, wyjaśnienia każdego wiersza, wskazówki dotyczące obsługi przypadków brzegowych oraz pomysły na rozszerzenie rozwiązania do przetwarzania wsadowego lub PDF‑ów. + +--- + +## Wymagania wstępne + +- Java 17 (lub dowolny nowszy JDK) zainstalowany i skonfigurowany. +- Maven lub Gradle do zarządzania zależnościami (pokażemy współrzędne Maven). +- Plik licencji Aspose OCR for Java (`Aspose.OCR.Java.lic`). Jeśli tylko testujesz, możesz pominąć krok licencji, ale wersja próbna doda znak wodny. +- Przykładowy obraz (`your_image.png`) umieszczony w miejscu dostępnym dla kodu. + +> **Pro tip:** przechowuj obrazy w dedykowanym folderze `resources` i wczytuj je przez classpath; unika to problemów z ścieżkami na różnych systemach operacyjnych. + +## Krok 1: Skonfiguruj projekt i dodaj zależność Aspose OCR + +Utwórz nowy projekt Maven (lub użyj istniejącego) i dodaj poniższe do swojego `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Uruchom `mvn clean install`, aby pobrać bibliotekę. Jeśli wolisz Gradle, równoważny kod to: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Teraz masz klasy **ocr image preprocessing** na swoim classpath. + +## Krok 2: Zastosuj licencję Aspose OCR (opcjonalnie, ale zalecane) + +Jeśli posiadasz licencję, zastosuj ją od razu na początku metody `main`. Pominięcie tego kroku działa, ale wersja darmowa dodaje znak wodny „Demo” do wyniku. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Dlaczego to ważne:** Wersja licencjonowana usuwa limity użytkowania i wyłącza znak wodny, dając czyste, gotowe do produkcji wyniki. + +## Krok 3: Utwórz instancję silnika OCR + +Silnik jest sercem procesu. Utworzenie jego instancji daje dostęp do wszystkich opcji **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +W tym momencie silnik jest gotowy, ale użyje domyślnych ustawień, które mogą nie być optymalne dla zeskanowanych dokumentów. Dostosujmy kilka. + +## Krok 4: Włącz Auto Deskew Images dla czystszych skanów + +Przechylone skany to częsty problem. Aspose oferuje funkcję **auto deskew images**, która automatycznie prostuje obraz przed rozpoznaniem. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Jak to działa:** Algorytm analizuje kąty linii bazowej tekstu i obraca obraz do najbardziej prawdopodobnej pionowej orientacji. To znacząco zwiększa dokładność zdjęć zrobionych telefonem. + +## Krok 5: Włącz Auto Language Detection + +Jeśli nie znasz języka obrazu źródłowego, pozwól silnikowi go określić. To jest ustawienie **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Gdy włączysz to, Aspose skanuje glify i wybiera najbardziej prawdopodobny model językowy, obsługując ponad 30 języków od razu. + +## Krok 6: Wczytaj obraz, który chcesz rozpoznać + +Możesz wczytać obraz z dysku, URL lub nawet tablicy bajtów. Dla prostoty odczytamy go z lokalnego pliku. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Wskazówka:** Jeśli pracujesz z dużymi obrazami, rozważ ich najpierw zmniejszenie przy pomocy `engine.getImagePreprocessing().setResizeFactor(0.5)`, aby przyspieszyć przetwarzanie bez utraty wielu szczegółów. + +## Krok 7: Wykonaj rozpoznawanie OCR i wyodrębnij tekst z obrazu + +Teraz silnik wykonuje swoją magię. Metoda `recognize` zwraca obiekt `OcrResult`, który zawiera rozpoznany tekst, wyniki pewności i inne informacje. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Konsola wyświetli zwykły tekst wyodrębniony z obrazu — to jest główny rezultat **extract text image**, który chcieliśmy osiągnąć. + +## Pełny działający przykład + +Poniżej znajduje się pełna klasa Java, która łączy wszystko razem. Skopiuj i wklej ją do `src/main/java/com/example/OcrDemo.java` i uruchom ją. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Oczekiwany wynik + +Jeśli obraz zawiera frazę „Hello World” na czystym skanie, zobaczysz: + +``` +=== Recognized Text === +Hello World +``` + +Dla bardziej złożonych dokumentów (np. wielojęzycznych paragonów), wynik będzie zawierał podziały wierszy i wykryty kod języka. + +## Częste pułapki i wskazówki + +| Problem | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| **Zniekształcone znaki** | Obraz jest zbyt ciemny lub zaszumiony. | Włącz `engine.getImagePreprocessing().setBinarization(true)` lub ręcznie dostosuj kontrast. | +| **Nieprawidłowy język** | Automatyczne wykrywanie nie działa poprawnie na stronach z mieszanymi językami. | Ustaw `engine.setLanguage(Language.English)` (lub odpowiedni enum), aby wymusić konkretny język. | +| **Wolne przetwarzanie** | Bardzo wysokiej rozdzielczości obrazy. | Zmniejsz rozdzielczość przy pomocy `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Błędy pamięci (Out‑of‑memory)** | Duża partia obrazów ładowana jednocześnie. | Przetwarzaj obrazy kolejno i wywołuj `engine.dispose()` po każdym uruchomieniu. | + +> **Pamiętaj:** Silnik OCR jest bezpieczny wątkowo dla operacji tylko do odczytu, ale tworzenie nowej instancji na wątek unika ukrytych błędów stanu. + +## Rozszerzanie rozwiązania + +Teraz, gdy wiesz **jak używać OCR** z Aspose, możesz chcieć: + +1. Przetwarzać PDF‑y – konwertować każdą stronę PDF na obraz (`PdfConverter`), a następnie podać go do tej samej pipeline. +2. Przetwarzać wsadowo folder – iterować po plikach w katalogu, stosując te same kroki, i zapisywać wyniki do CSV. +3. Zintegrować z usługą webową – udostępnić logikę OCR poprzez Spring Boot `@RestController`, który przyjmuje przesyłane pliki multipart. + +Wszystkie te scenariusze ponownie wykorzystują tę samą konfigurację **ocr image preprocessing**, którą zbudowaliśmy tutaj. + +## Zakończenie + +Omówiliśmy **jak używać OCR** w Javie z Aspose od początku do końca: zastosowanie licencji, utworzenie silnika, włączenie **auto deskew images**, włączenie **auto language detection**, wczytanie obrazu i w końcu **extract text image** przy użyciu jednego `System.out.println`. Kod jest w pełni samodzielny, działa na dowolnym nowszym JDK i demonstruje najlepsze praktyki pod kątem dokładności i wydajności. + +Wypróbuj go na własnych zdjęciach — może zeskanowanym kontrakcie lub zrzucie ekranu paragonu. Dostosuj flagi przetwarzania wstępnego, eksperymentuj z różnymi językami i szybko zobaczysz, dlaczego biblioteka OCR od Aspose jest solidnym wyborem do produkcyjnego wyodrębniania tekstu. + +Masz pytania lub chcesz podzielić się wynikami? zostaw komentarz poniżej lub napisz do mnie na GitHubie. Szczęśliwego kodowania! + +![Przykład użycia OCR w Javie](/images/ocr-java-example.png "Jak używać OCR w Javie – zrzut ekranu demo Aspose") + +## 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 odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak wykonać OCR tekstu obrazu z językiem przy użyciu Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Wyodrębnij tekst z obrazu w Javie przy użyciu Aspose.OCR w trybie wykrywania obszarów](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Jak używać OCR – zaawansowane techniki z Aspose.OCR dla Javy](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/polish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..9ee4a7b07 --- /dev/null +++ b/ocr/polish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Popraw dokładność OCR w Pythonie przy użyciu Aspose OCR. Dowiedz się, + jak ustawić język OCR, wczytać obraz do OCR i wyodrębnić tekst z obrazu przy użyciu + własnego słownika. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: pl +og_description: Popraw dokładność OCR w Pythonie, ustawiając język OCR, wczytując + obraz do OCR i wyodrębniając tekst z obrazu przy użyciu własnego słownika. +og_title: Popraw dokładność OCR w Pythonie – przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Popraw dokładność OCR w Pythonie – Kompletny przewodnik +url: /pl/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Popraw Dokładność OCR w Pythonie – Kompletny Przewodnik + +Zastanawiałeś się kiedyś, jak **poprawić dokładność OCR**, gdy skanowany tekst zawiera dziwne symbole, kody produktów lub nazwy marek? Nie jesteś sam. W wielu projektach domyślny silnik po prostu wypisuje bełkot, co jest prawdziwym zabójcą produktywności. + +W tym samouczku przeprowadzimy praktyczny, kompleksowy przykład, który pokaże Ci, jak **ustawić język OCR**, **załadować obraz do OCR**, **wykonać OCR na obrazie**, a na koniec **wyodrębnić tekst z obrazu** przy użyciu własnego słownika, który zwiększa współczynniki rozpoznawania. Po zakończeniu będziesz mieć gotowy do uruchomienia skrypt, który możesz wkleić do dowolnego projektu w Pythonie. + +## Co Zyskasz + +- W pełni funkcjonalny skrypt w Pythonie, który używa Aspose OCR do odczytu pliku PNG. +- Możliwość **poprawy dokładności OCR** poprzez konfigurację języka i własnej listy słów. +- Jasne wyjaśnienia, dlaczego każde ustawienie ma znaczenie, oraz wskazówki dotyczące obsługi przypadków brzegowych, takich jak znaki niełacińskie. +- Szybka lista kontrolna do rozwiązywania typowych problemów OCR. + +### Wymagania wstępne + +- Python 3.8 lub nowszy zainstalowany na twoim komputerze. +- Pakiet `aspose-ocr` (zainstaluj za pomocą `pip install aspose-ocr`). +- Przykładowy obraz (`technical_doc.png`) zawierający tekst, który chcesz odczytać. +- Podstawowa znajomość Pythona — nic skomplikowanego nie jest potrzebne. + +> **Pro tip:** Jeśli pracujesz w wirtualnym środowisku, aktywuj je przed instalacją pakietu. Dzięki temu zależności będą uporządkowane, a konflikty wersji uniknięte. + +--- + +## Krok 1: Zainstaluj i zaimportuj Aspose OCR + +First things first—let’s get the library into our environment and import the pieces we need. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Namespace `aspose.ocr` daje dostęp do klasy `OcrEngine`, która jest sercem procesu OCR. Importowanie jej tutaj utrzymuje resztę skryptu w czystości i czytelności. + +--- + +## Krok 2: Utwórz silnik OCR i **Ustaw język OCR** + +Dlaczego język ma znaczenie? Silniki OCR opierają się na modelach specyficznych dla języka, aby rozpoznawać kształty znaków i wzorce słów. Jeśli powiesz silnikowi, że skanujesz tekst po angielsku, zignoruje on cyrylicę i skupi się na alfabecie łacińskim, co dramatycznie **poprawia dokładność OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Uwaga:** Aspose OCR obsługuje ponad 50 języków. Zamień `ocr.Language.English` na `ocr.Language.Spanish`, `ocr.Language.French` itp., jeśli twój dokument nie jest po angielsku. + +--- + +## Krok 3: Zdefiniuj **Własny słownik**, aby zwiększyć dokładność + +Wyobraź sobie, że skanujesz faktury zawierające słowo „AsposeOCR” lub kody produktów takie jak „SKU12345”. Silnik nie zna tych terminów, więc zgaduje niepoprawnie. Dostarczenie własnej listy słów mówi silnikowi: *„Hej, te ciągi są prawidłowe — nie próbuj ich korygować.”* To szybki sposób na **poprawę dokładności OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Możesz wczytać tę listę z pliku lub bazy danych, jeśli masz setki wpisów — dla prostoty trzymaj ją w liście Pythona. + +--- + +## Krok 4: **Załaduj obraz do OCR** + +Teraz potrzebujemy obrazu. Metoda `Image.load` przyjmuje ścieżkę do dowolnego obsługiwanego formatu rastrowego (PNG, JPEG, BMP itp.). Jeśli plik nie zostanie znaleziony, silnik rzuci wyjątek, więc zabezpieczymy się przed tym. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Dlaczego ten krok ma znaczenie:** Poprawne załadowanie obrazu zapewnia, że silnik pracuje na dokładnych danych pikselowych, które zamierzasz analizować. Uszkodzone pliki lub błędne ścieżki to częste źródło frustracji. + +--- + +## Krok 5: **Wykonaj OCR na obrazie** i wyodrębnij wyniki + +Po skonfigurowaniu silnika i przygotowaniu obrazu, faktyczne rozpoznanie odbywa się jednym wywołaniem metody. Obiekt wyniku zawiera surowy tekst, oceny pewności oraz nawet informacje o układzie, jeśli będą potrzebne później. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Jeśli potrzebujesz **wyodrębnić tekst z obrazu** wiersz po wierszu, możesz podzielić go po znakach nowej linii: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Krok 6: Zweryfikuj wynik – Czy naprawdę **poprawia dokładność OCR**? + +Wypiszmy wynik i sprawdźmy, czy nasz własny słownik zrobił różnicę. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Typowy wynik dla przykładowego obrazu może wyglądać tak: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Zauważ, że nazwa marki, grecki znak i kod produktu pojawiają się dokładnie tak, jak je zdefiniowaliśmy. Bez własnego słownika silnik próbowałby je „korygować”, często dając coś w stylu „Aspose OCR” lub „SKU 1234”. + +--- + +## Typowe pułapki i jak sobie z nimi radzić + +| Problem | Dlaczego się pojawia | Rozwiązanie | +|-------|----------------|-----| +| **Złe znaki** | Nieprawidłowo ustawiony język lub obraz o niskiej rozdzielczości | Upewnij się, że `engine.language` odpowiada językowi źródłowemu i użyj skanu o wysokiej rozdzielczości (300 dpi lub wyższej). | +| **Ignorowane własne słowa** | Słownik nie został podłączony lub literówka w nazwie właściwości | Sprawdź ponownie `engine.text_processing.custom_dictionary = …`. | +| **Plik nie znaleziony** | Nieprawidłowa ścieżka lub brak uprawnień do pliku | Użyj `os.path.abspath()`, aby zweryfikować ścieżkę bezwzględną; uruchom skrypt z odpowiednimi uprawnieniami. | +| **Wolne przetwarzanie** | Duże obrazy lub wiele stron | Wstępnie przetwórz obraz (przytnij, zmień rozmiar) lub użyj `engine.recognize(image, max_threads=4)`, aby równolegle przetwarzać. | + +--- + +## Dalej: Zaawansowane ustawienia dla **poprawy dokładności OCR** + +1. **Pre‑processing** – Zastosuj zwiększenie kontrastu lub binaryzację przy pomocy Pillow przed przekazaniem obrazu do Aspose OCR. +2. **Wiele języków** – Ustaw `engine.language = ocr.Language.English | ocr.Language.French`, aby włączyć rozpoznawanie dwujęzyczne. +3. **OCR oparty na regionie** – Jeśli potrzebujesz tylko określonego obszaru (np. tabeli), najpierw przytnij obraz, aby zredukować szum. +4. **Filtrowanie pewności** – `result.confidence` zwraca wynik dla każdego znaku; możesz odrzucać wyniki o niskiej pewności programowo. + +--- + +## Pełny działający skrypt + +Poniżej znajduje się kompletny, gotowy do skopiowania skrypt, który zawiera wszystkie omówione kroki. Zapisz go jako `improve_ocr_accuracy.py` i uruchom z wiersza poleceń. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Uruchom go: + +```bash +python improve_ocr_accuracy.py +``` + +Powinieneś zobaczyć ładnie sformatowany wynik, który pokazaliśmy wcześniej. + +--- + +## Zakończenie + +Omówiliśmy prosty sposób na **poprawę dokładności OCR** w Pythonie poprzez: + +1. **Ustawienie języka OCR** zgodnego z dokumentem. +2. **Poprawne załadowanie obrazu**, aby silnik widział właściwe piksele. +3. **Wykonanie OCR na obrazie** jednym wywołaniem metody. +4. **Wyodrębnienie tekstu z obrazu** i weryfikację wyniku. +5. **Dodanie własnego słownika**, aby utrwalić terminy specyficzne dla domeny. + +To cały przepływ — od surowego obrazu do czystego, przeszukiwalnego tekstu — zamknięty w schludnym, wielokrotnego użytku skrypcie. + +Jeśli jesteś gotowy na kolejny krok, spróbuj eksperymentować z wstępnym przetwarzaniem obrazu (kontrast, prostowanie) lub przełącz się na konfigurację wielojęzyczną używając `ocr.Language.English | ocr.Language.German`. Te same zasady obowiązują, a Ty będziesz **poprawiać dokładność OCR** w szerszym zestawie dokumentów. + +Masz pytania lub nietypowy przypadek? zostaw komentarz poniżej i powodzenia w kodowaniu! + +![improve OCR accuracy + + +## Co powinieneś nauczyć się dalej? + + +Poniższe samouczki obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każde źródło 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. + +- [Wyodrębnij tekst z obrazu – optymalizacja OCR z Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [rozpoznaj tekst obrazu przy użyciu Aspose OCR dla wielu języków](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Jak ustawić wartość progową w rozpoznawaniu obrazu OCR](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/polish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..4bb7a4c1a --- /dev/null +++ b/ocr/polish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,289 @@ +--- +category: general +date: 2026-06-19 +description: Wykonaj OCR na obrazie przy użyciu biblioteki OCR w Pythonie. Dowiedz + się, jak wykrywać tekst na obrazie, rozpoznawać tekst z pliku JPEG i efektywnie + wyodrębniać tekst ze skanowanego obrazu. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: pl +og_description: Wykonaj OCR na obrazie przy użyciu Pythona i wyodrębnij tekst ze skanowanych + plików. Ten przewodnik krok po kroku przeprowadzi Cię przez ładowanie obrazów, prostowanie + oraz rozpoznawanie tekstu. +og_title: Wykonaj OCR na obrazie w Pythonie – Kompletny przewodnik po wyodrębnianiu + tekstu +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Wykonaj OCR na obrazie w Pythonie – Kompletny przewodnik po ekstrakcji tekstu +url: /pl/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wykonaj OCR na obrazie w Pythonie – Kompletny przewodnik po ekstrakcji tekstu + +Czy kiedykolwiek potrzebowałeś **perform OCR on image** plików, ale napotykałeś na problemy, ponieważ kod wyglądał zagadkowo? Nie jesteś sam. Niezależnie od tego, czy przekształcasz stos zeskanowanych paragonów w przeszukiwalne PDF‑y, czy wyciągasz podpisy z JPEG‑a do projektu data‑science, umiejętność rozpoznawania tekstu z JPEG‑ów i innych formatów jest niezbędna dla każdego programisty dziś. + +W tym tutorialu przeprowadzimy Cię przez kompletny, działający przykład, który pokaże, jak **detect text from image** pliki, **extract text from scanned image** dokumenty, a nawet **load image for OCR** w zaledwie kilku linijkach. Po zakończeniu będziesz mieć solidny, gotowy do produkcji fragment kodu, który możesz wkleić do własnych projektów — bez brakujących importów, bez niejasnych skrótów typu „zobacz dokumentację”. + +## Co zbudujesz + +- Mały skrypt w Pythonie, który tworzy silnik OCR, włącza auto‑deskew, ładuje JPEG (lub dowolny obsługiwany format) i wypisuje rozpoznany tekst. +- Wyjaśnienia **why** dlaczego każde ustawienie ma znaczenie, nie tylko **how** jak je wpisać. +- Porady dotyczące obsługi wielostronicowych PDF‑ów, języków nieangielskich oraz typowych pułapek, takich jak rozmyte skany. + +### Wymagania wstępne + +- Zainstalowany Python 3.8+ (przykład używa pakietu `ocr` dostępnego poprzez `pip install ocr-lib` – zamień na nazwę swojej biblioteki). +- Podstawowa znajomość funkcji Pythona i środowisk wirtualnych. +- Plik obrazu (JPEG, PNG, TIFF), który chcesz przetworzyć; użyjemy `skewed_page.jpg` jako przykładu. + +> **Pro tip:** Jeśli używasz Windows, uruchom terminal jako Administrator podczas instalacji biblioteki OCR, aby uniknąć problemów z uprawnieniami. + +## Wykonaj OCR na obrazie – konfiguracja i ustawienia + +Pierwszą rzeczą, której potrzebujesz, jest czysta instancja silnika OCR. Traktuj ją jak mózg operacji; bez odpowiedniej konfiguracji nawet najostrzejszy obraz zwróci bełkot. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters:** +Ustawienie `engine.language` zawęża zestaw znaków, którego oczekuje silnik OCR, co znacząco zwiększa dokładność. Jeśli pominiesz to, silnik będzie zgadywał, często myląc proste słowa. + +## Włącz automatyczne prostowanie – napraw przechylone skany + +Zeskanowane strony rzadko są idealnie płaskie. Delikatne przechylenie może zaburzyć segmentację znaków, zamieniając „Hello” w „H3llo”. Flaga `auto_deskew` robi ciężką pracę za Ciebie. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** Jeśli wiesz, że Twoje obrazy są już proste, wyłączenie deskew może zaoszczędzić kilka milisekund czasu przetwarzania — przydatne przy obsłudze tysięcy stron w trybie wsadowym. + +## Ładuj obraz do OCR – obsługa JPEG, PNG, TIFF + +Teraz faktycznie **load image for OCR**. Metoda `ocr.Image.load` jest elastyczna; akceptuje ścieżkę do dowolnego obsługiwanego formatu rastrowego. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial:** Biblioteka odczytuje plik do wewnętrznego bitmapu, stosując niezbędne konwersje przestrzeni kolorów. Pominięcie tego i przekazanie surowego strumienia bajtów spowodowałoby `FileNotFoundError` lub, co gorsza, ciche zwrócenie pustych wyników. + +Jeśli potrzebujesz **recognize text from JPEG** konkretnie, upewnij się, że rozszerzenie pliku to `.jpeg` lub `.jpg`. To samo wywołanie działa dla PNG (`.png`) lub TIFF (`.tif`) bez modyfikacji. + +## Wykonaj OCR na obrazie – uruchamianie silnika + +Gdy silnik jest gotowy, a obraz w pamięci, czas na **perform OCR on image** danych. Ta pojedyncza linia wykonuje ciężką pracę: wstępne przetwarzanie, segmentację, klasyfikację i składanie tekstu. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood?** +- Silnik stosuje transformację deskew (jeśli włączona). +- Uruchamia sieć neuronową lub backend Tesseract do identyfikacji znaków. +- Na koniec łączy znaki w słowa i linie, zwracając bogaty obiekt `result`. + +## Wyodrębnij tekst ze zeskanowanego obrazu – wyświetlenie wyników + +Ostatnim krokiem jest **extract text from scanned image** i wyświetlenie go. Atrybut `result.text` zawiera reprezentację zwykłego tekstu. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Typowy wynik wygląda tak: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Jeśli silnik OCR nie znajdzie żadnych znaków, `result.text` będzie pustym ciągiem. W takim przypadku sprawdź jakość obrazu lub rozważ dostosowanie właściwości `engine.confidence_threshold` (jeśli Twoja biblioteka to obsługuje). + +## Obsługa typowych wariantów + +### Rozpoznawanie tekstu z JPEG vs PNG + +Oba formaty są obsługiwane, ale kompresja JPEG może wprowadzać artefakty, które mylą silnik. Jeśli zauważasz częste błędy rozpoznawania, spróbuj najpierw przekonwertować JPEG na PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Wykrywanie tekstu z obrazu w wielu językach + +Jeśli Twój dokument miesza angielski i hiszpański, ustaw tryb wielojęzyczny: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Silnik będzie wtedy brał pod uwagę oba alfabety podczas rozpoznawania. + +### Wyodrębnianie tekstu ze zeskanowanych PDF‑ów + +Dla PDF‑ów musisz najpierw rasteryzować każdą stronę do obrazu. Biblioteki takie jak `pdf2image` ułatwiają to: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +## Pełny działający przykład + +Poniżej znajduje się kompletny skrypt, który możesz skopiować i wkleić do pliku `ocr_demo.py`. Zawiera obsługę błędów oraz mały pomocnik do pomiaru czasu wykonania. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (zakładając czysty skan): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +## Najczęściej zadawane pytania + +**Q: Czy mogę uruchomić to na serwerze bez interfejsu graficznego?** +A: Oczywiście. Biblioteka działa bez GUI; wystarczy, że niezbędne natywne binaria (np. Tesseract) będą zainstalowane na serwerze. + +**Q: Co zrobić, jeśli obraz jest rozmyty?** +A: Rozważ dodanie filtru wyostrzającego przed `engine.recognize`. Wiele bibliotek OCR udostępnia `image_preprocessing.sharpen = True` lub możesz użyć odwrotnego `cv2.GaussianBlur` z OpenCV. + +**Q: Czy skrypt obsługuje przetwarzanie wsadowe?** +A: Tak. Owiń `perform_ocr` w pętlę po liście ścieżek do plików, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/polish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..d7f0d5f3e --- /dev/null +++ b/ocr/polish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-06-19 +description: Wykonaj OCR na obrazie przy użyciu Aspose OCR Java. Dowiedz się, jak + załadować obraz do OCR, używać licencji Aspose i wyodrębnić tekst z obrazu w ciągu + kilku minut. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: pl +og_description: Wykonaj OCR na obrazie przy użyciu Aspose OCR Java. Ten przewodnik + pokazuje, jak używać licencji Aspose, wczytać obraz do OCR i wydajnie wyodrębnić + tekst z obrazu. +og_title: Wykonaj OCR na obrazie przy użyciu Aspose OCR Java – pełny tutorial +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Wykonaj OCR na obrazie przy użyciu Aspose OCR Java – Kompletny przewodnik krok + po kroku +url: /pl/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wykonaj OCR na obrazie przy użyciu Aspose OCR Java – Kompletny przewodnik krok po kroku + +Czy kiedykolwiek potrzebowałeś **wykonywać OCR na obrazie** plików, ale nie byłeś pewien, która biblioteka zapewni Ci niezawodne wyniki bez mnóstwa konfiguracji? Nie jesteś sam. W wielu rzeczywistych projektach — myśl o skanowaniu paszportów, digitalizacji faktur czy wyciąganiu tekstu ze zrzutów ekranu — możliwość szybkiego rozpoznawania danych tekstowych na obrazie jest przełomowa. + +W tym samouczku przeprowadzimy praktyczny przykład, który pokaże dokładnie, jak **wykonywać OCR na obrazie** przy użyciu Aspose OCR dla Javy. Omówimy wszystko, od zastosowania licencji Aspose, przez wczytanie obrazu, uruchomienie silnika, aż po **extract text from image**, abyś mógł go wykorzystać dalej. Bez zbędnych wstępów, po prostu działające rozwiązanie, które możesz skopiować i wkleić. + +## Co wyniesiesz z tego tutorialu + +- Jasny obraz tego, jak **use Aspose license** w projekcie Java. +- Dokładny kod potrzebny do **load image for OCR** i pozwalający silnikowi automatycznie wykrywać języki. +- Instrukcje krok po kroku, jak **recognize text image** oraz **extract text from image** w bezpieczny sposób. +- Wskazówki dotyczące radzenia sobie z typowymi problemami (puste wyniki, nieobsługiwane formaty i problemy z pamięcią). + +> **Wymagania wstępne** – Java 8 lub nowsza, Maven lub Gradle do zarządzania zależnościami oraz plik licencji Aspose OCR dla Javy (lub możesz uruchomić w trybie ewaluacyjnym). + +## Jak wykonać OCR na obrazie przy użyciu Aspose OCR Java + +Poniżej znajduje się kompletny, gotowy do uruchomienia program w Javie, który demonstruje cały przepływ. Zapisz go jako `AsposeOcrDemo.java` i uruchom w swoim IDE lub z wiersza poleceń. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Oczekiwany wynik w konsoli + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Jeśli uruchomisz program bez pliku licencji, pierwsza linia po prostu poinformuje, że jesteś w trybie ewaluacyjnym, ale OCR nadal działa. + +## Konfiguracja i użycie licencji Aspose + +### Dlaczego licencja ma znaczenie + +Używanie biblioteki w trybie ewaluacyjnym jest w porządku dla szybkich testów, ale dodaje znak wodny do wyniku i ogranicza liczbę stron, które możesz przetworzyć w jednym uruchomieniu. Zastosowanie kroku **use aspose license** usuwa te ograniczenia i sygnalizuje Aspose, że jesteś płacącym klientem. + +### Jak uzyskać i zastosować licencję + +1. Kup licencję w sklepie Aspose. +2. Pobierz plik `Aspose.OCR.Java.lic`. +3. Umieść go w miejscu, które aplikacja może odczytać — najczęściej w folderze `src/main/resources`. +4. Wywołaj `new License().setLicense("Aspose.OCR.Java.lic");` przed jakąkolwiek pracą OCR, jak pokazano w powyższym kodzie. + +> **Porada:** Jeśli wdrażasz na serwerze, użyj ścieżki bezwzględnej lub loadera zasobów class‑path, aby uniknąć `FileNotFoundException`. + +## Wczytaj obraz do przetwarzania OCR + +Linia `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` jest sercem kroku **load image for OCR**. Aspose OCR obsługuje szeroką gamę formatów: PNG, JPEG, BMP, TIFF, a nawet wielostronicowe PDF (w połączeniu z Aspose.Pdf). + +### Typowe problemy + +| Issue | Symptom | Fix | +|-------|---------|-----| +| Nieprawidłowa ścieżka pliku | `FileNotFoundException` | Sprawdź ponownie ścieżkę; użyj `Paths.get(...)` dla separatorów niezależnych od systemu. | +| Nieobsługiwany format | `UnsupportedOperationException` | Przekonwertuj obraz na PNG lub JPEG przed wczytaniem. | +| Duży obraz ( > 10 MP) | Błędy braku pamięci | Zmniejsz rozmiar obrazu przy użyciu `java.awt.Image` przed przekazaniem go do Aspose. | + +## Wyodrębnij tekst z obrazu i obsłuż wyniki + +Gdy silnik OCR zakończy pracę, obiekt `OcrResult` zawiera rozpoznany ciąg znaków. To tutaj **extract text from image** do dalszego przetwarzania — zapis do bazy danych, przekazanie do indeksu wyszukiwania lub do kolejnego etapu przetwarzania NLP. + +### Obsługa wielu języków + +Ponieważ ustawiliśmy `engine.setLanguage(Language.Auto)`, Aspose będzie próbował wykrywać języki w locie. Jeśli znasz język z góry (np. wszystkie dokumenty są po rosyjsku), możesz zamienić `Language.Auto` na `Language.Russian`, co przyspieszy działanie. + +### Wskazówki dotyczące post‑przetwarzania + +- **Usuń białe znaki**: `result.getText().trim()`. +- **Normalizuj zakończenia linii**: `result.getText().replace("\r\n", "\n")`. +- **Usuń znaki nie‑drukowalne**: użyj wyrażenia regularnego, np. `result.getText().replaceAll("[^\\p{Print}]", "")`. + +## Rozpoznaj tekst obrazu z zaawansowanymi opcjami (opcjonalnie) + +Jeśli potrzebujesz bardziej precyzyjnej kontroli, Aspose OCR oferuje dodatkowe właściwości: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +## Podsumowanie pełnego działającego przykładu + +Łącząc wszystko razem, końcowy program wykonuje następujące kroki w kolejności: + +1. **Perform OCR on image** – poprzez utworzenie `OcrEngine`. +2. **Use Aspose license** – opcjonalne, ale zalecane. +3. **Load image for OCR** – za pomocą `Image.load`. +4. **Set language detection** – `Language.Auto` aby **recognize text image** automatycznie. +5. **Extract text from image** – wydrukuj wynik, obsługując puste odpowiedzi w sposób elegancki. + +Możesz skopiować powyższy blok kodu bezpośrednio do projektu Maven z następującą zależnością: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Uruchom `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` i obserwuj, jak konsola wyświetla rozpoznany tekst. + +## Zakończenie + +Właśnie pokazaliśmy, jak **perform OCR on image** pliki przy użyciu Aspose OCR dla Javy, od zastosowania licencji po **loading the image for OCR**, **recognizing text image** oraz w końcu **extracting text from image** do dalszego wykorzystania. Podejście jest proste, działa z wieloma językami od razu i może być rozszerzone o zaawansowane opcje przetwarzania wstępnego w razie potrzeby. + +Co dalej? Spróbuj przekazać wynik OCR do indeksu wyszukiwania, generować PDF‑y z wyodrębnionym tekstem lub eksperymentować z różnymi formatami obrazów. Możliwości są nieograniczone, a dzięki solidnemu API Aspose spędzisz więcej czasu na budowaniu funkcji niż na walce z problemami OCR. + +Masz pytania lub napotkałeś nietypowy przypadek? zostaw komentarz poniżej — powodzenia w kodowaniu! + +## 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. + +- [Jak wyodrębnić tekst z obrazu z URL przy użyciu Aspose.OCR dla Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Konwertuj obraz na tekst w Javie przy użyciu Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Wyodrębnij tekst z obrazu w Javie z trybem Detect Areas w Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..6fc073564 --- /dev/null +++ b/ocr/portuguese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-19 +description: Crie PDF pesquisável a partir de uma imagem usando OCR em Python. Aprenda + a converter OCR em PDF, extrair texto de imagens e realizar OCR em imagens rapidamente. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: pt +og_description: Crie PDF pesquisável a partir de uma imagem com OCR em Python. Este + guia mostra como converter OCR para PDF, extrair texto de uma imagem e realizar + OCR em uma imagem. +og_title: Criar PDF pesquisável em Python – Guia completo de programação +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Criar PDF pesquisável em Python – Guia completo passo a passo +url: /pt/python-java/general/create-searchable-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 >}} + +# Criar PDF pesquisável em Python – Guia completo passo a passo + +Já precisou **criar PDF pesquisável** a partir de um recibo escaneado, mas não sabia por onde começar? Você não está sozinho—muitos desenvolvedores encontram o mesmo obstáculo quando tentam transformar uma foto de texto em um PDF que realmente pode ser pesquisado. + +Neste tutorial vamos percorrer uma solução prática que permite que você **perform OCR on image**, transforme esse resultado OCR em um **searchable PDF**, e ainda extraia o texto bruto caso precise dele para processamento adicional. Sem enrolação, apenas um exemplo funcional que você pode copiar‑colar no seu projeto hoje. + +## O que você aprenderá + +- Como configurar um motor OCR leve em Python +- Os passos exatos para **convert OCR to PDF** e salvá‑lo como um documento pesquisável +- Maneiras de **extract text from image** para análise posterior +- Dicas para lidar com armadilhas comuns, como orientação da imagem e arquivos grandes +- Um script completo e executável que você pode adaptar ao seu próprio caso de uso + +### Pré-requisitos + +- Python 3.8+ instalado na sua máquina +- Familiaridade básica com pip e ambientes virtuais (opcional, mas recomendado) +- Um arquivo de imagem (PNG, JPEG, etc.) que contenha texto claro e legível por máquina + +Se você tem isso, vamos mergulhar. + +## Etapa 1: Instale a Biblioteca Necessária + +O trecho de código que você viu antes usa um pacote fictício `ocr`, mas as mesmas ideias se aplicam a bibliotecas reais como **EasyOCR**, **pytesseract**, ou **pdfminer.six**. Para este guia usaremos **EasyOCR** porque é puro Python, suporta muitas línguas e fornece um método prático de conversão para PDF via um helper auxiliar. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Instale dentro de um ambiente virtual (`python -m venv venv && source venv/bin/activate`) para manter suas dependências organizadas. + +## Etapa 2: Inicialize o Motor OCR – Realize OCR na Imagem + +Agora que a biblioteca está pronta, criamos um motor OCR e instruímos que trabalhe com texto em inglês. Este é o primeiro ponto onde **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Por que precisamos de um objeto leitor dedicado? O EasyOCR pré‑carrega os modelos de idioma, então reutilizar o mesmo `reader` para múltiplas imagens é muito mais eficiente do que reinicializá‑lo a cada vez. + +## Etapa 3: Carregue a Imagem – Extraia Texto da Imagem + +Vamos trazer a foto para a memória. Esta etapa é onde **extract text from image** será feita mais adiante, mas primeiro apenas a carregamos. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Se sua imagem estiver de cabeça para baixo ou inclinada, considere usar os métodos `rotate` ou `transpose` do Pillow antes de enviá‑la ao motor OCR. Uma verificação visual rápida pode economizar horas de depuração depois. + +## Etapa 4: Execute o Motor OCR e Capture os Resultados + +Aqui está o núcleo do processo—enviar a imagem ao motor OCR e receber de volta dados estruturados. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +A flag `detail=1` nos fornece caixas delimitadoras, que precisaremos quando mais tarde **convert OCR to PDF**. Se você se importa apenas com strings brutas, defina `detail=0`. + +## Etapa 5: Converta o Resultado OCR em um PDF Pesquisável – Converter OCR em PDF + +O EasyOCR não fornece um escritor de PDF direto, mas podemos montar o PDF nós mesmos usando Pillow e a biblioteca `reportlab`. Para manter o tutorial leve, usaremos `fpdf2`, que nos permite incorporar a imagem original e sobrepor texto invisível. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +O que acabou de acontecer? Colocamos a imagem escaneada como camada visível e, em seguida, escrevemos as palavras reconhecidas por cima usando texto branco que se mistura ao fundo branco. As ferramentas de busca ainda leem a camada oculta, de modo que o PDF se torna **searchable** sem alterar a aparência visual. + +## Etapa 6: Salve os Bytes do PDF – Converter Imagem em PDF + +Se preferir manipular o PDF na memória (por exemplo, enviando‑o por uma API), pode capturar os bytes ao invés de gravar diretamente no disco. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Essa linha demonstra o fluxo clássico de **convert image to PDF**: você começa com uma imagem, executa OCR, sobrepõe texto e, finalmente, emite um stream de PDF. + +## Etapa 7: Verifique o Resultado – Verificações Rápidas + +Depois de executar o script, abra `receipt_searchable.pdf` em qualquer visualizador de PDF e teste a caixa de busca (Ctrl + F). Digite uma palavra que você sabe que aparece no recibo—se ele pular para o ponto correto, você **create searchable pdf** com sucesso! + +Se a busca falhar, verifique: + +1. As pontuações de confiança do OCR (`conf` values). Baixa confiança pode indicar que a imagem está borrada. +2. Coordenadas da caixa delimitadora—às vezes o EasyOCR as relata em uma orientação diferente. +3. Que o visualizador de PDF não esteja configurado no modo “apenas imagem” (raro, mas alguns visualizadores têm essa opção). + +## Script Completo Funcional + +Juntando tudo, aqui está o arquivo Python completo, pronto para ser executado: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Salve isso como `searchable_pdf.py`, substitua os placeholders `YOUR_DIRECTORY` por caminhos reais e execute: + +```bash +python searchable_pdf.py +``` + +Você deverá ver uma mensagem de confirmação e um PDF recém‑criado e pesquisável na sua pasta. + +## Perguntas Frequentes & Casos Limite + +**E se a imagem estiver em cores?** +EasyOCR funciona tanto com imagens em escala de cinza quanto em cores, mas converter para escala de cinza (`pil_image.convert("L")`) pode às vezes melhorar a precisão em digitalizações ruidosas. + +**Posso lidar com PDFs de várias páginas?** +Sim—faça um loop sobre cada imagem de página, execute as etapas de OCR e anexe cada página ao mesmo objeto `FPDF`. Apenas lembre‑se de resetar o cursor (`self.add_page()`) para cada nova imagem. + +**Existe uma forma de manter a camada de texto original ao invés de texto branco invisível?** +Se precisar de um PDF verdadeiro “texto‑sob‑imagem” (por exemplo, para acessibilidade), considere usar `pdfminer` ou `pikepdf` para incorporar uma camada de texto oculta com tags PDF adequadas. É mais avançado, mas o princípio permanece: imagem de fundo + texto sobreposto. + +**E se a confiança do OCR for baixa?** +Você pode filtrar palavras de baixa confiança: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Conclusão – O que alcançamos + +Começamos com uma imagem simples de um recibo, **performed OCR on image**, extraímos as strings reconhecidas e, finalmente, **create searchable pdf** que se comporta como qualquer documento escaneado profissionalmente. O processo cobriu todas as palavras‑chave secundárias—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, e **perform OCR on image**—para que você agora tenha uma caixa de ferramentas reutilizável para qualquer projeto similar. + +### Próximos passos + +- Experimente outras línguas passando seus códigos ISO para `easyocr.Reader(['en', 'es'])`. +- Troque EasyOCR por Tesseract se precisar de uma solução totalmente offline; o restante do pipeline permanece o mesmo. +- Adicione visualização da confiança OCR (desenhe caixas delimitadoras na imagem) para depurar digitalizações problemáticas. + +Tem uma variação que gostaria de compartilhar? Deixe um comentário, faça um fork + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que expandem 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. + +- [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/) +- [Converter Imagens em PDF C# – Salvar Resultado OCR de Múltiplas Páginas](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Como fazer OCR em Imagem – Realizar OCR em Imagem no Reconhecimento de Imagem 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/portuguese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/portuguese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..986fc20b4 --- /dev/null +++ b/ocr/portuguese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Extraia texto de imagens em Python com um motor OCR simples. Aprenda + como converter imagens escaneadas em texto, reconhecer texto em fotos e listar arquivos + de imagem em Python de forma eficiente. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: pt +og_description: Extraia texto de imagens em Python usando um motor OCR leve. Este + guia mostra como converter imagens escaneadas em texto, reconhecer texto em fotos + e listar arquivos de imagem em Python em poucos passos. +og_title: Extrair Texto de Imagens em Python – Guia Completo de OCR em Lote +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Extrair Texto de Imagens em Python – Guia Completo de OCR em Lote +url: /pt/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrair Texto de Imagens em Python – Guia Completo de OCR em Lote + +Já precisou **extrair texto de imagens** mas não sabia por onde começar? Você não está sozinho—desenvolvedores enfrentam constantemente o desafio de transformar PDFs escaneados, recibos fotografados ou capturas de tela em texto pesquisável. Neste tutorial vamos percorrer um exemplo completo, pronto‑para‑executar, que mostra como **converter imagens escaneadas em texto**, reconhecer texto a partir de fotos e até **listar arquivos de imagem estilo python**. Ao final, você terá um script reutilizável que processa uma pasta inteira de uma só vez. + +Cobriremos tudo que você precisa: bibliotecas necessárias, por que cada passo importa, tratamento de casos extremos e um pouco de solução de problemas. Não é preciso buscar documentação externa; o código abaixo é autocontido, e as explicações respondem ao “como” *e* ao “por que”. Pegue sua IDE favorita e vamos começar. + +--- + +## O Que Você Vai Construir + +- Inicializar um motor de OCR (usaremos o pacote `ocr` como ilustração). +- Escanear um diretório e **listar arquivos de imagem estilo python**, filtrando PNG, JPG e TIFF. +- Executar uma operação de **OCR em lote** em todas as imagens encontradas. +- Imprimir o texto extraído para cada arquivo, claramente rotulado. + +> **Dica de especialista:** Se você não tem a biblioteca `ocr` instalada, pode substituí‑la por `pytesseract` com algumas pequenas mudanças— a lógica central permanece a mesma. + +--- + +## Pré‑requisitos + +- Python 3.8+ (o script usa f‑strings e type hints). +- Uma biblioteca de OCR que exponha um `OcrEngine` com `recognize_batch`. Para este guia assumimos um pacote fictício `ocr`, mas o padrão funciona com bibliotecas reais. +- Uma pasta contendo os arquivos de imagem que você deseja processar (`.png`, `.jpg`, `.tif`). + +--- + +## Etapa 1 – Instalar & Importar Módulos Necessários + +Primeiro, certifique‑se de que o pacote de OCR está disponível. Se estiver usando uma biblioteca real como `pytesseract`, substitua a importação adequadamente. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Por que isso importa:** Importar `os` nos dá manipulação de caminhos multiplataforma, enquanto `typing.List` ajuda no autocomplete da IDE e na preparação para o futuro. + +--- + +## Etapa 2 – **Extrair Texto de Imagens**: Inicializar o Motor de OCR + +Criar o motor é o primeiro passo para qualquer trabalho de OCR. Também definimos o idioma para auto‑detecção, permitindo que o motor lide com documentos multilíngues. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explicação:** Ao encapsular a criação do motor em uma função mantemos o código modular. Se mais tarde precisar ajustar DPI ou modo de OCR, basta editar este único ponto. + +--- + +## Etapa 3 – **Listar Arquivos de Imagem Python**: Coletar Arquivos de um Diretório + +Agora precisamos localizar cada foto que será processada. A compreensão de lista abaixo espelha um padrão comum de “list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Tratamento de caso extremo:** A função ignora subpastas (você pode adicionar recursão depois) e filtra arquivos ocultos automaticamente porque eles normalmente não terminam com extensões suportadas. + +--- + +## Etapa 4 – **Converter Imagens Escaneadas em Texto**: Executar OCR em Lote + +A maioria das bibliotecas de OCR oferece um método em lote que é muito mais rápido que processar uma imagem por vez. Veja como chamá‑lo. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Por que em lote?** Enviar todas as imagens de uma vez reduz a sobrecarga (por exemplo, carregar o modelo de OCR repetidamente) e costuma gerar melhor utilização de CPU/GPU. + +--- + +## Etapa 5 – **Reconhecer Texto de Fotos**: Exibir os Resultados + +Por fim, iteramos sobre os nomes de arquivos pareados com os resultados de OCR, imprimindo um cabeçalho limpo para cada imagem. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Dica:** `strip()` remove espaços em branco iniciais/finais que o OCR costuma adicionar. + +--- + +## Script Completo – Junte Tudo + +Abaixo está o programa completo e executável. Salve como `batch_ocr.py` e execute `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Saída Esperada + +Supondo que a pasta contenha `invoice1.png` e `receipt.jpg`, você pode ver: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Cada bloco está claramente rotulado, facilitando o processamento posterior (por exemplo, salvar em um banco de dados). + +--- + +## Lidando com Problemas Comuns + +| Problema | Por que Acontece | Solução Rápida | +|----------|------------------|----------------| +| **Nenhum texto aparece** | Idioma do OCR não detectado ou imagem com baixo contraste. | Forçar um idioma (`engine.language = ocr.Language.English`) ou pré‑processar imagens (aumentar contraste). | +| **Erro de memória em lotes grandes** | O motor tenta carregar todas as imagens de uma vez. | Dividir `image_files` em blocos (`batch_size = 20`) e chamar `recognize_batch` repetidamente. | +| **Formato de arquivo não suportado** | Você adicionou um `.gif` ou `.bmp`. | Expandir a tupla `supported_exts` ou converter imagens para PNG/JPG antes. | +| **Texto Unicode corrompido** | OCR retorna bytes ao invés de strings. | Garantir que a biblioteca de OCR devolva Unicode (`result.text.decode('utf‑8')` se necessário). | + +--- + +## Expandindo o Fluxo de Trabalho + +Agora que você pode **extrair texto de imagens**, considere os próximos passos: + +- **Exportar para CSV** – Gravar cada nome de arquivo e seu texto extraído em uma planilha para análise. +- **Processamento paralelo** – Usar `concurrent.futures.ThreadPoolExecutor` para lidar com múltiplos lotes simultaneamente. +- **Integrar com OCR na nuvem** – Trocar o motor local por Google Vision ou Azure OCR para maior precisão em layouts complexos. +- **Adicionar pré‑processamento de imagem** – Bibliotecas como Pillow ou OpenCV podem endireitar, remover ruído ou aplicar limiar antes do OCR, melhorando os resultados. + +Todas essas ideias utilizam as mesmas funções centrais que construímos, então você não precisará começar do zero. + +--- + +## Conclusão + +Acabamos de percorrer uma solução completa para **extrair texto de imagens** em Python, cobrindo tudo desde **list image files python** até **recognize text from pictures** e, finalmente, **convert scanned images to text** em um lote organizado. O script é deliberadamente simples, mas flexível o suficiente para servir como base para projetos maiores—seja digitalizando recibos, construindo um arquivo pesquisável ou alimentando um pipeline de extração de dados. + +Teste, ajuste as etapas de pré‑processamento e veja sua precisão de OCR subir. Se encontrar dificuldades, revise a tabela “Lidando com Problemas Comuns”; a maioria dos problemas se resolve com uma pequena mudança de configuração. + +Pronto para o próximo desafio? Tente adicionar uma etapa de conversão de PDF‑para‑imagem usando `pdf2image`, e alimente essas imagens diretamente ao mesmo pipeline. O céu é o limite quando você combina OCR com o rico ecossistema do Python. + +Feliz codificação, e que seu texto seja sempre legível! + + +## 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 de implementação em seus próprios projetos. + +- [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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/portuguese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..7051ff957 --- /dev/null +++ b/ocr/portuguese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-19 +description: extraia texto de imagens usando OCR em Python. Aprenda detecção automática + de idioma, processamento paralelo e reconhecimento em lote em um tutorial conciso. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: pt +og_description: extraia texto de imagens com Python OCR. Este guia mostra detecção + automática de idioma, processamento paralelo e reconhecimento em lote em um único + tutorial. +og_title: extrair texto de imagens em Python – Guia completo de OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: extrair texto de imagens em Python – Guia completo de OCR +url: /pt/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# extrair texto de imagens em Python – Guia Completo de OCR + +Já se perguntou como **extrair texto de imagens** sem digitar manualmente cada palavra? Você não está sozinho. Seja digitalizando recibos antigos, criando um arquivo de documentos pesquisável ou apenas brincando com truques legais de IA, a capacidade de extrair texto de fotos é uma habilidade indispensável para qualquer desenvolvedor Python hoje. + +Neste tutorial vamos percorrer um exemplo completo, pronto‑para‑executar, que **extrai texto de imagens** usando um motor OCR popular. Vamos cobrir detecção automática de idioma, processamento paralelo para velocidade e reconhecimento de imagens em lote para que você possa lidar com dezenas de arquivos em segundos. Parece o que você precisa? Vamos mergulhar. + +## O que você aprenderá + +- Como instanciar o motor OCR com `ocr.OcrEngine`. +- Habilitar **detecção automática de idioma** para que o motor escolha o idioma correto por conta própria. +- Configurar **OCR com processamento paralelo** usando um pool de threads personalizado. +- Executar **reconhecimento de imagens em lote** em uma lista de arquivos. +- Imprimir o texto reconhecido para cada imagem, pronto para ser salvo ou indexado. + +Nenhuma documentação externa necessária—tudo que você precisa está aqui, e o código funciona imediatamente com o pacote `ocr` (instale‑o via `pip install ocr`). + +## Pré-requisitos + +1. Python 3.8 ou mais recente instalado. +2. O pacote `ocr` (`pip install ocr`). +3. Uma pasta de imagens PNG (ou JPG) que você deseja processar. +4. Familiaridade básica com funções e loops em Python. + +É isso—sem dependências pesadas, sem magia de GPU, apenas Python puro. + +![exemplo de extração de texto de imagens](https://example.com/ocr-demo.png "Captura de tela mostrando a saída da extração de texto de imagens") + +*Texto alternativo: captura de tela da demonstração de extração de texto de imagens* + +## Etapa 1 – Configurar o Motor OCR (Palavra‑chave Principal em Ação) + +Primeiro de tudo: crie uma instância do motor OCR. Pense em `ocr.OcrEngine()` como o cérebro por trás da operação; ele sabe como ler caracteres, linhas e parágrafos. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Por que precisamos de um motor explícito? Porque o **uso do ocr.OcrEngine** oferece controle granular sobre configurações de idioma, threads e muito mais. É a forma mais flexível de **extrair texto de imagens** comparado a helpers de uma linha. + +## Etapa 2 – Deixe o Motor Detectar Idiomas Automaticamente + +A maioria das bibliotecas OCR exige que você informe qual idioma procurar. Isso funciona para um projeto monolíngue, mas é trabalhoso para um lote com múltiplos idiomas. Felizmente, o pacote `ocr` suporta **detecção automática de idioma**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Definir `engine.language` para `ocr.Language.Auto` indica ao motor que ele deve analisar cada imagem e escolher o modelo de idioma apropriado. Essa linha diminuta economiza horas de configuração manual quando você lida com documentos internacionais. + +## Etapa 3 – Acelere com OCR de Processamento Paralelo + +Se você tem quatro ou mais núcleos de CPU, por que não usá‑los? O motor pode criar um pool de threads, permitindo que várias imagens sejam processadas ao mesmo tempo. É aqui que o **OCR com processamento paralelo** brilha. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Sinta‑se à vontade para ajustar o número `4` de acordo com sua máquina. Mais threads → execuções de lote mais rápidas, mas lembre‑se de que cada thread consome memória, então encontre o ponto ideal para seu ambiente. + +## Etapa 4 – Reunir as Imagens que Você Deseja Processar + +Agora precisamos de uma lista de caminhos de arquivos. Você pode montar essa lista manualmente, lê‑la de um CSV ou usar `glob`. Para clareza, vamos codificar uma lista curta: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Substitua `YOUR_DIRECTORY` pelo caminho real no seu sistema. Se você tem dezenas de arquivos, um rápido `glob.glob("*.png")` fará o trabalho pesado. + +## Etapa 5 – Executar Reconhecimento de Imagens em Lote + +Aqui está o coração do tutorial: uma única chamada que processa cada imagem em `files` e devolve uma lista de objetos de resultado. Essa é a funcionalidade de **reconhecimento de imagens em lote** que torna o OCR em grande escala prático. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Nos bastidores, o motor distribui cada arquivo entre as quatro threads de trabalho que configuramos anteriormente, ao mesmo tempo em que detecta automaticamente o idioma de cada foto. O método devolve uma lista onde cada elemento contém o texto reconhecido e metadados. + +## Etapa 6 – Imprimir (ou Armazenar) o Texto Extraído + +Finalmente, iteramos sobre os resultados e imprimimos o texto. Em um projeto real você provavelmente gravaria isso em um banco de dados ou em um arquivo CSV, mas imprimir mantém o exemplo simples. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Saída esperada** (truncada para brevidade): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Cada bloco mostra o nome do arquivo seguido da string derivada pelo OCR. Se uma imagem contém múltiplos idiomas, você verá os caracteres apropriados graças à etapa anterior de **detecção automática de idioma**. + +## Dicas Profissionais & Armadilhas Comuns + +- **A qualidade da imagem importa** – fotos borradas ou de baixo contraste gerarão lixo. Pré‑processar com OpenCV (`cv2.threshold`, `cv2.resize`) se necessário. +- **Contagem de threads vs. I/O** – Se suas imagens estão em um disco de rede lento, mais threads podem não ajudar. Fique de olho no uso de CPU com `top` ou `Task Manager`. +- **Manipulação de Unicode** – O `result.text` é uma string Unicode. Ao gravar em arquivos, abra‑os com `encoding="utf‑8"` para evitar `UnicodeEncodeError`s. +- **Uso de memória** – PDFs grandes podem consumir muita RAM. Se ocorrer `MemoryError`, reduza o tamanho do pool de threads ou processe as imagens em blocos menores. + +## Script Completo Funcional + +Abaixo está o script completo, pronto para copiar e colar, que incorpora cada passo que discutimos. Salve‑o como `batch_ocr.py` e execute `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Execute-o assim: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Você verá um bloco de texto bem formatado para cada imagem, provando que você pode **extrair texto de imagens** em escala. + +## O que vem a seguir? + +Agora que você dominou o básico de **extrair texto de imagens** com Python, considere explorar: + +- **Pós‑processamento**: limpe a saída do OCR com regex ou bibliotecas de linguagem natural. +- **Conversão para PDF**: alimente as strings extraídas em um gerador de PDF para PDFs pesquisáveis. +- **Serviços de OCR na nuvem**: compare os resultados on‑prem `ocr` com Google Vision ou Azure OCR para precisão em casos extremos. +- **Interface GUI**: construa um pequeno app Flask ou FastAPI que permita aos usuários fazer upload de imagens e ver instantaneamente o texto extraído. + +Cada um desses tópicos se baseia na fundação da **biblioteca OCR Python** que você acabou de configurar, e todos se beneficiam dos mesmos truques de **OCR com processamento paralelo** que usamos aqui. + +--- + +*Feliz codificação! Se encontrar algum problema, deixe um comentário abaixo—estou sempre disposto a ajudar a resolver peculiaridades do OCR.* + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que expandem 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. + +- [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 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/portuguese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/portuguese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..f35a415ff --- /dev/null +++ b/ocr/portuguese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-06-19 +description: Como extrair PDF usando OCR em Python – tutorial passo a passo cobrindo + extração de texto de PDF, reconhecimento de texto de imagem e um exemplo de OCR + em Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: pt +og_description: Como extrair PDF usando OCR em Python. Aprenda a extrair texto de + PDF, reconhecer texto de imagem e veja um exemplo completo de OCR em Python. +og_title: Como extrair texto de PDF com OCR em Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Como Extrair Texto de PDF com OCR em Python – Guia Completo +url: /pt/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Extrair Texto de PDF com OCR em Python – Guia Completo + +Já se perguntou **como extrair PDF** quando o arquivo é apenas uma imagem escaneada? Você não está sozinho. Em muitos projetos do mundo real — pense em contratos, faturas ou arquivos históricos — o PDF que você recebe não tem texto selecionável. A boa notícia? Algumas linhas de Python podem transformar essas páginas apenas de imagem em texto pesquisável e editável. + +Neste tutorial, percorreremos um **exemplo de OCR Python** prático que lê um PDF, renderiza sua primeira página como imagem e então **extrai texto de PDF** usando um motor OCR. Ao final, você saberá exatamente como **ler PDF com OCR**, por que cada etapa é importante e como adaptar o código para documentos multipáginas ou diferentes idiomas. + +## O que você aprenderá + +- Instalar e configurar uma biblioteca OCR confiável para Python. +- Converter páginas de PDF em imagens adequadas para OCR. +- **Reconhecer texto a partir de imagem** e obter strings Unicode limpas. +- Armadilhas comuns (PDFs de baixa resolução, páginas giradas) e como evitá‑las. +- Estender o script para lidar com múltiplas páginas ou processamento em lote. + +**Pré‑requisitos**: Python 3.8+, pip e um entendimento básico de ambientes virtuais. Não é necessária experiência prévia com OCR — basta acompanhar. + +--- + +## ## Como Extrair Texto de PDF com OCR em Python + +Este cabeçalho H2 contém nossa palavra‑chave principal exatamente onde os motores de busca adoram vê‑la. Vamos mergulhar direto no código. + +### Etapa 1 – Instalar os Pacotes Necessários + +Primeiro, precisamos de um motor OCR. O exemplo abaixo usa o popular pacote **ocr** (um wrapper leve ao redor do Tesseract). Se você preferir um backend diferente, os conceitos permanecem os mesmos. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Dica profissional:** No Linux, você também precisará do binário do Tesseract: `sudo apt-get install tesseract-ocr`. Usuários macOS podem obtê‑lo via Homebrew: `brew install tesseract`. + +### Etapa 2 – Inicializar o Motor OCR e Definir o Idioma + +Agora iniciamos o motor e instruímos a procurar por caracteres em inglês. Você pode trocar `ocr.Language.English` por qualquer código de idioma suportado. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Por que isso importa:** Especificar o idioma melhora drasticamente a precisão, pois o motor pode aplicar dicionários e modelos de caracteres específicos do idioma. + +### Etapa 3 – Carregar uma Página de PDF como Imagem + +OCR funciona em imagens raster, não em objetos PDF. O helper `ocr.Image.from_pdf` renderiza a página escolhida para um bitmap. Ajuste `page_number` para outras páginas (indexação baseada em 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Caso extremo:** Se o PDF contiver gráficos vetoriais em vez de imagens escaneadas, você pode obter uma renderização nítida. Para digitalizações de baixa resolução, considere aumentar o DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Etapa 4 – Reconhecer Texto a partir da Imagem Renderizada + +Aqui está o coração do **exemplo de ocr python**. O motor processa o bitmap e retorna um objeto contendo a string extraída. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +O atributo `ocr_result.text` contém a saída em texto simples, preservando quebras de linha quando possível. + +### Etapa 5 – Imprimir ou Armazenar o Texto Extraído + +Finalmente, exibimos o resultado. Em uma aplicação real, você provavelmente gravaria em um arquivo ou em um banco de dados. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Executar o script deve exibir algo como: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Esse é um fluxo completo de **extrair texto de pdf** usando OCR. + +--- + +## ## Reconhecer Texto a partir de Imagem – Ajustando a Precisão + +Se você está interessado apenas em **reconhecer texto a partir de imagem** (por exemplo, um JPEG de um recibo), pode pular a etapa de conversão de PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Dicas para melhores resultados:** + +- **Pré‑processar** a imagem: converter para escala de cinza, aplicar limiarização ou corrigir inclinação. Pillow facilita isso. +- **Aumentar o DPI** durante a renderização do PDF: resolução maior fornece mais detalhes ao motor OCR. +- **Habilitar a configuração do motor OCR** para segmentação de página (`ocr_engine.config = "--psm 6"` para blocos uniformes). + +## ## Ler PDF com OCR – Manipulando Múltiplas Páginas + +A maioria dos contratos abrange várias páginas. Iterar sobre cada página é simples: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Esta função **lê PDF com OCR**, concatena a saída e insere um marcador de quebra de página claro. Você pode então enviar `full_text` para um índice de busca ou armazená‑lo como um arquivo `.txt`. + +## ## Armadilhas Comuns e Como Corrigi‑las + +| Sintoma | Causa Provável | Correção | +|---------|----------------|----------| +| Caracteres embaralhados, muitos `?` | Idioma errado ou arquivos de dados de idioma ausentes | Instale o pacote de idioma Tesseract correto (`tesseract-ocr-`) e defina `ocr_engine.language`. | +| Linhas ausentes ou palavras truncadas | DPI baixo (abaixo de 150) | Renderize o PDF em 300 DPI ou mais (`dpi=300`). | +| Texto está rotacionado ou invertido | Página escaneada não está na posição correta | Use `ocr.Image.deskew(page_image)` antes do reconhecimento. | +| Processamento lento em PDFs grandes | Processamento das páginas sequencialmente em uma única thread | Paralelize com `concurrent.futures.ThreadPoolExecutor`. | + +## ## Estendendo o Exemplo OCR Python + +- **Exportar para PDF/A**: Após a extração, você pode incorporar o texto de volta a um PDF pesquisável usando `reportlab` ou `pypdf2`. +- **Detecção de idioma**: Use `langdetect` na saída OCR para mudar `ocr_engine.language` dinamicamente. +- **Processamento em lote**: Percorra um diretório com `os.listdir` e aplique `extract_all_pages` a cada arquivo. + +## ## Saída Esperada e Verificação + +Ao executar o script em uma digitalização clara, em idioma inglês, você deverá ver um bloco de texto limpo com pontuação correta. Verifique por: + +1. Comparar algumas linhas com a imagem escaneada original. +2. Executar uma contagem simples de palavras (`len(ocr_result.text.split())`) para garantir que a saída não esteja vazia. +3. Opcionalmente, alimentar o resultado em um corretor ortográfico como `pyspellchecker` para identificar erros de OCR. + +## Conclusão + +Cobremos **como extrair PDF** quando a análise tradicional falha, demonstramos um **exemplo completo de ocr python**, e explicamos como **reconhecer texto a partir de imagem** e **ler PDF com OCR** para cenários de página única e multipáginas. Com os trechos de código acima, você pode transformar qualquer PDF escaneado em texto pesquisável e editável — sem necessidade de digitação manual. + +Próximos passos? Experimente trocar o idioma para espanhol (`ocr.Language.Spanish`) ou experimente técnicas de pré‑processamento de imagem para melhorar a precisão. Se você está construindo um sistema de gerenciamento de documentos, considere indexar o texto extraído com Elasticsearch para buscas ultrarrápidas. + +Tem perguntas ou encontrou um PDF estranho? Deixe um comentário, e feliz codificação! + +![Como extrair PDF usando OCR em Python](image.png "Como extrair PDF usando OCR em Python") + +## 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/) +- [Reconhecer Texto de PDF – Operações OCR com Aspose.OCR para Java](/ocr/english/java/ocr-operations/) +- [Extrair texto de imagem C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/portuguese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..a7e8659a6 --- /dev/null +++ b/ocr/portuguese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-06-19 +description: Aprenda a usar OCR em Java com Aspose. Este guia passo a passo cobre + correção automática de inclinação de imagens, detecção automática de idioma e extração + fácil de texto em imagens. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: pt +og_description: 'Como usar OCR em Java com Aspose: um tutorial completo que abrange + correção automática de inclinação de imagens, detecção automática de idioma e extração + de texto de imagens em fotos.' +og_title: Como usar OCR em Java com Aspose – Guia completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Como usar OCR em Java com Aspose – Guia Completo +url: /pt/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Usar OCR em Java com Aspose – Guia Completo + +Já se perguntou **como usar OCR** em um projeto Java sem ficar de cabelo em pé com a configuração? Você não está sozinho. Muitos desenvolvedores encontram um obstáculo quando precisam **extrair texto de imagem** rapidamente, especialmente quando as digitalizações de origem estão tortas ou escritas em um idioma desconhecido. + +Neste tutorial, vamos percorrer um exemplo prático que mostra exatamente como usar OCR com Aspose, incluindo **auto deskew images**, **auto language detection**, e todo o pipeline de **ocr image preprocessing**. Ao final, você terá um trecho pronto‑para‑executar que imprime o texto reconhecido no console, e entenderá por que cada configuração é importante. + +> **O que você receberá:** um programa Java completo e executável, explicações de cada linha, dicas para lidar com casos extremos e ideias para expandir a solução para processamento em lote ou PDFs. + +--- + +## Pré-requisitos + +- Java 17 (ou qualquer JDK recente) instalado e configurado. +- Maven ou Gradle para gerenciamento de dependências (mostraremos as coordenadas Maven). +- Um arquivo de licença Aspose OCR for Java (`Aspose.OCR.Java.lic`). Se você está apenas testando, pode pular a etapa de licença, mas a versão de avaliação gratuita adicionará uma marca d'água. +- Uma imagem de exemplo (`your_image.png`) colocada em um local acessível ao código. + +> **Dica profissional:** mantenha suas imagens em uma pasta dedicada `resources` e carregue-as via classpath; isso evita dores de cabeça relacionadas a caminhos em diferentes sistemas operacionais. + +## Etapa 1: Configurar o Projeto e Adicionar a Dependência Aspose OCR + +Crie um novo projeto Maven (ou use o que já tem) e adicione o seguinte ao seu `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Execute `mvn clean install` para baixar a biblioteca. Se preferir Gradle, o equivalente é: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Agora você tem as classes de **ocr image preprocessing** no seu classpath. + +## Etapa 2: Aplicar sua Licença Aspose OCR (Opcional, mas Recomendado) + +Se você possui uma licença, aplique-a logo no início do seu método `main`. Pular esta etapa funciona, mas a versão gratuita adiciona uma marca d'água “Demo” na saída. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Por que isso importa:** A versão licenciada remove limites de uso e desativa a marca d'água, fornecendo resultados limpos e prontos para produção. + +## Etapa 3: Criar a Instância do Motor OCR + +O motor é o coração do processo. Instanciá‑lo dá acesso a todas as opções de **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Neste ponto o motor está pronto, mas usará as configurações padrão que podem não ser ideais para documentos escaneados. Vamos ajustar algumas. + +## Etapa 4: Habilitar Auto Deskew Images para Digitalizações Mais Nítidas + +Digitalizações inclinadas são um ponto problemático comum. Aspose oferece o recurso **auto deskew images** que endireita automaticamente a imagem antes do reconhecimento. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Como funciona:** O algoritmo analisa os ângulos da linha de base do texto e rotaciona a imagem para a orientação vertical mais provável. Isso melhora drasticamente a precisão para fotos tiradas com um celular. + +## Etapa 5: Ativar a Detecção Automática de Idioma + +Se você não souber o idioma da imagem de origem, deixe o motor descobrir. Esta é a configuração de **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Ao habilitar isso, a Aspose analisa os glifos e seleciona o modelo de idioma mais provável, suportando mais de 30 idiomas prontos para uso. + +## Etapa 6: Carregar a Imagem que Você Deseja Reconhecer + +Você pode carregar uma imagem do disco, de uma URL ou até mesmo de um array de bytes. Para simplificar, leremos de um arquivo local. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Dica:** Se você estiver lidando com imagens grandes, considere reduzir a amostra delas primeiro com `engine.getImagePreprocessing().setResizeFactor(0.5)` para acelerar o processamento sem perder muito detalhe. + +## Etapa 7: Executar o Reconhecimento OCR e Extrair Texto da Imagem + +Agora o motor faz sua mágica. O método `recognize` retorna um objeto `OcrResult` que contém o texto reconhecido, pontuações de confiança e mais. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +O console exibirá o texto simples extraído da imagem — este é o resultado principal de **extract text image** que nos propusemos a alcançar. + +## Exemplo Completo Funcional + +Abaixo está a classe Java completa que une tudo. Copie‑e cole em `src/main/java/com/example/OcrDemo.java` e execute. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Saída Esperada + +Se a imagem contiver a frase “Hello World” em uma digitalização limpa, você verá: + +``` +=== Recognized Text === +Hello World +``` + +Para documentos mais complexos (por exemplo, recibos multilíngues), a saída incluirá quebras de linha e o código do idioma detectado. + +## Armadilhas Comuns & Dicas Profissionais + +| Problema | Por que acontece | Solução | +|----------|------------------|---------| +| **Caracteres estranhos** | Imagem muito escura ou ruidosa. | Habilite `engine.getImagePreprocessing().setBinarization(true)` ou ajuste o contraste manualmente. | +| **Idioma errado** | Detecção automática falha em páginas com múltiplos idiomas. | Defina `engine.setLanguage(Language.English)` (ou o enum apropriado) para forçar um idioma específico. | +| **Processamento lento** | Imagens de resolução muito alta. | Reduza a escala com `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Erros de falta de memória** | Grande lote de imagens carregadas de uma vez. | Processar imagens sequencialmente e chamar `engine.dispose()` após cada execução. | + +> **Lembre‑se:** O motor OCR é seguro para threads em operações somente leitura, mas criar uma nova instância por thread evita bugs de estado oculto. + +## Expandindo a Solução + +Agora que você sabe **como usar OCR** com Aspose, você pode querer: + +1. Processar PDFs – Converta cada página PDF em uma imagem (`PdfConverter`) e então alimente‑a ao mesmo pipeline. +2. Processamento em lote de uma pasta – Percorra os arquivos de um diretório, aplicando as mesmas etapas, e escreva os resultados em um CSV. +3. Integrar com um serviço web – Exponha a lógica OCR via um `@RestController` Spring Boot que aceita uploads multipart. + +Todos esses cenários reutilizam a mesma configuração de **ocr image preprocessing** que construímos aqui. + +## Conclusão + +Cobremos **como usar OCR** em Java com Aspose do início ao fim: aplicando uma licença, criando o motor, ativando **auto deskew images**, habilitando **auto language detection**, carregando uma imagem e, finalmente, **extract text image** com um único `System.out.println`. O código é totalmente autocontido, roda em qualquer JDK recente e demonstra as melhores práticas para precisão e desempenho. + +Experimente com suas próprias imagens — talvez um contrato escaneado ou uma captura de tela de um recibo. Ajuste os flags de pré‑processamento, experimente diferentes idiomas e você verá rapidamente por que a biblioteca OCR da Aspose é uma escolha sólida para extração de texto em nível de produção. + +Tem perguntas ou quer compartilhar seus resultados? Deixe um comentário abaixo ou me avise no GitHub. Boa codificação! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## 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. + +- [Como fazer OCR de Texto de Imagem com Idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extrair Texto de Imagem Java com Aspose.OCR Modo Detectar Áreas](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Como Usar OCR - Técnicas Avançadas com Aspose.OCR para Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/portuguese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..bf918cf60 --- /dev/null +++ b/ocr/portuguese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Melhore a precisão do OCR em Python usando Aspose OCR. Aprenda como definir + o idioma do OCR, carregar a imagem para OCR e extrair texto da imagem com um dicionário + personalizado. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: pt +og_description: Melhore a precisão do OCR em Python definindo o idioma do OCR, carregando + uma imagem para OCR e extraindo texto da imagem com um dicionário personalizado. +og_title: Melhore a Precisão do OCR em Python – Guia Passo a Passo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Melhore a Precisão do OCR em Python – Guia Completo +url: /pt/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Melhore a Precisão do OCR em Python – Guia Completo + +Já se perguntou como **melhorar a precisão do OCR** quando o texto que você está escaneando contém símbolos estranhos, códigos de produto ou nomes de marcas? Você não está sozinho. Em muitos projetos o motor padrão simplesmente gera lixo, e isso é um verdadeiro obstáculo à produtividade. + +Neste tutorial vamos percorrer um exemplo prático, de ponta a ponta, que mostra como **definir o idioma do OCR**, **carregar a imagem para OCR**, **executar OCR na imagem** e, finalmente, **extrair texto da imagem** com um dicionário personalizado que aumenta as taxas de reconhecimento. Ao final, você terá um script pronto‑para‑executar que pode ser inserido em qualquer base de código Python. + +## O que Você Vai Aprender + +- Um script Python totalmente funcional que usa Aspose OCR para ler um arquivo PNG. +- A capacidade de **melhorar a precisão do OCR** configurando o idioma e uma lista de palavras personalizada. +- Explicações claras sobre por que cada configuração importa, além de dicas para lidar com casos extremos como caracteres não latinos. +- Uma lista de verificação rápida para solucionar problemas comuns de OCR. + +### Pré-requisitos + +- Python 3.8 ou superior instalado na sua máquina. +- Pacote `aspose-ocr` (instale via `pip install aspose-ocr`). +- Uma imagem de exemplo (`technical_doc.png`) que contém o texto que você deseja ler. +- Familiaridade básica com Python — nada de avançado é necessário. + +> **Dica profissional:** Se você estiver trabalhando em um ambiente virtual, ative‑o antes de instalar o pacote. Isso mantém suas dependências organizadas e evita conflitos de versão. + +--- + +## Passo 1: Instalar e Importar Aspose OCR + +Primeiro de tudo — vamos colocar a biblioteca no nosso ambiente e importar os componentes que precisamos. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +O namespace `aspose.ocr` dá acesso à classe `OcrEngine`, que é o coração do processo de OCR. Importá‑la aqui mantém o restante do script limpo e legível. + +--- + +## Passo 2: Criar um Motor OCR e **Definir o Idioma do OCR** + +Por que o idioma importa? Os motores OCR dependem de modelos específicos de idioma para reconhecer formas de caracteres e padrões de palavras. Se você informar ao motor que está escaneando texto em inglês, ele ignorará glifos cirílicos e focará no alfabeto latino, melhorando drasticamente a **precisão do OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Observação:** Aspose OCR suporta mais de 50 idiomas. Troque `ocr.Language.English` por `ocr.Language.Spanish`, `ocr.Language.French`, etc., se o seu documento não for em inglês. + +--- + +## Passo 3: Definir um **Dicionário Personalizado** para Aumentar a Precisão + +Imagine que você está escaneando faturas que contêm a palavra “AsposeOCR” ou códigos de produto como “SKU12345”. O motor não conhece esses termos, então ele adivinha incorretamente. Fornecer uma lista de palavras personalizada diz ao motor: *“Ei, essas strings são legítimas — não tente corrigi‑las.”* Isso é um ganho rápido para **melhorar a precisão do OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Você pode carregar essa lista a partir de um arquivo ou de um banco de dados se tiver centenas de entradas — basta mantê‑la em uma lista Python para simplificar. + +--- + +## Passo 4: **Carregar Imagem para OCR** + +Agora precisamos de uma imagem. O método `Image.load` aceita um caminho para qualquer formato raster suportado (PNG, JPEG, BMP, etc.). Se o arquivo não for encontrado, o motor lança uma exceção, então vamos proteger contra isso. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Por que este passo importa:** Carregar a imagem corretamente garante que o motor trabalhe com os dados de pixel exatos que você pretende analisar. Arquivos corrompidos ou caminhos errados são uma fonte comum de frustração. + +--- + +## Passo 5: **Executar OCR na Imagem** e Extrair Resultados + +Com o motor configurado e a imagem pronta, o reconhecimento real é uma única chamada de método. O objeto de resultado contém o texto bruto, pontuações de confiança e até informações de layout, se você precisar delas mais tarde. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Se precisar **extrair texto da imagem** linha por linha, pode dividir pelos caracteres de nova linha: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Passo 6: Verificar a Saída – Ela Realmente **Melhora a Precisão do OCR**? + +Vamos imprimir o resultado e ver se o nosso dicionário personalizado fez diferença. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +A saída típica para a imagem de exemplo pode ser semelhante a: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Observe como o nome da marca, o caractere grego e o código do produto aparecem exatamente como os definimos. Sem o dicionário personalizado, o motor teria tentado “corrigi‑los”, frequentemente produzindo algo como “Aspose OCR” ou “SKU 1234”. + +--- + +## Armadilhas Comuns & Como Resolvê‑las + +| Problema | Por que Acontece | Solução | +|----------|------------------|---------| +| **Caracteres lixo** | Idioma errado configurado ou imagem de baixa resolução | Certifique‑se de que `engine.language` corresponde ao idioma da fonte e use uma digitalização de alta DPI (300 dpi ou superior). | +| **Palavras personalizadas ignoradas** | Dicionário não anexado ou erro de digitação no nome da propriedade | Verifique novamente `engine.text_processing.custom_dictionary = …`. | +| **Arquivo não encontrado** | Caminho incorreto ou permissões de arquivo ausentes | Use `os.path.abspath()` para confirmar o caminho absoluto; execute o script com permissões adequadas. | +| **Processamento lento** | Imagens grandes ou muitas páginas | Pré‑procese a imagem (corte, redimensione) ou use `engine.recognize(image, max_threads=4)` para paralelizar. | + +--- + +## Avançando: Ajustes Avançados para **Melhorar a Precisão do OCR** + +1. **Pré‑processamento** – Aplique aumento de contraste ou binarização com Pillow antes de enviar a imagem ao Aspose OCR. +2. **Múltiplos Idiomas** – Defina `engine.language = ocr.Language.English | ocr.Language.French` para habilitar reconhecimento bilíngue. +3. **OCR por Região** – Se precisar apenas de uma área específica (por exemplo, uma tabela), recorte a imagem primeiro para reduzir ruído. +4. **Filtragem por Confiança** – `result.confidence` fornece uma pontuação por caractere; você pode descartar resultados de baixa confiança programaticamente. + +--- + +## Script Completo Funcional + +Abaixo está o script completo, pronto para copiar e colar, que incorpora cada passo que discutimos. Salve‑o como `improve_ocr_accuracy.py` e execute‑o a partir da linha de comando. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Execute: + +```bash +python improve_ocr_accuracy.py +``` + +Você deverá ver a saída formatada que exibimos anteriormente. + +--- + +## Conclusão + +Acabamos de cobrir uma maneira direta de **melhorar a precisão do OCR** em Python ao: + +1. **Definir o idioma do OCR** para corresponder ao seu documento. +2. **Carregar a imagem corretamente** para que o motor veja os pixels certos. +3. **Executar OCR na imagem** com uma única chamada de método. +4. **Extrair texto da imagem** e confirmar o resultado. +5. **Adicionar um dicionário personalizado** para fixar termos específicos do domínio. + +Esse é todo o fluxo de trabalho — da foto bruta ao texto limpo e pesquisável — embalado em um script organizado e reutilizável. + +Se você está pronto para o próximo desafio, experimente brincar com pré‑processamento de imagem (contraste, correção de inclinação) ou mude para uma configuração multilíngue usando `ocr.Language.English | ocr.Language.German`. Os mesmos princípios se aplicam, e você continuará **melhorando a precisão do OCR** em um conjunto mais amplo de documentos. + +Tem perguntas ou um caso extremo? Deixe um comentário abaixo, e feliz codificação! + +![improve OCR accuracy + + +## 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. + +- [Extrair Texto de Imagem – Otimização de OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Reconhecer texto em imagem com Aspose OCR para múltiplos idiomas](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Como Definir Valor de Limiar no Reconhecimento de Imagem OCR](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/portuguese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..f87f89172 --- /dev/null +++ b/ocr/portuguese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Execute OCR em imagens usando a biblioteca OCR do Python. Aprenda como + detectar texto em imagens, reconhecer texto em JPEG e extrair texto de imagens escaneadas + de forma eficiente. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: pt +og_description: Realize OCR em imagens com Python e extraia texto de arquivos escaneados. + Este guia orienta você passo a passo no carregamento de imagens, correção de inclinação + e reconhecimento de texto. +og_title: Realize OCR em Imagem com Python – Guia Completo de Extração de Texto +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Realize OCR em Imagem no Python – Guia Completo de Extração de Texto +url: /pt/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realize OCR em Imagem com Python – Guia Completo de Extração de Texto + +Já precisou **realizar OCR em arquivos de imagem** mas ficou travado porque o código parecia enigmático? Você não está sozinho. Seja transformando uma pilha de recibos escaneados em PDFs pesquisáveis ou extraindo legendas de um JPEG para um projeto de ciência de dados, a capacidade de reconhecer texto de JPEGs e outros formatos é uma habilidade indispensável para qualquer desenvolvedor hoje. + +Neste tutorial vamos percorrer um exemplo completo e executável que mostra como **detectar texto de arquivos de imagem**, **extrair texto de documentos escaneados** e até **carregar imagem para OCR** em apenas algumas linhas. Ao final, você terá um trecho sólido, pronto para produção, que pode ser inserido nos seus próprios projetos — sem importações ausentes, sem atalhos vagos de “ver docs”. + +## O que Você Vai Construir + +- Um pequeno script Python que cria um motor de OCR, habilita auto‑deskew, carrega um JPEG (ou qualquer formato suportado) e imprime o texto reconhecido. +- Explicações **por que** cada configuração importa, não apenas **como** digitá‑la. +- Dicas para lidar com PDFs de múltiplas páginas, idiomas não‑inglês e armadilhas comuns como escaneamentos borrados. + +### Pré‑requisitos + +- Python 3.8+ instalado (o exemplo usa o pacote `ocr` disponível via `pip install ocr-lib` – substitua pelo nome da sua biblioteca real). +- Familiaridade básica com funções Python e ambientes virtuais. +- Um arquivo de imagem (JPEG, PNG, TIFF) que você queira processar; usaremos `skewed_page.jpg` como placeholder. + +> **Dica de especialista:** Se você estiver no Windows, execute o terminal como Administrador ao instalar a biblioteca de OCR para evitar problemas de permissão. + +--- + +## Realize OCR em Imagem – Configuração e Preparação + +A primeira coisa que você precisa é uma instância limpa do motor de OCR. Pense nele como o cérebro por trás da operação; sem a configuração correta, até a imagem mais nítida retornará lixo. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Por que isso importa:** +Definir `engine.language` restringe o conjunto de caracteres que o motor de OCR espera, aumentando drasticamente a precisão. Se você pular isso, o motor tentará adivinhar, frequentemente interpretando palavras simples de forma errada. + +--- + +## Habilite Deskew Automático – Corrija Escaneamentos InclINados + +Páginas escaneadas raramente são perfeitamente planas. Uma leve inclinação pode atrapalhar a segmentação de caracteres, transformando “Hello” em “H3llo”. O parâmetro `auto_deskew` faz o trabalho pesado por você. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Caso de borda:** Se você souber que suas imagens já estão retas, desabilitar o deskew pode economizar alguns milissegundos de tempo de processamento — útil ao lidar com milhares de páginas em um job em lote. + +--- + +## Carregue Imagem para OCR – Suportando JPEG, PNG, TIFF + +Agora realmente **carregamos a imagem para OCR**. O método `ocr.Image.load` é flexível; aceita um caminho para qualquer formato raster suportado. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Por que esta etapa é crucial:** A biblioteca lê o arquivo para um bitmap interno, aplicando conversões de espaço de cor necessárias. Pular isso e passar um fluxo bruto de bytes geraria um `FileNotFoundError` ou, pior, produziria resultados vazios silenciosamente. + +Se precisar **reconhecer texto de arquivos JPEG** especificamente, basta garantir que a extensão do arquivo seja `.jpeg` ou `.jpg`. A mesma chamada funciona para PNG (`.png`) ou TIFF (`.tif`) sem modificação. + +--- + +## Realize OCR em Imagem – Executando o Motor + +Com o motor preparado e a imagem na memória, é hora de **realizar OCR em dados de imagem**. Esta única linha faz o trabalho pesado: pré‑processamento, segmentação, classificação e montagem do texto. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**O que acontece nos bastidores?** +- O motor aplica a transformação de deskew (se habilitada). +- Executa uma rede neural ou backend Tesseract para identificar caracteres. +- Por fim, junta os caracteres em palavras e linhas, retornando um objeto `result` rico. + +--- + +## Extraia Texto de Imagem Escaneada – Exiba os Resultados + +A etapa final é **extrair texto de imagem escaneada** e exibi‑lo. O atributo `result.text` contém a representação em texto puro. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +A saída típica se parece com: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Se o motor de OCR não encontrar nenhum caractere, `result.text` será uma string vazia. Nesse caso, verifique a qualidade da imagem ou considere ajustar a propriedade `engine.confidence_threshold` (se sua biblioteca a suportar). + +--- + +## Lidando com Variações Comuns + +### Reconhecer Texto de JPEG vs PNG + +Ambos os formatos são suportados, mas a compressão JPEG pode introduzir artefatos que confundem o motor. Se notar reconhecimentos errôneos frequentes, tente converter o JPEG para PNG primeiro: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detectar Texto de Imagem com Múltiplos Idiomas + +Se seu documento mistura Inglês e Espanhol, defina um modo multilíngue: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +O motor então considerará ambos os alfabetos durante o reconhecimento. + +### Extrair Texto de PDFs Escaneados + +Para PDFs, você precisa rasterizar cada página em uma imagem primeiro. Bibliotecas como `pdf2image` facilitam isso: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Exemplo Completo Funcional + +Abaixo está o script completo que você pode copiar‑colar em um arquivo `ocr_demo.py`. Ele inclui tratamento de erros e um pequeno helper para medir o tempo de execução. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Saída esperada** (supondo um escaneamento claro): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Perguntas Frequentes + +**P: Posso executar isso em um servidor sem interface gráfica?** +R: Absolutamente. A biblioteca funciona sem GUI; basta garantir que os binários nativos necessários (por exemplo, Tesseract) estejam instalados no servidor. + +**P: E se a imagem estiver borrada?** +R: Considere adicionar um filtro de nitidez antes de `engine.recognize`. Muitas bibliotecas de OCR expõem `image_preprocessing.sharpen = True` ou você pode usar `cv2.GaussianBlur` do OpenCV em sentido inverso. + +**P: O script suporta processamento em lote?** +R: Sim. Envolva `perform_ocr` em um loop sobre uma lista de caminhos de arquivos, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/portuguese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..efaca071f --- /dev/null +++ b/ocr/portuguese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-19 +description: Realize OCR em imagem usando Aspose OCR Java. Aprenda como carregar a + imagem para OCR, usar a licença Aspose e extrair texto da imagem em minutos. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: pt +og_description: Realize OCR em imagem com Aspose OCR Java. Este guia mostra como usar + a licença Aspose, carregar a imagem para OCR e extrair texto da imagem de forma + eficiente. +og_title: Realize OCR em imagem com Aspose OCR Java – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Realizar OCR em Imagem com Aspose OCR Java – Guia Completo Passo a Passo +url: /pt/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR em Imagem com Aspose OCR Java – Guia Completo Passo a Passo + +Já precisou **realizar OCR em imagem** mas não sabia qual biblioteca ofereceria resultados confiáveis sem muita configuração? Você não está sozinho. Em muitos projetos reais — pense em escanear passaportes, digitalizar notas fiscais ou extrair texto de capturas de tela — a capacidade de reconhecer rapidamente texto em imagens é um divisor de águas. + +Neste tutorial vamos percorrer um exemplo prático que mostra exatamente como **realizar OCR em imagem** usando Aspose OCR para Java. Cobriremos tudo, desde a aplicação da sua licença Aspose até o carregamento da imagem, a execução do motor e, finalmente, **extrair texto da imagem** para uso posterior. Sem enrolação, apenas uma solução funcional que você pode copiar‑colar. + +## O Que Você Vai Aprender + +- Uma visão clara de como **usar licença Aspose** em um projeto Java. +- O código exato necessário para **carregar imagem para OCR** e deixar o motor detectar idiomas automaticamente. +- Instruções passo a passo para **reconhecer texto em imagem** e **extrair texto da imagem** com segurança. +- Dicas para lidar com armadilhas comuns (resultados vazios, formatos não suportados e questões de memória). + +> **Pré‑requisitos** – Java 8 ou superior, Maven ou Gradle para gerenciamento de dependências e um arquivo de licença Aspose OCR para Java (ou você pode executar em modo de avaliação). + +--- + +## Como Realizar OCR em Imagem com Aspose OCR Java + +Abaixo está o programa Java completo, pronto para ser executado, que demonstra todo o fluxo. Salve-o como `AsposeOcrDemo.java` e execute-o a partir da sua IDE ou linha de comando. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Saída Esperada no Console + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Se você executar o programa sem um arquivo de licença, a primeira linha simplesmente indicará que está em modo de avaliação, mas o OCR continuará funcionando. + +--- + +## Configurar e Usar a Licença Aspose + +### Por Que a Licença É Importante + +Executar a biblioteca em modo de avaliação serve para testes rápidos, porém adiciona uma marca d’água ao resultado e limita o número de páginas que podem ser processadas por execução. Aplicar o passo **usar licença Aspose** remove essas restrições e sinaliza à Aspose que você é um cliente pagante. + +### Como Obter e Aplicar a Licença + +1. Compre uma licença na loja da Aspose. +2. Baixe o arquivo `Aspose.OCR.Java.lic`. +3. Coloque‑o em um local que sua aplicação possa ler — tipicamente a pasta `src/main/resources`. +4. Chame `new License().setLicense("Aspose.OCR.Java.lic");` antes de qualquer operação de OCR, como mostrado no código acima. + +> **Dica de especialista:** Se você for implantar em um servidor, use um caminho absoluto ou um carregador de recursos do class‑path para evitar `FileNotFoundException`. + +--- + +## Carregar Imagem para Processamento de OCR + +A linha `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` é o coração do passo **carregar imagem para OCR**. Aspose OCR suporta uma ampla gama de formatos: PNG, JPEG, BMP, TIFF e até PDFs multipáginas (quando combinados com Aspose.Pdf). + +### Armadilhas Comuns + +| Problema | Sintoma | Solução | +|----------|---------|---------| +| Caminho de arquivo errado | `FileNotFoundException` | Verifique o caminho; use `Paths.get(...)` para separadores independentes de SO. | +| Formato não suportado | `UnsupportedOperationException` | Converta a imagem para PNG ou JPEG antes de carregá‑la. | +| Imagem muito grande ( > 10 MP) | Erros de falta de memória | Reduza a escala da imagem usando `java.awt.Image` antes de enviá‑la ao Aspose. | + +--- + +## Extrair Texto da Imagem e Manipular Resultados + +Quando o motor de OCR termina, o objeto `OcrResult` contém a string reconhecida. É aqui que **extraímos texto da imagem** para processamento posterior — salvar em um banco de dados, alimentar um índice de busca ou alimentar um pipeline de NLP downstream. + +### Lidando com Múltiplos Idiomas + +Como definimos `engine.setLanguage(Language.Auto)`, a Aspose tentará detectar os idiomas em tempo real. Se você souber o idioma antecipadamente (por exemplo, todos os documentos são em russo), pode substituir `Language.Auto` por `Language.Russian` para melhorar o desempenho. + +### Dicas de Pós‑Processamento + +- **Remover espaços em branco**: `result.getText().trim()`. +- **Normalizar quebras de linha**: `result.getText().replace("\r\n", "\n")`. +- **Eliminar caracteres não imprimíveis**: use uma expressão regular como `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Reconhecer Texto em Imagem com Opções Avançadas (Opcional) + +Se precisar de controle mais fino, Aspose OCR oferece propriedades adicionais: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Esses ajustes são úteis quando você está lidando com documentos escaneados que apresentam inclinação ou baixo contraste. + +--- + +## Recapitulação do Exemplo Completo + +Juntando tudo, o programa final executa as etapas a seguir, nesta ordem: + +1. **Realizar OCR em imagem** – criando um `OcrEngine`. +2. **Usar licença Aspose** – opcional, mas recomendado. +3. **Carregar imagem para OCR** – via `Image.load`. +4. **Definir detecção de idioma** – `Language.Auto` para **reconhecer texto em imagem** automaticamente. +5. **Extrair texto da imagem** – imprimir o resultado, tratando respostas vazias de forma elegante. + +Você pode copiar o bloco de código acima diretamente para um projeto Maven com esta dependência: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Execute `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` e veja o console exibir o texto reconhecido. + +--- + +## Conclusão + +Acabamos de mostrar como **realizar OCR em imagem** usando Aspose OCR para Java, desde a aplicação de uma licença até **carregar a imagem para OCR**, **reconhecer texto em imagem** e, finalmente, **extrair texto da imagem** para uso posterior. A abordagem é direta, funciona com vários idiomas nativamente e pode ser estendida com opções avançadas de pré‑processamento quando necessário. + +Qual o próximo passo? Experimente alimentar a saída do OCR em um índice de busca, gerar PDFs com o texto extraído ou testar diferentes formatos de imagem. As possibilidades são infinitas, e com a robusta API da Aspose você passará mais tempo construindo funcionalidades do que lutando contra as peculiaridades do OCR. + +Tem dúvidas ou encontrou um caso extremo? Deixe um comentário abaixo — feliz codificação! + +## 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 de implementação em seus próprios projetos. + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/russian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9ef076461 --- /dev/null +++ b/ocr/russian/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Создайте PDF с поисковым текстом из изображения с помощью OCR на Python. + Узнайте, как преобразовать OCR в PDF, извлечь текст из изображения и быстро выполнить + OCR на изображении. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: ru +og_description: Создайте PDF с возможностью поиска из изображения с помощью Python + OCR. Это руководство показывает, как преобразовать OCR в PDF, извлечь текст из изображения + и выполнить OCR на изображении. +og_title: Создание PDF с поиском в Python – Полное пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Создание PDF с возможностью поиска в Python — Полное пошаговое руководство +url: /ru/python-java/general/create-searchable-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 в Python – Полное пошаговое руководство + +Когда‑нибудь вам нужно было **create searchable PDF** из отсканированного чека, но вы не знали, с чего начать? Вы не одиноки — многие разработчики сталкиваются с тем же, когда впервые пытаются превратить изображение текста в PDF, по которому действительно можно искать. + +В этом руководстве мы пройдем практическое решение, которое позволяет вам **perform OCR on image**, превратить результат OCR в **searchable PDF**, а также извлечь необработанный текст, если он нужен для дальнейшей обработки. Без лишних слов, только рабочий пример, который вы можете скопировать и вставить в свой проект уже сегодня. + +## Что вы узнаете + +- Как настроить лёгкий OCR‑движок в Python +- Точные шаги для **convert OCR to PDF** и сохранения его как поискового документа +- Способы **extract text from image** для последующего анализа +- Советы по работе с распространёнными проблемами, такими как ориентация изображения и большие файлы +- Полный, исполняемый скрипт, который вы можете адаптировать под свой случай использования + +### Требования + +- Установленный Python 3.8+ на вашем компьютере +- Базовое знакомство с pip и виртуальными окружениями (необязательно, но рекомендуется) +- Файл изображения (PNG, JPEG и т.д.), содержащий чёткий, машинно‑читаемый текст + +Если всё это у вас есть, давайте начнём. + +## Шаг 1: Установите необходимую библиотеку + +Фрагмент кода, который вы видели ранее, использует вымышленный пакет `ocr`, но те же идеи применимы к реальным библиотекам, таким как **EasyOCR**, **pytesseract** или **pdfminer.six**. Для этого руководства мы будем использовать **EasyOCR**, потому что он полностью написан на Python, поддерживает множество языков и предоставляет удобный метод конвертации в PDF через вспомогательный помощник. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Устанавливайте внутри виртуального окружения (`python -m venv venv && source venv/bin/activate`), чтобы ваши зависимости оставались упорядоченными. + +## Шаг 2: Инициализируйте OCR‑движок – Perform OCR on Image + +Теперь, когда библиотека готова, мы создаём OCR‑движок и указываем ему работать с английским текстом. Это первое место, где мы **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Зачем нужен отдельный объект‑чтения? EasyOCR предварительно загружает языковые модели, поэтому повторное использование одного и того же `reader` для нескольких изображений гораздо эффективнее, чем повторная инициализация каждый раз. + +## Шаг 3: Загрузите изображение – Extract Text from Image + +Давайте загрузим изображение в память. Этот шаг позже будет использоваться для **extract text from image**, но сейчас мы просто его загружаем. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Если ваше изображение перевёрнуто или искажено, рассмотрите возможность использования методов `rotate` или `transpose` из Pillow перед передачей его в OCR‑движок. Быстрая визуальная проверка может сэкономить часы отладки позже. + +## Шаг 4: Запустите OCR‑движок и получите результаты + +Это ядро процесса — отправка изображения в OCR‑движок и получение обратно структурированных данных. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Флаг `detail=1` предоставляет нам ограничительные рамки, которые понадобятся позже для **convert OCR to PDF**. Если вам нужны только строки, установите `detail=0`. + +## Шаг 5: Преобразуйте результат OCR в поисковый PDF – Convert OCR to PDF + +EasyOCR не предоставляет прямой записи PDF, но мы можем собрать PDF самостоятельно, используя Pillow и библиотеку `reportlab`. Чтобы руководство оставалось лёгким, мы будем использовать `fpdf2`, который позволяет встраивать оригинальное изображение и накладывать невидимый текст. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Что только что произошло? Мы разместили отсканированное изображение как видимый слой, затем записали распознанные слова сверху, используя белый текст, который сливается с белым фоном. Поисковые инструменты всё равно читают скрытый слой, поэтому PDF становится **searchable** без изменения визуального вида. + +## Шаг 6: Сохраните PDF‑байты — Convert Image to PDF + +Если вы предпочитаете работать с PDF в памяти (например, отправлять его через API), вы можете захватить байты вместо прямой записи на диск. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Эта строка демонстрирует классический рабочий процесс **convert image to PDF**: вы начинаете с изображения, запускаете OCR, накладываете текст и в конце выводите поток PDF. + +## Шаг 7: Проверьте результат — Быстрые проверки + +После выполнения скрипта откройте `receipt_searchable.pdf` в любом PDF‑просмотрщике и попробуйте поиск (Ctrl + F). Введите слово, которое, как вы знаете, присутствует в чеке — если оно переходит к нужному месту, вы успешно **create searchable pdf**! + +Если поиск не срабатывает, проверьте: + +1. Оценки уверенности OCR (`conf` значения). Низкая уверенность может означать, что изображение размыто. +2. Координаты ограничительных рамок — иногда EasyOCR сообщает их в иной ориентации. +3. Что просмотрщик PDF не установлен в режим «только изображение» (редко, но некоторые просмотрщики имеют такую опцию). + +## Полный рабочий скрипт + +Объединив всё вместе, представляем полный готовый к запуску файл Python: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Сохраните этот файл как `searchable_pdf.py`, замените заполнители `YOUR_DIRECTORY` реальными путями и запустите: + +```bash +python searchable_pdf.py +``` + +Вы должны увидеть сообщение подтверждения и совершенно новый поисковый PDF в вашей папке. + +## Часто задаваемые вопросы и особые случаи + +**Что если изображение цветное?** +EasyOCR работает как с черно‑белыми, так и с цветными изображениями, но преобразование в градации серого (`pil_image.convert("L")`) иногда повышает точность на шумных сканах. + +**Можно ли обрабатывать многостраничные PDF?** +Да — выполните цикл по каждому изображению страницы, запустите шаги OCR и добавьте каждую страницу к тому же объекту `FPDF`. Просто не забудьте сбросить курсор (`self.add_page()`) для каждого нового изображения. + +**Есть ли способ сохранить оригинальный текстовый слой вместо невидимого белого текста?** +Если вам нужен настоящий PDF «текст‑под‑изображением» (например, для доступности), рассмотрите использование `pdfminer` или `pikepdf` для встраивания скрытого текстового слоя с правильными PDF‑тегами. Это более продвинуто, но принцип остаётся тем же: фоновое изображение + наложенный текст. + +**Что если уверенность OCR низкая?** +Вы можете отфильтровать слова с низкой уверенностью: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Итоги — Что мы достигли + +Мы начали с простого изображения чека, **performed OCR on image**, извлекли распознанные строки и в конце **create searchable pdf**, который ведёт себя как любой профессионально отсканированный документ. Процесс охватил все вторичные ключевые слова — **convert OCR to PDF**, **extract text from image**, **convert image to PDF**, и **perform OCR on image** — так что теперь у вас есть повторно используемый набор инструментов для любого похожего проекта. + +### Следующие шаги + +- Поэкспериментируйте с другими языками, передавая их ISO‑коды в `easyocr.Reader(['en', 'es'])`. +- Замените EasyOCR на Tesseract, если вам требуется полностью офлайн‑решение; остальная часть конвейера остаётся той же. +- Добавьте визуализацию уверенности 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/russian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..3ce6a587c --- /dev/null +++ b/ocr/russian/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Извлекайте текст из изображений в Python с помощью простого OCR‑движка. + Узнайте, как преобразовать отсканированные изображения в текст, распознавать текст + на фотографиях и эффективно перечислять файлы изображений в Python. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: ru +og_description: Извлекайте текст из изображений в Python с помощью лёгкого OCR‑движка. + Это руководство покажет, как преобразовать отсканированные изображения в текст, + распознать текст на фотографиях и перечислить файлы изображений в Python за несколько + шагов. +og_title: Извлечение текста из изображений в Python — Полное руководство по пакетному + OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Извлечение текста из изображений в Python – Полное руководство по пакетному + OCR +url: /ru/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Извлечение текста из изображений в Python – Полное руководство по пакетному OCR + +Когда‑то вам нужно **извлечь текст из изображений**, но вы не знали, с чего начать? Вы не одиноки — разработчики постоянно сталкиваются с задачей преобразования отсканированных PDF, сфотографированных чеков или скриншотов в поисковый текст. В этом руководстве мы пройдём через полностью готовый к запуску пример, показывающий, как **преобразовать отсканированные изображения в текст**, распознавать текст на картинках и даже **list image files python**‑style. К концу вы получите переиспользуемый скрипт, который обрабатывает всю папку за один проход. + +Мы охватим всё необходимое: требуемые библиотеки, почему важен каждый шаг, обработку граничных случаев и небольшие советы по отладке. Не нужно искать внешнюю документацию; код ниже самодостаточен, а пояснения отвечают на вопросы «как» *и* «почему». Откройте ваш любимый IDE и приступим. + +--- + +## Что вы построите + +- Инициализировать OCR‑движок (для иллюстрации мы используем пакет `ocr`). +- Просканировать каталог и **list image files python**‑style, отфильтровав PNG, JPG и TIFF. +- Выполнить **batch OCR** над всеми найденными изображениями. +- Вывести извлечённый текст для каждого файла, чётко помеченный. + +> **Pro tip:** Если у вас не установлен пакет `ocr`, его можно заменить на `pytesseract` с несколькими небольшими изменениями — основная логика останется той же. + +--- + +## Предварительные требования + +- Python 3.8+ (скрипт использует f‑строки и подсказки типов). +- OCR‑библиотека, предоставляющая `OcrEngine` с методом `recognize_batch`. В этом руководстве мы предполагаем вымышленный пакет `ocr`, но шаблон работает и с реальными библиотеками. +- Папка, содержащая изображения, которые вы хотите обработать (`.png`, `.jpg`, `.tif`). + +--- + +## Шаг 1 – Установить и импортировать необходимые модули + +Сначала убедитесь, что OCR‑пакет доступен. Если вы используете реальную библиотеку, например `pytesseract`, замените импорт соответствующим образом. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Почему это важно:** Импорт `os` даёт кроссплатформенную работу с путями, а `typing.List` помогает автодополнению в IDE и делает код более устойчивым к будущим изменениям. + +--- + +## Шаг 2 – **Extract Text from Images**: Инициализировать OCR‑движок + +Создание движка — первый шаг к любой работе с OCR. Мы также задаём язык автоопределения, чтобы движок мог обрабатывать документы с несколькими языками. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Пояснение:** Обёртывание создания движка в функцию делает код модульным. Если позже понадобится изменить DPI или режим OCR, править нужно будет только в одном месте. + +--- + +## Шаг 3 – **List Image Files Python**: Сбор файлов из каталога + +Теперь нужно найти каждую картинку, которую будем обрабатывать. Ниже приведён list comprehension, отражающий типичный паттерн «list image files python». + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Обработка граничных случаев:** Функция игнорирует подпапки (рекурсию можно добавить позже) и автоматически отбрасывает скрытые файлы, поскольку они обычно не заканчиваются поддерживаемыми расширениями. + +--- + +## Шаг 4 – **Convert Scanned Images to Text**: Выполнить пакетный OCR + +Большинство OCR‑библиотек предоставляют пакетный метод, который работает гораздо быстрее, чем обработка по одному изображению. Вот как его вызвать. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Почему пакетный режим?** Передача всех изображений сразу уменьшает накладные расходы (например, повторную загрузку модели OCR) и часто даёт лучшую загрузку CPU/GPU. + +--- + +## Шаг 5 – **Recognize Text from Pictures**: Вывести результаты + +Наконец, мы проходим по парам имён файлов и результатов OCR, печатая чистый заголовок для каждого изображения. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Совет:** `strip()` удаляет начальные и конечные пробелы, которые OCR часто добавляет. + +--- + +## Полный скрипт – собрать всё вместе + +Ниже полностью готовая к запуску программа. Сохраните её как `batch_ocr.py` и запустите `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Ожидаемый вывод + +Если в папке находятся `invoice1.png` и `receipt.jpg`, вы можете увидеть следующее: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Каждый блок чётко помечен, что упрощает последующую обработку (например, сохранение в базу данных). + +--- + +## Обработка распространённых проблем + +| Проблема | Почему происходит | Быстрое решение | +|----------|-------------------|-----------------| +| **Текст не появляется** | Язык OCR не определён или изображение слишком низкоконтрастное. | Принудительно задать язык (`engine.language = ocr.Language.English`) или предварительно обработать изображения (увеличить контраст). | +| **Ошибка памяти при больших пакетах** | Движок пытается загрузить все изображения сразу. | Разделить `image_files` на части (`batch_size = 20`) и вызывать `recognize_batch` последовательно. | +| **Неподдерживаемый формат файла** | Вы добавили `.gif` или `.bmp`. | Расширить кортеж `supported_exts` или предварительно конвертировать изображения в PNG/JPG. | +| **Искажение Unicode** | OCR возвращает байты вместо строк. | Убедиться, что библиотека выводит Unicode (`result.text.decode('utf‑8')`, если нужно). | + +--- + +## Расширение рабочего процесса + +Теперь, когда вы умеете **extract text from images**, рассмотрите следующие шаги: + +- **Экспорт в CSV** – Записать каждое имя файла и извлечённый текст в таблицу для аналитики. +- **Параллельная обработка** – Использовать `concurrent.futures.ThreadPoolExecutor` для одновременной обработки нескольких пакетов. +- **Интеграция с облачным OCR** – Заменить локальный движок на Google Vision или Azure OCR для более высокой точности при сложных макетах. +- **Добавить предобработку изображений** – Библиотеки вроде Pillow или OpenCV могут выпрямлять, удалять шум или применять пороговую обработку перед OCR, повышая качество результатов. + +Все эти идеи естественно используют те же базовые функции, которые мы построили, так что начинать с нуля не придётся. + +--- + +## Заключение + +Мы только что прошли через полное решение для **extract text from images** в Python, охватив всё от **list image files python** до **recognize text from pictures** и, наконец, **convert scanned images to text** в удобном пакетном режиме. Скрипт преднамеренно прост, но достаточно гибок, чтобы служить основой для более крупных проектов — будь то оцифровка чеков, создание поискового архива или построение конвейера извлечения данных. + +Попробуйте его, подправьте шаги предобработки и наблюдайте, как растёт точность OCR. Если возникнут трудности, вернитесь к таблице «Обработка распространённых проблем» — большинство вопросов решается небольшими изменениями конфигурации. + +Готовы к следующему вызову? Попробуйте добавить шаг конвертации PDF в изображения с помощью `pdf2image`, а затем передать полученные изображения в тот же конвейер. Возможности безграничны, когда OCR сочетается с богатой экосистемой Python. + +Счастливого кодинга, и пусть ваш текст всегда будет читаемым! + + +## Что изучать дальше? + + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом гайде. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности 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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/russian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..17d79aef6 --- /dev/null +++ b/ocr/russian/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-19 +description: Извлекайте текст из изображений с помощью Python OCR. Узнайте об автоматическом + определении языка, параллельной обработке и пакетном распознавании в кратком руководстве. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: ru +og_description: Извлекать текст из изображений с помощью Python OCR. Это руководство + демонстрирует автоматическое определение языка, параллельную обработку и пакетное + распознавание в одном учебнике. +og_title: Извлечение текста из изображений в Python — Полное руководство по OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Извлечение текста из изображений в Python — Полное руководство по OCR +url: /ru/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# извлечение текста из изображений в Python – Полное руководство по OCR + +Задумывались ли вы когда‑нибудь, как **извлечь текст из изображений** без ручного ввода каждого слова? Вы не одиноки. Будь то оцифровка старых чеков, создание поискового архива документов или просто игра с крутыми AI‑трюками, способность извлекать текст из картинок — это обязательный навык для любого разработчика Python сегодня. + +В этом руководстве мы пройдем полный, готовый к запуску пример, который **извлекает текст из изображений** с помощью популярного OCR‑движка. Мы рассмотрим автоматическое определение языка, параллельную обработку для ускорения и пакетное распознавание изображений, чтобы вы могли обрабатывать десятки файлов за секунды. Звучит как то, что вам нужно? Давайте начнём. + +## Что вы узнаете + +- Как создать экземпляр OCR‑движка с помощью `ocr.OcrEngine`. +- Включение **автоматического определения языка**, чтобы движок сам выбирал нужный язык. +- Настройка **параллельной обработки OCR** с пользовательским пулом потоков. +- Запуск **пакетного распознавания изображений** для списка файлов. +- Вывод распознанного текста для каждого изображения, готового к сохранению или индексации. + +Никакой внешней документации не требуется — всё, что нужно, находится здесь, а код работает сразу после установки пакета `ocr` (установите его через `pip install ocr`). + +## Требования + +1. Python 3.8 или новее установлен. +2. Пакет `ocr` (`pip install ocr`). +3. Папка с PNG (или JPG) изображениями, которые вы хотите обработать. +4. Базовое знакомство с функциями и циклами Python. + +Вот и всё — без тяжёлых зависимостей, без магии GPU, просто чистый Python. + +![пример извлечения текста из изображений](https://example.com/ocr-demo.png "Скриншот, показывающий вывод извлечения текста из изображений") + +*Alt text: скриншот демонстрации извлечения текста из изображений* + +## Шаг 1 – Настройка OCR‑движка (Основное ключевое слово в действии) + +First thing’s first: create an OCR engine instance. Think of `ocr.OcrEngine()` as the brain behind the operation; it knows how to read characters, lines, and paragraphs. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Why do we need an explicit engine? Because the **ocr.OcrEngine usage** gives you fine‑grained control over language settings, threading, and more. It’s the most flexible way to **extract text from images** compared to one‑liner helpers. + +## Шаг 2 – Позвольте движку автоматически определять языки + +Most OCR libraries require you to tell them which language to look for. That’s fine for a single‑language project, but cumbersome for a mixed‑language batch. Luckily, the `ocr` package supports **automatic language detection**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Setting `engine.language` to `ocr.Language.Auto` tells the engine to sniff each image and pick the appropriate language model. This tiny line saves you hours of manual configuration when you’re dealing with international documents. + +## Шаг 3 – Ускорьте процесс с помощью параллельной обработки OCR + +If you have four or more CPU cores, why not use them? The engine can spin up a thread pool, letting multiple images be processed at the same time. This is where **parallel processing OCR** shines. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Feel free to adjust the number `4` based on your machine. More threads → faster batch runs, but remember that each thread consumes memory, so find a sweet spot for your environment. + +## Шаг 4 – Сбор изображений для обработки + +Now we need a list of file paths. You can build this list manually, read it from a CSV, or use `glob`. For clarity, we’ll hard‑code a short list: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Replace `YOUR_DIRECTORY` with the actual path on your system. If you have dozens of files, a quick `glob.glob("*.png")` will do the heavy lifting. + +## Шаг 5 – Запуск пакетного распознавания изображений + +Here’s the heart of the tutorial: a single call that processes every image in `files` and returns a list of result objects. This is the **batch image recognition** feature that makes large‑scale OCR practical. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Behind the scenes, the engine distributes each file across the four worker threads we configured earlier, while also auto‑detecting the language for each picture. The method returns a list where each element holds the recognized text and metadata. + +## Шаг 6 – Вывод (или сохранение) извлечённого текста + +Finally, we loop over the results and print the text. In a real project you’d probably write this to a database or a CSV file, but printing keeps the example simple. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Expected output** (truncated for brevity): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Each block shows the filename followed by the OCR‑derived string. If an image contains multiple languages, you’ll see the appropriate characters appear thanks to the earlier **automatic language detection** step. + +## Профессиональные советы и распространённые подводные камни + +- **Image quality matters** – blurry or low‑contrast pictures will produce garbage. Pre‑process with OpenCV (`cv2.threshold`, `cv2.resize`) if needed. +- **Thread count vs. I/O** – If your images live on a slow network drive, more threads might not help. Keep an eye on CPU usage with `top` or `Task Manager`. +- **Unicode handling** – The `result.text` is a Unicode string. When writing to files, open them with `encoding="utf‑8"` to avoid `UnicodeEncodeError`s. +- **Memory usage** – Large PDFs can consume a lot of RAM. If you hit `MemoryError`, reduce the thread pool size or process images in smaller chunks. + +## Полный рабочий скрипт + +Below is the complete, copy‑and‑paste‑ready script that incorporates every step we discussed. Save it as `batch_ocr.py` and run `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Run it like this: + +```bash +python batch_ocr.py ./my_images 4 +``` + +You’ll see a nicely formatted block of text for each image, proving that you can **extract text from images** at scale. + +## Что дальше? + +Now that you’ve mastered the basics of **extract text from images** with Python, consider exploring: + +- **Post‑processing**: очистка вывода OCR с помощью regex или библиотек обработки естественного языка. +- **PDF conversion**: передача извлечённых строк в генератор PDF для поисковых PDF‑файлов. +- **Cloud OCR services**: сравнение локальных результатов `ocr` с Google Vision или Azure OCR для точности в граничных случаях. +- **GUI front‑end**: создание небольшого приложения на Flask или FastAPI, позволяющего пользователям загружать изображения и мгновенно видеть извлечённый текст. + +Each of these topics builds on the **Python OCR library** foundation you just set up, and they all benefit from the same **parallel processing OCR** tricks we used here. + +--- + +*Счастливого кодинга! Если возникнут проблемы, оставляйте комментарий ниже — я всегда готов помочь с нюансами OCR.* + +## Что следует изучить дальше? + +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. + +- [Извлечение текста из изображения с 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/) +- [Извлечение текста из изображения – оптимизация 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/russian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/russian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..37369b85c --- /dev/null +++ b/ocr/russian/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-06-19 +description: Как извлечь PDF с помощью OCR в Python – пошаговое руководство, охватывающее + извлечение текста из PDF, распознавание текста на изображении и пример OCR на Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: ru +og_description: Как извлекать PDF с помощью OCR в Python. Узнайте, как извлекать текст + из PDF, распознавать текст на изображении, и посмотрите полный пример OCR на Python. +og_title: Как извлечь текст из PDF с помощью OCR в Python – Полный учебник +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Как извлечь текст из PDF с помощью OCR в Python — полное руководство +url: /ru/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как извлечь текст из PDF с помощью OCR в Python – Полное руководство + +Когда‑нибудь задавались вопросом **как извлечь содержимое PDF**, если файл представляет собой просто отсканированное изображение? Вы не одиноки. Во многих реальных проектах — контракты, счета‑фактуры, исторические архивы — получаемый PDF не содержит выделяемого текста. Хорошая новость? Пара строк кода на Python могут превратить такие страницы‑изображения в поисковый, редактируемый текст. + +В этом руководстве мы пройдём практический **OCR Python example**, который читает PDF, рендерит первую страницу как изображение, а затем **извлекает текст из PDF** с помощью OCR‑движка. К концу вы точно будете знать, как **читать PDF с OCR**, почему каждый шаг важен и как адаптировать код для многостраничных документов или разных языков. + +## Что вы узнаете + +- Установить и настроить надёжную OCR‑библиотеку для Python. +- Преобразовать страницы PDF в изображения, подходящие для OCR. +- **Распознавать текст с изображения** и получать чистые Unicode‑строки. +- Распространённые подводные камни (PDF низкого разрешения, повернутые страницы) и как их избежать. +- Расширить скрипт для обработки нескольких страниц или пакетной обработки. + +**Prerequisites**: Python 3.8+, pip и базовое понимание виртуальных окружений. Предыдущий опыт работы с OCR не требуется — просто следуйте инструкциям. + +--- + +## ## Как извлечь текст из PDF с помощью OCR в Python + +Этот заголовок H2 содержит наш основной ключевой запрос именно там, где поисковые системы любят его видеть. Переходим сразу к коду. + +### Шаг 1 – Установите необходимые пакеты + +Сначала нам нужен OCR‑движок. В примере ниже используется популярный пакет **ocr** (тонкая обёртка над Tesseract). Если вы предпочитаете другой бекенд, концепции остаются теми же. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Совет:** В Linux также понадобится бинарный файл Tesseract: `sudo apt-get install tesseract-ocr`. Пользователи macOS могут установить его через Homebrew: `brew install tesseract`. + +### Шаг 2 – Инициализируйте OCR‑движок и задайте язык + +Теперь запускаем движок и указываем искать английские символы. Вы можете заменить `ocr.Language.English` на любой поддерживаемый код языка. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Почему это важно:** Указание языка существенно повышает точность, поскольку движок может применять языковые словари и модели символов. + +### Шаг 3 – Загрузите страницу PDF как изображение + +OCR работает с растровыми изображениями, а не с объектами PDF. Помощник `ocr.Image.from_pdf` рендерит выбранную страницу в bitmap. Измените `page_number` для других страниц (нумерация с нуля). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Особый случай:** Если PDF содержит векторную графику вместо отсканированных изображений, вы можете получить чёткое рендеринг. Для сканов низкого разрешения рассмотрите увеличение DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Шаг 4 – Распознавайте текст с отрендеренного изображения + +Это сердце **ocr python example**. Движок обрабатывает bitmap и возвращает объект, содержащий извлечённую строку. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Атрибут `ocr_result.text` содержит обычный текстовый вывод, сохраняющий разрывы строк там, где это возможно. + +### Шаг 5 – Выведите или сохраните извлечённый текст + +Наконец, выводим результат. В реальном приложении вы, вероятно, запишете его в файл или базу данных. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Запуск скрипта должен отобразить что‑то вроде: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Это полный **extract text from pdf** рабочий процесс с использованием OCR. + +--- + +## ## Распознавать текст с изображения – Улучшение точности + +Если вам нужен только **recognize text from image** (например, JPEG‑чек), можно пропустить шаг конвертации PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Советы для лучшего результата:** + +- **Предобработать** изображение: перевести в градации серого, применить пороговую обработку или исправить наклон. Pillow делает это легко. +- **Увеличить DPI** при рендеринге PDF: более высокое разрешение даёт OCR‑движку больше деталей. +- **Включить конфигурацию OCR‑движка** для сегментации страниц (`ocr_engine.config = "--psm 6"` для однородных блоков). + +--- + +## ## Читать PDF с OCR – Обработка нескольких страниц + +Большинство контрактов охватывают несколько страниц. Перебор каждой страницы прост: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Эта функция **reads PDF with OCR**, конкатенирует вывод и вставляет чёткий маркер разрыва страницы. Затем вы можете передать `full_text` в поисковый индекс или сохранить как файл `.txt`. + +--- + +## ## Распространённые проблемы и как их исправить + +| Симптом | Вероятная причина | Решение | +|---------|-------------------|---------| +| Искажённые символы, много `?` | Неправильный язык или отсутствие файлов данных языка | Установите правильный языковой пакет Tesseract (`tesseract-ocr-`) и задайте `ocr_engine.language`. | +| Пропущенные строки или усечённые слова | Низкое DPI (менее 150) | Рендерите PDF с 300 DPI или выше (`dpi=300`). | +| Текст повернут или вверх‑вниз | Сканированная страница не выровнена | Используйте `ocr.Image.deskew(page_image)` перед распознаванием. | +| Медленная обработка больших PDF | Последовательная обработка страниц в одном потоке | Параллелизуйте с `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Расширение OCR Python Example + +- **Экспорт в PDF/A**: После извлечения вы можете встроить текст обратно в поисковый PDF с помощью `reportlab` или `pypdf2`. +- **Определение языка**: Используйте `langdetect` на выводе OCR, чтобы динамически переключать `ocr_engine.language`. +- **Пакетная обработка**: Пройдитесь по директории с `os.listdir` и примените `extract_all_pages` к каждому файлу. + +--- + +## ## Ожидаемый вывод и проверка + +Когда вы запустите скрипт на чистом скане на английском, вы должны увидеть аккуратный блок текста с правильной пунктуацией. Проверьте, выполнив: + +1. Сравнение нескольких строк с оригинальным отсканированным изображением. +2. Запуск простого подсчёта слов (`len(ocr_result.text.split())`), чтобы убедиться, что вывод не пустой. +3. При желании, передайте результат в проверщик орфографии, например `pyspellchecker`, чтобы обнаружить ошибки OCR. + +--- + +## Заключение + +Мы рассмотрели **как извлечь PDF**, когда традиционный парсинг не работает, продемонстрировали полный **ocr python example** и объяснили, как **recognize text from image** и **read PDF with OCR** для одно‑ и много‑страничных сценариев. С помощью приведённых выше фрагментов кода вы теперь можете превратить любой отсканированный PDF в поисковый, редактируемый текст — без ручного перепечатывания. + +Следующие шаги? Попробуйте переключить язык на испанский (`ocr.Language.Spanish`) или поэкспериментировать с методами предобработки изображений для повышения точности. Если вы создаёте систему управления документами, рассмотрите индексацию извлечённого текста в Elasticsearch для молниеносного поиска. + +Есть вопросы или столкнулись с причудливым PDF? Оставьте комментарий, и счастливого кодинга! + +![Как извлечь PDF с помощью OCR в Python](image.png "Как извлечь PDF с помощью OCR в Python") + + +## Что вам стоит изучить дальше? + + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом гайде. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/russian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..0072b76ab --- /dev/null +++ b/ocr/russian/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-06-19 +description: Узнайте, как использовать OCR в Java с Aspose. Это пошаговое руководство + охватывает автоматическое выравнивание изображений, автоматическое определение языка + и простое извлечение текста из изображения. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: ru +og_description: 'Как использовать OCR в Java с Aspose: полное руководство, охватывающее + автоматическое исправление наклона изображений, автоматическое определение языка + и извлечение текста из картинок.' +og_title: Как использовать OCR в Java с Aspose – Полное руководство +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Как использовать OCR в Java с Aspose – Полное руководство +url: /ru/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как использовать OCR в Java с Aspose – Полное руководство + +Когда‑нибудь задумывались **how to use OCR** в Java‑проекте, не теряя волосы от настройки? Вы не одиноки. Многие разработчики сталкиваются с проблемой, когда нужно быстро **extract text image** данные, особенно если исходные сканы кривые или написаны на неизвестном языке. + +В этом руководстве мы пройдем практический пример, который покажет вам точно, как использовать OCR с Aspose, включая **auto deskew images**, **auto language detection** и полный конвейер **ocr image preprocessing**. К концу у вас будет готовый к запуску фрагмент кода, который выводит распознанный текст в консоль, и вы поймете, почему каждый параметр важен. + +> **What you’ll get:** полный, исполняемый Java‑программ, объяснения каждой строки, советы по обработке граничных случаев и идеи по расширению решения для пакетной обработки или PDF. + +--- + +## Требования + +- Java 17 (или любой современный JDK), установленный и настроенный. +- Maven или Gradle для управления зависимостями (мы покажем координаты Maven). +- Файл лицензии Aspose OCR for Java (`Aspose.OCR.Java.lic`). Если вы просто тестируете, можете пропустить шаг с лицензией, но бесплатная версия добавит водяной знак. +- Пример изображения (`your_image.png`), размещенный в доступном для кода месте. + +> **Pro tip:** Храните изображения в отдельной папке `resources` и загружайте их через classpath; это избавит от проблем с путями на разных ОС. + +## Шаг 1: Настройка проекта и добавление зависимости Aspose OCR + +Создайте новый Maven‑проект (или используйте существующий) и добавьте следующее в ваш `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Запустите `mvn clean install`, чтобы загрузить библиотеку. Если вы предпочитаете Gradle, эквивалент выглядит так: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Теперь у вас есть классы **ocr image preprocessing** в classpath. + +## Шаг 2: Применение лицензии Aspose OCR (необязательно, но рекомендуется) + +Если у вас есть лицензия, примените её сразу в начале вашего метода `main`. Пропуск этого шага работает, но бесплатная версия накладывает водяной знак «Demo» на вывод. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Why this matters:** лицензированная версия снимает ограничения использования и отключает водяной знак, предоставляя чистые, готовые к продакшену результаты. + +## Шаг 3: Создание экземпляра OCR Engine + +Движок — сердце процесса. Его создание дает доступ ко всем параметрам **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +На данном этапе движок готов, но будет использовать настройки по умолчанию, которые могут быть не оптимальны для сканированных документов. Давайте подправим несколько. + +## Шаг 4: Включение Auto Deskew Images для более чистых сканов + +Наклонённые сканы — распространённая проблема. Aspose предоставляет функцию **auto deskew images**, которая автоматически выравнивает изображение перед распознаванием. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **How it works:** алгоритм анализирует углы базовой линии текста и вращает изображение в наиболее вероятную вертикальную ориентацию. Это значительно повышает точность для фотографий, сделанных телефоном. + +## Шаг 5: Включение Auto Language Detection + +Если вы не знаете язык исходного изображения, позвольте движку определить его. Это настройка **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Когда вы включаете это, Aspose сканирует глифы и выбирает наиболее вероятную языковую модель, поддерживая более 30 языков сразу. + +## Шаг 6: Загрузка изображения для распознавания + +Вы можете загрузить изображение с диска, по URL или даже из массива байтов. Для простоты мы будем читать локальный файл. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tip:** если вы работаете с большими изображениями, рассмотрите возможность их понижения разрешения сначала с помощью `engine.getImagePreprocessing().setResizeFactor(0.5)`, чтобы ускорить обработку без значительной потери деталей. + +## Шаг 7: Выполнение OCR‑распознавания и извлечение Text Image + +Теперь движок делает свою магию. Метод `recognize` возвращает объект `OcrResult`, содержащий распознанный текст, оценки уверенности и многое другое. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Консоль отобразит простой текст, извлечённый из изображения — это основной результат **extract text image**, к которому мы стремились. + +## Полный рабочий пример + +Ниже полный Java‑класс, который связывает всё вместе. Скопируйте его в `src/main/java/com/example/OcrDemo.java` и запустите. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Ожидаемый вывод + +Если изображение содержит фразу «Hello World» на чистом скане, вы увидите: + +``` +=== Recognized Text === +Hello World +``` + +Для более сложных документов (например, многоязычных чеков) вывод будет включать разрывы строк и код обнаруженного языка. + +## Распространённые проблемы и профессиональные советы + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | Image is too dark or noisy. | Enable `engine.getImagePreprocessing().setBinarization(true)` or adjust the contrast manually. | +| **Wrong language** | Auto detection misfires on mixed‑language pages. | Set `engine.setLanguage(Language.English)` (or the appropriate enum) to force a specific language. | +| **Slow processing** | Very high‑resolution images. | Downscale with `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Out‑of‑memory errors** | Large batch of images loaded at once. | Process images sequentially and call `engine.dispose()` after each run. | + +> **Remember:** OCR‑движок потокобезопасен для операций только чтения, но создание нового экземпляра на каждый поток избегает скрытых ошибок состояния. + +## Расширение решения + +Теперь, когда вы знаете **how to use OCR** с Aspose, вы можете захотеть: + +1. **Process PDFs** – Преобразуйте каждую страницу PDF в изображение (`PdfConverter`), затем передайте её в тот же конвейер. +2. **Batch process a folder** – Пройдитесь по файлам в каталоге, применяя те же шаги, и запишите результаты в CSV. +3. **Integrate with a web service** – Откройте логику OCR через Spring Boot `@RestController`, принимающий multipart‑загрузки. + +Все эти сценарии повторно используют ту же конфигурацию **ocr image preprocessing**, которую мы построили здесь. + +## Заключение + +Мы рассмотрели **how to use OCR** в Java с Aspose от начала до конца: применение лицензии, создание движка, включение **auto deskew images**, активацию **auto language detection**, загрузку изображения и, наконец, **extract text image** с помощью единственного `System.out.println`. Код полностью автономен, работает на любой современной JDK и демонстрирует лучшие практики для точности и производительности. + +Попробуйте его с вашими собственными изображениями — возможно, сканированным контрактом или скриншотом чека. Настройте флаги предобработки, экспериментируйте с разными языками, и вы быстро поймёте, почему библиотека OCR от Aspose — надёжный выбор для извлечения текста в продакшн‑среде. + +Есть вопросы или хотите поделиться результатами? Оставьте комментарий ниже или напишите мне на GitHub. Счастливого кодинга! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полные работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Как выполнять OCR текста изображения с определением языка с помощью Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Извлечение текста из изображения Java с Aspose.OCR в режиме обнаружения областей](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Как использовать OCR — продвинутые техники с Aspose.OCR для Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/russian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..8e7360a05 --- /dev/null +++ b/ocr/russian/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Повышайте точность OCR в Python с помощью Aspose OCR. Узнайте, как установить + язык OCR, загрузить изображение для распознавания и извлечь текст из изображения + с пользовательским словарём. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: ru +og_description: Повышайте точность OCR в Python, задавая язык OCR, загружая изображение + для OCR и извлекая текст из изображения с помощью пользовательского словаря. +og_title: Улучшите точность OCR в Python – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Улучшение точности OCR в Python — Полное руководство +url: /ru/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Улучшение точности OCR в Python – Полное руководство + +Задумывались ли вы когда‑нибудь, как **повысить точность OCR**, когда сканируемый текст содержит странные символы, коды продуктов или названия брендов? Вы не одиноки. Во многих проектах стандартный движок просто выдаёт бессмыслицу, и это серьёзный удар по продуктивности. + +В этом руководстве мы пройдём практический, сквозной пример, который покажет, как **установить язык OCR**, **загрузить изображение для OCR**, **выполнить OCR на изображении** и, наконец, **извлечь текст из изображения** с помощью пользовательского словаря, повышающего коэффициент распознавания. К концу вы получите готовый к запуску скрипт, который можно вставить в любой код Python. + +## Что вы получите + +- Полностью рабочий скрипт на Python, использующий Aspose OCR для чтения PNG‑файла. +- Возможность **повысить точность OCR**, настроив язык и пользовательский список слов. +- Чёткие объяснения, почему каждый параметр важен, а также советы по работе с краевыми случаями, такими как нелатинские символы. +- Быстрый чек‑лист для устранения распространённых проблем OCR. + +### Предварительные требования + +- Python 3.8 или новее, установленный на вашем компьютере. +- Пакет `aspose-ocr` (установить через `pip install aspose-ocr`). +- Пример изображения (`technical_doc.png`), содержащего текст, который вы хотите прочитать. +- Базовое знакомство с Python — ничего сложного не требуется. + +> **Pro tip:** Если вы работаете в виртуальном окружении, активируйте его перед установкой пакета. Это сохраняет порядок в зависимостях и избегает конфликтов версий. + +--- + +## Шаг 1: Установить и импортировать Aspose OCR + +Сначала — загрузим библиотеку в наше окружение и импортируем необходимые части. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Пространство имён `aspose.ocr` даёт доступ к классу `OcrEngine`, который является сердцем процесса OCR. Импортируя его здесь, мы делаем остальную часть скрипта чистой и читаемой. + +--- + +## Шаг 2: Создать OCR‑движок и **установить язык OCR** + +Почему язык имеет значение? OCR‑движки полагаются на языко‑специфичные модели для распознавания форм символов и шаблонов слов. Если вы укажете, что сканируете английский текст, движок проигнорирует кириллические глифы и сосредоточится на латинском алфавите, что значительно **повысит точность OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Note:** Aspose OCR поддерживает более 50 языков. Замените `ocr.Language.English` на `ocr.Language.Spanish`, `ocr.Language.French` и т.д., если ваш документ не на английском. + +--- + +## Шаг 3: Определить **пользовательский словарь** для повышения точности + +Представьте, что вы сканируете счета, содержащие слово «AsposeOCR» или коды продуктов вроде «SKU12345». Движок не знает этих терминов, поэтому делает неверные предположения. Предоставив пользовательский список слов, вы говорите движку: *«Эти строки легитимны — не пытайтесь их исправлять»*. Это быстрый способ **повысить точность OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Вы можете загрузить этот список из файла или базы данных, если у вас сотни записей — просто храните его в списке Python для простоты. + +--- + +## Шаг 4: **Загрузить изображение для OCR** + +Теперь нам нужно изображение. Метод `Image.load` принимает путь к любому поддерживаемому растровому формату (PNG, JPEG, BMP и т.д.). Если файл не найден, движок бросит исключение, поэтому мы защитим этот случай. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Why this step matters:** Корректная загрузка изображения гарантирует, что движок работает с точными пиксельными данными, которые вы собираетесь анализировать. Повреждённые файлы или неверные пути — частый источник разочарования. + +--- + +## Шаг 5: **Выполнить OCR на изображении** и извлечь результаты + +С настроенным движком и готовым изображением фактическое распознавание — это один вызов метода. Объект результата содержит исходный текст, оценки уверенности и даже информацию о макете, если она понадобится позже. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Если нужно **извлечь текст из изображения** построчно, можно разбить его по символам новой строки: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Шаг 6: Проверить вывод — действительно ли **повышает точность OCR**? + +Выведем результат и посмотрим, изменил ли наш пользовательский словарь ситуацию. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Типичный вывод для примера изображения может выглядеть так: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Обратите внимание, как название бренда, греческий символ и код продукта отображаются точно так, как мы их задали. Без пользовательского словаря движок попытался бы «исправить» их, часто получая что‑то вроде «Aspose OCR» или «SKU 1234». + +--- + +## Распространённые проблемы и способы их решения + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| **Garbage characters** | Неправильно установлен язык или изображение низкого разрешения | Убедитесь, что `engine.language` соответствует исходному языку и используйте сканирование с высоким DPI (300 dpi или выше). | +| **Custom words ignored** | Словарь не подключён или опечатка в имени свойства | Проверьте `engine.text_processing.custom_dictionary = …`. | +| **File not found** | Неправильный путь или отсутствие прав доступа к файлу | Используйте `os.path.abspath()` для проверки абсолютного пути; запускайте скрипт с нужными правами. | +| **Slow processing** | Большие изображения или много страниц | Предобработайте изображение (обрезка, изменение размера) или используйте `engine.recognize(image, max_threads=4)` для параллелизации. | + +--- + +## Дальше: продвинутые настройки для **повышения точности OCR** + +1. **Предобработка** – примените улучшение контраста или бинаризацию с помощью Pillow перед передачей изображения в Aspose OCR. +2. **Несколько языков** – установите `engine.language = ocr.Language.English | ocr.Language.French`, чтобы включить двуязычное распознавание. +3. **OCR по региону** – если нужен только определённый участок (например, таблица), сначала обрежьте изображение, чтобы уменьшить шум. +4. **Фильтрация по уверенности** – `result.confidence` предоставляет оценку уверенности для каждого символа; вы можете программно отбрасывать результаты с низкой уверенностью. + +--- + +## Полный рабочий скрипт + +Ниже представлен полностью готовый к копированию скрипт, включающий каждый шаг, о котором мы говорили. Сохраните его как `improve_ocr_accuracy.py` и запустите из командной строки. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Запустите: + +```bash +python improve_ocr_accuracy.py +``` + +Вы должны увидеть красиво отформатированный вывод, который мы показывали ранее. + +--- + +## Заключение + +Мы только что рассмотрели простой способ **повысить точность OCR** в Python, выполнив: + +1. **Установку языка OCR** в соответствии с вашим документом. +2. **Корректную загрузку изображения**, чтобы движок видел правильные пиксели. +3. **Выполнение OCR на изображении** одним вызовом метода. +4. **Извлечение текста из изображения** и подтверждение результата. +5. **Добавление пользовательского словаря** для закрепления терминов, специфичных для домена. + +Это весь рабочий процесс — от сырого изображения до чистого, поискового текста — упакованный в аккуратный, переиспользуемый скрипт. + +Если вы готовы к следующему вызову, попробуйте поэкспериментировать с предобработкой изображений (контраст, выравнивание) или переключитесь на многоязычную настройку, используя `ocr.Language.English | ocr.Language.German`. Принципы остаются теми же, и вы будете **повышать точность OCR** для более широкого набора документов. + +Есть вопросы или странный краевой случай? Оставьте комментарий ниже, и happy coding! + +![improve OCR accuracy + + +## Что изучать дальше? + + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Извлечение текста из изображения – оптимизация OCR с Aspose.OCR для .NET](/ocr/english/net/ocr-optimization/) +- [Распознавание текста изображения с Aspose OCR для нескольких языков](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Как установить пороговое значение в распознавании изображений OCR](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/russian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..efd180f8b --- /dev/null +++ b/ocr/russian/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Выполните OCR на изображении с помощью библиотеки OCR для Python. Узнайте, + как обнаруживать текст на изображении, распознавать текст из JPEG и эффективно извлекать + текст из отсканированного изображения. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: ru +og_description: Выполняйте OCR изображения с помощью Python и извлекайте текст из + отсканированных файлов. Это руководство пошагово проведёт вас через загрузку изображений, + исправление наклона и распознавание текста. +og_title: Выполните OCR изображения в Python — Полное руководство по извлечению текста +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Выполнить OCR изображения в Python – Полное руководство по извлечению текста +url: /ru/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Выполнить OCR на изображении в Python – Полное руководство по извлечению текста + +Когда‑то вам нужно **выполнить OCR на изображении**, но код выглядел непонятно? Вы не одиноки. Будь то преобразование кучи отсканированных чеков в поисковые PDF или извлечение подписей из JPEG для проекта по data‑science, умение распознавать текст из JPEG и других форматов — обязательный навык для любого разработчика сегодня. + +В этом руководстве мы пройдём через полностью рабочий пример, показывающий, как **обнаружить текст на изображениях**, **извлечь текст из отсканированных изображений**, и даже **загрузить изображение для OCR** всего в несколько строк. К концу вы получите готовый к продакшну фрагмент кода, который можно вставить в свои проекты — без пропущенных импортов и неопределённых «см. документацию» сокращений. + +## Что вы построите + +- Маленький скрипт на Python, который создаёт OCR‑движок, включает авто‑выравнивание, загружает JPEG (или любой поддерживаемый формат) и выводит распознанный текст. +- Объяснения **почему** каждое настройка важна, а не только **как** её написать. +- Советы по работе с многостраничными PDF, нелатинскими языками и типичными проблемами, такими как размытые сканы. + +### Предпосылки + +- Установлен Python 3.8+ (в примере используется пакет `ocr`, доступный через `pip install ocr-lib` — замените на название вашей библиотеки). +- Базовое знакомство с функциями Python и виртуальными окружениями. +- Файл изображения (JPEG, PNG, TIFF), который вы хотите обработать; в примере используется `skewed_page.jpg` как заполнитель. + +> **Pro tip:** Если вы работаете в Windows, запустите терминал от имени администратора при установке OCR‑библиотеки, чтобы избежать проблем с правами доступа. + +--- + +## Выполнить OCR на изображении – Настройка и конфигурация + +Первое, что нужно — чистый экземпляр OCR‑движка. Считайте его мозгом операции; без правильной конфигурации даже самое чёткое изображение вернёт бессмыслицу. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Почему это важно:** +Установка `engine.language` ограничивает набор символов, которые ожидает OCR‑движок, что резко повышает точность. Если пропустить этот шаг, движок будет угадывать, часто ошибаясь даже в простых словах. + +--- + +## Включить автоматическое выравнивание – исправление наклонённых сканов + +Отсканированные страницы редко бывают идеально ровными. Небольшой наклон может нарушить сегментацию символов, превратив “Hello” в “H3llo”. Флаг `auto_deskew` делает всю тяжёлую работу за вас. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Пограничный случай:** Если вы знаете, что ваши изображения уже выровнены, отключение выравнивания может сэкономить несколько миллисекунд времени обработки — полезно при работе с тысячами страниц в пакетном режиме. + +--- + +## Загрузить изображение для OCR – поддержка JPEG, PNG, TIFF + +Теперь мы действительно **загружаем изображение для OCR**. Метод `ocr.Image.load` гибок; он принимает путь к любому поддерживаемому растровому формату. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Почему этот шаг критичен:** Библиотека читает файл во внутренний bitmap, при необходимости преобразуя цветовое пространство. Пропуск этого шага и передача необработанного потока байтов вызовет `FileNotFoundError` или, что ещё хуже, тихо вернёт пустой результат. + +Если вам нужно **распознать текст из JPEG** файлов, просто убедитесь, что расширение файла `.jpeg` или `.jpg`. Тот же вызов работает и для PNG (`.png`) или TIFF (`.tif`) без изменений. + +--- + +## Выполнить OCR на изображении – запуск движка + +С движком, подготовленным и изображением в памяти, пришло время **выполнить OCR на изображении**. Эта одна строка делает всю тяжёлую работу: предобработку, сегментацию, классификацию и сборку текста. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Что происходит «под капотом»?** +- Движок применяет трансформацию выравнивания (если включена). +- Запускает нейронную сеть или бекенд Tesseract для идентификации символов. +- Наконец, склеивает символы в слова и строки, возвращая богатый объект `result`. + +--- + +## Извлечь текст из отсканированного изображения – вывод результатов + +Последний шаг — **извлечь текст из отсканированного изображения** и отобразить его. Атрибут `result.text` содержит текстовое представление. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Типичный вывод выглядит так: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Если OCR‑движок не найдёт ни одного символа, `result.text` будет пустой строкой. В этом случае проверьте качество изображения или попробуйте отрегулировать свойство `engine.confidence_threshold` (если ваша библиотека поддерживает его). + +--- + +## Обработка распространённых вариантов + +### Распознавать текст из JPEG vs PNG + +Оба формата поддерживаются, но сжатие JPEG может добавить артефакты, сбивающие движок. Если вы замечаете частые ошибки распознавания, попробуйте сначала конвертировать JPEG в PNG: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Обнаружить текст на изображении с несколькими языками + +Если ваш документ содержит английский и испанский, включите многоязычный режим: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Движок тогда будет учитывать оба алфавита при распознавании. + +### Извлечь текст из отсканированных PDF + +Для PDF необходимо сначала растеризовать каждую страницу в изображение. Библиотеки вроде `pdf2image` делают это без труда: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Полный рабочий пример + +Ниже полный скрипт, который можно скопировать в файл `ocr_demo.py`. В нём есть обработка ошибок и небольшой помощник для измерения времени выполнения. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Ожидаемый вывод** (при чистом скане): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Часто задаваемые вопросы + +**В: Можно ли запускать это на сервере без графического интерфейса?** +О: Конечно. Библиотека работает без GUI; просто убедитесь, что необходимые нативные бинарники (например, Tesseract) установлены на сервере. + +**В: Что делать, если изображение размыто?** +О: Попробуйте добавить фильтр резкости перед `engine.recognize`. Многие OCR‑библиотеки предоставляют `image_preprocessing.sharpen = True` или можно использовать обратный `cv2.GaussianBlur` из OpenCV. + +**В: Поддерживает ли скрипт пакетную обработку?** +О: Да. Оберните `perform_ocr` в цикл по списку путей к файлам, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/russian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..05f399601 --- /dev/null +++ b/ocr/russian/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-19 +description: Выполните OCR изображения с помощью Aspose OCR Java. Узнайте, как загрузить + изображение для OCR, использовать лицензию Aspose и извлечь текст из изображения + за несколько минут. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: ru +og_description: Выполните OCR изображения с помощью Aspose OCR Java. Это руководство + показывает, как использовать лицензию Aspose, загрузить изображение для OCR и эффективно + извлечь текст из изображения. +og_title: Выполнить OCR изображения с помощью Aspose OCR Java – Полный учебник +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Распознавание текста на изображении с помощью Aspose OCR Java – Полное пошаговое + руководство +url: /ru/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Выполнение OCR на изображении с помощью Aspose OCR Java – Полное пошаговое руководство + +Когда‑то вам нужно было **выполнить OCR на изображении**, но вы не знали, какая библиотека даст надёжные результаты без кучи настроек? Вы не одиноки. Во многих реальных проектах — сканирование паспортов, оцифровка счетов или извлечение текста из скриншотов — возможность быстро распознавать текст на изображениях меняет правила игры. + +В этом руководстве мы пройдём через практический пример, показывающий, как **выполнить OCR на изображении** с помощью Aspose OCR для Java. Мы охватим всё: от применения лицензии Aspose до загрузки изображения, запуска движка и, наконец, **извлечения текста из изображения**, чтобы вы могли использовать его дальше. Без лишних слов, только работающая реализация, которую можно скопировать и вставить. + +## Что вы получите в результате + +- Чёткое представление о том, как **использовать лицензию Aspose** в Java‑проекте. +- Точный код, необходимый для **загрузки изображения для OCR** и автоматического определения языков движком. +- Пошаговые инструкции по **распознаванию текста на изображении** и безопасному **извлечению текста из изображения**. +- Советы по работе с распространёнными проблемами (пустые результаты, неподдерживаемые форматы и вопросы памяти). + +> **Prerequisites** – Java 8 или новее, Maven или Gradle для управления зависимостями и файл лицензии Aspose OCR for Java (или вы можете работать в режиме оценки). + +--- + +## Как выполнить OCR на изображении с Aspose OCR Java + +Ниже представлен полностью готовый к запуску Java‑программный код, демонстрирующий весь процесс. Сохраните его как `AsposeOcrDemo.java` и запустите из IDE или командной строки. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Ожидаемый вывод в консоль + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Если запустить программу без файла лицензии, первая строка просто укажет, что вы работаете в режиме оценки, но OCR всё равно будет работать. + +--- + +## Настройка и использование лицензии Aspose + +### Почему лицензия важна + +Запуск библиотеки в режиме оценки подходит для быстрых тестов, но добавляет водяной знак к результату и ограничивает количество страниц, которые можно обработать за один запуск. Шаг **использовать лицензию Aspose** снимает эти ограничения и сообщает Aspose, что вы платный клиент. + +### Как получить и применить её + +1. Приобретите лицензию в магазине Aspose. +2. Скачайте файл `Aspose.OCR.Java.lic`. +3. Поместите его туда, где приложение сможет его прочитать — обычно в папку `src/main/resources`. +4. Вызовите `new License().setLicense("Aspose.OCR.Java.lic");` перед любой работой с OCR, как показано в коде выше. + +> **Pro tip:** При развертывании на сервере используйте абсолютный путь или загрузчик ресурсов из class‑path, чтобы избежать `FileNotFoundException`. + +--- + +## Загрузка изображения для обработки OCR + +Строка `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` является сердцем шага **загрузить изображение для OCR**. Aspose OCR поддерживает широкий спектр форматов: PNG, JPEG, BMP, TIFF и даже многостраничные PDF (в сочетании с Aspose.Pdf). + +### Распространённые подводные камни + +| Проблема | Симптом | Решение | +|----------|---------|---------| +| Неправильный путь к файлу | `FileNotFoundException` | Проверьте путь; используйте `Paths.get(...)` для независимых от ОС разделителей. | +| Неподдерживаемый формат | `UnsupportedOperationException` | Конвертируйте изображение в PNG или JPEG перед загрузкой. | +| Огромное изображение ( > 10 МП) | Ошибки нехватки памяти | Уменьшите размер изображения с помощью `java.awt.Image` перед передачей в Aspose. | + +--- + +## Извлечение текста из изображения и обработка результатов + +После завершения работы OCR‑движка объект `OcrResult` содержит распознанную строку. Здесь мы **извлекаем текст из изображения** для дальнейшей обработки — сохранения в базе данных, передачи в поисковый индекс или в downstream‑pipeline NLP. + +### Работа с несколькими языками + +Поскольку мы установили `engine.setLanguage(Language.Auto)`, Aspose попытается определить язык «на лету». Если язык известен заранее (например, все документы на русском), замените `Language.Auto` на `Language.Russian` для повышения производительности. + +### Советы по постобработке + +- **Удалить лишние пробелы**: `result.getText().trim()`. +- **Нормализовать окончания строк**: `result.getText().replace("\r\n", "\n")`. +- **Удалить непечатные символы**: используйте регулярное выражение, например `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Распознавание текста на изображении с расширенными опциями (необязательно) + +Если нужен более тонкий контроль, Aspose OCR предлагает дополнительные свойства: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Эти настройки полезны, когда вы работаете со сканами, страдающими от наклона или низкого контраста. + +--- + +## Полный рабочий пример в обзоре + +Объединив всё вместе, окончательная программа выполняет следующие шаги последовательно: + +1. **Выполнить OCR на изображении** — создавая `OcrEngine`. +2. **Использовать лицензию Aspose** — опционально, но рекомендуется. +3. **Загрузить изображение для OCR** — через `Image.load`. +4. **Установить автоматическое определение языка** — `Language.Auto` для **распознавания текста на изображении**. +5. **Извлечь текст из изображения** — вывести результат, корректно обрабатывая пустые ответы. + +Вы можете скопировать блок кода выше непосредственно в Maven‑проект с такой зависимостью: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Запустите `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` и наблюдайте, как консоль выводит распознанный текст. + +--- + +## Заключение + +Мы только что показали, как **выполнить OCR на изображении** с помощью Aspose OCR для Java: от применения лицензии до **загрузки изображения для OCR**, **распознавания текста на изображении** и, наконец, **извлечения текста из изображения** для дальнейшего использования. Подход прост, работает с несколькими языками «из коробки» и может быть расширен с помощью продвинутых вариантов предобработки при необходимости. + +Что дальше? Попробуйте передать вывод OCR в поисковый индекс, генерировать PDF‑файлы с извлечённым текстом или экспериментировать с разными форматами изображений. Возможности безграничны, а благодаря надёжному API Aspose вы будете тратить больше времени на построение функций, а не на борьбу с quirks OCR. + +Есть вопросы или столкнулись с редким случаем? Оставьте комментарий ниже — happy coding! + +## Что стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом пособии. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3f4228000 --- /dev/null +++ b/ocr/spanish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-06-19 +description: Crear PDF buscable a partir de una imagen usando OCR con Python. Aprende + a convertir OCR a PDF, extraer texto de una imagen y realizar OCR en una imagen + rápidamente. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: es +og_description: Crea un PDF buscable a partir de una imagen con OCR en Python. Esta + guía muestra cómo convertir OCR a PDF, extraer texto de una imagen y realizar OCR + en la imagen. +og_title: Crear PDF buscable en Python – Guía completa de programación +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Crear PDF buscable en Python – Guía completa paso a paso +url: /es/python-java/general/create-searchable-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 >}} + +# Crear PDF buscable en Python – Guía completa paso a paso + +¿Alguna vez necesitaste **crear un PDF buscable** a partir de un recibo escaneado pero no sabías por dónde empezar? No estás solo: muchos desarrolladores se topan con el mismo obstáculo cuando intentan convertir una foto de texto en un PDF que realmente se pueda buscar. + +En este tutorial recorreremos una solución práctica que te permite **realizar OCR en una imagen**, convertir ese resultado de OCR en un **PDF buscable**, e incluso extraer el texto sin procesar si lo necesitas para un procesamiento posterior. Sin rodeos, solo un ejemplo funcional que puedes copiar‑pegar en tu proyecto hoy mismo. + +## Lo que aprenderás + +- Cómo configurar un motor OCR ligero en Python +- Los pasos exactos para **convertir OCR a PDF** y guardarlo como documento buscable +- Formas de **extraer texto de una imagen** para análisis posterior +- Consejos para manejar problemas comunes como la orientación de la imagen y archivos grandes +- Un script completo y ejecutable que puedes adaptar a tu caso de uso + +### Requisitos previos + +- Python 3.8+ instalado en tu máquina +- Familiaridad básica con pip y entornos virtuales (opcional pero recomendado) +- Un archivo de imagen (PNG, JPEG, etc.) que contenga texto claro y legible por máquina + +Si tienes eso, vamos a sumergirnos. + +## Paso 1: Instalar la biblioteca requerida + +El fragmento de código que viste antes usa un paquete ficticio `ocr`, pero las mismas ideas se aplican a bibliotecas reales como **EasyOCR**, **pytesseract** o **pdfminer.six**. Para esta guía usaremos **EasyOCR** porque es puro Python, soporta muchos idiomas y devuelve un práctico método de conversión a PDF mediante un ayudante auxiliar. + +```bash +pip install easyocr pillow +``` + +> **Consejo profesional:** Instala dentro de un entorno virtual (`python -m venv venv && source venv/bin/activate`) para mantener tus dependencias ordenadas. + +## Paso 2: Inicializar el motor OCR – Realizar OCR en la imagen + +Ahora que la biblioteca está lista, creamos un motor OCR y le indicamos que trabaje con texto en inglés. Este es el primer lugar donde **realizamos OCR en la imagen**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +¿Por qué necesitamos un objeto lector dedicado? EasyOCR precarga los modelos de idioma, por lo que reutilizar el mismo `reader` para múltiples imágenes es mucho más eficiente que volver a inicializarlo cada vez. + +## Paso 3: Cargar la imagen – Extraer texto de la imagen + +Vamos a cargar la foto en memoria. Este paso es donde más tarde **extraeremos texto de la imagen**, pero primero solo la cargamos. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Si tu imagen está al revés o sesgada, considera usar los métodos `rotate` o `transpose` de Pillow antes de pasarla al motor OCR. Una rápida revisión visual puede ahorrarte horas de depuración después. + +## Paso 4: Ejecutar el motor OCR y capturar resultados + +Aquí está el núcleo del proceso: enviar la imagen al motor OCR y obtener datos estructurados de vuelta. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +La bandera `detail=1` nos da cajas delimitadoras, que necesitaremos cuando más adelante **convirtamos OCR a PDF**. Si solo te interesan las cadenas crudas, establece `detail=0`. + +## Paso 5: Convertir el resultado OCR a un PDF buscable – Convertir OCR a PDF + +EasyOCR no proporciona un escritor de PDF directo, pero podemos ensamblar el PDF nosotros mismos usando Pillow y la biblioteca `reportlab`. Para mantener el tutorial ligero, usaremos `fpdf2`, que nos permite incrustar la imagen original y superponer texto invisible. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +¿Qué acaba de pasar? Colocamos la imagen escaneada como capa visible, luego escribimos las palabras reconocidas encima usando texto blanco que se funde con el fondo blanco. Las herramientas de búsqueda aún leen la capa oculta, por lo que el PDF se vuelve **buscable** sin alterar la apariencia visual. + +## Paso 6: Guardar los bytes del PDF – Convertir imagen a PDF + +Si prefieres manejar el PDF en memoria (por ejemplo, enviándolo a través de una API), puedes capturar los bytes en lugar de escribir directamente en disco. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Esa línea muestra el clásico flujo de trabajo **convertir imagen a PDF**: comienzas con una imagen, ejecutas OCR, superpones texto y finalmente emites un flujo de PDF. + +## Paso 7: Verificar el resultado – Chequeos rápidos + +Después de ejecutar el script, abre `receipt_searchable.pdf` en cualquier visor de PDF y prueba la caja de búsqueda (Ctrl + F). Escribe una palabra que sepas que aparece en el recibo; si salta al lugar correcto, ¡has **creado un PDF buscable** con éxito! + +Si la búsqueda falla, verifica: + +1. Los puntajes de confianza del OCR (`conf`). Una confianza baja puede indicar que la imagen está borrosa. +2. Las coordenadas de las cajas delimitadoras; a veces EasyOCR las reporta en una orientación diferente. +3. Que el visor de PDF no esté en modo “solo imagen” (raro, pero algunos visores tienen esa opción). + +## Script completo y funcional + +Juntando todo, aquí tienes el archivo Python completo y listo para ejecutar: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Guárdalo como `searchable_pdf.py`, reemplaza los marcadores `YOUR_DIRECTORY` con rutas reales, y ejecuta: + +```bash +python searchable_pdf.py +``` + +Deberías ver un mensaje de confirmación y un nuevo PDF buscable en tu carpeta. + +## Preguntas frecuentes y casos límite + +**¿Qué pasa si la imagen es en color?** +EasyOCR funciona tanto con imágenes en escala de grises como en color, pero convertir a escala de grises (`pil_image.convert("L")`) a veces mejora la precisión en escaneos ruidosos. + +**¿Puedo manejar PDFs de varias páginas?** +Sí: itera sobre cada imagen de página, ejecuta los pasos de OCR y agrega cada página al mismo objeto `FPDF`. Solo recuerda reiniciar el cursor (`self.add_page()`) para cada nueva imagen. + +**¿Existe una forma de mantener la capa de texto original en lugar de texto blanco invisible?** +Si necesitas un PDF verdadero “texto‑sobre‑imagen” (por ejemplo, para accesibilidad), considera usar `pdfminer` o `pikepdf` para incrustar una capa de texto oculta con etiquetas PDF apropiadas. Es más avanzado, pero el principio sigue siendo el mismo: imagen de fondo + texto superpuesto. + +**¿Qué hacer si la confianza del OCR es baja?** +Puedes filtrar palabras de baja confianza: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Conclusión – Lo que logramos + +Partimos de una simple imagen de un recibo, **realizamos OCR en la imagen**, extrajimos las cadenas reconocidas y finalmente **creamos un PDF buscable** que se comporta como cualquier documento escaneado profesionalmente. El proceso cubrió todas las palabras clave secundarias—**convertir OCR a PDF**, **extraer texto de la imagen**, **convertir imagen a PDF**, y **realizar OCR en la imagen**—por lo que ahora dispones de una caja de herramientas reutilizable para cualquier proyecto similar. + +### Próximos pasos + +- Experimenta con otros idiomas pasando sus códigos ISO a `easyocr.Reader(['en', 'es'])`. +- Cambia EasyOCR por Tesseract si necesitas una solución totalmente offline; el resto del pipeline permanece igual. +- Añade visualización de confianza OCR (dibuja cajas delimitadoras sobre la imagen) para depurar escaneos problemáticos. + +¿Tienes una variante que quieras compartir? Deja un comentario, haz un fork + + +## ¿Qué deberías aprender después? + + +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 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/spanish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..f079efbdb --- /dev/null +++ b/ocr/spanish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: Extrae texto de imágenes en Python con un motor OCR sencillo. Aprende + cómo convertir imágenes escaneadas a texto, reconocer texto de fotos y listar archivos + de imagen en Python de manera eficiente. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: es +og_description: Extrae texto de imágenes en Python usando un motor OCR ligero. Esta + guía te muestra cómo convertir imágenes escaneadas a texto, reconocer texto en fotos + y listar archivos de imagen en Python en unos pocos pasos. +og_title: Extraer texto de imágenes en Python – Guía completa de OCR por lotes +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Extraer texto de imágenes en Python – Guía completa de OCR por lotes +url: /es/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraer texto de imágenes en Python – Guía completa de OCR por lotes + +¿Alguna vez necesitaste **extraer texto de imágenes** pero no sabías por dónde comenzar? No estás solo—los desarrolladores se enfrentan constantemente al desafío de convertir PDFs escaneados, recibos fotografiados o capturas de pantalla en texto buscable. En este tutorial recorreremos un ejemplo completo, listo‑para‑ejecutar, que muestra cómo **convertir imágenes escaneadas a texto**, reconocer texto de fotos y hasta **list image files python**‑style. Al final tendrás un script reutilizable que procesa una carpeta completa de una sola vez. + +Cubrirémos todo lo que necesitas: bibliotecas requeridas, por qué cada paso es importante, manejo de casos límite y un poco de solución de problemas. No es necesario buscar documentación externa; el código a continuación es autónomo, y las explicaciones responden al “cómo” *y* al “por qué”. Prepara tu IDE favorito y vamos a comenzar. + +--- + +## Lo que construirás + +- Inicializar un motor OCR (usaremos el paquete `ocr` como ilustración). +- Escanear un directorio y **list image files python**‑style, filtrando PNG, JPG y TIFF. +- Ejecutar una operación de **batch OCR** en todas las imágenes encontradas. +- Imprimir el texto extraído para cada archivo, claramente etiquetado. + +> **Consejo profesional:** Si no tienes la biblioteca `ocr` instalada, puedes cambiarla por `pytesseract` con algunos cambios menores—la lógica central permanece igual. + +--- + +## Requisitos previos + +- Python 3.8+ (el script usa f‑strings y anotaciones de tipo). +- Una biblioteca OCR que exponga un `OcrEngine` con `recognize_batch`. Para esta guía asumimos un paquete ficticio `ocr`, pero el patrón funciona con bibliotecas reales. +- Una carpeta que contenga los archivos de imagen que deseas procesar (`.png`, `.jpg`, `.tif`). + +--- + +## Paso 1 – Instalar e Importar los Módulos Requeridos + +Primero, asegúrate de que el paquete OCR esté disponible. Si estás usando una biblioteca real como `pytesseract`, reemplaza la importación en consecuencia. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Por qué es importante:** Importar `os` nos brinda manejo de rutas multiplataforma, mientras que `typing.List` ayuda con el autocompletado del IDE y la preparación para el futuro. + +--- + +## Paso 2 – **Extraer texto de imágenes**: Inicializar el Motor OCR + +Crear el motor es el primer paso para cualquier trabajo de OCR. También configuramos el idioma para auto‑detección, de modo que el motor pueda manejar documentos multilingües. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Explicación:** Al encapsular la creación del motor en una función mantenemos el código modular. Si más adelante necesitas ajustar DPI o el modo OCR, solo editas este punto. + +--- + +## Paso 3 – **List Image Files Python**: Recopilar archivos de un directorio + +Ahora necesitamos localizar cada imagen que queremos procesar. La comprensión de lista a continuación refleja un patrón común de “list image files python”. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Manejo de casos límite:** La función ignora subcarpetas (puedes añadir recursión más adelante) y filtra automáticamente los archivos ocultos porque típicamente no terminan con extensiones soportadas. + +--- + +## Paso 4 – **Convertir imágenes escaneadas a texto**: Ejecutar OCR por lotes + +La mayoría de las bibliotecas OCR ofrecen un método por lotes que es mucho más rápido que procesar una imagen a la vez. Así es como lo llamamos. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **¿Por qué por lotes?** Enviar todas las imágenes a la vez reduce la sobrecarga (p. ej., cargar el modelo OCR repetidamente) y a menudo brinda una mejor utilización de CPU/GPU. + +--- + +## Paso 5 – **Recognize Text from Pictures**: Mostrar los resultados + +Finalmente, iteramos sobre los nombres de archivo emparejados y los resultados OCR, imprimiendo un encabezado limpio para cada imagen. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Consejo:** `strip()` elimina los espacios en blanco al inicio y al final que OCR suele añadir. + +--- + +## Script completo – Juntarlo todo + +A continuación se muestra el programa completo y ejecutable. Guárdalo como `batch_ocr.py` y ejecuta `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Salida esperada + +Suponiendo que la carpeta contiene `invoice1.png` y `receipt.jpg`, podrías ver: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Cada bloque está claramente etiquetado, lo que hace que el procesamiento posterior (p. ej., guardar en una base de datos) sea sencillo. + +--- + +## Manejo de problemas comunes + +| Problema | Por qué ocurre | Solución rápida | +|----------|----------------|-----------------| +| **No aparece texto** | El idioma del OCR no se detecta o la imagen tiene muy bajo contraste. | Forzar un idioma (`engine.language = ocr.Language.English`) o preprocesar imágenes (aumentar contraste). | +| **Error de memoria en lotes grandes** | El motor intenta cargar todas las imágenes a la vez. | Dividir `image_files` en fragmentos (`batch_size = 20`) y llamar a `recognize_batch` repetidamente. | +| **Formato de archivo no soportado** | Has añadido un `.gif` o `.bmp`. | Amplía la tupla `supported_exts` o convierte las imágenes a PNG/JPG previamente. | +| **Desorden de Unicode** | El OCR devuelve bytes en lugar de cadenas. | Asegúrate de que la biblioteca OCR devuelva Unicode (`result.text.decode('utf‑8')` si es necesario). | + +--- + +## Extender el flujo de trabajo + +Ahora que puedes **extraer texto de imágenes**, considera los siguientes pasos: + +- **Exportar a CSV** – Escribe cada nombre de archivo y su texto extraído en una hoja de cálculo para análisis. +- **Procesamiento en paralelo** – Usa `concurrent.futures.ThreadPoolExecutor` para manejar múltiples lotes simultáneamente. +- **Integrar con OCR en la nube** – Cambia el motor local por Google Vision o Azure OCR para mayor precisión en diseños complejos. +- **Agregar preprocesamiento de imágenes** – Bibliotecas como Pillow o OpenCV pueden enderezar, reducir ruido o aplicar umbral a las imágenes antes del OCR, mejorando los resultados. + +Todas estas ideas utilizan naturalmente las mismas funciones principales que construimos, por lo que no tendrás que comenzar desde cero. + +--- + +## Conclusión + +Acabamos de repasar una solución completa para **extraer texto de imágenes** en Python, cubriendo todo desde **list image files python** hasta **recognize text from pictures** y finalmente **convert scanned images to text** en un lote ordenado. El script es deliberadamente simple pero lo suficientemente flexible como para servir de base a proyectos más grandes—ya sea que estés digitalizando recibos, creando un archivo buscable o impulsando una canalización de extracción de datos. + +Pruébalo, ajusta los pasos de preprocesamiento y observa cómo mejora la precisión de tu OCR. Si encuentras problemas, revisa la tabla de “Manejo de problemas comunes”; la mayoría de los inconvenientes se resuelven con un pequeño cambio de configuración. + +¿Listo para el próximo desafío? Intenta añadir un paso de conversión de PDF a imagen usando `pdf2image`, y luego alimenta esas imágenes directamente al mismo pipeline. El cielo es el límite cuando combinas OCR con el rico ecosistema de Python. + +¡Feliz codificación, y que tu texto sea siempre legible! + +## ¿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 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/) +- [Extraer imágenes de texto – Conceptos básicos de OCR con Aspose.OCR para Java](/ocr/english/java/ocr-basics/) +- [Cómo extraer texto de una imagen desde URL usando Aspose.OCR para Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/spanish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..dadb2d79c --- /dev/null +++ b/ocr/spanish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-19 +description: Extrae texto de imágenes usando OCR de Python. Aprende detección automática + de idioma, procesamiento paralelo y reconocimiento por lotes en un tutorial conciso. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: es +og_description: Extrae texto de imágenes con Python OCR. Esta guía muestra detección + automática de idioma, procesamiento en paralelo y reconocimiento por lotes en un + solo tutorial. +og_title: extraer texto de imágenes en Python – Guía completa de OCR +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Extraer texto de imágenes en Python – Guía completa de OCR +url: /es/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# extraer texto de imágenes en Python – Guía completa de OCR + +¿Alguna vez te has preguntado cómo **extraer texto de imágenes** sin tener que escribir manualmente cada palabra? No eres el único. Ya sea que estés digitalizando recibos antiguos, creando un archivo de documentos buscable, o simplemente jugando con trucos de IA, la capacidad de obtener texto de fotos es una habilidad imprescindible para cualquier desarrollador Python hoy en día. + +En este tutorial recorreremos un ejemplo completo, listo para ejecutar, que **extrae texto de imágenes** usando un motor OCR popular. Cubriremos detección automática de idioma, procesamiento en paralelo para mayor velocidad y reconocimiento de imágenes por lotes para que puedas manejar docenas de archivos en segundos. ¿Suena como lo que necesitas? Vamos al grano. + +## Lo que aprenderás + +- Cómo instanciar el motor OCR con `ocr.OcrEngine`. +- Habilitar **detección automática de idioma** para que el motor elija el idioma correcto por sí mismo. +- Configurar **OCR con procesamiento paralelo** mediante un pool de hilos personalizado. +- Ejecutar **reconocimiento de imágenes por lotes** sobre una lista de archivos. +- Imprimir el texto reconocido para cada imagen, listo para guardarse o indexarse. + +No necesitas documentación externa—todo lo que necesitas está aquí, y el código funciona directamente con el paquete `ocr` (instálalo vía `pip install ocr`). + +## Requisitos previos + +Antes de comenzar, asegúrate de tener: + +1. Python 3.8 o superior instalado. +2. El paquete `ocr` (`pip install ocr`). +3. Una carpeta con imágenes PNG (o JPG) que quieras procesar. +4. Familiaridad básica con funciones y bucles en Python. + +Eso es todo—sin dependencias pesadas, sin magia de GPU, solo Python puro. + +![extract text from images example](https://example.com/ocr-demo.png "Captura de pantalla que muestra la salida de extraer texto de imágenes") + +*Texto alternativo: captura de pantalla de la demostración de extracción de texto de imágenes* + +## Paso 1 – Configurar el motor OCR (Palabra clave principal en acción) + +Lo primero: crear una instancia del motor OCR. Piensa en `ocr.OcrEngine()` como el cerebro detrás de la operación; sabe cómo leer caracteres, líneas y párrafos. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +¿Por qué necesitamos un motor explícito? Porque el **uso de ocr.OcrEngine** te brinda control granular sobre la configuración de idioma, hilos y más. Es la forma más flexible de **extraer texto de imágenes** comparado con los ayudantes de una sola línea. + +## Paso 2 – Dejar que el motor detecte idiomas automáticamente + +La mayoría de las bibliotecas OCR requieren que les indiques el idioma a buscar. Eso está bien para un proyecto monolingüe, pero resulta engorroso para un lote multilingüe. Afortunadamente, el paquete `ocr` soporta **detección automática de idioma**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Configurar `engine.language` a `ocr.Language.Auto` indica al motor que analice cada imagen y elija el modelo de idioma apropiado. Esta pequeña línea te ahorra horas de configuración manual cuando trabajas con documentos internacionales. + +## Paso 3 – Acelerar las cosas con OCR de procesamiento paralelo + +Si tienes cuatro o más núcleos de CPU, ¿por qué no usarlos? El motor puede crear un pool de hilos, permitiendo que varias imágenes se procesen simultáneamente. Aquí es donde brilla el **OCR con procesamiento paralelo**. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Siéntete libre de ajustar el número `4` según tu máquina. Más hilos → ejecuciones por lotes más rápidas, pero recuerda que cada hilo consume memoria, así que encuentra el punto óptimo para tu entorno. + +## Paso 4 – Reunir las imágenes que deseas procesar + +Ahora necesitamos una lista de rutas de archivo. Puedes crear esta lista manualmente, leerla desde un CSV, o usar `glob`. Para mayor claridad, codificaremos una lista corta: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Reemplaza `YOUR_DIRECTORY` con la ruta real en tu sistema. Si tienes docenas de archivos, un rápido `glob.glob("*.png")` hará el trabajo pesado. + +## Paso 5 – Ejecutar reconocimiento de imágenes por lotes + +Este es el corazón del tutorial: una única llamada que procesa cada imagen en `files` y devuelve una lista de objetos de resultado. Esta es la función de **reconocimiento de imágenes por lotes** que hace práctico el OCR a gran escala. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Detrás de escena, el motor distribuye cada archivo entre los cuatro hilos de trabajo que configuramos antes, mientras también detecta automáticamente el idioma de cada foto. El método devuelve una lista donde cada elemento contiene el texto reconocido y metadatos. + +## Paso 6 – Imprimir (o almacenar) el texto extraído + +Finalmente, iteramos sobre los resultados e imprimimos el texto. En un proyecto real probablemente lo escribirías en una base de datos o en un archivo CSV, pero imprimir mantiene el ejemplo simple. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Salida esperada** (truncada por brevedad): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Cada bloque muestra el nombre del archivo seguido de la cadena derivada por OCR. Si una imagen contiene varios idiomas, verás los caracteres correspondientes gracias al paso previo de **detección automática de idioma**. + +## Consejos profesionales y errores comunes + +- **La calidad de la imagen importa** – fotos borrosas o de bajo contraste producirán basura. Pre‑procésalas con OpenCV (`cv2.threshold`, `cv2.resize`) si es necesario. +- **Número de hilos vs. I/O** – Si tus imágenes están en una unidad de red lenta, más hilos quizá no ayuden. Vigila el uso de CPU con `top` o el **Administrador de tareas**. +- **Manejo de Unicode** – `result.text` es una cadena Unicode. Al escribir a archivos, ábrelos con `encoding="utf‑8"` para evitar `UnicodeEncodeError`s. +- **Uso de memoria** – PDFs grandes pueden consumir mucha RAM. Si encuentras `MemoryError`, reduce el tamaño del pool de hilos o procesa las imágenes en bloques más pequeños. + +## Script completo y funcional + +A continuación tienes el script completo, listo para copiar y pegar, que incorpora cada paso que discutimos. Guárdalo como `batch_ocr.py` y ejecuta `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Ejecuta así: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Verás un bloque de texto bien formateado para cada imagen, demostrando que puedes **extraer texto de imágenes** a gran escala. + +## ¿Qué sigue? + +Ahora que dominas los fundamentos de **extraer texto de imágenes** con Python, considera explorar: + +- **Post‑procesamiento**: limpia la salida OCR con expresiones regulares o bibliotecas de procesamiento de lenguaje natural. +- **Conversión a PDF**: alimenta las cadenas extraídas a un generador de PDF para PDFs buscables. +- **Servicios OCR en la nube**: compara los resultados locales de `ocr` con Google Vision o Azure OCR para casos límite de precisión. +- **Interfaz gráfica**: crea una pequeña aplicación Flask o FastAPI que permita a los usuarios subir imágenes y ver instantáneamente el texto extraído. + +Cada uno de estos temas se basa en la **biblioteca OCR de Python** que acabas de configurar, y todos se benefician de los mismos trucos de **OCR con procesamiento paralelo** que usamos aquí. + +--- + +*¡Feliz codificación! Si encuentras algún inconveniente, deja un comentario abajo—siempre estoy dispuesto a ayudar con los trucos del OCR.* + +## ¿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 que domines funciones adicionales de la API y explores enfoques de implementación alternativos en tus propios proyectos. + +- [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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/spanish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..dd7bcfa61 --- /dev/null +++ b/ocr/spanish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-19 +description: Cómo extraer PDF usando OCR en Python – tutorial paso a paso que cubre + extraer texto de PDF, reconocer texto de una imagen y un ejemplo de OCR en Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: es +og_description: Cómo extraer PDF usando OCR en Python. Aprende a extraer texto de + PDF, reconocer texto de una imagen y ver un ejemplo completo de OCR en Python. +og_title: Cómo extraer texto de PDF con OCR en Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Cómo extraer texto de PDF con OCR en Python – Guía completa +url: /es/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo extraer texto de PDF con OCR en Python – Guía completa + +¿Alguna vez te has preguntado **cómo extraer PDF** cuando el archivo es solo una imagen escaneada? No eres el único. En muchos proyectos del mundo real —piensa en contratos, facturas o archivos históricos— el PDF que recibes no tiene texto seleccionable. ¿La buena noticia? Unas pocas líneas de Python pueden convertir esas páginas solo de imagen en texto buscable y editable. + +En este tutorial recorreremos un **ejemplo de OCR en Python** que lee un PDF, renderiza su primera página como una imagen y luego **extrae texto de PDF** usando un motor OCR. Al final sabrás exactamente cómo **leer PDF con OCR**, por qué cada paso es importante y cómo adaptar el código para documentos multipágina o diferentes idiomas. + +## Qué aprenderás + +- Instalar y configurar una biblioteca OCR fiable para Python. +- Convertir páginas PDF a imágenes aptas para OCR. +- **Reconocer texto de imagen** y obtener cadenas Unicode limpias. +- Trampas comunes (PDFs de baja resolución, páginas rotadas) y cómo evitarlas. +- Extender el script para manejar varias páginas o procesamiento por lotes. + +**Requisitos previos**: Python 3.8+, pip y un entendimiento básico de entornos virtuales. No se necesita experiencia previa en OCR —solo sigue los pasos. + +--- + +## ## Cómo extraer texto de PDF con OCR en Python + +Este encabezado H2 contiene nuestra palabra clave principal justo donde a los motores de búsqueda les encanta verla. Vamos directo al código. + +### Paso 1 – Instalar los paquetes requeridos + +Primero, necesitamos un motor OCR. El ejemplo a continuación usa el popular paquete **ocr** (un contenedor ligero alrededor de Tesseract). Si prefieres otro backend, los conceptos siguen siendo los mismos. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Consejo profesional:** En Linux, también necesitarás el binario de Tesseract: `sudo apt-get install tesseract-ocr`. Los usuarios de macOS pueden obtenerlo vía Homebrew: `brew install tesseract`. + +### Paso 2 – Inicializar el motor OCR y establecer el idioma + +Ahora iniciamos el motor y le indicamos que busque caracteres en inglés. Puedes cambiar `ocr.Language.English` por cualquier código de idioma soportado. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Por qué es importante:** Especificar el idioma mejora drásticamente la precisión porque el motor puede aplicar diccionarios y modelos de caracteres específicos del idioma. + +### Paso 3 – Cargar una página PDF como imagen + +OCR funciona sobre imágenes raster, no sobre objetos PDF. El ayudante `ocr.Image.from_pdf` renderiza la página elegida a un mapa de bits. Ajusta `page_number` para otras páginas (indexado desde 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Caso límite:** Si el PDF contiene gráficos vectoriales en lugar de imágenes escaneadas, podrías obtener un renderizado nítido. Para escaneos de baja resolución, considera aumentar el DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Paso 4 – Reconocer texto de la imagen renderizada + +Este es el corazón del **ejemplo de ocr python**. El motor procesa el mapa de bits y devuelve un objeto que contiene la cadena extraída. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +El atributo `ocr_result.text` contiene la salida de texto plano, preservando los saltos de línea donde sea posible. + +### Paso 5 – Imprimir o almacenar el texto extraído + +Finalmente, mostramos el resultado. En una aplicación real probablemente escribirías a un archivo o a una base de datos. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Ejecutar el script debería mostrar algo como: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Ese es un flujo completo de **extraer texto de pdf** usando OCR. + +--- + +## ## Reconocer texto de imagen – Ajustando la precisión + +Si solo te interesa **reconocer texto de imagen** (por ejemplo, un JPEG de un recibo), puedes omitir el paso de conversión PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Consejos para obtener mejores resultados:** + +- **Pre‑procesar** la imagen: convertir a escala de grises, aplicar umbralado o corregir la inclinación. Pillow facilita esto. +- **Aumentar DPI** durante el renderizado del PDF: mayor resolución brinda más detalle al motor OCR. +- **Activar la configuración del motor OCR** para segmentación de página (`ocr_engine.config = "--psm 6"` para bloques uniformes). + +--- + +## ## Leer PDF con OCR – Manejo de múltiples páginas + +La mayoría de los contratos abarcan varias páginas. Recorrer cada página es sencillo: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Esta función **lee PDF con OCR**, concatena la salida e inserta un marcador de salto de página claro. Luego puedes pasar `full_text` a un índice de búsqueda o guardarlo como archivo `.txt`. + +--- + +## ## Trampas comunes y cómo solucionarlas + +| Síntoma | Causa probable | Solución | +|---------|----------------|----------| +| Caracteres distorsionados, muchos `?` | Idioma incorrecto o faltan archivos de datos del idioma | Instala el paquete de idioma correcto de Tesseract (`tesseract-ocr-`) y establece `ocr_engine.language`. | +| Falta de líneas o palabras truncadas | DPI bajo (menos de 150) | Renderiza el PDF a 300 DPI o más (`dpi=300`). | +| El texto está rotado o al revés | Página escaneada no está orientada correctamente | Usa `ocr.Image.deskew(page_image)` antes del reconocimiento. | +| Procesamiento lento en PDFs grandes | Procesar páginas secuencialmente en un solo hilo | Paraleliza con `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Extender el ejemplo OCR en Python + +- **Exportar a PDF/A**: Después de la extracción, puedes incrustar el texto de nuevo en un PDF buscable usando `reportlab` o `pypdf2`. +- **Detección de idioma**: Usa `langdetect` sobre la salida OCR para cambiar `ocr_engine.language` dinámicamente. +- **Procesamiento por lotes**: Recorre un directorio con `os.listdir` y aplica `extract_all_pages` a cada archivo. + +--- + +## ## Resultado esperado y verificación + +Cuando ejecutes el script contra un escaneo claro en inglés, deberías ver un bloque limpio de texto con puntuación correcta. Verifica mediante: + +1. Comparar algunas líneas con la imagen escaneada original. +2. Ejecutar un simple recuento de palabras (`len(ocr_result.text.split())`) para asegurar que la salida no esté vacía. +3. Opcionalmente, pasar el resultado a un corrector ortográfico como `pyspellchecker` para detectar errores de OCR. + +--- + +## Conclusión + +Hemos cubierto **cómo extraer PDF** cuando el análisis tradicional falla, demostrado un **ejemplo completo de ocr python**, y explicado cómo **reconocer texto de imagen** y **leer PDF con OCR** tanto para escenarios de una sola página como multipágina. Con los fragmentos de código anteriores ahora puedes convertir cualquier PDF escaneado en texto buscable y editable—sin necesidad de volver a escribir manualmente. + +¿Próximos pasos? Prueba cambiar el idioma a español (`ocr.Language.Spanish`) o experimenta con técnicas de pre‑procesamiento de imágenes para mejorar la precisión. Si estás construyendo un sistema de gestión documental, considera indexar el texto extraído con Elasticsearch para búsquedas ultrarrápidas. + +¿Tienes preguntas o te encuentras con un PDF problemático? ¡Deja un comentario y feliz codificación! + +![Cómo extraer PDF usando OCR en Python](image.png "Cómo extraer PDF usando OCR en Python") + +## ¿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/) +- [Reconocer texto PDF – Operaciones OCR con Aspose.OCR para Java](/ocr/english/java/ocr-operations/) +- [Extraer texto de imagen en C# con selección de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/spanish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..eb20f0fe4 --- /dev/null +++ b/ocr/spanish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-06-19 +description: Aprende a usar OCR en Java con Aspose. Esta guía paso a paso cubre la + corrección automática de inclinación de imágenes, la detección automática de idioma + y la extracción fácil de texto de imágenes. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: es +og_description: 'Cómo usar OCR en Java con Aspose: una guía completa que cubre la + corrección automática de inclinación de imágenes, la detección automática de idioma + y la extracción de texto de imágenes.' +og_title: Cómo usar OCR en Java con Aspose – Guía completa +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Cómo usar OCR en Java con Aspose – Guía completa +url: /es/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo usar OCR en Java con Aspose – Guía completa + +¿Alguna vez te has preguntado **cómo usar OCR** en un proyecto Java sin volverte loco con la configuración? No eres el único. Muchos desarrolladores se topan con un obstáculo cuando necesitan **extraer texto de imagen** rápidamente, especialmente cuando los escaneos de origen están torcidos o están escritos en un idioma desconocido. + +En este tutorial recorreremos un ejemplo práctico que te muestra exactamente cómo usar OCR con Aspose, incluyendo **auto deskew images**, **auto language detection**, y todo el pipeline de **ocr image preprocessing**. Al final tendrás un fragmento listo para ejecutar que imprime el texto reconocido en la consola, y comprenderás por qué cada configuración es importante. + +> **Lo que obtendrás:** un programa Java completo y ejecutable, explicaciones de cada línea, consejos para manejar casos límite y ideas para ampliar la solución a procesamiento por lotes o PDFs. + +--- + +## Requisitos previos + +- Java 17 (o cualquier JDK reciente) instalado y configurado. +- Maven o Gradle para la gestión de dependencias (mostraremos las coordenadas de Maven). +- Un archivo de licencia de Aspose OCR for Java (`Aspose.OCR.Java.lic`). Si solo estás probando, puedes omitir el paso de licencia, pero la versión de prueba gratuita añadirá una marca de agua. +- Una imagen de ejemplo (`your_image.png`) colocada en un lugar accesible para el código. + +> **Consejo profesional:** mantén tus imágenes en una carpeta dedicada `resources` y cárgalas a través del classpath; evita dolores de cabeza relacionados con rutas en diferentes sistemas operativos. + +## Paso 1: Configurar el proyecto y agregar la dependencia de Aspose OCR + +Crea un nuevo proyecto Maven (o usa el que ya tienes) y agrega lo siguiente a tu `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Ejecuta `mvn clean install` para descargar la biblioteca. Si prefieres Gradle, el equivalente es: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Ahora tienes las clases de **ocr image preprocessing** en tu classpath. + +## Paso 2: Aplicar tu licencia de Aspose OCR (Opcional pero recomendado) + +Si posees una licencia, aplícala al inicio de tu método `main`. Omitir este paso funciona, pero la versión gratuita agrega una marca de agua “Demo” en la salida. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Por qué es importante:** La versión con licencia elimina los límites de uso y desactiva la marca de agua, brindándote resultados limpios y listos para producción. + +## Paso 3: Crear la instancia del motor OCR + +El motor es el corazón del proceso. Instanciarlo te da acceso a todas las opciones de **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +En este punto el motor está listo, pero usará la configuración predeterminada que podría no ser óptima para documentos escaneados. Ajustemos algunas. + +## Paso 4: Habilitar Auto Deskew Images para escaneos más limpios + +Los escaneos inclinados son un punto de dolor común. Aspose ofrece una función de **auto deskew images** que endereza automáticamente la imagen antes del reconocimiento. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Cómo funciona:** El algoritmo analiza los ángulos de la línea base del texto y rota la imagen a la orientación vertical más probable. Esto mejora drásticamente la precisión para fotos tomadas con un teléfono. + +## Paso 5: Activar Auto Language Detection + +Si no conoces el idioma de la imagen fuente, deja que el motor lo descubra. Esta es la configuración de **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Cuando habilitas esto, Aspose escanea los glifos y selecciona el modelo de idioma más probable, soportando más de 30 idiomas de forma predeterminada. + +## Paso 6: Cargar la imagen que deseas reconocer + +Puedes cargar una imagen desde disco, una URL o incluso un arreglo de bytes. Para simplificar, leeremos desde un archivo local. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Consejo:** Si trabajas con imágenes grandes, considera reducir su escala primero con `engine.getImagePreprocessing().setResizeFactor(0.5)` para acelerar el procesamiento sin perder mucho detalle. + +## Paso 7: Realizar el reconocimiento OCR y extraer texto de la imagen + +Ahora el motor hace su magia. El método `recognize` devuelve un objeto `OcrResult` que contiene el texto reconocido, puntuaciones de confianza y más. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +La consola mostrará el texto plano extraído de la imagen—este es el resultado central de **extract text image** que nos propusimos lograr. + +## Ejemplo completo en funcionamiento + +A continuación está la clase Java completa que une todo. Copia y pega en `src/main/java/com/example/OcrDemo.java` y ejecútala. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Salida esperada + +Si la imagen contiene la frase “Hello World” en un escaneo limpio, verás: + +``` +=== Recognized Text === +Hello World +``` + +Para documentos más complejos (p. ej., recibos multilingües), la salida incluirá saltos de línea y el código del idioma detectado. + +## Errores comunes y consejos profesionales + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Caracteres basura** | La imagen está demasiado oscura o ruidosa. | Habilita `engine.getImagePreprocessing().setBinarization(true)` o ajusta el contraste manualmente. | +| **Idioma incorrecto** | La detección automática falla en páginas con varios idiomas. | Establece `engine.setLanguage(Language.English)` (o el enum apropiado) para forzar un idioma específico. | +| **Procesamiento lento** | Imágenes de muy alta resolución. | Reduce la escala con `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Errores de falta de memoria** | Gran lote de imágenes cargadas de una vez. | Procesa las imágenes secuencialmente y llama a `engine.dispose()` después de cada ejecución. | + +> **Recuerda:** El motor OCR es seguro para hilos en operaciones de solo lectura, pero crear una nueva instancia por hilo evita errores de estado oculto. + +## Extender la solución + +Ahora que sabes **cómo usar OCR** con Aspose, podrías querer: + +1. **Procesar PDFs** – Convierte cada página PDF a una imagen (`PdfConverter`) y luego pásala al mismo pipeline. +2. **Procesamiento por lotes de una carpeta** – Recorre los archivos en un directorio, aplicando los mismos pasos, y escribe los resultados en un CSV. +3. **Integrar con un servicio web** – Expón la lógica OCR mediante un `@RestController` de Spring Boot que acepte cargas multipart. + +Todos esos escenarios reutilizan la misma configuración de **ocr image preprocessing** que construimos aquí. + +## Conclusión + +Hemos cubierto **cómo usar OCR** en Java con Aspose de principio a fin: aplicar una licencia, crear el motor, activar **auto deskew images**, habilitar **auto language detection**, cargar una imagen y, finalmente, **extract text image** con un solo `System.out.println`. El código es completamente autónomo, se ejecuta en cualquier JDK reciente y demuestra las mejores prácticas para precisión y rendimiento. + +Pruébalo con tus propias imágenes—quizás un contrato escaneado o una captura de pantalla de un recibo. Ajusta las banderas de preprocesamiento, experimenta con diferentes idiomas y verás rápidamente por qué la biblioteca OCR de Aspose es una opción sólida para extracción de texto de nivel de producción. + +¿Tienes preguntas o quieres compartir tus resultados? Deja un comentario abajo o envíame un mensaje en GitHub. ¡Feliz codificación! + +![Ejemplo de cómo usar OCR en Java](/images/ocr-java-example.png "Cómo usar OCR en Java – captura de pantalla de la demo de Aspose") + +## ¿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 de texto de imagen con idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extraer texto de una imagen Java con Aspose.OCR modo detección de áreas](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Cómo usar OCR - Técnicas avanzadas con Aspose.OCR para Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/spanish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..0f11ff538 --- /dev/null +++ b/ocr/spanish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,320 @@ +--- +category: general +date: 2026-06-19 +description: Mejora la precisión del OCR en Python usando Aspose OCR. Aprende cómo + establecer el idioma del OCR, cargar una imagen para OCR y extraer texto de la imagen + con un diccionario personalizado. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: es +og_description: Mejora la precisión del OCR en Python configurando el idioma del OCR, + cargando una imagen para OCR y extrayendo texto de la imagen con un diccionario + personalizado. +og_title: Mejora la precisión del OCR en Python – Guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Mejora la precisión del OCR en Python – Guía completa +url: /es/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mejora la Precisión del OCR en Python – Guía Completa + +¿Alguna vez te has preguntado cómo **mejorar la precisión del OCR** cuando el texto que escaneas contiene símbolos extraños, códigos de producto o nombres de marca? No estás solo. En muchos proyectos el motor predeterminado solo genera basura, y eso mata la productividad. + +En este tutorial recorreremos un ejemplo práctico, de extremo a extremo, que te muestra cómo **establecer el idioma del OCR**, **cargar la imagen para OCR**, **realizar OCR en la imagen**, y finalmente **extraer texto de la imagen** con un diccionario personalizado que aumenta las tasas de reconocimiento. Al final tendrás un script listo para ejecutar que puedes incorporar a cualquier base de código Python. + +## Lo Que Aprenderás + +- Un script Python totalmente funcional que usa Aspose OCR para leer un archivo PNG. +- La capacidad de **mejorar la precisión del OCR** configurando el idioma y una lista de palabras personalizada. +- Explicaciones claras de por qué cada configuración importa, más consejos para manejar casos límite como caracteres no latinos. +- Una lista de verificación rápida para solucionar problemas comunes del OCR. + +### Requisitos Previos + +- Python 3.8 o superior instalado en tu máquina. +- Paquete `aspose-ocr` (instálalo vía `pip install aspose-ocr`). +- Una imagen de ejemplo (`technical_doc.png`) que contenga el texto que deseas leer. +- Familiaridad básica con Python—no se requiere nada avanzado. + +> **Consejo profesional:** Si trabajas en un entorno virtual, actívalo antes de instalar el paquete. Mantiene tus dependencias ordenadas y evita conflictos de versiones. + +--- + +## Paso 1: Instalar e Importar Aspose OCR + +Lo primero—pongamos la biblioteca en nuestro entorno e importemos los componentes que necesitamos. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +El espacio de nombres `aspose.ocr` te da acceso a la clase `OcrEngine`, que es el corazón del proceso OCR. Importarla aquí mantiene el resto del script limpio y legible. + +--- + +## Paso 2: Crear un Motor OCR y **Establecer el Idioma del OCR** + +¿Por qué importa el idioma? Los motores OCR dependen de modelos específicos por idioma para reconocer formas de caracteres y patrones de palabras. Si le dices al motor que estás escaneando texto en inglés, ignorará los glifos cirílicos y se centrará en el alfabeto latino, mejorando drásticamente la **precisión del OCR**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Nota:** Aspose OCR soporta más de 50 idiomas. Cambia `ocr.Language.English` por `ocr.Language.Spanish`, `ocr.Language.French`, etc., si tu documento no está en inglés. + +--- + +## Paso 3: Definir un **Diccionario Personalizado** para Aumentar la Precisión + +Imagina que estás escaneando facturas que contienen la palabra “AsposeOCR” o códigos de producto como “SKU12345”. El motor no conoce esos términos, así que los adivina incorrectamente. Proveer una lista de palabras personalizada le dice al motor: *“Hey, estas cadenas son válidas—no intentes corregirlas.”* Eso es una victoria rápida para **mejorar la precisión del OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Puedes cargar esta lista desde un archivo o una base de datos si tienes cientos de entradas—simplemente mantenla en una lista Python para simplificar. + +--- + +## Paso 4: **Cargar la Imagen para OCR** + +Ahora necesitamos una imagen. El método `Image.load` acepta una ruta a cualquier formato raster compatible (PNG, JPEG, BMP, etc.). Si el archivo no se encuentra, el motor lanza una excepción, así que lo protegeremos contra eso. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Por qué este paso importa:** Cargar la imagen correctamente asegura que el motor trabaje con los datos de píxeles exactos que pretendes analizar. Archivos corruptos o rutas incorrectas son una fuente frecuente de frustración. + +--- + +## Paso 5: **Realizar OCR en la Imagen** y Extraer Resultados + +Con el motor configurado y la imagen lista, el reconocimiento real es una única llamada a método. El objeto de resultado contiene el texto bruto, puntuaciones de confianza e incluso información de diseño si la necesitas más adelante. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Si necesitas **extraer texto de la imagen** línea por línea, puedes dividir por caracteres de nueva línea: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Paso 6: Verificar la Salida – ¿Realmente **Mejora la Precisión del OCR**? + +Imprimamos el resultado y veamos si nuestro diccionario personalizado marcó la diferencia. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Una salida típica para la imagen de ejemplo podría verse así: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Observa cómo el nombre de la marca, el carácter griego y el código de producto aparecen exactamente como los definimos. Sin el diccionario personalizado, el motor habría intentado “corregir” esos valores, a menudo produciendo algo como “Aspose OCR” o “SKU 1234”. + +--- + +## Problemas Comunes y Cómo Abordarlos + +| Problema | Por Qué Ocurre | Solución | +|----------|----------------|----------| +| **Caracteres basura** | Idioma incorrecto o imagen de baja resolución | Asegúrate de que `engine.language` coincida con el idioma fuente y usa un escaneo de alta DPI (300 dpi o más). | +| **Palabras personalizadas ignoradas** | Diccionario no adjuntado o error tipográfico en el nombre de la propiedad | Verifica `engine.text_processing.custom_dictionary = …`. | +| **Archivo no encontrado** | Ruta incorrecta o permisos insuficientes | Usa `os.path.abspath()` para confirmar la ruta absoluta; ejecuta el script con los permisos adecuados. | +| **Procesamiento lento** | Imágenes grandes o muchas páginas | Pre‑procesa la imagen (recorta, redimensiona) o usa `engine.recognize(image, max_threads=4)` para paralelizar. | + +--- + +## Avanzando: Ajustes Avanzados para **Mejorar la Precisión del OCR** + +1. **Pre‑procesamiento** – Aplica mejora de contraste o binarización con Pillow antes de pasar la imagen a Aspose OCR. +2. **Múltiples Idiomas** – Configura `engine.language = ocr.Language.English | ocr.Language.French` para habilitar reconocimiento bilingüe. +3. **OCR por Región** – Si solo necesitas un área específica (p. ej., una tabla), recorta la imagen primero para reducir ruido. +4. **Filtrado por Confianza** – `result.confidence` brinda una puntuación por carácter; puedes descartar resultados de baja confianza programáticamente. + +--- + +## Script Completo Funcional + +A continuación tienes el script completo, listo para copiar y pegar, que incorpora cada paso que discutimos. Guárdalo como `improve_ocr_accuracy.py` y ejecútalo desde la línea de comandos. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Ejecuta: + +```bash +python improve_ocr_accuracy.py +``` + +Deberías ver la salida formateada que mostramos anteriormente. + +--- + +## Conclusión + +Acabamos de cubrir una forma sencilla de **mejorar la precisión del OCR** en Python mediante: + +1. **Establecer el idioma del OCR** para que coincida con tu documento. +2. **Cargar la imagen correctamente** para que el motor vea los píxeles adecuados. +3. **Realizar OCR en la imagen** con una única llamada a método. +4. **Extraer texto de la imagen** y confirmar el resultado. +5. **Agregar un diccionario personalizado** para fijar términos específicos del dominio. + +Ese es todo el flujo de trabajo—desde la foto cruda hasta texto limpio y buscable—envuelto en un script reutilizable. + +Si estás listo para el siguiente desafío, prueba a experimentar con pre‑procesamiento de imágenes (contraste, corrección de inclinación) o cambia a una configuración multilingüe usando `ocr.Language.English | ocr.Language.German`. Los mismos principios se aplican, y seguirás **mejorando la precisión del OCR** en un conjunto más amplio de documentos. + +¿Tienes preguntas o un caso límite extraño? Deja un comentario abajo, ¡y feliz codificación! + +![improve OCR accuracy + + +## ¿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. + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/spanish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..3024e0f92 --- /dev/null +++ b/ocr/spanish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-19 +description: Realiza OCR en una imagen usando la biblioteca OCR de Python. Aprende + cómo detectar texto en una imagen, reconocer texto de un JPEG y extraer texto de + una imagen escaneada de manera eficiente. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: es +og_description: Realiza OCR en imágenes con Python y extrae texto de archivos escaneados. + Esta guía te lleva paso a paso por la carga de imágenes, la corrección de inclinación + y el reconocimiento de texto. +og_title: Realiza OCR en una imagen con Python – Guía completa de extracción de texto +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Realizar OCR en una imagen con Python – Guía completa de extracción de texto +url: /es/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR en Imagen con Python – Guía Completa de Extracción de Texto + +¿Alguna vez necesitaste **realizar OCR en imagen** archivos pero te encontraste con un muro porque el código parecía críptico? No eres el único. Ya sea que estés convirtiendo una pila de recibos escaneados en PDFs buscables o extrayendo subtítulos de un JPEG para un proyecto de ciencia de datos, la capacidad de reconocer texto de JPEGs y otros formatos es una habilidad imprescindible para cualquier desarrollador hoy. + +En este tutorial recorreremos un ejemplo completo y ejecutable que te muestra cómo **detect text from image** archivos, **extract text from scanned image** documentos, e incluso **load image for OCR** en solo unas cuantas líneas. Al final, tendrás un fragmento sólido y listo para producción que puedes insertar en tus propios proyectos—sin importaciones faltantes, sin atajos vagos de “ver docs”. + +## Lo Que Construirás + +- Un pequeño script de Python que crea un motor OCR, habilita auto‑deskew, carga un JPEG (o cualquier formato compatible) y muestra el texto reconocido. +- Explicaciones de **por qué** cada configuración importa, no solo de **cómo** escribirla. +- Consejos para manejar PDFs de varias páginas, idiomas no ingleses y trampas comunes como escaneos borrosos. + +### Requisitos Previos + +- Python 3.8+ instalado (el ejemplo usa el paquete `ocr` disponible vía `pip install ocr-lib` – reemplaza con el nombre real de tu biblioteca). +- Familiaridad básica con funciones de Python y entornos virtuales. +- Un archivo de imagen (JPEG, PNG, TIFF) que quieras procesar; usaremos `skewed_page.jpg` como ejemplo. + +> **Pro tip:** Si estás en Windows, ejecuta tu terminal como Administrador al instalar la biblioteca OCR para evitar problemas de permisos. + +## Realizar OCR en Imagen – Configuración y Preparación + +Lo primero que necesitas es una instancia limpia del motor OCR. Piensa en ella como el cerebro detrás de la operación; sin una configuración adecuada, incluso la imagen más nítida devolverá basura. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Por qué esto importa:** +Configurar `engine.language` reduce el conjunto de caracteres que el motor OCR espera, aumentando drásticamente la precisión. Si omites esto, el motor intentará adivinar, a menudo malinterpretando palabras simples. + +## Habilitar Deskew Automático – Corregir Escaneos Inclinados + +Las páginas escaneadas rara vez están perfectamente planas. Una ligera inclinación puede desorientar la segmentación de caracteres, convirtiendo “Hello” en “H3llo”. La bandera `auto_deskew` hace el trabajo pesado por ti. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Caso límite:** Si sabes que tus imágenes ya están rectas, desactivar el deskew puede ahorrar unos milisegundos de tiempo de procesamiento—útil cuando manejas miles de páginas en un trabajo por lotes. + +## Cargar Imagen para OCR – Compatibilidad con JPEG, PNG, TIFF + +Ahora realmente **load image for OCR**. El método `ocr.Image.load` es flexible; acepta una ruta a cualquier formato raster compatible. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Por qué este paso es crucial:** La biblioteca lee el archivo a un bitmap interno, aplicando cualquier conversión de espacio de color necesaria. Omitir esto y pasar un flujo de bytes crudo provocaría un `FileNotFoundError` o, peor aún, produciría resultados vacíos sin advertencia. + +Si necesitas **recognize text from JPEG** específicamente, solo asegúrate de que la extensión del archivo sea `.jpeg` o `.jpg`. La misma llamada funciona para PNG (`.png`) o TIFF (`.tif`) sin modificaciones. + +## Realizar OCR en Imagen – Ejecutando el Motor + +Con el motor preparado y la imagen en memoria, es momento de **perform OCR on image** datos. Esta única línea hace el trabajo pesado: pre‑procesamiento, segmentación, clasificación y ensamblado de texto. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**¿Qué ocurre bajo el capó?** +- El motor aplica la transformación de deskew (si está habilitada). +- Ejecuta una red neuronal o backend Tesseract para identificar caracteres. +- Finalmente, une los caracteres en palabras y líneas, devolviendo un objeto `result` rico. + +## Extraer Texto de Imagen Escaneada – Mostrar los Resultados + +El paso final es **extract text from scanned image** y mostrarlo. El atributo `result.text` contiene la representación de texto plano. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Una salida típica se ve así: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Si el motor OCR no encuentra ningún carácter, `result.text` será una cadena vacía. En ese caso, verifica la calidad de la imagen o considera ajustar la propiedad `engine.confidence_threshold` (si tu biblioteca lo soporta). + +## Manejo de Variaciones Comunes + +### Reconocer Texto de JPEG vs PNG + +Ambos formatos son compatibles, pero la compresión JPEG puede introducir artefactos que confunden al motor. Si notas errores frecuentes de reconocimiento, intenta convertir el JPEG a PNG primero: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detectar Texto de Imagen con Múltiples Idiomas + +Si tu documento mezcla inglés y español, establece un modo multilingüe: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +El motor considerará ambos alfabetos durante el reconocimiento. + +### Extraer Texto de PDFs Escaneados + +Para PDFs, primero debes rasterizar cada página en una imagen. Bibliotecas como `pdf2image` hacen esto sin complicaciones: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +## Ejemplo Completo Funcional + +A continuación tienes el script completo que puedes copiar‑pegar en un archivo `ocr_demo.py`. Incluye manejo de errores y un pequeño ayudante para medir el tiempo de ejecución. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Salida esperada** (asumiendo un escaneo claro): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +## Preguntas Frecuentes + +**Q: ¿Puedo ejecutar esto en un servidor sin interfaz gráfica?** +A: Absolutamente. La biblioteca funciona sin GUI; solo asegúrate de que los binarios nativos necesarios (p. ej., Tesseract) estén instalados en el servidor. + +**Q: ¿Qué pasa si la imagen está borrosa?** +A: Considera añadir un filtro de enfoque antes de `engine.recognize`. Muchas bibliotecas OCR exponen `image_preprocessing.sharpen = True` o puedes usar `cv2.GaussianBlur` de OpenCV en sentido inverso. + +**Q: ¿El script soporta procesamiento por lotes?** +A: Sí. Envuelve `perform_ocr` en un bucle sobre una lista de rutas de archivo, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/spanish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..799799d4b --- /dev/null +++ b/ocr/spanish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-19 +description: Realiza OCR en una imagen usando Aspose OCR Java. Aprende cómo cargar + la imagen para OCR, usar la licencia de Aspose y extraer texto de la imagen en minutos. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: es +og_description: Realiza OCR en una imagen con Aspose OCR Java. Esta guía muestra cómo + usar la licencia de Aspose, cargar la imagen para OCR y extraer texto de la imagen + de manera eficiente. +og_title: Realizar OCR en una imagen con Aspose OCR Java – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Realizar OCR en una imagen con Aspose OCR Java – Guía completa paso a paso +url: /es/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR en Imagen con Aspose OCR Java – Guía Completa Paso a Paso + +¿Alguna vez necesitaste **perform OCR on image** archivos pero no estabas seguro de qué biblioteca te daría resultados fiables sin una tonelada de configuración? No estás solo. En muchos proyectos del mundo real—piensa en escanear pasaportes, digitalizar facturas o extraer texto de capturas de pantalla—la capacidad de reconocer rápidamente datos de texto en imágenes es un factor decisivo. + +En este tutorial recorreremos un ejemplo práctico que muestra exactamente cómo **perform OCR on image** usando Aspose OCR para Java. Cubriremos todo, desde aplicar tu licencia Aspose hasta cargar la imagen, ejecutar el motor y finalmente **extract text from image** para que puedas usarlo en etapas posteriores. Sin rodeos, solo una solución funcional que puedes copiar y pegar. + +## Lo Que Aprenderás + +- Una visión clara de cómo **use Aspose license** en un proyecto Java. +- El código exacto necesario para **load image for OCR** y permitir que el motor detecte automáticamente los idiomas. +- Instrucciones paso a paso para **recognize text image** contenido y **extract text from image** de forma segura. +- Consejos para manejar problemas comunes (resultados vacíos, formatos no compatibles y problemas de memoria). + +> **Prerequisites** – Java 8 o superior, Maven o Gradle para la gestión de dependencias, y un archivo de licencia Aspose OCR para Java (o puedes ejecutar en modo de evaluación). + +--- + +## Cómo Realizar OCR en Imagen con Aspose OCR Java + +A continuación se muestra el programa Java completo, listo para ejecutar, que demuestra todo el flujo. Guárdalo como `AsposeOcrDemo.java` y ejecútalo desde tu IDE o la línea de comandos. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Salida Esperada en la Consola + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Si ejecutas el programa sin un archivo de licencia, la primera línea simplemente indicará que estás en modo de evaluación, pero el OCR seguirá funcionando. + +--- + +## Configurar y Usar la Licencia Aspose + +### Por Qué Importa una Licencia + +Ejecutar la biblioteca en modo de evaluación está bien para pruebas rápidas, pero agrega una marca de agua al resultado y limita la cantidad de páginas que puedes procesar por ejecución. Aplicar el paso **use aspose license** elimina estas restricciones y le indica a Aspose que eres un cliente de pago. + +### Cómo Obtenerla y Aplicarla + +1. Compra una licencia en la tienda de Aspose. +2. Descarga el archivo `Aspose.OCR.Java.lic`. +3. Colócalo en un lugar donde tu aplicación pueda leerlo—comúnmente la carpeta `src/main/resources`. +4. Llama a `new License().setLicense("Aspose.OCR.Java.lic");` antes de cualquier trabajo de OCR, como se muestra en el código anterior. + +> **Pro tip:** Si despliegas en un servidor, usa una ruta absoluta o un cargador de recursos del class‑path para evitar `FileNotFoundException`. + +--- + +## Cargar Imagen para el Procesamiento OCR + +La línea `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` es el núcleo del paso **load image for OCR**. Aspose OCR admite una amplia gama de formatos: PNG, JPEG, BMP, TIFF e incluso PDFs de varias páginas (cuando se combina con Aspose.Pdf). + +### Problemas Comunes + +| Problema | Síntoma | Solución | +|----------|---------|----------| +| Ruta de archivo incorrecta | `FileNotFoundException` | Verifica la ruta; usa `Paths.get(...)` para separadores independientes del SO. | +| Formato no compatible | `UnsupportedOperationException` | Convierte la imagen a PNG o JPEG antes de cargarla. | +| Imagen enorme ( > 10 MP) | Errores de falta de memoria | Reduce la escala de la imagen usando `java.awt.Image` antes de pasarla a Aspose. | + +--- + +## Extraer Texto de la Imagen y Manejar Resultados + +Una vez que el motor OCR termina, el objeto `OcrResult` contiene la cadena reconocida. Aquí es donde **extract text from image** para procesamiento posterior—guardarlo en una base de datos, alimentarlo a un índice de búsqueda o a una canalización NLP posterior. + +### Tratando Múltiples Idiomas + +Como establecimos `engine.setLanguage(Language.Auto)`, Aspose intentará detectar los idiomas sobre la marcha. Si conoces el idioma de antemano (p. ej., todos los documentos son rusos), puedes reemplazar `Language.Auto` por `Language.Russian` para mejorar el rendimiento. + +### Consejos de Post‑Procesamiento + +- **Eliminar espacios en blanco**: `result.getText().trim()`. +- **Normalizar finales de línea**: `result.getText().replace("\r\n", "\n")`. +- **Eliminar caracteres no imprimibles**: usa una expresión regular como `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Reconocer Texto en Imagen con Opciones Avanzadas (Opcional) + +Si necesitas un control más fino, Aspose OCR ofrece propiedades adicionales: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Estos ajustes son útiles cuando trabajas con documentos escaneados que presentan inclinación o bajo contraste. + +--- + +## Recapitulación del Ejemplo Completo Funcional + +Uniendo todo, el programa final realiza lo siguiente en orden: + +1. **Perform OCR on image** – creando un `OcrEngine`. +2. **Use Aspose license** – opcional pero recomendado. +3. **Load image for OCR** – mediante `Image.load`. +4. **Set language detection** – `Language.Auto` para **recognize text image** automáticamente. +5. **Extract text from image** – imprimir el resultado, manejando respuestas vacías de forma elegante. + +Puedes copiar el bloque de código anterior directamente en un proyecto Maven con esta dependencia: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Ejecuta `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` y observa cómo la consola muestra el texto reconocido. + +--- + +## Conclusión + +Acabamos de mostrarte cómo **perform OCR on image** archivos usando Aspose OCR para Java, desde aplicar una licencia hasta **loading the image for OCR**, **recognize text image** contenido, y finalmente **extract text from image** para uso posterior. El enfoque es sencillo, funciona con múltiples idiomas desde el principio y puede ampliarse con opciones avanzadas de preprocesamiento cuando sea necesario. + +¿Qué sigue? Intenta alimentar la salida del OCR a un índice de búsqueda, generar PDFs con el texto extraído o experimentar con diferentes formatos de imagen. Las posibilidades son infinitas, y con la robusta API de Aspose pasarás más tiempo construyendo funcionalidades que lidiando con peculiaridades del OCR. + +¿Tienes preguntas o te encuentras con un caso extremo? Deja un comentario abajo—¡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. + +- [Cómo extraer texto de una imagen desde URL usando Aspose.OCR para Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convertir Imagen a Texto en Java usando Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extraer Texto de Imagen Java con Aspose.OCR Modo Detectar Áreas](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3f0db1a18 --- /dev/null +++ b/ocr/swedish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-19 +description: Skapa sökbar PDF från en bild med Python OCR. Lär dig konvertera OCR + till PDF, extrahera text från bild och utföra OCR på bild snabbt. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: sv +og_description: Skapa sökbar PDF från en bild med Python OCR. Denna guide visar hur + man konverterar OCR till PDF, extraherar text från en bild och utför OCR på bilden. +og_title: Skapa sökbar PDF i Python – Fullständig programmeringsgenomgång +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Skapa sökbar PDF i Python – Komplett steg‑för‑steg‑guide +url: /sv/python-java/general/create-searchable-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 >}} + +# Skapa sökbar PDF i Python – Komplett steg‑för‑steg‑guide + +Har du någonsin behövt **skapa sökbar PDF** från ett skannat kvitto men inte vetat var du ska börja? Du är inte ensam—många utvecklare stöter på samma hinder när de första gången försöker omvandla en bild av text till en PDF som du faktiskt kan söka i. + +I den här handledningen går vi igenom en praktisk lösning som låter dig **utföra OCR på bild**, omvandla OCR‑resultatet till en **sökbar PDF**, och även hämta den råa texten om du behöver den för vidare bearbetning. Inga onödiga utsvävningar, bara ett fungerande exempel som du kan kopiera‑klistra in i ditt projekt redan idag. + +## Vad du kommer att lära dig + +- Hur du sätter upp en lättviktig OCR‑motor i Python +- De exakta stegen för att **konvertera OCR till PDF** och spara den som ett sökbart dokument +- Sätt att **extrahera text från bild** för efterföljande analys +- Tips för att hantera vanliga fallgropar som bildorientering och stora filer +- Ett komplett, körbart skript som du kan anpassa till ditt eget användningsområde + +### Förutsättningar + +- Python 3.8+ installerat på din maskin +- Grundläggande kunskap om pip och virtuella miljöer (valfritt men rekommenderat) +- En bildfil (PNG, JPEG, etc.) som innehåller tydlig, maskinläsbar text + +Om du har detta, låt oss dyka ner. + +## Steg 1: Installera det nödvändiga biblioteket + +Kodsnutten du såg tidigare använder ett fiktivt `ocr`‑paket, men samma idéer gäller för verkliga bibliotek som **EasyOCR**, **pytesseract** eller **pdfminer.six**. För den här guiden använder vi **EasyOCR** eftersom det är rent Python, stöder många språk och levererar en praktisk PDF‑konverteringsmetod via en hjälpfunktion. + +```bash +pip install easyocr pillow +``` + +> **Proffstips:** Installera i en virtuell miljö (`python -m venv venv && source venv/bin/activate`) för att hålla dina beroenden organiserade. + +## Steg 2: Initiera OCR‑motorn – Utför OCR på bild + +Nu när biblioteket är redo skapar vi en OCR‑motor och talar om för den att arbeta med engelsk text. Detta är den första platsen där vi **utför OCR på bild**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Varför behöver vi ett dedikerat läsar‑objekt? EasyOCR för‑laddar språkmodeller, så att återanvända samma `reader` för flera bilder är mycket effektivare än att initiera om den varje gång. + +## Steg 3: Ladda bilden – Extrahera text från bild + +Låt oss läsa in bilden i minnet. Detta steg är där vi senare **extraherar text från bild**, men först laddar vi bara in den. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Om din bild är upp och ner eller sned, överväg att använda Pillow:s `rotate` eller `transpose`‑metoder innan du skickar den till OCR‑motorn. En snabb visuell kontroll kan spara dig timmar av felsökning senare. + +## Steg 4: Kör OCR‑motorn och fånga resultaten + +Här är kärnan i processen—att skicka bilden till OCR‑motorn och få tillbaka strukturerad data. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Flaggan `detail=1` ger oss begränsningsrutor, vilket vi kommer att behöva när vi senare **konverterar OCR till PDF**. Om du bara är intresserad av råa strängar, sätt `detail=0`. + +## Steg 5: Konvertera OCR‑resultat till en sökbar PDF – Konvertera OCR till PDF + +EasyOCR erbjuder ingen direkt PDF‑skrivare, men vi kan själva sätta ihop PDF‑filen med Pillow och `reportlab`‑biblioteket. För att hålla handledningen lättviktig använder vi `fpdf2`, som låter oss bädda in den ursprungliga bilden och överlagra osynlig text. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Vad hände just nu? Vi placerade den skannade bilden som det synliga lagret, och skrev sedan de igenkända orden ovanpå med vit text som smälter in i den vita bakgrunden. Sökapparater läser fortfarande det dolda lagret, så PDF‑filen blir **sökbar** utan att ändra det visuella utseendet. + +## Steg 6: Spara PDF‑byten – Konvertera bild till PDF + +Om du föredrar att hantera PDF‑filen i minnet (t.ex. skicka den via ett API), kan du fånga bytena istället för att skriva direkt till disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Den raden demonstrerar det klassiska **konvertera bild till PDF**‑flödet: du börjar med en bild, kör OCR, överlagrar text och slutligen genererar ett PDF‑ström. + +## Steg 7: Verifiera resultatet – Snabba kontroller + +Efter att du kört skriptet, öppna `receipt_searchable.pdf` i någon PDF‑visare och testa sökrutan (Ctrl + F). Skriv in ett ord du vet finns på kvittot—om det hoppar till rätt ställe har du lyckats **skapa sökbar pdf**! + +Om sökningen misslyckas, dubbelkolla: + +1. OCR‑konfidenspoängen (`conf`‑värden). Låg konfidens kan betyda att bilden är suddig. +2. Koordinaterna för begränsningsrutorna—ibland rapporterar EasyOCR dem i en annan orientering. +3. Att PDF‑visaren inte är inställd på “endast bild”‑läge (sällsynt, men vissa visare har den möjligheten). + +## Fullt fungerande skript + +När allt sätts ihop, här är den kompletta, körklara Python‑filen: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Spara den som `searchable_pdf.py`, ersätt `YOUR_DIRECTORY`‑platshållarna med faktiska sökvägar, och kör: + +```bash +python searchable_pdf.py +``` + +Du bör se ett bekräftelsemeddelande och en helt ny sökbar PDF i din mapp. + +## Vanliga frågor & kantfall + +**Vad händer om bilden är i färg?** +EasyOCR fungerar både med gråskala‑ och färgbilder, men att konvertera till gråskala (`pil_image.convert("L")`) kan ibland förbättra noggrannheten på brusiga skanningar. + +**Kan jag hantera flersidiga PDF‑filer?** +Ja—loopa över varje sidbild, kör OCR‑stegen och lägg till varje sida i samma `FPDF`‑objekt. Glöm inte att återställa markören (`self.add_page()`) för varje ny bild. + +**Finns det ett sätt att behålla det ursprungliga textlagret istället för osynlig vit text?** +Om du behöver ett riktigt “text‑under‑bild”‑PDF (t.ex. för tillgänglighet), överväg att använda `pdfminer` eller `pikepdf` för att bädda in ett dolt textlager med korrekta PDF‑taggar. Det är mer avancerat, men principen är densamma: bakgrundsbild + överlagrad text. + +**Vad gör jag om OCR‑konfidensen är låg?** +Du kan filtrera bort ord med låg konfidens: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Sammanfattning – Vad vi uppnådde + +Vi började med en enkel bild av ett kvitto, **utförde OCR på bild**, extraherade de igenkända strängarna och slutligen **skapade sökbar pdf** som beter sig som vilket professionellt skannat dokument som helst. Processen täckte varje sekundärt nyckelord—**konvertera OCR till PDF**, **extrahera text från bild**, **konvertera bild till PDF**, och **utföra OCR på bild**—så du nu har en återanvändbar verktygslåda för liknande projekt. + +### Nästa steg + +- Experimentera med andra språk genom att skicka deras ISO‑koder till `easyocr.Reader(['en', 'es'])`. +- Byt ut EasyOCR mot Tesseract om du behöver en helt offline‑lösning; resten av pipeline förblir densamma. +- Lägg till visualisering av OCR‑konfidens (rita begränsningsrutor på bilden) för att felsöka problematiska skanningar. + +Har du ett eget knep du vill dela? Kommentera gärna, fork + +## Vad bör du lära dig härnäst? + +De följande handledningarna täcker närliggande ämnen som bygger på teknikerna som demonstrerats 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 implementationsmetoder i dina egna projekt. + +- [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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/swedish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/swedish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..4bdae41c8 --- /dev/null +++ b/ocr/swedish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: Extrahera text från bilder i Python med en enkel OCR-motor. Lär dig hur + du konverterar skannade bilder till text, känner igen text från bilder och listar + bildfiler i Python effektivt. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: sv +og_description: Extrahera text från bilder i Python med en lättviktig OCR-motor. Den + här guiden visar hur du konverterar skannade bilder till text, känner igen text + i bilder och listar bildfiler i Python på några få steg. +og_title: Extrahera text från bilder i Python – Fullständig batch‑OCR‑guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Extrahera text från bilder i Python – Fullständig batch‑OCR‑guide +url: /sv/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahera text från bilder i Python – Fullständig batch‑OCR‑guide + +Har du någonsin behövt **extrahera text från bilder** men inte vetat var du ska börja? Du är inte ensam—utvecklare ställs ständigt inför utmaningen att omvandla skannade PDF‑filer, fotograferade kvitton eller skärmdumpar till sökbar text. I den här handledningen går vi igenom ett komplett, färdigt exempel som visar hur man **konverterar skannade bilder till text**, känner igen text i bilder och till och med **listar bildfiler python**‑stil. När du är klar har du ett återanvändbart skript som bearbetar en hel mapp på en gång. + +Vi täcker allt du behöver: nödvändiga bibliotek, varför varje steg är viktigt, hantering av kantfall och lite felsökning. Ingen anledning att jaga externa dokument; koden nedan är självständig, och förklaringarna svarar på både “hur” *och* “varför”. Ta fram din favorit‑IDE, så sätter vi igång. + +--- + +## Vad du kommer att bygga + +- Initiera en OCR‑motor (vi använder paketet `ocr` som exempel). +- Skanna en katalog och **lista bildfiler python**‑stil, filtrera PNG, JPG och TIFF. +- Kör en **batch‑OCR**‑operation på alla hittade bilder. +- Skriv ut den extraherade texten för varje fil, tydligt märkt. + +> **Pro tip:** Om du inte har `ocr`‑biblioteket installerat kan du byta ut det mot `pytesseract` med några få ändringar—logiken förblir densamma. + +--- + +## Förutsättningar + +- Python 3.8+ (skriptet använder f‑strängar och typ‑hints). +- Ett OCR‑bibliotek som exponerar en `OcrEngine` med `recognize_batch`. I den här guiden antar vi ett fiktivt `ocr`‑paket, men mönstret fungerar med riktiga bibliotek. +- En mapp som innehåller bildfiler du vill bearbeta (`.png`, `.jpg`, `.tif`). + +--- + +## Steg 1 – Installera & importera nödvändiga moduler + +Först, se till att OCR‑paketet är tillgängligt. Om du använder ett riktigt bibliotek som `pytesseract` ersätter du importen därefter. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Varför detta är viktigt:** Import av `os` ger oss plattformsoberoende sökvägshantering, medan `typing.List` hjälper IDE‑autocomplete och framtidssäkerhet. + +--- + +## Steg 2 – **Extrahera text från bilder**: Initiera OCR‑motorn + +Att skapa motorn är första steget mot all OCR‑arbete. Vi sätter också språket till auto‑detect så att motorn kan hantera blandade språk. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Förklaring:** Genom att kapsla in motor‑skapandet i en funktion håller vi koden modulär. Om du senare behöver justera DPI eller OCR‑läge ändrar du bara detta ställe. + +--- + +## Steg 3 – **Lista bildfiler python**: Samla filer från en katalog + +Nu måste vi hitta varje bild vi vill bearbeta. List‑comprehensionen nedan speglar ett vanligt “list image files python”‑mönster. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Hantering av kantfall:** Funktionen ignorerar undermappar (du kan lägga till rekursion senare) och filtrerar automatiskt bort dolda filer eftersom de vanligtvis inte slutar med de stödjade filändelserna. + +--- + +## Steg 4 – **Konvertera skannade bilder till text**: Kör batch‑OCR + +De flesta OCR‑bibliotek erbjuder en batch‑metod som är mycket snabbare än att bearbeta en bild i taget. Så här anropar vi den. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Varför batch?** Att skicka alla bilder på en gång minskar overhead (t.ex. att ladda OCR‑modellen upprepade gånger) och ger ofta bättre CPU/GPU‑utnyttjande. + +--- + +## Steg 5 – **Känn igen text i bilder**: Visa resultaten + +Till sist itererar vi över de parade filnamnen och OCR‑resultaten och skriver ut ett rent rubrik för varje bild. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Tips:** `strip()` tar bort inledande/slutlig blanksteg som OCR ofta lägger till. + +--- + +## Fullt skript – Sätt ihop allt + +Nedan är det kompletta, körbara programmet. Spara det som `batch_ocr.py` och kör `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Förväntad output + +Om mappen innehåller `invoice1.png` och `receipt.jpg` kan du se följande: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Varje block är tydligt märkt, vilket gör efterföljande bearbetning (t.ex. att spara till en databas) enkel. + +--- + +## Hantera vanliga fallgropar + +| Problem | Varför det händer | Snabb lösning | +|---------|-------------------|---------------| +| **Ingen text visas** | OCR‑språket upptäcks inte eller bilden har för låg kontrast. | Tvinga ett språk (`engine.language = ocr.Language.English`) eller förbehandla bilder (öka kontrast). | +| **Minnesfel vid stora batcher** | Motorn försöker ladda alla bilder samtidigt. | Dela `image_files` i delar (`batch_size = 20`) och anropa `recognize_batch` upprepade gånger. | +| **Filformatet stöds inte** | Du lade till en `.gif` eller `.bmp`. | Utöka `supported_exts`‑tuple eller konvertera bilder till PNG/JPG i förväg. | +| **Unicode‑förvrängning** | OCR returnerar bytes istället för strängar. | Säkerställ att OCR‑biblioteket levererar Unicode (`result.text.decode('utf‑8')` om behövs). | + +--- + +## Utöka arbetsflödet + +Nu när du kan **extrahera text från bilder**, överväg följande nästa steg: + +- **Export till CSV** – Skriv varje filnamn och dess extraherade text till ett kalkylblad för analys. +- **Parallell bearbetning** – Använd `concurrent.futures.ThreadPoolExecutor` för att hantera flera batcher samtidigt. +- **Integrera med moln‑OCR** – Byt ut den lokala motorn mot Google Vision eller Azure OCR för högre precision på komplexa layouter. +- **Lägg till bildförbehandling** – Bibliotek som Pillow eller OpenCV kan räta upp, avbrusa eller tröskla bilder innan OCR, vilket förbättrar resultatet. + +Alla dessa idéer bygger naturligt på samma kärnfunktioner som vi har skapat, så du behöver inte börja om från början. + +--- + +## Slutsats + +Vi har just gått igenom en komplett lösning för att **extrahera text från bilder** i Python, och täckt allt från **lista bildfiler python** till **känna igen text i bilder** och slutligen **konvertera skannade bilder till text** i en prydlig batch. Skriptet är avsiktligt enkelt men ändå flexibelt nog att fungera som grund för större projekt—oavsett om du digitaliserar kvitton, bygger ett sökbart arkiv eller driver en data‑extraktionspipeline. + +Kör det, justera förbehandlingsstegen, och se din OCR‑precision öka. Stöt du på problem, gå tillbaka till tabellen “Hantera vanliga fallgropar”; de flesta problem löses med en liten konfigurationsändring. + +Redo för nästa utmaning? Prova att lägga till ett PDF‑till‑bild‑konverteringssteg med `pdf2image`, och mata sedan in dessa bilder direkt i samma pipeline. Himlen är gränsen när du kombinerar OCR med Pythons rika ekosystem. + +Happy coding, and may your text be ever legible! + +## Vad du bör lära dig härnäst? + +De följande handledningarna täcker nära beslä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 implementeringsmetoder i dina egna projekt. + +- [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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/swedish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..d46647c4f --- /dev/null +++ b/ocr/swedish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: Extrahera text från bilder med Python OCR. Lär dig automatisk språkdetektering, + parallell bearbetning och batchigenkänning i en kortfattad handledning. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: sv +og_description: Extrahera text från bilder med Python OCR. Denna guide visar automatisk + språkdetektering, parallell bearbetning och batchigenkänning i en enda handledning. +og_title: extrahera text från bilder i Python – Fullständig OCR-guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Extrahera text från bilder i Python – Fullständig OCR-guide +url: /sv/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# extrahera text från bilder i Python – Fullständig OCR‑guide + +Har du någonsin funderat på hur man **extraherar text från bilder** utan att manuellt skriva in varje ord? Du är inte ensam. Oavsett om du digitaliserar gamla kvitton, bygger ett sökbart dokumentarkiv eller bara leker med häftiga AI‑trick, är förmågan att hämta text från bilder en nödvändig färdighet för alla Python‑utvecklare idag. + +I den här handledningen går vi igenom ett komplett, färdigt exempel som **extraherar text från bilder** med en populär OCR‑motor. Vi täcker automatisk språkdetection, parallell bearbetning för hastighet och batch‑bildigenkänning så att du kan hantera dussintals filer på några sekunder. Låter det som vad du behöver? Då kör vi igång. + +## Vad du kommer att lära dig + +- Hur du instansierar OCR‑motorn med `ocr.OcrEngine`. +- Aktivera **automatisk språkdetection** så att motorn själv väljer rätt språk. +- Konfigurera **parallell bearbetning OCR** med en egen trådpott. +- Köra **batch‑bildigenkänning** på en lista med filer. +- Skriva ut den igenkända texten för varje bild, redo att sparas eller indexeras. + +Ingen extern dokumentation behövs – allt du behöver finns här, och koden fungerar direkt med `ocr`‑paketet (installera det via `pip install ocr`). + +## Förutsättningar + +Innan vi börjar, se till att du har: + +1. Python 3.8 eller nyare installerat. +2. `ocr`‑paketet (`pip install ocr`). +3. En mapp med PNG‑ (eller JPG‑) bilder du vill bearbeta. +4. Grundläggande kunskap om Python‑funktioner och loopar. + +Det är allt – inga tunga beroenden, ingen GPU‑magik, bara ren Python. + +![extract text from images example](https://example.com/ocr-demo.png "Screenshot showing extract text from images output") + +*Alt text: demonstrationsskärmbild för extrahera text från bilder* + +## Steg 1 – Ställ in OCR‑motorn (Primärt nyckelord i handling) + +Först och främst: skapa en OCR‑motorinstans. Tänk på `ocr.OcrEngine()` som hjärnan bakom operationen; den vet hur man läser tecken, rader och stycken. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Varför behöver vi en explicit motor? För att **ocr.OcrEngine‑användning** ger dig fin‑granulär kontroll över språkinställningar, trådar och mer. Det är det mest flexibla sättet att **extrahera text från bilder** jämfört med enkla en‑rad‑hjälpare. + +## Steg 2 – Låt motorn automatiskt upptäcka språk + +De flesta OCR‑bibliotek kräver att du anger vilket språk de ska leta efter. Det fungerar för ett enspråkigt projekt, men är krångligt för en blandad språk‑batch. Lyckligtvis stödjer `ocr`‑paketet **automatisk språkdetection**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Genom att sätta `engine.language` till `ocr.Language.Auto` får motorn sniffa varje bild och välja rätt språkmodell. Den här lilla raden sparar dig timmar av manuell konfiguration när du hanterar internationella dokument. + +## Steg 3 – Snabba upp med parallell bearbetning OCR + +Om du har fyra eller fler CPU‑kärnor, varför inte använda dem? Motorn kan starta en trådpott som låter flera bilder bearbetas samtidigt. Här glänser **parallell bearbetning OCR**. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Justera gärna siffran `4` efter din maskin. Fler trådar → snabbare batch‑körningar, men kom ihåg att varje tråd förbrukar minne, så hitta en bra balans för din miljö. + +## Steg 4 – Samla bilderna du vill bearbeta + +Nu behöver vi en lista med filsökvägar. Du kan bygga listan manuellt, läsa den från en CSV eller använda `glob`. För tydlighetens skull hårdkodar vi en kort lista: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Byt ut `YOUR_DIRECTORY` mot den faktiska sökvägen på ditt system. Om du har dussintals filer räcker ett snabbt `glob.glob("*.png")` för att göra det tunga lyftet. + +## Steg 5 – Kör batch‑bildigenkänning + +Här är kärnan i handledningen: ett enda anrop som bearbetar varje bild i `files` och returnerar en lista med resultatobjekt. Detta är **batch‑bildigenkänning**‑funktionen som gör storskalig OCR praktisk. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Bakom kulisserna fördelar motorn varje fil över de fyra arbets‑trådarna vi konfigurerade tidigare, samtidigt som den automatiskt upptäcker språk för varje bild. Metoden returnerar en lista där varje element innehåller den igenkända texten och metadata. + +## Steg 6 – Skriv ut (eller lagra) den extraherade texten + +Till sist loopar vi över resultaten och skriver ut texten. I ett riktigt projekt skulle du sannolikt skriva detta till en databas eller en CSV‑fil, men utskrift håller exemplet enkelt. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Förväntad utskrift** (avkortad för korthet): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Varje block visar filnamnet följt av den OCR‑genererade strängen. Om en bild innehåller flera språk ser du de korrekta tecknen tack vare steget **automatisk språkdetection** tidigare. + +## Pro‑tips & Vanliga fallgropar + +- **Bildkvalitet spelar roll** – suddiga eller lågkontrastbilder ger skräp. Förprocessa med OpenCV (`cv2.threshold`, `cv2.resize`) om det behövs. +- **Trådräkning vs. I/O** – Om dina bilder ligger på en långsam nätverksdisk hjälper fler trådar kanske inte. Håll koll på CPU‑användning med `top` eller **Task Manager**. +- **Unicode‑hantering** – `result.text` är en Unicode‑sträng. När du skriver till filer, öppna dem med `encoding="utf‑8"` för att undvika `UnicodeEncodeError`s. +- **Minnesanvändning** – Stora PDF‑filer kan äta mycket RAM. Om du får `MemoryError`, minska trådpottens storlek eller bearbeta bilder i mindre portioner. + +## Fullt fungerande skript + +Nedan är det kompletta, kopiera‑och‑klistra‑klara skriptet som inkluderar varje steg vi gått igenom. Spara det som `batch_ocr.py` och kör `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Kör det så här: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Du får ett snyggt formaterat textblock för varje bild, vilket bevisar att du kan **extrahera text från bilder** i skala. + +## Vad blir nästa steg? + +Nu när du behärskar grunderna i **extrahera text från bilder** med Python, fundera på att utforska: + +- **Post‑processering**: rensa OCR‑utdata med regex eller naturliga språk‑bibliotek. +- **PDF‑konvertering**: mata in de extraherade strängarna i en PDF‑generator för sökbara PDF‑filer. +- **Moln‑OCR‑tjänster**: jämför lokala `ocr`‑resultat med Google Vision eller Azure OCR för kantfallens noggrannhet. +- **GUI‑frontend**: bygg en liten Flask‑ eller FastAPI‑app som låter användare ladda upp bilder och omedelbart se den extraherade texten. + +Alla dessa ämnen bygger på **Python OCR‑biblioteket** du just satt upp, och de drar nytta av samma **parallell bearbetning OCR**‑knep som vi använde här. + +--- + +*Lycka till med kodandet! Om du stöter på problem, lämna en kommentar nedan – jag hjälper gärna till med OCR‑buggar.* + +## Vad bör du lära dig härnäst? + +De följande handledningarna 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. + +- [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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/swedish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..81a20bb21 --- /dev/null +++ b/ocr/swedish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-19 +description: Hur man extraherar PDF med OCR i Python – steg‑för‑steg‑handledning som + täcker att extrahera text från PDF, känna igen text från bild och ett OCR‑exempel + i Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: sv +og_description: Hur man extraherar PDF med OCR i Python. Lär dig att extrahera text + från PDF, känna igen text från bild och se ett komplett OCR-exempel i Python. +og_title: Hur man extraherar PDF‑text med OCR i Python – Fullständig handledning +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Hur man extraherar PDF‑text med OCR i Python – Komplett guide +url: /sv/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man extraherar PDF‑text med OCR i Python – Komplett guide + +Har du någonsin undrat **hur man extraherar PDF**‑innehåll när filen bara är en skannad bild? Du är inte ensam. I många verkliga projekt—tänk kontrakt, fakturor eller historiska arkiv—har PDF‑filen du får ingen markerbar text. De goda nyheterna? Några rader Python kan förvandla dessa bild‑endast sidor till sökbar, redigerbar text. + +I den här handledningen går vi igenom ett praktiskt **OCR Python‑exempel** som läser en PDF, renderar dess första sida som en bild och sedan **extraherar text från PDF** med en OCR‑motor. I slutet kommer du att veta exakt hur man **läser PDF med OCR**, varför varje steg är viktigt och hur man anpassar koden för flersidiga dokument eller olika språk. + +## Vad du kommer att lära dig + +- Installera och konfigurera ett pålitligt OCR‑bibliotek för Python. +- Konvertera PDF‑sidor till bilder som är lämpliga för OCR. +- **Känna igen text från bild** och hämta rena Unicode‑strängar. +- Vanliga fallgropar (PDF med låg upplösning, roterade sidor) och hur man undviker dem. +- Utöka skriptet för att hantera flera sidor eller batch‑bearbetning. + +**Förutsättningar**: Python 3.8+, pip och en grundläggande förståelse för virtuella miljöer. Ingen tidigare OCR‑erfarenhet krävs—följ bara med. + +--- + +## ## Hur man extraherar PDF‑text med OCR i Python + +Denna H2‑rubrik innehåller vårt primära nyckelord precis där sökmotorer gillar att se det. Låt oss dyka rakt in i koden. + +### Steg 1 – Installera de nödvändiga paketen + +Först behöver vi en OCR‑motor. Exemplet nedan använder det populära **ocr**‑paketet (ett lätt omslag runt Tesseract). Om du föredrar en annan backend, förblir koncepten desamma. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Proffstips:** På Linux behöver du också Tesseract‑binären: `sudo apt-get install tesseract-ocr`. macOS‑användare kan hämta den via Homebrew: `brew install tesseract`. + +### Steg 2 – Initiera OCR‑motorn och ange språk + +Nu startar vi motorn och talar om för den att leta efter engelska tecken. Du kan byta `ocr.Language.English` mot någon annan stödd språkkod. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Varför detta är viktigt:** Att specificera språket förbättrar noggrannheten dramatiskt eftersom motorn kan använda språkspecifika ordböcker och teckenmodeller. + +### Steg 3 – Ladda en PDF‑sida som en bild + +OCR fungerar på rasterbilder, inte PDF‑objekt. Hjälpfunktionen `ocr.Image.from_pdf` renderar den valda sidan till en bitmap. Justera `page_number` för andra sidor (0‑baserad indexering). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Edge case:** Om PDF‑filen innehåller vektorgrafik snarare än skannade bilder kan du få en skarp rendering. För lågupplösta skanningar, överväg att öka DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Steg 4 – Känna igen text från den renderade bilden + +Här är kärnan i **ocr python example**. Motorn bearbetar bitmapen och returnerar ett objekt som innehåller den extraherade strängen. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +`ocr_result.text`‑attributet innehåller ren‑text‑utdata, med radbrytningar bevarade där det är möjligt. + +### Steg 5 – Skriv ut eller lagra den extraherade texten + +Till sist skriver vi ut resultatet. I en riktig applikation skulle du troligen skriva till en fil eller en databas. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Att köra skriptet bör visa något liknande: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Det är ett komplett **extract text from pdf**‑arbetsflöde med OCR. + +--- + +## ## Känna igen text från bild – Justera noggrannhet + +Om du bara är intresserad av **recognize text from image** (t.ex. en JPEG‑bild av ett kvitto), kan du hoppa över PDF‑konverteringssteget: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Tips för bättre resultat:** + +- **Förbehandla** bilden: konvertera till gråskala, applicera tröskelvärde eller räta upp den. Pillow gör detta enkelt. +- **Öka DPI** vid PDF‑rendering: högre upplösning ger OCR‑motorn mer detaljer. +- **Aktivera OCR‑motorns konfiguration** för sidsegmentering (`ocr_engine.config = "--psm 6"` för enhetliga block). + +--- + +## ## Läs PDF med OCR – Hantera flera sidor + +De flesta kontrakt sträcker sig över flera sidor. Att loopa över varje sida är enkelt: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Denna funktion **läser PDF med OCR**, konkatenerar utskriften och sätter in en tydlig sidbrytarmarkör. Du kan sedan mata `full_text` i ett sökindex eller lagra den som en `.txt`‑fil. + +--- + +## ## Vanliga fallgropar och hur man åtgärdar dem + +| Symtom | Trolig orsak | Åtgärd | +|--------|--------------|--------| +| Förvrängda tecken, många `?` | Fel språk eller saknade språkdatafiler | Installera rätt Tesseract‑språkpaket (`tesseract-ocr-`) och sätt `ocr_engine.language`. | +| Saknade rader eller avklippta ord | Låg DPI (under 150) | Rendera PDF med 300 DPI eller högre (`dpi=300`). | +| Text är roterad eller upp och ner | Skannad sida inte upprätt | Använd `ocr.Image.deskew(page_image)` före igenkänning. | +| Långsam bearbetning på stora PDF‑filer | Bearbetar sidor sekventiellt på en enda tråd | Parallellisera med `concurrent.futures.ThreadPoolExecutor`. | + +--- + +## ## Utöka OCR Python‑exemplet + +- **Exportera till PDF/A**: Efter extraktion kan du bädda in texten tillbaka i en sökbar PDF med `reportlab` eller `pypdf2`. +- **Språkdetection**: Använd `langdetect` på OCR‑utdata för att dynamiskt byta `ocr_engine.language`. +- **Batch‑bearbetning**: Gå igenom en katalog med `os.listdir` och applicera `extract_all_pages` på varje fil. + +--- + +## ## Förväntad output och verifiering + +När du kör skriptet mot en klar, engelskspråkig skanning bör du se ett rent textblock med korrekt interpunktion. Verifiera genom att: + +1. Jämföra några rader med den ursprungliga skannade bilden. +2. Köra en enkel ordräkning (`len(ocr_result.text.split())`) för att säkerställa att output inte är tom. +3. Eventuellt mata resultatet i en stavningskontroll som `pyspellchecker` för att upptäcka OCR‑fel. + +--- + +## Slutsats + +Vi har gått igenom **hur man extraherar PDF**‑innehåll när traditionell parsning misslyckas, demonstrerat ett komplett **ocr python‑exempel**, och förklarat hur man **känner igen text från bild** och **läser PDF med OCR** för både enkelsidiga och flersidiga scenarier. Med kodsnuttarna ovan kan du nu omvandla vilken skannad PDF som helst till sökbar, redigerbar text—slut på manuellt omskrivning. + +Nästa steg? Prova att byta språk till spanska (`ocr.Language.Spanish`) eller experimentera med bild‑förbehandlingstekniker för att öka noggrannheten. Om du bygger ett dokumenthanteringssystem, överväg att indexera den extraherade texten med Elasticsearch för blixtsnabb sökning. + +Har du frågor eller stöter på en knepig PDF? Lämna en kommentar, och lycka till med kodandet! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + +## 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. + +- [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/) +- [Känna igen PDF‑text – OCR‑operationer med Aspose.OCR för Java](/ocr/english/java/ocr-operations/) +- [Extrahera bildtext i C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/swedish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..e94723790 --- /dev/null +++ b/ocr/swedish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-19 +description: Lär dig hur du använder OCR i Java med Aspose. Denna steg‑för‑steg‑guide + täcker automatisk korrigering av snedställda bilder, automatisk språkdetektering + och enkel extrahering av text från bilder. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: sv +og_description: 'Hur man använder OCR i Java med Aspose: en fullständig genomgång + som täcker automatisk räta upp av bilder, automatisk språkidentifiering och extrahering + av text från bilder.' +og_title: Hur man använder OCR i Java med Aspose – Komplett guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Hur man använder OCR i Java med Aspose – Komplett guide +url: /sv/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så använder du OCR i Java med Aspose – Komplett guide + +Har du någonsin undrat **hur man använder OCR** i ett Java‑projekt utan att dra i håret över konfigurationen? Du är inte ensam. Många utvecklare stöter på problem när de snabbt måste **extrahera text från bild**‑data, särskilt när källskanningarna är sneda eller skrivna på ett okänt språk. + +I den här handledningen går vi igenom ett praktiskt exempel som visar exakt hur du använder OCR med Aspose, inklusive **auto deskew images**, **auto language detection** och hela **ocr image preprocessing**‑pipeline. När du är klar har du ett färdigt kodsnutt som skriver ut den igenkända texten till konsolen, och du förstår varför varje inställning är viktig. + +> **Vad du får:** ett komplett, körbart Java‑program, förklaringar av varje rad, tips för att hantera kantfall och idéer för att utöka lösningen till batch‑bearbetning eller PDF‑filer. + +--- + +## Förutsättningar + +- Java 17 (eller någon nyare JDK) installerad och konfigurerad. +- Maven eller Gradle för beroendehantering (vi visar Maven‑koordinaterna). +- En Aspose OCR för Java licensfil (`Aspose.OCR.Java.lic`). Om du bara testar kan du hoppa över licenssteget, men gratisversionen lägger till ett vattenmärke. +- En exempelbild (`your_image.png`) placerad på en plats som är åtkomlig för koden. + +> **Pro tip:** håll dina bilder i en dedikerad `resources`‑mapp och ladda dem via classpath; det undviker sökvägsrelaterade problem på olika OS. + +--- + +## Steg 1: Ställ in projektet och lägg till Aspose OCR‑beroende + +Skapa ett nytt Maven‑projekt (eller använd ditt befintliga) och lägg till följande i din `pom.xml`: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Kör `mvn clean install` för att hämta biblioteket. Om du föredrar Gradle är motsvarande: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Nu har du **ocr image preprocessing**‑klasserna på din classpath. + +--- + +## Steg 2: Applicera din Aspose OCR‑licens (valfritt men rekommenderat) + +Om du har en licens, applicera den i början av din `main`‑metod. Att hoppa över detta steg fungerar, men gratisversionen lägger ett “Demo”‑vattenmärke på resultatet. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Varför detta är viktigt:** Den licensierade versionen tar bort användningsgränser och inaktiverar vattenmärket, så du får rena, produktionsklara resultat. + +--- + +## Steg 3: Skapa OCR‑motorinstansen + +Motorn är hjärtat i processen. När du instansierar den får du tillgång till alla **ocr image preprocessing**‑alternativ. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Vid detta tillfälle är motorn redo, men den använder standardinställningar som kanske inte är optimala för skannade dokument. Låt oss justera några. + +--- + +## Steg 4: Aktivera Auto Deskew Images för renare skanningar + +Sneda skanningar är ett vanligt problem. Aspose erbjuder en **auto deskew images**‑funktion som automatiskt räta upp bilden innan igenkänning. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Hur det fungerar:** Algoritmen analyserar textbaslinjens vinklar och roterar bilden till den mest sannolika upprätta orienteringen. Detta förbättrar noggrannheten dramatiskt för foton tagna med en telefon. + +--- + +## Steg 5: Slå på Auto Language Detection + +Om du inte vet vilket språk källbilden har, låt motorn lista ut det. Detta är inställningen **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +När du aktiverar detta skannar Aspose glyferna och väljer den mest sannolika språkmodellen, med stöd för över 30 språk direkt ur lådan. + +--- + +## Steg 6: Ladda bilden du vill känna igen + +Du kan ladda en bild från disk, en URL eller till och med en byte‑array. För enkelhetens skull läser vi från en lokal fil. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Tips:** Om du arbetar med stora bilder, överväg att först nedskala dem med `engine.getImagePreprocessing().setResizeFactor(0.5)` för att snabba upp bearbetningen utan att förlora mycket detalj. + +--- + +## Steg 7: Utför OCR‑igenkänning och extrahera Text Image + +Nu gör motorn sin magi. Metoden `recognize` returnerar ett `OcrResult`‑objekt som innehåller den igenkända texten, förtroendescore och mer. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Konsolen visar den rena texten som extraherats från bilden – detta är kärnresultatet **extract text image** som vi ville uppnå. + +--- + +## Fullt fungerande exempel + +Nedan är den kompletta Java‑klassen som binder ihop allt. Kopiera och klistra in den i `src/main/java/com/example/OcrDemo.java` och kör den. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Förväntat resultat + +Om bilden innehåller frasen “Hello World” på en ren skanning, kommer du att se: + +``` +=== Recognized Text === +Hello World +``` + +För mer komplexa dokument (t.ex. flerspråkiga kvitton) kommer utskriften att innehålla radbrytningar och den upptäckta språkkoden. + +--- + +## Vanliga fallgropar & Pro‑tips + +| Problem | Varför det händer | Lösning | +|---------|-------------------|---------| +| **Skräptecken** | Bilden är för mörk eller brusig. | Aktivera `engine.getImagePreprocessing().setBinarization(true)` eller justera kontrasten manuellt. | +| **Fel språk** | Automatisk detektering misslyckas på blandade språk‑sidor. | Sätt `engine.setLanguage(Language.English)` (eller motsvarande enum) för att tvinga ett specifikt språk. | +| **Långsam bearbetning** | Mycket högupplösta bilder. | Skala ner med `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Minnesbristfel** | Stort parti bilder laddas på en gång. | Bearbeta bilder sekventiellt och anropa `engine.dispose()` efter varje körning. | + +> **Kom ihåg:** OCR‑motorn är trådsäker för enbart läs‑operationer, men att skapa en ny instans per tråd undviker dolda tillståndsbuggar. + +--- + +## Utöka lösningen + +Nu när du vet **hur man använder OCR** med Aspose kan du vilja: + +1. **Processa PDF‑filer** – Konvertera varje PDF‑sida till en bild (`PdfConverter`) och skicka den genom samma pipeline. +2. **Batch‑processa en mapp** – Loopa igenom filer i en katalog, applicera samma steg och skriv resultat till en CSV. +3. **Integrera med en webbtjänst** – Exponera OCR‑logiken via en Spring Boot `@RestController` som accepterar multipart‑uppladdningar. + +Alla dessa scenarier återanvänder samma **ocr image preprocessing**‑konfiguration som vi byggde här. + +--- + +## Slutsats + +Vi har gått igenom **hur man använder OCR** i Java med Aspose från början till slut: applicera en licens, skapa motorn, slå på **auto deskew images**, aktivera **auto language detection**, ladda en bild och slutligen **extract text image** med ett enda `System.out.println`. Koden är helt självständig, körs på vilken modern JDK som helst och demonstrerar bästa praxis för noggrannhet och prestanda. + +Prova själv med dina egna bilder – kanske ett skannat kontrakt eller en skärmdump av ett kvitto. Justera förbehandlingsflaggorna, experimentera med olika språk, så ser du snabbt varför Asposes OCR‑bibliotek är ett stabilt val för produktionsklassisk textutvinning. + +Har du frågor eller vill dela dina resultat? Lämna en kommentar nedan eller kontakta mig på GitHub. Lycka till med kodandet! + +--- + +![Exempel på hur man använder OCR i Java](/images/ocr-java-example.png "Hur man använder OCR i Java – Aspose demo skärmbild") + + +## 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. + +- [Hur man OCR‑ar bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extrahera text från bild i Java med Aspose.OCR Detektera områden‑läge](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Hur man använder OCR – Avancerade tekniker med Aspose.OCR för Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/swedish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..25d28dfe8 --- /dev/null +++ b/ocr/swedish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Förbättra OCR‑noggrannheten i Python med Aspose OCR. Lär dig hur du ställer + in OCR‑språk, laddar en bild för OCR och extraherar text från bilden med en anpassad + ordlista. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: sv +og_description: Förbättra OCR‑noggrannheten i Python genom att ställa in OCR‑språk, + ladda en bild för OCR och extrahera text från bilden med en anpassad ordlista. +og_title: Förbättra OCR‑noggrannheten i Python – Steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Förbättra OCR‑noggrannheten i Python – Komplett guide +url: /sv/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Förbättra OCR‑noggrannhet i Python – Komplett guide + +Har du någonsin undrat hur du **förbättrar OCR‑noggrannhet** när texten du skannar innehåller konstiga symboler, produktkoder eller varumärkesnamn? Du är inte ensam. I många projekt ger standardmotorn bara nonsens, och det är en riktig produktivitetsböda. + +I den här handledningen går vi igenom ett praktiskt, end‑to‑end‑exempel som visar hur du **anger OCR‑språk**, **laddar bild för OCR**, **utför OCR på bild** och slutligen **extraherar text från bild** med en anpassad ordlista som ökar igenkänningsgraden. När du är klar har du ett färdigt skript som du kan lägga in i vilken Python‑kodbas som helst. + +## Vad du får med dig + +- Ett fullt fungerande Python‑skript som använder Aspose OCR för att läsa en PNG‑fil. +- Förmågan att **förbättra OCR‑noggrannhet** genom att konfigurera språk och en anpassad ordlista. +- Klara förklaringar till varför varje inställning är viktig, samt tips för att hantera kantfall som icke‑latinska tecken. +- En snabb checklista för att felsöka vanliga OCR‑problem. + +### Förutsättningar + +- Python 3.8 eller nyare installerat på din maskin. +- `aspose-ocr`‑paketet (installera via `pip install aspose-ocr`). +- En exempelbild (`technical_doc.png`) som innehåller den text du vill läsa. +- Grundläggande kunskap om Python — inget avancerat krävs. + +> **Pro tip:** Om du arbetar i en virtuell miljö, aktivera den innan du installerar paketet. Det håller dina beroenden organiserade och undviker versionskonflikter. + +--- + +## Steg 1: Installera och importera Aspose OCR + +First things first—let’s get the library into our environment and import the pieces we need. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr`‑namnutrymmet ger dig åtkomst till `OcrEngine`‑klassen, som är hjärtat i OCR‑processen. Att importera den här håller resten av skriptet rent och lättläst. + +--- + +## Steg 2: Skapa en OCR‑motor och **ange OCR‑språk** + +Varför spelar språket roll? OCR‑motorer förlitar sig på språk‑specifika modeller för att känna igen teckenformer och ordmönster. Om du talar om för motorn att du skannar engelsk text, kommer den att ignorera kyrilliska tecken och fokusera på det latinska alfabetet, vilket dramatiskt **förbättrar OCR‑noggrannhet**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Note:** Aspose OCR supports over 50 languages. Swap `ocr.Language.English` for `ocr.Language.Spanish`, `ocr.Language.French`, etc., if your document isn’t English. + +--- + +## Steg 3: Definiera en **anpassad ordlista** för att öka noggrannheten + +Föreställ dig att du skannar fakturor som innehåller ordet “AsposeOCR” eller produktkoder som “SKU12345”. Motorn känner inte till dessa termer, så den gissar fel. Att tillhandahålla en anpassad ordlista säger till motorn, *“Hej, de här strängarna är legitima—försök inte korrigera dem.”* Det är en snabb vinst för **förbättra OCR‑noggrannhet**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Du kan läsa in listan från en fil eller en databas om du har hundratals poster—behåll den i en Python‑lista för enkelhetens skull. + +--- + +## Steg 4: **Ladda bild för OCR** + +Now we need an image. The `Image.load` method accepts a path to any supported raster format (PNG, JPEG, BMP, etc.). If the file can’t be found, the engine throws an exception, so we’ll guard against that. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Why this step matters:** Loading the image correctly ensures the engine works with the exact pixel data you intend to analyze. Corrupted files or wrong paths are a common source of frustration. + +--- + +## Steg 5: **Utför OCR på bild** och extrahera resultat + +With the engine configured and the image ready, the actual recognition is a single method call. The result object contains the raw text, confidence scores, and even layout information if you need it later. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +If you need to **extract text from image** line by line, you can split on newline characters: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Steg 6: Verifiera resultatet – Gör det verkligen **förbättra OCR‑noggrannhet**? + +Let’s print the result and see if our custom dictionary made a difference. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Typical output for the sample image might look like: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Notice how the brand name, Greek character, and product code appear exactly as we defined them. Without the custom dictionary, the engine would have tried to “correct” them, often producing something like “Aspose OCR” or “SKU 1234”. + +--- + +## Vanliga fallgropar & hur du löser dem + +| Problem | Varför det händer | Lösning | +|---------|-------------------|---------| +| **Skräptecken** | Fel språk inställt eller låg upplösning på bilden | Se till att `engine.language` matchar källspråket och använd en hög‑DPI‑skanning (300 dpi eller högre). | +| **Anpassade ord ignoreras** | Ordlista inte bifogad eller stavfel i egenskapsnamnet | Dubbelkolla `engine.text_processing.custom_dictionary = …`. | +| **Fil ej hittad** | Felaktig sökväg eller saknade filbehörigheter | Använd `os.path.abspath()` för att verifiera den absoluta sökvägen; kör skriptet med rätt behörigheter. | +| **Långsam bearbetning** | Stora bilder eller många sidor | Förbehandla bilden (beskär, ändra storlek) eller använd `engine.recognize(image, max_threads=4)` för parallellisering. | + +--- + +## Gå djupare: Avancerade justeringar för **förbättra OCR‑noggrannhet** + +1. **Förbehandling** – Applicera kontrastförbättring eller binarisering med Pillow innan du skickar bilden till Aspose OCR. +2. **Flera språk** – Sätt `engine.language = ocr.Language.English | ocr.Language.French` för att möjliggöra flerspråkig igenkänning. +3. **Region‑baserad OCR** – Om du bara behöver ett specifikt område (t.ex. en tabell), beskära bilden först för att minska brus. +4. **Konfidensfiltrering** – `result.confidence` ger ett poäng per tecken; du kan programatiskt filtrera bort låga konfidensresultat. + +--- + +## Fullt fungerande skript + +Below is the complete, copy‑paste‑ready script that incorporates every step we discussed. Save it as `improve_ocr_accuracy.py` and run it from the command line. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Run it: + +```bash +python improve_ocr_accuracy.py +``` + +You should see the nicely formatted output we displayed earlier. + +--- + +## Slutsats + +We’ve just covered a straightforward way to **improve OCR accuracy** in Python by: + +1. **Setting the OCR language** to match your document. +2. **Loading the image correctly** so the engine sees the right pixels. +3. **Performing OCR on the image** with a single method call. +4. **Extracting text from the image** and confirming the result. +5. **Adding a custom dictionary** to lock in domain‑specific terms. + +That’s the entire workflow—from raw picture to clean, searchable text—wrapped up in a tidy, reusable script. + +If you’re ready for the next challenge, try experimenting with image pre‑processing (contrast, deskew) or switch to a multilingual setup using `ocr.Language.English | ocr.Language.German`. The same principles apply, and you’ll keep **improving OCR accuracy** across a broader set of documents. + +Got questions or a weird edge case? Drop a comment below, and happy coding! + +![improve OCR accuracy + + +## Vad du bör lära dig härnäst? + + +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. + +- [Extrahera text från bild – OCR‑optimering med Aspose.OCR för .NET](/ocr/english/net/ocr-optimization/) +- [igenkänn textbild med Aspose OCR för flera språk](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Hur man ställer in tröskelvärde i OCR‑bildigenkänning](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/swedish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..ae391e947 --- /dev/null +++ b/ocr/swedish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-19 +description: Utför OCR på bild med Pythons OCR‑bibliotek. Lär dig hur du upptäcker + text i en bild, känner igen text från JPEG och extraherar text från skannad bild + på ett effektivt sätt. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: sv +og_description: Utför OCR på bild med Python och extrahera text från skannade filer. + Den här guiden leder dig genom att ladda bilder, räta upp dem och känna igen text + steg för steg. +og_title: Utför OCR på bild i Python – Fullständig guide för textutdragning +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Utför OCR på bild i Python – Fullständig guide för textutdragning +url: /sv/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utför OCR på bild i Python – Fullständig guide för textutvinning + +Har du någonsin behövt **utföra OCR på bild**‑filer men fastnat eftersom koden såg kryptisk ut? Du är inte ensam. Oavsett om du omvandlar en hög med skannade kvitton till sökbara PDF‑filer eller drar ut bildtexter från en JPEG för ett data‑science‑projekt, är förmågan att känna igen text från JPEG‑filer och andra format ett måste för alla utvecklare idag. + +I den här handledningen går vi igenom ett komplett, körbart exempel som visar hur du **detekterar text från bild**‑filer, **extraherar text från skannad bild**‑dokument, och till och med **laddar bild för OCR** med bara några få rader kod. När du är klar har du ett robust, produktionsklart kodstycke som du kan klistra in i dina egna projekt – utan saknade imports, utan vaga “se docs”-genvägar. + +## Vad du kommer att bygga + +- Ett litet Python‑skript som skapar en OCR‑motor, aktiverar auto‑deskew, laddar en JPEG (eller något annat stödd format) och skriver ut den igenkända texten. +- Förklaringar till **varför** varje inställning är viktig, inte bara **hur** du skriver den. +- Tips för att hantera flersidiga PDF‑filer, icke‑engelska språk och vanliga fallgropar som suddiga skanningar. + +### Förutsättningar + +- Python 3.8+ installerat (exemplet använder paketet `ocr` som finns via `pip install ocr-lib` – byt ut mot ditt faktiska biblioteksnamn). +- Grundläggande kunskap om Python‑funktioner och virtuella miljöer. +- En bildfil (JPEG, PNG, TIFF) som du vill bearbeta; vi använder `skewed_page.jpg` som exempel. + +> **Proffstips:** Om du kör Windows, starta terminalen som administratör när du installerar OCR‑biblioteket för att undvika behörighetsproblem. + +--- + +## Utför OCR på bild – Installation och konfiguration + +Det första du behöver är en ren OCR‑motorinstans. Tänk på den som hjärnan bakom operationen; utan rätt konfiguration kommer även den skarpaste bilden att ge nonsens. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Varför detta är viktigt:** +Genom att sätta `engine.language` begränsar du teckenuppsättningen som OCR‑motorn förväntar sig, vilket dramatiskt ökar noggrannheten. Om du hoppar över detta kommer motorn att gissa, vilket ofta leder till felaktiga ord. + +--- + +## Aktivera automatisk deskew – Åtgärda snedvridna skanningar + +Skannade sidor är sällan helt plana. En liten lutning kan störa teckensegmenteringen och göra av “Hello” till “H3llo”. Flaggan `auto_deskew` sköter det tunga arbetet åt dig. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** Om du vet att dina bilder redan är raka kan du inaktivera deskew för att spara några millisekunder i behandlingstid – användbart när du hanterar tusentals sidor i ett batchjobb. + +--- + +## Ladda bild för OCR – Stöd för JPEG, PNG, TIFF + +Nu **laddar vi bild för OCR**. Metoden `ocr.Image.load` är flexibel; den accepterar en sökväg till vilket som helst stödd rasterformat. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Varför detta steg är avgörande:** Biblioteket läser in filen till en intern bitmap, och utför eventuell färgrymdskonvertering. Att hoppa över detta och skicka en rå byte‑ström skulle ge ett `FileNotFoundError` eller, ännu värre, tyst producera tomma resultat. + +Om du specifikt behöver **igenkänna text från JPEG**‑filer, se bara till att filändelsen är `.jpeg` eller `.jpg`. Samma anrop fungerar för PNG (`.png`) eller TIFF (`.tif`) utan ändring. + +--- + +## Utför OCR på bild – Kör motorn + +Med motorn förberedd och bilden i minnet är det dags att **utföra OCR på bild**‑data. Denna enda rad gör det tunga arbetet: förbehandling, segmentering, klassificering och textsammanställning. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Vad händer under huven?** +- Motorn applicerar deskew‑transformationen (om den är aktiverad). +- Den kör ett neuralt nätverk eller Tesseract‑backend för att identifiera tecken. +- Slutligen sys tecknen ihop till ord och rader, och ett rikt `result`‑objekt returneras. + +--- + +## Extrahera text från skannad bild – Visa resultaten + +Det sista steget är att **extrahera text från skannad bild** och visa den. Attributet `result.text` innehåller den rena textrepresentationen. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Typiskt utdata ser ut så här: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Om OCR‑motorn misslyckas med att hitta några tecken blir `result.text` en tom sträng. I så fall, dubbelkolla bildkvaliteten eller överväg att justera egenskapen `engine.confidence_threshold` (om ditt bibliotek stödjer det). + +--- + +## Hantera vanliga variationer + +### Igenkänna text från JPEG vs PNG + +Båda formaten stöds, men JPEG‑komprimering kan introducera artefakter som förvirrar motorn. Om du märker frekventa feligenkänningar, försök konvertera JPEG‑filen till PNG först: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Detektera text från bild med flera språk + +Om ditt dokument blandar engelska och spanska, sätt ett flerspråkigt läge: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Motorn kommer då att beakta båda alfabeten under igenkänning. + +### Extrahera text från skannade PDF‑filer + +För PDF‑filer måste du rasterisera varje sida till en bild först. Bibliotek som `pdf2image` gör detta enkelt: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Fullt fungerande exempel + +Nedan är det kompletta skriptet som du kan kopiera‑klistra in i en fil som heter `ocr_demo.py`. Det innehåller felhantering och en liten hjälpfunktion för att mäta körningstid. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Förväntat utdata** (förutsatt en klar skanning): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Vanliga frågor + +**Q: Kan jag köra detta på en huvudlös server?** +A: Absolut. Biblioteket fungerar utan ett GUI; se bara till att de nödvändiga inhemska binärerna (t.ex. Tesseract) är installerade på servern. + +**Q: Vad händer om bilden är suddig?** +A: Överväg att lägga till ett skärpande filter innan `engine.recognize`. Många OCR‑bibliotek exponerar `image_preprocessing.sharpen = True` eller så kan du använda OpenCV:s `cv2.GaussianBlur` i omvänd riktning. + +**Q: Stöder skriptet batch‑bearbetning?** +A: Ja. Wrappa `perform_ocr` i en loop över en lista med sökvägar, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/swedish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..0491494c5 --- /dev/null +++ b/ocr/swedish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-06-19 +description: Utför OCR på bild med Aspose OCR Java. Lär dig hur du laddar bild för + OCR, använder Aspose‑licens och extraherar text från bilden på några minuter. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: sv +og_description: Utför OCR på bild med Aspose OCR Java. Denna guide visar hur du använder + Aspose-licens, laddar bild för OCR och extraherar text från bilden effektivt. +og_title: Utför OCR på bild med Aspose OCR Java – Fullständig handledning +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Utför OCR på bild med Aspose OCR Java – Komplett steg‑för‑steg‑guide +url: /sv/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utför OCR på bild med Aspose OCR Java – Komplett steg‑för‑steg‑guide + +Har du någonsin behövt **perform OCR on image**‑filer men varit osäker på vilket bibliotek som ger pålitliga resultat utan en massa konfiguration? Du är inte ensam. I många verkliga projekt—tänk skanning av pass, digitalisering av fakturor eller extrahering av text från skärmbilder—är förmågan att snabbt känna igen text i bilddata en spelväxlare. + +I den här handledningen går vi igenom ett praktiskt exempel som visar exakt hur du **perform OCR on image** med Aspose OCR för Java. Vi täcker allt från att tillämpa din Aspose‑licens till att ladda bilden, köra motorn och slutligen **extract text from image** så att du kan använda den vidare. Inga onödiga detaljer, bara en fungerande lösning du kan kopiera‑klistra. + +## Vad du kommer att få med dig + +- En tydlig bild av hur du **use Aspose license** i ett Java‑projekt. +- Den exakta koden som behövs för att **load image for OCR** och låta motorn auto‑detektera språk. +- Steg‑för‑steg‑instruktioner för att **recognize text image**‑innehåll och **extract text from image** på ett säkert sätt. +- Tips för att hantera vanliga fallgropar (tomma resultat, format som inte stöds och minnesproblem). + +> **Förutsättningar** – Java 8 eller nyare, Maven eller Gradle för beroendehantering, och en Aspose OCR för Java‑licensfil (eller så kan du köra i utvärderingsläge). + +## Så utför du OCR på bild med Aspose OCR Java + +Nedan är det fullständiga, färdiga Java‑programmet som demonstrerar hela flödet. Spara det som `AsposeOcrDemo.java` och kör det från din IDE eller kommandorad. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Förväntad konsolutmatning + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Om du kör programmet utan en licensfil kommer den första raden bara att ange att du är i utvärderingsläge, men OCR‑funktionen fungerar ändå. + +## Konfigurera och använd Aspose‑licens + +### Varför en licens är viktig + +Att köra biblioteket i utvärderingsläge är okej för snabba tester, men det lägger till ett vattenmärke i resultatet och begränsar antalet sidor du kan bearbeta per körning. Att tillämpa steget **use aspose license** tar bort dessa begränsningar och signalerar till Aspose att du är en betalande kund. + +### Hur du skaffar och använder den + +1. Köp en licens från Aspose‑butiken. +2. Ladda ner filen `Aspose.OCR.Java.lic`. +3. Placera den någonstans där din applikation kan läsa den—vanligtvis i mappen `src/main/resources`. +4. Anropa `new License().setLicense("Aspose.OCR.Java.lic");` innan någon OCR‑arbete, som visas i koden ovan. + +> **Proffstips:** Om du distribuerar till en server, använd en absolut sökväg eller en class‑path‑resursladdare för att undvika `FileNotFoundException`. + +## Ladda bild för OCR‑bearbetning + +Raden `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` är kärnan i steget **load image for OCR**. Aspose OCR stödjer ett brett spektrum av format: PNG, JPEG, BMP, TIFF och även flersidiga PDF‑filer (när kombinerat med Aspose.Pdf). + +### Vanliga fallgropar + +| Problem | Symtom | Åtgärd | +|---------|--------|-------| +| Fel filväg | `FileNotFoundException` | Dubbelkolla sökvägen; använd `Paths.get(...)` för OS‑oberoende separatorer. | +| Format som inte stöds | `UnsupportedOperationException` | Konvertera bilden till PNG eller JPEG innan du laddar den. | +| Stor bild ( > 10 MP) | Out‑of‑memory‑fel | Skala ner bilden med `java.awt.Image` innan du skickar den till Aspose. | + +## Extrahera text från bild och hantera resultat + +När OCR‑motorn är klar innehåller `OcrResult`‑objektet den igenkända strängen. Här **extract text from image** för vidare bearbetning—spara till en databas, mata ett sökindex eller en efterföljande NLP‑pipeline. + +### Hantera flera språk + +Eftersom vi sätter `engine.setLanguage(Language.Auto)` kommer Aspose att försöka upptäcka språk i farten. Om du vet språket i förväg (t.ex. alla dokument är ryska) kan du ersätta `Language.Auto` med `Language.Russian` för en prestandaförbättring. + +### Tips för efterbehandling + +- **Trim whitespace**: `result.getText().trim()`. +- **Normalize line endings**: `result.getText().replace("\r\n", "\n")`. +- **Remove non‑printable characters**: use a regex like `result.getText().replaceAll("[^\\p{Print}]", "")`. + +## Känn igen text i bild med avancerade alternativ (valfritt) + +Om du behöver finare kontroll erbjuder Aspose OCR ytterligare egenskaper: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +## Sammanfattning av komplett fungerande exempel + +När allt sätts ihop gör det slutgiltiga programmet följande i ordning: + +1. **Perform OCR on image** – genom att skapa en `OcrEngine`. +2. **Use Aspose license** – valfritt men rekommenderat. +3. **Load image for OCR** – via `Image.load`. +4. **Set language detection** – `Language.Auto` för att **recognize text image** automatiskt. +5. **Extract text from image** – skriv ut resultatet och hantera tomma svar på ett smidigt sätt. + +Du kan kopiera kodblocket ovan direkt in i ett Maven‑projekt med detta beroende: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Kör `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` och se konsolen visa den igenkända texten. + +## Slutsats + +Vi har just visat dig hur du **perform OCR on image**‑filer med Aspose OCR för Java, från att tillämpa en licens till **loading the image for OCR**, **recognizing text image**‑innehåll och slutligen **extracting text from image** för vidare användning. Metoden är enkel, fungerar med flera språk direkt och kan utökas med avancerade förbehandlingsalternativ vid behov. + +Vad blir nästa steg? Prova att mata OCR‑utdata i ett sökindex, generera PDF‑filer med den extraherade texten eller experimentera med olika bildformat. Möjligheterna är oändliga, och med Asposes robusta API kommer du att spendera mer tid på att bygga funktioner än att kämpa med OCR‑detaljer. + +Har du frågor eller stöter på ett edge‑case? Lämna en kommentar nedan—lycka till med kodandet! + +## 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 implementeringsmetoder i dina egna projekt. + +- [Hur man extraherar text från bild från URL med Aspose.OCR för Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Konvertera bild till text i Java med Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extrahera text från bild Java med Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/thai/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..484865b75 --- /dev/null +++ b/ocr/thai/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-19 +description: สร้าง PDF ที่ค้นหาได้จากภาพโดยใช้ Python OCR. เรียนรู้วิธีแปลง OCR เป็น + PDF, ดึงข้อความจากภาพ, และทำ OCR บนภาพอย่างรวดเร็ว. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: th +og_description: สร้างไฟล์ PDF ที่ค้นหาได้จากภาพด้วย Python OCR คู่มือนี้แสดงวิธีแปลง + OCR เป็น PDF, ดึงข้อความจากภาพ, และทำ OCR บนภาพ. +og_title: สร้างไฟล์ PDF ที่ค้นหาได้ใน Python – คู่มือการเขียนโปรแกรมเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: สร้าง PDF ที่ค้นหาได้ใน Python – คู่มือขั้นตอนเต็มแบบครบถ้วน +url: /th/python-java/general/create-searchable-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 ที่ค้นหาได้ใน Python – คู่มือขั้นตอนเต็ม + +เคยต้องการ **สร้าง PDF ที่ค้นหาได้** จากใบเสร็จที่สแกน แต่ไม่แน่ใจว่าจะเริ่มต้นอย่างไรหรือไม่? คุณไม่ได้อยู่คนเดียว—นักพัฒนาหลายคนเจออุปสรรคเดียวกันเมื่อลองแปลงรูปภาพของข้อความเป็น PDF ที่คุณสามารถค้นหาได้จริง + +ในบทแนะนำนี้เราจะพาคุณผ่านโซลูชันเชิงปฏิบัติที่ทำให้คุณ **ทำ OCR บนภาพ**, แปลงผล OCR เป็น **PDF ที่ค้นหาได้**, และแม้กระทั่งดึงข้อความดิบออกมา หากคุณต้องการใช้ต่อในกระบวนการอื่น ๆ ไม่ต้องมีส่วนเกิน เพียงตัวอย่างทำงานที่คุณสามารถคัดลอก‑วางเข้าโปรเจกต์ของคุณได้ทันที + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีตั้งค่าเครื่อง OCR ที่มีน้ำหนักเบาใน Python +- ขั้นตอนที่แน่นอนเพื่อ **แปลง OCR เป็น PDF** และบันทึกเป็นเอกสารที่ค้นหาได้ +- วิธี **ดึงข้อความจากภาพ** เพื่อการวิเคราะห์ต่อไป +- เคล็ดลับการจัดการกับปัญหาทั่วไป เช่น การหมุนภาพและไฟล์ขนาดใหญ่ +- สคริปต์สมบูรณ์ที่สามารถรันได้และปรับใช้กับกรณีของคุณเอง + +### ข้อกำหนดเบื้องต้น + +- Python 3.8+ ติดตั้งบนเครื่องของคุณ +- ความคุ้นเคยพื้นฐานกับ pip และ virtual environment (ไม่บังคับแต่แนะนำ) +- ไฟล์ภาพ (PNG, JPEG, ฯลฯ) ที่มีข้อความที่อ่านได้ชัดเจน + +ถ้าคุณมีทั้งหมดนี้แล้ว ไปต่อกันเลย + +## ขั้นตอนที่ 1: ติดตั้งไลบรารีที่จำเป็น + +โค้ดสแนปที่คุณเห็นก่อนหน้านี้ใช้แพคเกจ `ocr` ที่เป็นตัวอย่างเท่านั้น แต่แนวคิดเดียวกันสามารถใช้กับไลบรารีจริงเช่น **EasyOCR**, **pytesseract**, หรือ **pdfminer.six** สำหรับคู่มือนี้เราจะใช้ **EasyOCR** เพราะเป็นไลบรารี pure Python รองรับหลายภาษา และมีเมธอดแปลงเป็น PDF ผ่านตัวช่วยเสริม + +```bash +pip install easyocr pillow +``` + +> **เคล็ดลับ:** ติดตั้งภายใน virtual environment (`python -m venv venv && source venv/bin/activate`) เพื่อให้การจัดการ dependencies เป็นระเบียบ + +## ขั้นตอนที่ 2: เริ่มต้นเครื่อง OCR – ทำ OCR บนภาพ + +เมื่อไลบรารีพร้อมแล้ว เราจะสร้าง engine OCR และบอกให้ทำงานกับข้อความภาษาอังกฤษ นี่คือจุดแรกที่เราจะ **ทำ OCR บนภาพ** + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +ทำไมต้องใช้วัตถุ reader แยก? EasyOCR โหลดโมเดลภาษาไว้ล่วงหน้า การใช้ `reader` เดียวกันสำหรับหลายภาพจึงมีประสิทธิภาพมากกว่าการสร้างใหม่ทุกครั้ง + +## ขั้นตอนที่ 3: โหลดภาพ – ดึงข้อความจากภาพ + +เราจะนำรูปภาพเข้ามาในหน่วยความจำ ขั้นตอนนี้คือจุดที่เราจะ **ดึงข้อความจากภาพ** ในภายหลัง แต่ตอนนี้เราจะเพียงแค่โหลดภาพเท่านั้น + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +หากภาพของคุณกลับหัวหรือเอียง ให้พิจารณาใช้เมธอด `rotate` หรือ `transpose` ของ Pillow ก่อนส่งให้ engine OCR การตรวจสอบภาพอย่างรวดเร็วจะช่วยประหยัดเวลาการดีบักหลายชั่วโมง + +## ขั้นตอนที่ 4: รันเครื่อง OCR และบันทึกผลลัพธ์ + +นี่คือหัวใจของกระบวนการ—ส่งภาพให้ engine OCR แล้วรับข้อมูลที่จัดโครงสร้างกลับมา + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +แฟล็ก `detail=1` จะให้ข้อมูล bounding box ซึ่งจำเป็นเมื่อเราต้อง **แปลง OCR เป็น PDF** หากคุณต้องการแค่สตริงดิบเท่านั้น ให้ตั้งค่า `detail=0` + +## ขั้นตอนที่ 5: แปลงผล OCR เป็น PDF ที่ค้นหาได้ – แปลง OCR เป็น PDF + +EasyOCR ไม่ได้มีเมธอดเขียน PDF โดยตรง แต่เราสามารถต่อ PDF เองโดยใช้ Pillow และไลบรารี `reportlab` เพื่อให้บทแนะนำนี้เบา เราจะใช้ `fpdf2` ซึ่งช่วยให้เราฝังภาพต้นฉบับและวางข้อความที่มองไม่เห็นลงบนภาพได้ + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +เกิดอะไรขึ้น? เราใส่ภาพสแกนเป็นเลเยอร์ที่มองเห็นได้ แล้วเขียนคำที่ OCR ตรวจจับได้บนด้านบนด้วยข้อความสีขาวที่ซ่อนอยู่ในพื้นหลังสีขาว เครื่องมือค้นหายังคงอ่านเลเยอร์ที่ซ่อนอยู่ ทำให้ PDF กลายเป็น **searchable** โดยไม่เปลี่ยนรูปลักษณ์ของภาพ + +## ขั้นตอนที่ 6: บันทึกไบต์ของ PDF – แปลงภาพเป็น PDF + +หากคุณต้องการจัดการ PDF ในหน่วยความจำ (เช่น ส่งผ่าน API) คุณสามารถดึงไบต์แทนการเขียนลงดิสก์ได้ + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +บรรทัดนี้แสดงการทำงานแบบคลาสสิกของ **convert image to PDF**: เริ่มจากภาพ, รัน OCR, วางข้อความ, แล้วส่งออกสตรีม PDF + +## ขั้นตอนที่ 7: ตรวจสอบผลลัพธ์ – ตรวจสอบอย่างรวดเร็ว + +หลังจากรันสคริปต์แล้ว เปิด `receipt_searchable.pdf` ด้วยโปรแกรมดู PDF ใดก็ได้และลองใช้ช่องค้นหา (Ctrl + F) พิมพ์คำที่คุณรู้ว่ามีในใบเสร็จ—ถ้าตำแหน่งกระโดดไปที่ตรงนั้น คุณได้ **สร้าง PDF ที่ค้นหาได้** สำเร็จ! + +หากการค้นหาไม่ทำงาน ให้ตรวจสอบสองอย่างต่อไปนี้: + +1. คะแนนความเชื่อมั่นของ OCR (`conf` values) คะแนนต่ำอาจหมายถึงภาพเบลอ +2. พิกัด bounding box—บางครั้ง EasyOCR รายงานในแนวทิศทางที่ต่างกัน +3. ตรวจสอบว่าโปรแกรมดู PDF ไม่ได้ตั้งเป็นโหมด “image‑only” (หายาก แต่บางโปรแกรมมีตัวเลือกนี้) + +## สคริปต์ทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือไฟล์ Python ที่พร้อมรันเต็มรูปแบบ: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +บันทึกไฟล์นี้เป็น `searchable_pdf.py` แทนที่ค่า `YOUR_DIRECTORY` ด้วยพาธจริงของคุณ แล้วรัน: + +```bash +python searchable_pdf.py +``` + +คุณจะเห็นข้อความยืนยันและ PDF ที่ค้นหาได้ใหม่ปรากฏในโฟลเดอร์ของคุณ + +## คำถามทั่วไปและกรณีขอบ + +**ถ้าภาพเป็นสีจะทำอย่างไร?** +EasyOCR รองรับทั้งภาพระดับสีเทาและสีเต็ม แต่การแปลงเป็นระดับสีเทา (`pil_image.convert("L")`) บางครั้งช่วยเพิ่มความแม่นยำบนสแกนที่มีเสียงรบกวน + +**ฉันสามารถจัดการกับ PDF หลายหน้าได้หรือไม่?** +ได้—วนลูปแต่ละหน้าภาพ, รันขั้นตอน OCR, แล้วเพิ่มแต่ละหน้าเข้าไปในอ็อบเจ็กต์ `FPDF` เดียวกัน เพียงจำไว้ว่าให้รีเซ็ตเคอร์เซอร์ (`self.add_page()`) สำหรับแต่ละภาพใหม่ + +**มีวิธีใส่เลเยอร์ข้อความต้นฉบับแทนการใช้ข้อความสีขาวที่มองไม่เห็นหรือไม่?** +หากต้องการ PDF “text‑under‑image” ที่แท้จริง (เช่น เพื่อการเข้าถึง) ให้พิจารณาใช้ `pdfminer` หรือ `pikepdf` เพื่อฝังเลเยอร์ข้อความที่ซ่อนอยู่พร้อมแท็ก PDF ที่เหมาะสม นี่เป็นขั้นตอนที่ซับซ้อนกว่า แต่หลักการยังคงเหมือนเดิม: ภาพพื้นหลัง + วางข้อความทับ + +**ถ้าความเชื่อมั่นของ OCR ต่ำควรทำอย่างไร?** +คุณสามารถกรองคำที่ความเชื่อมั่นต่ำออกได้: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## สรุป – สิ่งที่เราบรรลุ + +เราเริ่มจากภาพใบเสร็จง่าย ๆ, **ทำ OCR บนภาพ**, ดึงสตริงที่ตรวจจับได้, และสุดท้าย **สร้าง PDF ที่ค้นหาได้** ที่ทำงานเหมือนเอกสารสแกนระดับมืออาชีพ กระบวนการนี้ครอบคลุมคีย์เวิร์ดรองทุกคำ—**แปลง OCR เป็น PDF**, **ดึงข้อความจากภาพ**, **แปลงภาพเป็น PDF**, และ **ทำ OCR บนภาพ**—ดังนั้นคุณจึงมีเครื่องมือที่ใช้ซ้ำได้สำหรับโปรเจกต์ใด ๆ ที่คล้ายกัน + +### ขั้นตอนต่อไป + +- ทดลองใช้ภาษาอื่นโดยส่งรหัส ISO ไปยัง `easyocr.Reader(['en', 'es'])` +- เปลี่ยน EasyOCR เป็น Tesseract หากต้องการโซลูชันที่ทำงานแบบออฟไลน์ทั้งหมด; ส่วนของ pipeline จะยังคงเหมือนเดิม +- เพิ่มการแสดงผลความเชื่อมั่นของ OCR (วาด bounding box บนภาพ) เพื่อดีบักสแกนที่มีปัญหา + +มีไอเดียหรือวิธีที่คุณอยากแชร์ไหม? แสดงความคิดเห็นหรือ fork โปรเจกต์ + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/thai/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/thai/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..c5af2d315 --- /dev/null +++ b/ocr/thai/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-19 +description: ดึงข้อความจากรูปภาพใน Python ด้วยเครื่องมือ OCR อย่างง่าย เรียนรู้วิธีแปลงรูปสแกนเป็นข้อความ + จดจำข้อความจากรูปภาพ และแสดงรายการไฟล์รูปภาพใน Python อย่างมีประสิทธิภาพ +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: th +og_description: ดึงข้อความจากรูปภาพใน Python ด้วยเครื่องมือ OCR ที่มีน้ำหนักเบา คู่มือนี้จะแสดงวิธีแปลงรูปสแกนเป็นข้อความ, + จดจำข้อความจากภาพ, และแสดงรายการไฟล์รูปภาพใน Python เพียงไม่กี่ขั้นตอน. +og_title: ดึงข้อความจากรูปภาพใน Python – คู่มือ OCR แบบเต็มชุด +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: สกัดข้อความจากรูปภาพด้วย Python – คู่มือ OCR แบบเต็มชุด +url: /th/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดึงข้อความจากรูปภาพใน Python – คู่มือ OCR แบบชุดเต็ม + +เคยต้อง **ดึงข้อความจากรูปภาพ** แต่ไม่รู้จะเริ่มต้นอย่างไรหรือไม่? คุณไม่ได้เป็นคนเดียว—นักพัฒนาต่าง ๆ มักเผชิญกับความท้าทายในการแปลง PDF ที่สแกน, ใบเสร็จที่ถ่ายรูป, หรือภาพหน้าจอให้เป็นข้อความที่ค้นหาได้ ในบทเรียนนี้เราจะเดินผ่านตัวอย่างที่พร้อมรันเต็มรูปแบบที่แสดงวิธี **แปลงภาพสแกนเป็นข้อความ**, จดจำข้อความจากรูปภาพ, และแม้กระทั่ง **list image files python**‑style. เมื่อเสร็จสิ้นคุณจะได้สคริปต์ที่นำกลับมาใช้ใหม่ได้ซึ่งประมวลผลโฟลเดอร์ทั้งหมดในครั้งเดียว + +เราจะครอบคลุมทุกอย่างที่คุณต้องการ: ไลบรารีที่จำเป็น, เหตุผลที่แต่ละขั้นตอนสำคัญ, การจัดการกรณีขอบ, และเคล็ดลับการแก้ปัญหา ไม่ต้องไล่ตามเอกสารภายนอก; โค้ดด้านล่างเป็นอิสระและคำอธิบายตอบทั้ง “อย่างไร” *และ* “ทำไม”. เปิด IDE ที่คุณชอบแล้วเริ่มกันเลย + +--- + +## สิ่งที่คุณจะสร้าง + +- เริ่มต้นเครื่อง OCR (เราจะใช้แพ็กเกจ `ocr` เป็นตัวอย่าง) +- สแกนไดเรกทอรีและ **list image files python**‑style, กรอง PNG, JPG, และ TIFF +- รันการทำ **batch OCR** บนรูปภาพทั้งหมดที่พบ +- พิมพ์ข้อความที่ดึงได้สำหรับแต่ละไฟล์พร้อมป้ายกำกับชัดเจน + +> **เคล็ดลับมืออาชีพ:** หากคุณยังไม่ได้ติดตั้งไลบรารี `ocr` คุณสามารถสลับเป็น `pytesseract` ด้วยการเปลี่ยนแปลงเล็กน้อย—ตรรกะหลักยังคงเหมือนเดิม + +--- + +## ข้อกำหนดเบื้องต้น + +- Python 3.8+ (สคริปต์ใช้ f‑strings และ type hints) +- ไลบรารี OCR ที่เปิดเผย `OcrEngine` พร้อมเมธอด `recognize_batch` สำหรับคู่มือนี้เราจะสมมติว่าใช้แพ็กเกจ `ocr` แต่วิธีการนี้ใช้ได้กับไลบรารีจริงเช่นกัน +- โฟลเดอร์ที่มีไฟล์รูปภาพที่ต้องการประมวลผล (`.png`, `.jpg`, `.tif`) + +--- + +## ขั้นตอนที่ 1 – ติดตั้งและนำเข้าโมดูลที่จำเป็น + +ก่อนอื่นให้แน่ใจว่าแพ็กเกจ OCR พร้อมใช้งาน หากคุณใช้ไลบรารีจริงเช่น `pytesseract` ให้เปลี่ยนการนำเข้าให้สอดคล้อง + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **ทำไมจึงสำคัญ:** การนำเข้า `os` ทำให้เราจัดการเส้นทางแบบข้ามแพลตฟอร์มได้, ส่วน `typing.List` ช่วยให้ IDE แนะนำโค้ดและทำให้โค้ดพร้อมสำหรับอนาคต + +--- + +## ขั้นตอนที่ 2 – **Extract Text from Images**: เริ่มต้นเครื่อง OCR + +การสร้างเอนจินเป็นขั้นตอนแรกของงาน OCR ใด ๆ เรายังตั้งค่าภาษาให้ตรวจจับอัตโนมัติเพื่อให้เอนจินจัดการกับเอกสารหลายภาษาได้ + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **คำอธิบาย:** การห่อหุ้มการสร้างเอนจินในฟังก์ชันทำให้โค้ดเป็นโมดูลาร์ หากคุณต้องการปรับ DPI หรือโหมด OCR ในภายหลัง เพียงแก้ไขส่วนนี้เท่านั้น + +--- + +## ขั้นตอนที่ 3 – **List Image Files Python**: รวบรวมไฟล์จากไดเรกทอรี + +ตอนนี้เราต้องหาภาพทุกไฟล์ที่ต้องการประมวลผล รายการเชิงความเข้าใจด้านล่างเป็นรูปแบบ “list image files python” ที่พบบ่อย + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **การจัดการกรณีขอบ:** ฟังก์ชันนี้ละเว้นโฟลเดอร์ย่อย (คุณสามารถเพิ่มการทำซ้ำในภายหลัง) และกรองไฟล์ที่ซ่อนโดยอัตโนมัติ เนื่องจากไฟล์เหล่านั้นมักไม่มีนามสกุลที่รองรับ + +--- + +## ขั้นตอนที่ 4 – **Convert Scanned Images to Text**: รัน Batch OCR + +ไลบรารี OCR ส่วนใหญ่มีเมธอด batch ที่เร็วกว่าเมื่อประมวลผลทีละภาพ นี่คือวิธีเรียกใช้ + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **ทำไมต้อง batch?** การส่งรูปภาพทั้งหมดพร้อมกันลดค่าโอเวอร์เฮด (เช่น การโหลดโมเดล OCR ซ้ำหลายครั้ง) และมักทำให้การใช้ CPU/GPU มีประสิทธิภาพมากขึ้น + +--- + +## ขั้นตอนที่ 5 – **Recognize Text from Pictures**: แสดงผลลัพธ์ + +สุดท้าย เราวนลูปผ่านชื่อไฟล์และผล OCR คู่กัน แล้วพิมพ์หัวข้อที่สะอาดสำหรับแต่ละรูป + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **เคล็ดลับ:** `strip()` ลบช่องว่างต้นและท้ายที่ OCR มักเพิ่มเข้ามา + +--- + +## สคริปต์เต็ม – รวมทุกอย่างไว้ด้วยกัน + +ด้านล่างเป็นโปรแกรมที่สมบูรณ์และสามารถรันได้ บันทึกเป็น `batch_ocr.py` แล้วรัน `python batch_ocr.py ` + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### ผลลัพธ์ที่คาดหวัง + +สมมติว่าโฟลเดอร์มี `invoice1.png` และ `receipt.jpg` คุณอาจเห็น: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +แต่ละบล็อกจะมีป้ายกำกับชัดเจน ทำให้การประมวลผลต่อไป (เช่น การบันทึกลงฐานข้อมูล) ง่ายดาย + +--- + +## การจัดการกับปัญหาที่พบบ่อย + +| ปัญหา | ทำไมเกิดขึ้น | วิธีแก้เร็ว | +|-------|--------------|------------| +| **ไม่มีข้อความปรากฏ** | ภาษา OCR ไม่ถูกตรวจจับหรือภาพมีคอนทราสต์ต่ำ | บังคับใช้ภาษา (`engine.language = ocr.Language.English`) หรือทำการปรับภาพล่วงหน้า (เพิ่มคอนทราสต์) | +| **Memory error เมื่อประมวลผลชุดใหญ่** | เอนจินพยายามโหลดภาพทั้งหมดพร้อมกัน | แบ่ง `image_files` เป็นชิ้นย่อย (`batch_size = 20`) แล้วเรียก `recognize_batch` หลายครั้ง | +| **ไฟล์ฟอร์แมตไม่รองรับ** | คุณใส่ `.gif` หรือ `.bmp` | ขยายทูเพิล `supported_exts` หรือแปลงภาพเป็น PNG/JPG ก่อน | +| **Unicode garbling** | OCR คืนค่าเป็นไบต์แทนสตริง | ตรวจสอบให้ไลบรารี OCR ส่งออก Unicode (`result.text.decode('utf‑8')` หากจำเป็น) | + +--- + +## การขยายเวิร์กโฟลว์ + +เมื่อคุณ **extract text from images** แล้ว ลองทำขั้นตอนต่อไปเหล่านี้: + +- **Export to CSV** – เขียนชื่อไฟล์และข้อความที่ดึงได้ลงสเปรดชีตเพื่อวิเคราะห์ +- **Parallel processing** – ใช้ `concurrent.futures.ThreadPoolExecutor` เพื่อจัดการหลาย batch พร้อมกัน +- **Integrate with cloud OCR** – สลับเอนจินโลคัลเป็น Google Vision หรือ Azure OCR เพื่อความแม่นยำสูงกับเลเอาต์ซับซ้อน +- **Add image preprocessing** – ไลบรารีอย่าง Pillow หรือ OpenCV สามารถทำ deskew, denoise, หรือ threshold ภาพก่อน OCR เพื่อเพิ่มผลลัพธ์ + +แนวคิดทั้งหมดนี้ใช้ฟังก์ชันหลักที่เราสร้างไว้แล้ว จึงไม่ต้องเริ่มจากศูนย์ + +--- + +## สรุป + +เราได้เดินผ่านโซลูชันเต็มรูปแบบเพื่อ **extract text from images** ใน Python ครอบคลุมตั้งแต่ **list image files python** ถึง **recognize text from pictures** และสุดท้าย **convert scanned images to text** แบบ batch สคริปต์นี้ออกแบบให้เรียบง่ายแต่ยืดหยุ่นพอที่จะเป็นฐานสำหรับโปรเจกต์ขนาดใหญ่—ไม่ว่าจะเป็นการดิจิไทซ์ใบเสร็จ, สร้างคลังข้อมูลที่ค้นหาได้, หรือขับเคลื่อน pipeline การสกัดข้อมูล + +ลองใช้งาน ปรับขั้นตอนการพรี‑โปรเซส แล้วดูความแม่นยำของ OCR เพิ่มขึ้น หากเจออุปสรรค ให้กลับไปดูตาราง “การจัดการกับปัญหาที่พบบ่อย” ส่วนใหญ่แก้ได้ด้วยการปรับค่าเล็กน้อย + +พร้อมสำหรับความท้าทายต่อไปหรือยัง? ลองเพิ่มขั้นตอนแปลง PDF‑to‑image ด้วย `pdf2image` แล้วส่งภาพเหล่านั้นเข้าสู่ pipeline เดียวกัน ความเป็นไปได้ไม่มีที่สิ้นสุดเมื่อคุณผสาน OCR กับอีโคซิสเต็มของ Python + +Happy coding, and may your text be ever legible! + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ 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 Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/thai/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..e50f4e940 --- /dev/null +++ b/ocr/thai/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: ดึงข้อความจากรูปภาพด้วย Python OCR. เรียนรู้การตรวจจับภาษาที่อัตโนมัติ + การประมวลผลแบบขนาน และการรับรู้แบบชุดในบทเรียนสั้น ๆ. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: th +og_description: ดึงข้อความจากรูปภาพด้วย Python OCR. คู่มือนี้แสดงการตรวจจับภาษาอัตโนมัติ, + การประมวลผลแบบขนาน, และการรับรู้แบบชุดในบทเรียนเดียว. +og_title: ดึงข้อความจากรูปภาพใน Python – คู่มือ OCR เต็ม +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: สกัดข้อความจากรูปภาพใน Python – คู่มือ OCR ฉบับเต็ม +url: /th/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดึงข้อความจากรูปภาพใน Python – คู่มือ OCR ฉบับเต็ม + +เคยสงสัยไหมว่าจะแยก **extract text from images** อย่างไรโดยไม่ต้องพิมพ์ทุกคำด้วยตนเอง? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะกำลังดิจิไทซ์ใบเสร็จเก่า, สร้างคลังเอกสารที่ค้นหาได้, หรือแค่เล่นกับเทคนิค AI ที่เจ๋ง ความสามารถในการดึงข้อความจากรูปภาพเป็นทักษะที่จำเป็นสำหรับนักพัฒนา Python ทุกคนในวันนี้. + +ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่างที่สมบูรณ์และพร้อมรันที่ **extracts text from images** ด้วยเครื่องมือ OCR ยอดนิยม เราจะครอบคลุมการตรวจจับภาษาอัตโนมัติ, การประมวลผลแบบขนานเพื่อความเร็ว, และการจดจำภาพแบบแบตช์ เพื่อให้คุณจัดการกับหลายสิบไฟล์ในไม่กี่วินาที ฟังดูตรงกับความต้องการของคุณหรือไม่? มาเริ่มกันเลย. + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีสร้างอินสแตนซ์ของ OCR engine ด้วย `ocr.OcrEngine`. +- เปิดใช้งาน **automatic language detection** เพื่อให้ engine เลือกภาษาที่ถูกต้องโดยอัตโนมัติ. +- กำหนดค่า **parallel processing OCR** ด้วย thread pool ที่กำหนดเอง. +- รัน **batch image recognition** บนรายการไฟล์. +- พิมพ์ข้อความที่จดจำได้สำหรับแต่ละภาพ, พร้อมสำหรับการบันทึกหรือทำดัชนี. + +ไม่ต้องอ้างอิงเอกสารภายนอก—ทุกอย่างที่คุณต้องการอยู่ที่นี่แล้ว, และโค้ดทำงานได้ทันทีด้วยแพคเกจ `ocr` (ติดตั้งโดยใช้ `pip install ocr`). + +## ข้อกำหนดเบื้องต้น + +ก่อนเริ่ม, ตรวจสอบว่าคุณมี: + +1. Python 3.8 หรือใหม่กว่า +2. `ocr` package (`pip install ocr`) +3. โฟลเดอร์ที่มีรูปภาพ PNG (หรือ JPG) ที่ต้องการประมวลผล +4. ความคุ้นเคยพื้นฐานกับฟังก์ชันและลูปของ Python + +เท่านี้—ไม่มีการพึ่งพาที่ซับซ้อน, ไม่มีการใช้ GPU, เพียงแค่ Python ธรรมดา. + +![ตัวอย่างการดึงข้อความจากรูปภาพ](https://example.com/ocr-demo.png "ภาพหน้าจอแสดงผลลัพธ์การดึงข้อความจากรูปภาพ") + +*ข้อความแทน: ภาพสาธิตการดึงข้อความจากรูปภาพ* + +## ขั้นตอนที่ 1 – ตั้งค่า OCR Engine (คีย์เวิร์ดหลักในแอคชัน) + +อันดับแรก: สร้างอินสแตนซ์ของ OCR engine. คิดว่า `ocr.OcrEngine()` เป็นสมองของการทำงาน; มันรู้วิธีอ่านอักขระ, บรรทัด, และย่อหน้า. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +ทำไมเราต้องการ engine ที่กำหนดเอง? เพราะการใช้ **ocr.OcrEngine usage** ให้คุณควบคุมการตั้งค่าภาษา, การทำงานหลายเธรด, และอื่น ๆ อย่างละเอียด มันเป็นวิธีที่ยืดหยุ่นที่สุดในการ **extract text from images** เมื่อเทียบกับฟังก์ชันหนึ่งบรรทัด. + +## ขั้นตอนที่ 2 – ให้ Engine ตรวจจับภาษาด้วยตนเอง + +ไลบรารี OCR ส่วนใหญ่ต้องการให้คุณระบุภาษาที่ต้องการค้นหา ซึ่งเหมาะกับโครงการที่ใช้ภาษาเดียว แต่ทำให้ยุ่งยากสำหรับแบตช์ที่มีหลายภาษา โชคดีที่แพคเกจ `ocr` รองรับ **automatic language detection**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +การตั้งค่า `engine.language` เป็น `ocr.Language.Auto` จะบอก engine ให้ตรวจสอบแต่ละภาพและเลือกโมเดลภาษาที่เหมาะสม บรรทัดเล็ก ๆ นี้ช่วยคุณประหยัดเวลาการตั้งค่าด้วยตนเองหลายชั่วโมงเมื่อทำงานกับเอกสารระหว่างประเทศ. + +## ขั้นตอนที่ 3 – เร่งความเร็วด้วย Parallel Processing OCR + +หากคุณมีคอร์ CPU สี่คอร์หรือมากกว่า ทำไมไม่ใช้มัน? Engine สามารถสร้าง thread pool เพื่อให้หลายภาพถูกประมวลผลพร้อมกัน นี่คือจุดเด่นของ **parallel processing OCR**. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +คุณสามารถปรับจำนวน `4` ตามเครื่องของคุณได้ จำนวนเธรดที่มากขึ้น → การรันแบตช์ที่เร็วขึ้น, แต่จำไว้ว่าทุกเธรดใช้หน่วยความจำ, ดังนั้นหาจุดที่เหมาะสมสำหรับสภาพแวดล้อมของคุณ. + +## ขั้นตอนที่ 4 – รวบรวมรูปภาพที่ต้องการประมวลผล + +ตอนนี้เราต้องการรายการเส้นทางไฟล์ คุณสามารถสร้างรายการนี้ด้วยตนเอง, อ่านจาก CSV, หรือใช้ `glob`. เพื่อความชัดเจน เราจะกำหนดรายการสั้น ๆ ด้วยการเขียนโค้ดตรง: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +แทนที่ `YOUR_DIRECTORY` ด้วยเส้นทางจริงบนระบบของคุณ หากคุณมีหลายสิบไฟล์, การใช้ `glob.glob("*.png")` อย่างรวดเร็วจะทำงานหนักให้คุณ. + +## ขั้นตอนที่ 5 – รัน Batch Image Recognition + +นี่คือหัวใจของบทแนะนำ: การเรียกเดียวที่ประมวลผลทุกภาพใน `files` และคืนรายการอ็อบเจ็กต์ผลลัพธ์ นี่คือฟีเจอร์ **batch image recognition** ที่ทำให้ OCR ขนาดใหญ่เป็นไปได้จริง. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +เบื้องหลัง, engine จะกระจายไฟล์แต่ละไฟล์ไปยังสี่เธรดทำงานที่เราตั้งค่าไว้ก่อนหน้า, พร้อมกับตรวจจับภาษาของแต่ละภาพโดยอัตโนมัติ วิธีนี้คืนรายการที่แต่ละองค์ประกอบเก็บข้อความที่จดจำได้และเมตาดาต้า. + +## ขั้นตอนที่ 6 – พิมพ์ (หรือบันทึก) ข้อความที่ดึงออกมา + +สุดท้าย, เราจะวนลูปผลลัพธ์และพิมพ์ข้อความ ในโครงการจริงคุณอาจบันทึกลงฐานข้อมูลหรือไฟล์ CSV, แต่การพิมพ์ทำให้ตัวอย่างง่ายขึ้น. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**ผลลัพธ์ที่คาดหวัง** (ตัดทอนเพื่อความกระชับ): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +แต่ละบล็อกจะแสดงชื่อไฟล์ตามด้วยสตริงที่ได้จาก OCR หากภาพมีหลายภาษา, คุณจะเห็นอักขระที่เหมาะสมปรากฏขึ้นเนื่องจากขั้นตอน **automatic language detection** ก่อนหน้า. + +## เคล็ดลับระดับมืออาชีพ & จุดบกพร่องทั่วไป + +- **Image quality matters** – รูปภาพที่เบลอหรือคอนทราสต์ต่ำจะให้ผลลัพธ์เป็นขยะ. เตรียมการล่วงหน้าด้วย OpenCV (`cv2.threshold`, `cv2.resize`) หากจำเป็น. +- **Thread count vs. I/O** – หากรูปภาพของคุณอยู่บนไดรฟ์เครือข่ายที่ช้า, การเพิ่มจำนวนเธรดอาจไม่ช่วย. คอยตรวจสอบการใช้ CPU ด้วย `top` หรือ `Task Manager`. +- **Unicode handling** – `result.text` เป็นสตริง Unicode. เมื่อเขียนไฟล์, เปิดด้วย `encoding="utf‑8"` เพื่อหลีกเลี่ยง `UnicodeEncodeError`s. +- **Memory usage** – PDF ขนาดใหญ่สามารถใช้ RAM มาก. หากเจอ `MemoryError`, ลดขนาด thread pool หรือประมวลผลภาพเป็นชิ้นเล็ก ๆ. + +## สคริปต์ทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์ที่พร้อมคัดลอกและวางครบถ้วนซึ่งรวมทุกขั้นตอนที่เราอธิบายไว้. บันทึกเป็น `batch_ocr.py` และรัน `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +รันโดยใช้คำสั่งดังนี้: + +```bash +python batch_ocr.py ./my_images 4 +``` + +คุณจะเห็นบล็อกข้อความที่จัดรูปแบบอย่างสวยงามสำหรับแต่ละภาพ, แสดงให้เห็นว่าคุณสามารถ **extract text from images** ในระดับใหญ่ได้. + +## ขั้นตอนต่อไปคืออะไร? + +เมื่อคุณเชี่ยวชาญพื้นฐานของ **extract text from images** ด้วย Python แล้ว, ลองสำรวจต่อไปนี้: + +- **Post‑processing**: ทำความสะอาดผลลัพธ์ OCR ด้วย regex หรือไลบรารีประมวลผลภาษาธรรมชาติ. +- **PDF conversion**: ส่งสตริงที่ดึงออกไปยังตัวสร้าง PDF เพื่อสร้าง PDF ที่ค้นหาได้. +- **Cloud OCR services**: เปรียบเทียบผลลัพธ์ `ocr` ภายในเครื่องกับ Google Vision หรือ Azure OCR เพื่อความแม่นยำในกรณีพิเศษ. +- **GUI front‑end**: สร้างแอป Flask หรือ FastAPI ขนาดเล็กที่ให้ผู้ใช้อัปโหลดรูปภาพและดูข้อความที่ดึงออกได้ทันที. + +แต่ละหัวข้อเหล่านี้ต่อยอดจากพื้นฐาน **Python OCR library** ที่คุณตั้งค่าไว้, และทั้งหมดจะได้ประโยชน์จากเทคนิค **parallel processing 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/) +- [ดึงข้อความจากรูปภาพ – การปรับแต่ง 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/thai/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/thai/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..b4aee7f2f --- /dev/null +++ b/ocr/thai/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-19 +description: วิธีดึงข้อมูลจาก PDF ด้วย OCR ใน Python – บทเรียนทีละขั้นตอนที่ครอบคลุมการดึงข้อความจาก + PDF, การจดจำข้อความจากภาพ, และตัวอย่าง OCR ด้วย Python +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: th +og_description: วิธีดึงข้อมูลจาก PDF ด้วย OCR ใน Python. เรียนรู้การดึงข้อความจาก + PDF, การจดจำข้อความจากภาพ, และดูตัวอย่าง OCR ด้วย Python อย่างครบถ้วน. +og_title: วิธีดึงข้อความจาก PDF ด้วย OCR ใน Python – คำแนะนำเต็ม +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: วิธีดึงข้อความจาก PDF ด้วย OCR ใน Python – คู่มือฉบับสมบูรณ์ +url: /th/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีดึงข้อความจาก PDF ด้วย OCR ใน Python – คู่มือฉบับสมบูรณ์ + +เคยสงสัย **วิธีดึงข้อความจาก PDF** เมื่อไฟล์เป็นเพียงภาพสแกนหรือไม่? คุณไม่ได้เป็นคนเดียว ในหลายโครงการจริง—เช่น สัญญา ใบแจ้งหนี้ หรือเอกสารประวัติศาสตร์—PDF ที่คุณได้รับไม่มีข้อความที่เลือกได้ ข่าวดีคือ? เพียงไม่กี่บรรทัดของ Python ก็สามารถเปลี่ยนหน้าที่เป็นภาพอย่างเดียวให้กลายเป็นข้อความที่ค้นหาและแก้ไขได้ + +ในบทเรียนนี้เราจะเดินผ่าน **ตัวอย่าง OCR Python** ที่อ่าน PDF, แปลงหน้าหนึ่งเป็นภาพ, แล้ว **ดึงข้อความจาก PDF** ด้วยเครื่องมือ OCR. เมื่อจบคุณจะรู้วิธี **อ่าน PDF ด้วย OCR** อย่างแม่นยำ ทำไมขั้นตอนแต่ละขั้นตอนสำคัญ และจะปรับโค้ดให้รองรับเอกสารหลายหน้า หรือหลายภาษาอย่างไร + +## สิ่งที่คุณจะได้เรียน + +- ติดตั้งและตั้งค่าไลบรารี OCR ที่เชื่อถือได้สำหรับ Python +- แปลงหน้าของ PDF เป็นภาพที่เหมาะกับ OCR +- **จดจำข้อความจากภาพ** และรับสตริง Unicode ที่สะอาด +- ปัญหาที่พบบ่อย (PDF ความละเอียดต่ำ, หน้าเอียง) และวิธีหลีกเลี่ยง +- ขยายสคริปต์เพื่อจัดการหลายหน้า หรือประมวลผลเป็นชุด + +**ข้อกำหนดเบื้องต้น**: Python 3.8+, pip, และความเข้าใจพื้นฐานเกี่ยวกับ virtual environment ไม่จำเป็นต้องมีประสบการณ์ OCR มาก่อน—เพียงทำตามขั้นตอน + +--- + +## ## วิธีดึงข้อความจาก PDF ด้วย OCR ใน Python + +หัวข้อ H2 นี้มีคีย์เวิร์ดหลักของเราตรงที่เครื่องมือค้นหาชอบเห็น ไปดิ่งสู่โค้ดกันเลย + +### ขั้นตอนที่ 1 – ติดตั้งแพ็กเกจที่จำเป็น + +ก่อนอื่นเราต้องมีเครื่องมือ OCR ตัวอย่างด้านล่างใช้แพ็กเกจ **ocr** ที่เป็น wrapper บาง ๆ ของ Tesseract หากคุณชอบ backend อื่น แนวคิดยังคงเหมือนเดิม + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **เคล็ดลับ:** บน Linux คุณยังต้องติดตั้งไบนารีของ Tesseract ด้วย: `sudo apt-get install tesseract-ocr` ผู้ใช้ macOS สามารถติดตั้งผ่าน Homebrew: `brew install tesseract` + +### ขั้นตอนที่ 2 – เริ่มต้นเครื่องมือ OCR และกำหนดภาษา + +ตอนนี้เราจะสตาร์ท engine และบอกให้มองหาตัวอักษรภาษาอังกฤษ คุณสามารถสลับ `ocr.Language.English` ไปเป็นโค้ดภาษาที่รองรับอื่นได้ + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**ทำไมขั้นตอนนี้สำคัญ:** การระบุภาษาอย่างชัดเจนช่วยเพิ่มความแม่นยำอย่างมาก เพราะ engine สามารถใช้พจนานุกรมและโมเดลอักขระเฉพาะภาษา + +### ขั้นตอนที่ 3 – โหลดหน้า PDF เป็นภาพ + +OCR ทำงานกับภาพ raster ไม่ใช่วัตถุ PDF `ocr.Image.from_pdf` helper จะเรนเดอร์หน้าที่เลือกเป็นบิตแมพ ปรับ `page_number` เพื่อเลือกหน้าอื่น (เริ่มจาก 0) + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **กรณีขอบ:** หาก PDF มีกราฟิกเวกเตอร์แทนภาพสแกน คุณอาจได้การเรนเดอร์ที่คมชัด สำหรับสแกนความละเอียดต่ำ ให้เพิ่ม DPI: `ocr.Image.from_pdf(..., dpi=300)` + +### ขั้นตอนที่ 4 – จดจำข้อความจากภาพที่เรนเดอร์แล้ว + +นี่คือหัวใจของ **ocr python example** engine จะประมวลผลบิตแมพและคืนอ็อบเจกต์ที่มีสตริงที่ดึงออกมา + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +แอตทริบิวต์ `ocr_result.text` จะเก็บผลลัพธ์เป็น plain‑text พร้อมรักษาการขึ้นบรรทัดเมื่อเป็นไปได้ + +### ขั้นตอนที่ 5 – พิมพ์หรือบันทึกข้อความที่ดึงได้ + +สุดท้ายเราจะแสดงผลลัพธ์ ในแอปพลิเคชันจริงคุณอาจเขียนลงไฟล์หรือฐานข้อมูล + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +การรันสคริปต์ควรแสดงผลประมาณนี้: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +นี่คือเวิร์กโฟลว์ **extract text from pdf** แบบครบวงจรด้วย OCR + +--- + +## ## จดจำข้อความจากภาพ – ปรับความแม่นยำ + +หากคุณสนใจเพียง **จดจำข้อความจากภาพ** (เช่น JPEG ของใบเสร็จ) คุณสามารถข้ามขั้นตอนแปลง PDF ได้: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**เคล็ดลับเพื่อผลลัพธ์ที่ดีกว่า:** + +- **Pre‑process** ภาพ: แปลงเป็น grayscale, ใช้ thresholding, หรือ deskew. Pillow ทำได้ง่าย +- **Increase DPI** ระหว่างการเรนเดอร์ PDF: ความละเอียดสูงให้รายละเอียดมากขึ้นกับ OCR engine +- **Enable OCR engine’s config** สำหรับการแบ่งหน้า (`ocr_engine.config = "--psm 6"` สำหรับบล็อกที่สม่ำเสมอ) + +--- + +## ## อ่าน PDF ด้วย OCR – จัดการหลายหน้า + +สัญญาส่วนใหญ่มีหลายหน้า การวนลูปแต่ละหน้าเป็นเรื่องง่าย: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +ฟังก์ชันนี้ **reads PDF with OCR**, รวมผลลัพธ์เข้าด้วยกันและแทรกเครื่องหมายแบ่งหน้าอย่างชัดเจน จากนั้นคุณสามารถส่ง `full_text` ไปยังดัชนีการค้นหา หรือบันทึกเป็นไฟล์ `.txt` + +--- + +## ## ปัญหาที่พบบ่อยและวิธีแก้ + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| ตัวอักษรแปลก ๆ, มี `?` มาก | ภาษาไม่ถูกต้องหรือไม่มีไฟล์ข้อมูลภาษา | ติดตั้งแพ็ก Tesseract ภาษาที่ตรง (`tesseract-ocr-`) และตั้ง `ocr_engine.language` | +| ขาดบรรทัดหรือคำตัด | DPI ต่ำ (ต่ำกว่า 150) | เรนเดอร์ PDF ที่ 300 DPI หรือสูงกว่า (`dpi=300`) | +| ข้อความเอียงหรือหัวกลับ | หน้าสแกนไม่อยู่ในแนวตั้ง | ใช้ `ocr.Image.deskew(page_image)` ก่อนจดจำ | +| ประมวลผลช้าใน PDF ขนาดใหญ่ | ประมวลผลหน้าแบบต่อเนื่องในเธรดเดียว | ทำ parallel ด้วย `concurrent.futures.ThreadPoolExecutor` | + +--- + +## ## ขยายตัวอย่าง OCR Python + +- **Export to PDF/A**: หลังจากดึงข้อความแล้ว คุณสามารถฝังข้อความกลับเข้า PDF ที่ค้นหาได้ด้วย `reportlab` หรือ `pypdf2` +- **ตรวจจับภาษา**: ใช้ `langdetect` กับผลลัพธ์ OCR เพื่อสลับ `ocr_engine.language` แบบไดนามิก +- **ประมวลผลเป็นชุด**: เดินสำรวจโฟลเดอร์ด้วย `os.listdir` แล้วเรียก `extract_all_pages` กับทุกไฟล์ + +--- + +## ## ผลลัพธ์ที่คาดหวังและการตรวจสอบ + +เมื่อคุณรันสคริปต์กับสแกนภาษาอังกฤษที่ชัดเจน ควรเห็นบล็อกข้อความที่สะอาดและมีเครื่องหมายวรรคตอนที่ถูกต้อง ตรวจสอบโดย: + +1. เปรียบเทียบบรรทัดบางบรรทัดกับภาพสแกนต้นฉบับ +2. รันการนับคำง่าย ๆ (`len(ocr_result.text.split())`) เพื่อให้แน่ใจว่าผลลัพธ์ไม่ว่างเปล่า +3. ทางเลือก, ส่งผลลัพธ์ไปยัง spell‑checker อย่าง `pyspellchecker` เพื่อตรวจจับข้อผิดพลาดของ OCR + +--- + +## สรุป + +เราได้อธิบาย **วิธีดึงข้อความจาก PDF** เมื่อการแยกข้อมูลแบบดั้งเดิมล้มเหลว, แสดง **ocr python example** แบบเต็ม, และอธิบายวิธี **จดจำข้อความจากภาพ** และ **อ่าน PDF ด้วย OCR** ทั้งในกรณีหน้าเดียวและหลายหน้า ด้วยโค้ดตัวอย่างข้างต้น คุณสามารถแปลง PDF สแกนใด ๆ ให้เป็นข้อความที่ค้นหาและแก้ไขได้—ไม่ต้องพิมพ์ใหม่อีกต่อไป + +ขั้นตอนต่อไป? ลองสลับภาษาเป็นสเปน (`ocr.Language.Spanish`) หรือทดลองเทคนิคการพรี‑โปรเซสภาพเพื่อเพิ่มความแม่นยำ หากคุณกำลังสร้างระบบจัดการเอกสาร, พิจารณาดัชนีข้อความที่ดึงได้ด้วย Elasticsearch เพื่อการค้นหาเร็วแสง + +มีคำถามหรือเจอ PDF ที่แปลกประหลาด? แสดงความคิดเห็นได้เลย, Happy coding! + +![วิธีดึงข้อความจาก PDF ด้วย OCR ใน Python](image.png "วิธีดึงข้อความจาก PDF ด้วย OCR ใน Python") + + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานครบถ้วนพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ 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/) +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/thai/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..2daeafb56 --- /dev/null +++ b/ocr/thai/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-06-19 +description: เรียนรู้วิธีใช้ OCR ใน Java กับ Aspose คู่มือแบบขั้นตอนนี้ครอบคลุมการปรับแนวภาพอัตโนมัติ + การตรวจจับภาษาอัตโนมัติ และการสกัดข้อความจากภาพได้อย่างง่ายดาย. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: th +og_description: 'วิธีใช้ OCR ใน Java กับ Aspose: คู่มือเต็มที่ครอบคลุมการแก้ไขการเอียงอัตโนมัติของภาพ, + การตรวจจับภาษาอัตโนมัติ, และการสกัดข้อความจากรูปภาพ.' +og_title: วิธีใช้ OCR ใน Java กับ Aspose – คู่มือครบวงจร +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: วิธีใช้ OCR ใน Java กับ Aspose – คู่มือฉบับสมบูรณ์ +url: /th/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีใช้ OCR ใน Java กับ Aspose – คู่มือครบถ้วน + +เคยสงสัย **วิธีใช้ OCR** ในโครงการ Java โดยไม่ต้องเสียศีรษะกับการตั้งค่ามากหรือไม่? คุณไม่ได้เป็นคนเดียวที่เจอปัญหา นักพัฒนาจำนวนมากมักเจออุปสรรคเมื่อจำเป็นต้อง **extract text image** อย่างรวดเร็ว โดยเฉพาะเมื่อสแกนต้นฉบับเป็นภาพเอียงหรือเป็นภาษาที่ไม่รู้จัก + +ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่างเชิงปฏิบัติที่แสดงให้เห็นอย่างชัดเจนว่า **วิธีใช้ OCR** กับ Aspose อย่างไร รวมถึง **auto deskew images**, **auto language detection**, และกระบวนการ **ocr image preprocessing** เต็มรูปแบบ เมื่อเสร็จสิ้นคุณจะได้โค้ดสั้นที่พร้อมรันซึ่งพิมพ์ข้อความที่จดจำได้ลงคอนโซล และคุณจะเข้าใจว่าการตั้งค่าแต่ละอย่างสำคัญอย่างไร + +> **สิ่งที่คุณจะได้:** โปรแกรม Java ที่สมบูรณ์และรันได้, คำอธิบายของแต่ละบรรทัด, เคล็ดลับการจัดการกรณีขอบ, และแนวคิดในการขยายโซลูชันเพื่อการประมวลผลเป็นชุดหรือ PDF + +--- + +## ข้อกำหนดเบื้องต้น + +- Java 17 (หรือ JDK ล่าสุดใดก็ได้) ที่ติดตั้งและกำหนดค่าแล้ว +- Maven หรือ Gradle สำหรับการจัดการ dependencies (เราจะแสดงพิกัด Maven) +- ไฟล์ลิขสิทธิ์ Aspose OCR for Java (`Aspose.OCR.Java.lic`). หากคุณเพียงทดสอบ สามารถข้ามขั้นตอนลิขสิทธิ์ได้ แต่รุ่นทดลองจะใส่ลายน้ำ +- ตัวอย่างรูปภาพ (`your_image.png`) ที่วางไว้ในตำแหน่งที่โค้ดเข้าถึงได้ + +> **เคล็ดลับมืออาชีพ:** เก็บรูปภาพของคุณในโฟลเดอร์ `resources` แยกเฉพาะและโหลดผ่าน classpath; จะช่วยหลีกเลี่ยงปัญหาเกี่ยวกับเส้นทางบนระบบปฏิบัติการต่างๆ + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และเพิ่ม Aspose OCR Dependency + +สร้างโปรเจกต์ Maven ใหม่ (หรือใช้โปรเจกต์ที่มีอยู่) แล้วเพิ่มสิ่งต่อไปนี้ในไฟล์ `pom.xml` ของคุณ: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +รัน `mvn clean install` เพื่อดึงไลบรารี หากคุณชอบ Gradle ให้ใช้คำสั่งที่เทียบเท่า: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +ตอนนี้คุณมีคลาส **ocr image preprocessing** อยู่ใน classpath แล้ว + +## ขั้นตอนที่ 2: ใส่ลิขสิทธิ์ Aspose OCR ของคุณ (ไม่บังคับแต่แนะนำ) + +หากคุณมีลิขสิทธิ์ ให้ใส่ไว้ตั้งแต่ต้นเมธอด `main` ของคุณ การข้ามขั้นตอนนี้ก็ทำงานได้ แต่เวอร์ชันฟรีจะใส่ลายน้ำ “Demo” บนผลลัพธ์ + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **ทำไมจึงสำคัญ:** เวอร์ชันที่มีลิขสิทธิ์จะลบข้อจำกัดการใช้งานและปิดลายน้ำ ทำให้คุณได้ผลลัพธ์ที่สะอาดและพร้อมใช้งานในผลิตภัณฑ์ + +## ขั้นตอนที่ 3: สร้างอินสแตนซ์ของ OCR Engine + +Engine เป็นหัวใจของกระบวนการ การสร้างอินสแตนซ์จะทำให้คุณเข้าถึงตัวเลือก **ocr image preprocessing** ทั้งหมด + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +ในจุดนี้ engine พร้อมใช้งานแล้ว แต่จะใช้การตั้งค่าเริ่มต้นซึ่งอาจไม่เหมาะกับเอกสารสแกน เรามาปรับแต่งบางอย่างกัน + +## ขั้นตอนที่ 4: เปิดใช้งาน Auto Deskew Images เพื่อสแกนที่สะอาดขึ้น + +สแกนเอียงเป็นปัญหาที่พบบ่อย Aspose มีฟีเจอร์ **auto deskew images** ที่จะทำให้ภาพตรงอัตโนมัติก่อนการจดจำ + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **วิธีการทำงาน:** อัลกอริธึมวิเคราะห์มุมฐานของข้อความและหมุนภาพให้ตรงกับแนวตั้งที่เป็นไปได้มากที่สุด ซึ่งจะเพิ่มความแม่นยำอย่างมากสำหรับภาพถ่ายที่ถ่ายด้วยโทรศัพท์ + +## ขั้นตอนที่ 5: เปิดใช้งาน Auto Language Detection + +หากคุณไม่ทราบภาษาของภาพต้นฉบับ ให้ engine ค้นหาด้วยตนเอง นี่คือการตั้งค่า **auto language detection** + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +เมื่อเปิดใช้งาน Aspose จะสแกน glyphs และเลือกโมเดลภาษาที่เป็นไปได้มากที่สุด รองรับกว่า 30 ภาษาโดยอัตโนมัติ + +## ขั้นตอนที่ 6: โหลดภาพที่ต้องการจดจำ + +คุณสามารถโหลดภาพจากดิสก์, URL, หรือแม้กระทั่ง byte array เพื่อความง่าย เราจะอ่านจากไฟล์ในเครื่อง + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **เคล็ดลับ:** หากคุณทำงานกับภาพขนาดใหญ่ ควรลดขนาดภาพก่อนด้วย `engine.getImagePreprocessing().setResizeFactor(0.5)` เพื่อเร่งการประมวลผลโดยไม่สูญเสียรายละเอียดมาก + +## ขั้นตอนที่ 7: ทำการจดจำ OCR และ Extract Text Image + +ตอนนี้ engine ทำงานของมัน เมธอด `recognize` จะคืนค่าอ็อบเจกต์ `OcrResult` ที่มีข้อความที่จดจำได้, คะแนนความมั่นใจ, และอื่นๆ + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +คอนโซลจะแสดงข้อความธรรมดาที่ดึงจากภาพ—นี่คือผลลัพธ์หลัก **extract text image** ที่เราตั้งเป้าหมาย + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นคลาส Java ที่สมบูรณ์ซึ่งรวมทุกอย่างเข้าด้วยกัน คัดลอกและวางลงใน `src/main/java/com/example/OcrDemo.java` แล้วรัน + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +หากภาพมีข้อความ “Hello World” บนสแกนที่สะอาด คุณจะเห็น: + +``` +=== Recognized Text === +Hello World +``` + +สำหรับเอกสารที่ซับซ้อนกว่า (เช่น ใบเสร็จหลายภาษา) ผลลัพธ์จะรวมการขึ้นบรรทัดใหม่และรหัสภาษาที่ตรวจพบ + +## ข้อผิดพลาดทั่วไป & เคล็ดลับมืออาชีพ + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **อักขระขยะ** | ภาพมืดเกินไปหรือมีสัญญาณรบกวน | เปิดใช้งาน `engine.getImagePreprocessing().setBinarization(true)` หรือปรับความคอนทราสต์ด้วยตนเอง | +| **ภาษาผิด** | การตรวจจับอัตโนมัติทำงานผิดพลาดบนหน้าที่มีหลายภาษา | ตั้งค่า `engine.setLanguage(Language.English)` (หรือ enum ที่เหมาะสม) เพื่อบังคับใช้ภาษาที่ต้องการ | +| **การประมวลผลช้า** | ภาพความละเอียดสูงมาก | ลดขนาดด้วย `engine.getImagePreprocessing().setResizeFactor(0.5)` | +| **ข้อผิดพลาด Out‑of‑memory** | โหลดชุดภาพจำนวนมากพร้อมกัน | ประมวลผลภาพต่อเนื่องและเรียก `engine.dispose()` หลังการรันแต่ละครั้ง | + +> **จำไว้:** OCR engine ปลอดภัยต่อการทำงานหลายเธรดสำหรับการอ่านอย่างเดียว แต่การสร้างอินสแตนซ์ใหม่ต่อเธรดจะหลีกเลี่ยงบั๊กสถานะที่ซ่อนอยู่ + +## การขยายโซลูชัน + +เมื่อคุณรู้ **วิธีใช้ OCR** กับ Aspose แล้ว คุณอาจต้องการ: + +1. ประมวลผล PDF – แปลงแต่ละหน้าของ PDF เป็นภาพ (`PdfConverter`) แล้วส่งเข้าไปใน pipeline เดียวกัน +2. ประมวลผลเป็นชุดในโฟลเดอร์ – วนลูปไฟล์ในไดเรกทอรี, ใช้ขั้นตอนเดียวกัน, และบันทึกผลลัพธ์เป็น CSV +3. รวมเข้ากับเว็บเซอร์วิส – เปิดเผยตรรกะ OCR ผ่าน Spring Boot `@RestController` ที่รับการอัปโหลดแบบ multipart + +ทุกสถานการณ์เหล่านี้ใช้การกำหนดค่า **ocr image preprocessing** เดียวกันที่เราสร้างไว้ที่นี่ + +## สรุป + +เราได้อธิบาย **วิธีใช้ OCR** ใน Java กับ Aspose ตั้งแต่ต้นจนจบ: การใส่ลิขสิทธิ์, การสร้าง engine, การเปิด **auto deskew images**, การเปิด **auto language detection**, การโหลดภาพ, และสุดท้าย **extract text image** ด้วย `System.out.println` เพียงบรรทัดเดียว โค้ดเป็นอิสระเต็มรูปแบบ ทำงานบน JDK ล่าสุดใดก็ได้ และแสดงแนวทางปฏิบัติที่ดีที่สุดสำหรับความแม่นยำและประสิทธิภาพ + +ลองใช้กับรูปภาพของคุณเอง—อาจเป็นสัญญาที่สแกนหรือภาพหน้าจอของใบเสร็จ ปรับค่า preprocessing, ทดลองกับภาษาต่างๆ แล้วคุณจะเห็นว่าไลบรารี OCR ของ Aspose เป็นตัวเลือกที่มั่นคงสำหรับการสกัดข้อความระดับการผลิต + +มีคำถามหรืออยากแชร์ผลลัพธ์? แสดงความคิดเห็นด้านล่างหรือทักมาที่ GitHub ของฉัน ขอให้สนุกกับการเขียนโค้ด! + +![ตัวอย่างการใช้ OCR ใน Java](/images/ocr-java-example.png "การใช้ OCR ใน Java – ภาพสาธิต Aspose") + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบอื่นในโปรเจกต์ของคุณ + +- [วิธี OCR ข้อความในภาพพร้อมภาษาโดยใช้ Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [ดึงข้อความจากภาพ Java ด้วย Aspose.OCR โหมดตรวจจับพื้นที่](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [วิธีใช้ OCR - เทคนิคขั้นสูงกับ Aspose.OCR สำหรับ Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/thai/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..4531ba484 --- /dev/null +++ b/ocr/thai/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,316 @@ +--- +category: general +date: 2026-06-19 +description: ปรับปรุงความแม่นยำของ OCR ใน Python ด้วย Aspose OCR. เรียนรู้วิธีตั้งค่าภาษา + OCR, โหลดภาพสำหรับ OCR, และสกัดข้อความจากภาพด้วยพจนานุกรมที่กำหนดเอง. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: th +og_description: ปรับปรุงความแม่นยำของ OCR ใน Python ด้วยการตั้งค่าภาษา OCR, โหลดภาพสำหรับ + OCR, และสกัดข้อความจากภาพด้วยพจนานุกรมที่กำหนดเอง. +og_title: ปรับปรุงความแม่นยำของ OCR ใน Python – คู่มือแบบทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: ปรับปรุงความแม่นยำของ OCR ใน Python – คู่มือฉบับสมบูรณ์ +url: /th/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ปรับปรุงความแม่นยำของ OCR ใน Python – คู่มือฉบับสมบูรณ์ + +เคยสงสัยไหมว่า **ปรับปรุงความแม่นยำของ OCR** อย่างไรเมื่อข้อความที่คุณสแกนมีสัญลักษณ์แปลก ๆ รหัสสินค้า หรือชื่อแบรนด์? คุณไม่ได้อยู่คนเดียว ในหลายโครงการเอนจินเริ่มต้นมักให้ผลลัพธ์เป็นตัวอักษรไร้สาระ ซึ่งเป็นสาเหตุสำคัญที่ทำให้ประสิทธิภาพการทำงานลดลง + +ในบทเรียนนี้เราจะพาคุณผ่านตัวอย่างเชิงปฏิบัติแบบครบวงจร ที่แสดงให้เห็นวิธี **ตั้งค่าภาษา OCR**, **โหลดภาพสำหรับ OCR**, **ทำ OCR บนภาพ**, และสุดท้าย **ดึงข้อความจากภาพ** ด้วยพจนานุกรมที่กำหนดเองเพื่อเพิ่มอัตราการจดจำ เมื่อเสร็จแล้วคุณจะได้สคริปต์พร้อมรันที่สามารถนำไปใช้ในโค้ด Python ใดก็ได้ + +## สิ่งที่คุณจะได้เรียนรู้ + +- สคริปต์ Python ทำงานเต็มรูปแบบที่ใช้ Aspose OCR เพื่ออ่านไฟล์ PNG +- ความสามารถในการ **ปรับปรุงความแม่นยำของ OCR** ด้วยการกำหนดภาษาและรายการคำที่กำหนดเอง +- คำอธิบายที่ชัดเจนว่าทำไมการตั้งค่าแต่ละอย่างจึงสำคัญ พร้อมเคล็ดลับการจัดการกับกรณีขอบเช่นอักขระที่ไม่ใช่ละติน +- เช็คลิสต์สั้น ๆ สำหรับการแก้ไขปัญหา OCR ที่พบบ่อย + +### ข้อกำหนดเบื้องต้น + +- Python 3.8 หรือใหม่กว่า ติดตั้งบนเครื่องของคุณ +- แพ็กเกจ `aspose-ocr` (ติดตั้งด้วย `pip install aspose-ocr`) +- ตัวอย่างภาพ (`technical_doc.png`) ที่มีข้อความที่คุณต้องการอ่าน +- ความคุ้นเคยพื้นฐานกับ Python—ไม่ต้องการความเชี่ยวชาญพิเศษ + +> **เคล็ดลับระดับมืออาชีพ:** หากคุณทำงานในสภาพแวดล้อมเสมือน (virtual environment) ให้เปิดใช้งานก่อนติดตั้งแพ็กเกจ จะช่วยให้การจัดการ dependencies เป็นระเบียบและหลีกเลี่ยงการชนกันของเวอร์ชัน + +--- + +## ขั้นตอนที่ 1: ติดตั้งและนำเข้า Aspose OCR + +เริ่มจากการนำไลบรารีเข้ามาในสภาพแวดล้อมและนำเข้าโมดูลที่เราต้องการใช้ + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +เนมสเปซ `aspose.ocr` ให้คุณเข้าถึงคลาส `OcrEngine` ซึ่งเป็นหัวใจของกระบวนการ OCR การนำเข้าที่นี่ทำให้สคริปต์ส่วนอื่นอ่านง่ายและเป็นระเบียบ + +--- + +## ขั้นตอนที่ 2: สร้าง OCR Engine และ **ตั้งค่าภาษา OCR** + +ทำไมภาษาถึงสำคัญ? เอนจิน OCR พึ่งพาโมเดลเฉพาะภาษาเพื่อจดจำรูปแบบอักขระและคำ หากคุณบอกเอนจินว่ากำลังสแกนข้อความภาษาอังกฤษ มันจะละเว้น glyph Cyrillic และมุ่งเน้นที่อักษรละติน ซึ่งจะ **ปรับปรุงความแม่นยำของ OCR** อย่างมาก + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **หมายเหตุ:** Aspose OCR รองรับมากกว่า 50 ภาษา เปลี่ยน `ocr.Language.English` เป็น `ocr.Language.Spanish`, `ocr.Language.French` ฯลฯ หากเอกสารของคุณไม่ใช่ภาษาอังกฤษ + +--- + +## ขั้นตอนที่ 3: กำหนด **พจนานุกรมแบบกำหนดเอง** เพื่อเพิ่มความแม่นยำ + +ลองนึกภาพว่าคุณกำลังสแกนใบแจ้งหนี้ที่มีคำว่า “AsposeOCR” หรือรหัสสินค้าเช่น “SKU12345” เอนจินไม่รู้จักคำเหล่านี้จึงคาดเดาผิด การใส่รายการคำที่กำหนดเองบอกเอนจินว่า *“นี่คือสตริงที่ถูกต้อง—อย่าพยายามแก้ไข”* ซึ่งเป็นวิธีเร็ว ๆ สำหรับ **ปรับปรุงความแม่นยำของ OCR** + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +คุณสามารถโหลดรายการนี้จากไฟล์หรือฐานข้อมูลได้หากมีหลายร้อยรายการ—เพียงเก็บไว้ในลิสต์ Python เพื่อความง่าย + +--- + +## ขั้นตอนที่ 4: **โหลดภาพสำหรับ OCR** + +ตอนนี้เราต้องมีภาพ เมธอด `Image.load` รับพาธของรูปแบบ raster ที่รองรับ (PNG, JPEG, BMP ฯลฯ) หากไฟล์ไม่พบ เอนจินจะโยนข้อยกเว้น ดังนั้นเราจึงต้องตรวจสอบล่วงหน้า + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **ทำไมขั้นตอนนี้สำคัญ:** การโหลดภาพอย่างถูกต้องทำให้เอนจินทำงานกับข้อมูลพิกเซลที่คุณต้องการวิเคราะห์ ไฟล์เสียหรือพาธผิดเป็นสาเหตุที่ทำให้ผู้ใช้หงุดหงิดบ่อยครั้ง + +--- + +## ขั้นตอนที่ 5: **ทำ OCR บนภาพ** และดึงผลลัพธ์ + +เมื่อเอนจินตั้งค่าเรียบร้อยและภาพพร้อม การจดจำจริงเป็นเพียงการเรียกเมธอดเดียว ผลลัพธ์จะมีข้อความดิบ, คะแนนความเชื่อมั่น, และแม้กระทั่งข้อมูลเลย์เอาต์หากต้องการใช้ต่อ + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +หากต้องการ **ดึงข้อความจากภาพ** ทีละบรรทัด คุณสามารถแยกด้วยอักขระ newline ได้: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## ขั้นตอนที่ 6: ตรวจสอบผลลัพธ์ – จริง ๆ แล้ว **ปรับปรุงความแม่นยำของ OCR** หรือไม่? + +พิมพ์ผลลัพธ์และดูว่าพจนานุกรมที่กำหนดเองทำให้ผลลัพธ์ดีขึ้นหรือไม่ + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +ผลลัพธ์ตัวอย่างสำหรับภาพที่ให้มาอาจมีลักษณะดังนี้: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +สังเกตว่าชื่อแบรนด์, ตัวอักษรกรีก, และรหัสสินค้าปรากฏตามที่เรากำหนดไว้ หากไม่มีพจนานุกรมแบบกำหนดเอง เอนจินอาจพยายาม “แก้ไข” ให้เป็น “Aspose OCR” หรือ “SKU 1234” + +--- + +## ข้อผิดพลาดทั่วไปและวิธีแก้ไข + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|----------| +| **อักขระแปลก** | ตั้งค่าภาษาไม่ตรงหรือภาพความละเอียดต่ำ | ตรวจสอบให้ `engine.language` ตรงกับภาษาต้นฉบับและใช้การสแกนความละเอียดสูง (300 dpi หรือมากกว่า) | +| **คำที่กำหนดเองไม่ทำงาน** | พจนานุกรมไม่ได้เชื่อมต่อหรือพิมพ์ชื่อ property ผิด | ตรวจสอบ `engine.text_processing.custom_dictionary = …` อีกครั้ง | +| **ไม่พบไฟล์** | พาธผิดหรือไม่มีสิทธิ์เข้าถึงไฟล์ | ใช้ `os.path.abspath()` เพื่อตรวจสอบพาธเต็ม; รันสคริปต์ด้วยสิทธิ์ที่เหมาะสม | +| **การประมวลผลช้า** | ภาพขนาดใหญ่หรือหลายหน้า | ทำการพรี‑โปรเซสภาพ (ครอบ, ปรับขนาด) หรือใช้ `engine.recognize(image, max_threads=4)` เพื่อประมวลผลแบบขนาน | + +--- + +## ต่อไป: การปรับแต่งขั้นสูงสำหรับ **ปรับปรุงความแม่นยำของ OCR** + +1. **พรี‑โปรเซส** – ใช้ Pillow ปรับคอนทราสต์หรือทำไบนารีไลเซชันก่อนส่งภาพให้ Aspose OCR +2. **หลายภาษา** – ตั้งค่า `engine.language = ocr.Language.English | ocr.Language.French` เพื่อเปิดการจดจำสองภาษาพร้อมกัน +3. **OCR ตามพื้นที่** – หากต้องการเฉพาะส่วน (เช่น ตาราง) ให้ครอบภาพก่อนเพื่อลดสัญญาณรบกวน +4. **กรองตามความเชื่อมั่น** – `result.confidence` ให้คะแนนความเชื่อมั่นต่ออักขระ; คุณสามารถละทิ้งผลลัพธ์ที่ความเชื่อมั่นต่ำได้โดยโปรแกรม + +--- + +## สคริปต์ทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์พร้อมคัดลอก‑วางที่รวมทุกขั้นตอนที่อธิบายไว้ บันทึกเป็น `improve_ocr_accuracy.py` แล้วรันจากคอมมานด์ไลน์ + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +รันสคริปต์: + +```bash +python improve_ocr_accuracy.py +``` + +คุณควรเห็นผลลัพธ์ที่จัดรูปแบบอย่างสวยงามตามที่แสดงไว้ก่อนหน้านี้ + +--- + +## สรุป + +เราได้สรุปวิธี **ปรับปรุงความแม่นยำของ OCR** ใน Python อย่างเป็นขั้นตอนโดย: + +1. **ตั้งค่าภาษา OCR** ให้ตรงกับเอกสารของคุณ +2. **โหลดภาพอย่างถูกต้อง** เพื่อให้เอนจินเห็นพิกเซลที่ต้องการ +3. **ทำ OCR บนภาพ** ด้วยเมธอดเดียว +4. **ดึงข้อความจากภาพ** และตรวจสอบผลลัพธ์ +5. **เพิ่มพจนานุกรมแบบกำหนดเอง** เพื่อคงคำเฉพาะโดเมน + +นี่คือเวิร์กโฟลว์ทั้งหมด—from ภาพดิบถึงข้อความที่ค้นหาได้—ในสคริปต์ที่เรียบง่ายและนำกลับมาใช้ใหม่ได้ หากคุณพร้อมรับความท้าทายต่อไป ลองทดลองพรี‑โปรเซสภาพ (คอนทราสต์, แก้ไขการเอียง) หรือสลับไปใช้การตั้งค่าหลายภาษาโดยใช้ `ocr.Language.English | ocr.Language.German` หลักการเดียวกันจะช่วย **ปรับปรุงความแม่นยำของ OCR** ในชุดเอกสารที่หลากหลายยิ่งขึ้น + +มีคำถามหรือกรณีขอบแปลก ๆ? แสดงความคิดเห็นด้านล่าง แล้วขอให้เขียนโค้ดอย่างสนุกสนาน! + +![improve OCR accuracy + + +## คุณควรเรียนรู้อะไรต่อไป? + + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานแบบอื่นในโปรเจกต์ของคุณ + +- [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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/thai/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..381b31030 --- /dev/null +++ b/ocr/thai/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-19 +description: ทำ OCR บนภาพโดยใช้ไลบรารี ocr ของ Python เรียนรู้วิธีตรวจจับข้อความจากภาพ, + จดจำข้อความจากไฟล์ JPEG, และสกัดข้อความจากภาพสแกนอย่างมีประสิทธิภาพ. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: th +og_description: ทำ OCR บนภาพด้วย Python และดึงข้อความจากไฟล์สแกน คู่มือนี้จะพาคุณผ่านขั้นตอนการโหลดภาพ + การแก้ไขการเอียง และการจดจำข้อความอย่างเป็นขั้นตอน +og_title: ทำ OCR บนรูปภาพด้วย Python – คู่มือการสกัดข้อความเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: ทำ OCR บนรูปภาพด้วย Python – คู่มือการสกัดข้อความเต็มรูปแบบ +url: /th/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ทำ OCR บนรูปภาพด้วย Python – คู่มือการสกัดข้อความเต็มรูปแบบ + +เคยต้องการ **perform OCR on image** ไฟล์แต่เจออุปสรรคเพราะโค้ดดูซับซ้อน? คุณไม่ใช่คนเดียว ไม่ว่าจะเปลี่ยนใบเสร็จสแกนเป็น PDF ที่ค้นหาได้หรือดึงคำบรรยายจาก JPEG สำหรับโครงการ data‑science ความสามารถในการจดจำข้อความจาก JPEG และรูปแบบอื่นเป็นทักษะที่จำเป็นสำหรับนักพัฒนาทุกคนในวันนี้. + +ในบทแนะนำนี้เราจะพาคุณผ่านตัวอย่างที่สมบูรณ์และสามารถรันได้ ซึ่งจะแสดงวิธี **detect text from image** ไฟล์, **extract text from scanned image** เอกสาร, และแม้กระทั่ง **load image for OCR** ด้วยเพียงไม่กี่บรรทัด เมื่อจบคุณจะได้โค้ดสแนปช็อตที่พร้อมใช้งานในระดับ production ที่สามารถนำไปใส่ในโปรเจกต์ของคุณได้—ไม่มีการนำเข้าแบบหายไป ไม่มีทางลัด “ดูเอกสาร” ที่คลุมเครือ. + +## สิ่งที่คุณจะสร้าง + +- สคริปต์ Python เล็ก ๆ ที่สร้าง OCR engine, เปิดใช้งาน auto‑deskew, โหลด JPEG (หรือรูปแบบที่รองรับใด ๆ) และพิมพ์ข้อความที่จดจำได้. +- คำอธิบายของ **why** แต่ละการตั้งค่า ทำไมจึงสำคัญ, ไม่ใช่แค่ **how** ที่พิมพ์. +- เคล็ดลับการจัดการ PDF หลายหน้า, ภาษาไม่ใช่ภาษาอังกฤษ, และข้อผิดพลาดทั่วไปเช่นสแกนเบลอ. + +### ข้อกำหนดเบื้องต้น + +- ติดตั้ง Python 3.8+ (ตัวอย่างใช้แพคเกจ `ocr` ที่สามารถติดตั้งได้ด้วย `pip install ocr-lib` – แทนที่ด้วยชื่อไลบรารีของคุณ). +- ความคุ้นเคยพื้นฐานกับฟังก์ชัน Python และ virtual environments. +- ไฟล์รูปภาพ (JPEG, PNG, TIFF) ที่คุณต้องการประมวลผล; เราจะใช้ `skewed_page.jpg` เป็นตัวอย่าง. + +> **Pro tip:** หากคุณใช้ Windows ให้รันเทอร์มินัลในฐานะ Administrator ขณะติดตั้งไลบรารี OCR เพื่อหลีกเลี่ยงปัญหาการอนุญาต. + +## ทำ OCR บนรูปภาพ – การตั้งค่าและการกำหนดค่า + +สิ่งแรกที่คุณต้องการคืออินสแตนซ์ของ OCR engine ที่สะอาด คิดว่าเป็นสมองของการทำงาน; หากไม่มีการกำหนดค่าที่เหมาะสม แม้ภาพที่คมชัดที่สุดก็จะให้ผลลัพธ์เป็นข้อความไร้สาระ. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Why this matters:** +การตั้งค่า `engine.language` จะจำกัดชุดอักขระที่ OCR engine คาดหวัง, เพิ่มความแม่นยำอย่างมาก. หากข้ามขั้นตอนนี้, engine จะพยายามเดา ซึ่งมักทำให้คำง่าย ๆ ผิดพลาด. + +## เปิดใช้งาน Automatic Deskew – แก้ไขการสแกนเอียง + +หน้าที่สแกนมักไม่เรียบสมบูรณ์ การเอียงเล็กน้อยอาจทำให้การแยกอักขระผิดพลาด, ทำให้ “Hello” กลายเป็น “H3llo”. ธง `auto_deskew` จะทำงานหนักให้คุณ. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Edge case:** หากคุณทราบว่ารูปภาพของคุณเรียงตรงอยู่แล้ว การปิด deskew สามารถลดเวลาประมวลผลลงหลายมิลลิวินาที—มีประโยชน์เมื่อจัดการกับหลายพันหน้าในงานแบช. + +## โหลดรูปภาพสำหรับ OCR – รองรับ JPEG, PNG, TIFF + +ตอนนี้เราจริง ๆ **load image for OCR**. เมธอด `ocr.Image.load` มีความยืดหยุ่น; มันรับพาธไปยังรูปแบบ raster ที่รองรับใด ๆ. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Why this step is crucial:** ไลบรารีอ่านไฟล์เข้าสู่บิตแมพภายใน, ทำการแปลงสีที่จำเป็น. การข้ามขั้นตอนนี้และส่งสตรีมไบต์ดิบจะทำให้เกิด `FileNotFoundError` หรือแย่กว่า, ผลลัพธ์ว่างเปล่าโดยไม่มีการแจ้ง. + +หากคุณต้องการ **recognize text from JPEG** โดยเฉพาะ, เพียงตรวจสอบให้ส่วนขยายไฟล์เป็น `.jpeg` หรือ `.jpg`. การเรียกเดียวกันทำงานกับ PNG (`.png`) หรือ TIFF (`.tif`) โดยไม่ต้องแก้ไข. + +## ทำ OCR บนรูปภาพ – การรัน Engine + +เมื่อ engine พร้อมและรูปภาพอยู่ในหน่วยความจำ, ถึงเวลาที่จะ **perform OCR on image** ข้อมูล. บรรทัดเดียวนี้ทำงานหนัก: การเตรียมข้อมูล, การแยกส่วน, การจำแนก, และการประกอบข้อความ. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**What happens under the hood?** +- Engine ใช้การแปลง deskew (หากเปิดใช้งาน). +- มันรัน neural network หรือ backend ของ Tesseract เพื่อระบุอักขระ. +- สุดท้าย, มันเชื่อมอักขระเป็นคำและบรรทัด, ส่งคืนอ็อบเจกต์ `result` ที่เต็มรูปแบบ. + +## สกัดข้อความจากสแกนภาพ – แสดงผลลัพธ์ + +ขั้นตอนสุดท้ายคือ **extract text from scanned image** และแสดงผล. แอตทริบิวต์ `result.text` มีการแสดงผลเป็นข้อความธรรมดา. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +ผลลัพธ์ทั่วไปจะมีลักษณะดังนี้: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +หาก OCR engine ไม่พบอักขระใด ๆ, `result.text` จะเป็นสตริงว่าง. ในกรณีนั้น, ตรวจสอบคุณภาพของรูปภาพอีกครั้งหรือพิจารณาปรับค่า `engine.confidence_threshold` (หากไลบรารีของคุณรองรับ). + +## การจัดการกับความแตกต่างทั่วไป + +### การจดจำข้อความจาก JPEG vs PNG + +ทั้งสองรูปแบบได้รับการสนับสนุน, แต่การบีบอัด JPEG อาจทำให้เกิดอาร์ติแฟคต์ที่ทำให้ engine สับสน. หากคุณพบการจดจำผิดบ่อย, ลองแปลง JPEG เป็น PNG ก่อน: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### การตรวจจับข้อความจากรูปภาพหลายภาษา + +หากเอกสารของคุณผสมภาษาอังกฤษและสเปน, ตั้งค่าโหมดหลายภาษา: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +### สกัดข้อความจาก PDF ที่สแกน + +สำหรับ PDF, คุณต้อง rasterize แต่ละหน้ามาเป็นรูปภาพก่อน. ไลบรารีอย่าง `pdf2image` ทำให้ขั้นตอนนี้ง่ายดาย: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์เต็มที่คุณสามารถคัดลอก‑วางลงในไฟล์ `ocr_demo.py`. มันรวมการจัดการข้อผิดพลาดและตัวช่วยเล็ก ๆ เพื่อวัดเวลาในการทำงาน. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Expected output** (สมมติว่าการสแกนชัดเจน): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +## คำถามที่พบบ่อย + +**Q: Can I run this on a headless server?** +A: แน่นอน. ไลบรารีทำงานได้โดยไม่มี GUI; เพียงตรวจสอบให้แน่ใจว่าไบนารีเนทีฟที่จำเป็น (เช่น Tesseract) ถูกติดตั้งบนเซิร์ฟเวอร์. + +**Q: What if the image is blurry?** +A: พิจารณาเพิ่มฟิลเตอร์ทำให้คมก่อน `engine.recognize`. ไลบรารี OCR หลายตัวเปิดให้ใช้ `image_preprocessing.sharpen = True` หรือคุณสามารถใช้ `cv2.GaussianBlur` ของ OpenCV ในทางกลับกัน. + +**Q: Does the script support batch processing?** +A: ใช่. ห่อ `perform_ocr` ไว้ในลูปที่วนผ่านรายการของพาธไฟล์, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/thai/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..824a188db --- /dev/null +++ b/ocr/thai/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-06-19 +description: ทำการ OCR บนรูปภาพโดยใช้ Aspose OCR Java เรียนรู้วิธีโหลดรูปภาพสำหรับ + OCR ใช้ไลเซนส์ของ Aspose และสกัดข้อความจากรูปภาพในเวลาไม่กี่นาที. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: th +og_description: ทำ OCR บนรูปภาพด้วย Aspose OCR Java คู่มือนี้แสดงวิธีใช้ใบอนุญาต Aspose, + โหลดรูปภาพสำหรับ OCR, และดึงข้อความจากรูปภาพอย่างมีประสิทธิภาพ. +og_title: ทำ OCR บนภาพด้วย Aspose OCR Java – บทเรียนเต็ม +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: ทำ OCR บนภาพด้วย Aspose OCR Java – คู่มือขั้นตอนเต็ม +url: /th/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ทำ OCR บนรูปภาพด้วย Aspose OCR Java – คู่มือขั้นตอนเต็ม + +เคยต้อง **ทำ OCR บนรูปภาพ** แต่ไม่แน่ใจว่าคลังไหนให้ผลลัพธ์ที่เชื่อถือได้โดยไม่ต้องตั้งค่ามากมายหรือไม่? คุณไม่ได้เป็นคนเดียว ในหลายโครงการจริง—เช่น การสแกนพาสปอร์ต, การแปลงใบแจ้งหนี้เป็นดิจิทัล, หรือการดึงข้อความจากภาพหน้าจอ—ความสามารถในการจดจำข้อความจากข้อมูลภาพอย่างรวดเร็วเป็นตัวเปลี่ยนเกม + +ในบทเรียนนี้เราจะพาคุณผ่านตัวอย่างเชิงปฏิบัติที่แสดงอย่างชัดเจนว่า **ทำ OCR บนรูปภาพ** อย่างไรโดยใช้ Aspose OCR สำหรับ Java เราจะครอบคลุมทุกอย่างตั้งแต่การใช้ลิขสิทธิ์ Aspose ไปจนถึงการโหลดรูปภาพ, การรันเอนจิน, และสุดท้าย **ดึงข้อความจากรูปภาพ** เพื่อใช้ต่อในขั้นตอนถัดไป ไม่มีส่วนเกิน เพียงโซลูชันที่ทำงานได้จริงที่คุณสามารถคัดลอก‑วางได้ + +## สิ่งที่คุณจะได้เรียนรู้ + +- ภาพรวมที่ชัดเจนว่าต้อง **ใช้ลิขสิทธิ์ Aspose** ในโครงการ Java อย่างไร +- โค้ดที่จำเป็นสำหรับ **โหลดรูปภาพสำหรับ OCR** และให้เอนจินตรวจจับภาษาต่าง ๆ อัตโนมัติ +- คำแนะนำขั้นตอน‑ต่อ‑ขั้นตอนเพื่อ **จดจำข้อความในภาพ** และ **ดึงข้อความจากรูปภาพ** อย่างปลอดภัย +- เคล็ดลับการจัดการกับปัญหาที่พบบ่อย (ผลลัพธ์ว่าง, ฟอร์แมตที่ไม่รองรับ, ปัญหาเรื่องหน่วยความจำ) + +> **ข้อกำหนดเบื้องต้น** – Java 8 หรือใหม่กว่า, Maven หรือ Gradle สำหรับจัดการ dependency, และไฟล์ลิขสิทธิ์ Aspose OCR สำหรับ Java (หรือคุณสามารถรันในโหมดประเมินผล) + +--- + +## วิธีทำ OCR บนรูปภาพด้วย Aspose OCR Java + +ด้านล่างเป็นโปรแกรม Java เต็มรูปแบบที่พร้อมรัน แสดงกระบวนการทั้งหมด บันทึกเป็น `AsposeOcrDemo.java` แล้วรันจาก IDE หรือ command line ของคุณ + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### ผลลัพธ์ที่คาดว่าจะเห็นใน Console + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +หากคุณรันโปรแกรมโดยไม่มีไฟล์ลิขสิทธิ์ บรรทัดแรกจะแสดงว่าอยู่ในโหมดประเมินผลเท่านั้น แต่ OCR ยังทำงานได้ตามปกติ + +--- + +## ตั้งค่าและใช้ลิขสิทธิ์ Aspose + +### ทำไมลิขสิทธิ์ถึงสำคัญ + +การใช้ไลบรารีในโหมดประเมินผลเหมาะสำหรับการทดสอบเร็ว ๆ แต่จะมีลายน้ำบนผลลัพธ์และจำกัดจำนวนหน้าที่ประมวลผลต่อการรันหนึ่งครั้ง การทำ **ใช้ลิขสิทธิ์ Aspose** จะลบข้อจำกัดเหล่านี้และบ่งบอกให้ Aspose ทราบว่าคุณเป็นลูกค้าที่ชำระเงินแล้ว + +### วิธีรับและนำไปใช้ + +1. ซื้อไลเซนส์จากร้านค้า Aspose +2. ดาวน์โหลดไฟล์ `Aspose.OCR.Java.lic` +3. วางไฟล์ไว้ในตำแหน่งที่แอปพลิเคชันของคุณสามารถอ่านได้—โดยทั่วไปคือโฟลเดอร์ `src/main/resources` +4. เรียก `new License().setLicense("Aspose.OCR.Java.lic");` ก่อนทำงาน OCR ใด ๆ ตามที่แสดงในโค้ดด้านบน + +> **เคล็ดลับระดับมืออาชีพ:** หากคุณทำการดีพลอยไปยังเซิร์ฟเวอร์ ให้ใช้พาธแบบ absolute หรือ class‑path resource loader เพื่อหลีกเลี่ยง `FileNotFoundException` + +--- + +## โหลดรูปภาพสำหรับการประมวลผล OCR + +บรรทัด `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` เป็นหัวใจของขั้นตอน **โหลดรูปภาพสำหรับ OCR** Aspose OCR รองรับฟอร์แมตหลากหลาย: PNG, JPEG, BMP, TIFF, และแม้กระทั่ง PDF แบบหลายหน้า (เมื่อรวมกับ Aspose.Pdf) + +### ปัญหาที่พบบ่อย + +| ปัญหา | อาการ | วิธีแก้ | +|-------|---------|-----| +| พาธไฟล์ผิด | `FileNotFoundException` | ตรวจสอบพาธอีกครั้ง; ใช้ `Paths.get(...)` เพื่อให้แยกตัวคั่นแบบ OS‑independent | +| ฟอร์แมตไม่รองรับ | `UnsupportedOperationException` | แปลงภาพเป็น PNG หรือ JPEG ก่อนโหลด | +| ภาพขนาดใหญ่ (> 10 MP) | เกิดข้อผิดพลาด Out‑of‑memory | ลดขนาดภาพด้วย `java.awt.Image` ก่อนส่งให้ Aspose | + +--- + +## ดึงข้อความจากรูปภาพและจัดการผลลัพธ์ + +เมื่อเอนจิน OCR ทำงานเสร็จแล้ว วัตถุ `OcrResult` จะบรรจุสตริงที่จดจำได้ ที่นี่คือจุดที่เราจะ **ดึงข้อความจากรูปภาพ** เพื่อการประมวลผลต่อไป—เช่น บันทึกลงฐานข้อมูล, ส่งไปยังดัชนีการค้นหา, หรือส่งต่อไปยัง pipeline NLP + +### การจัดการหลายภาษา + +เพราะเราได้ตั้งค่า `engine.setLanguage(Language.Auto)` Aspose จะพยายามตรวจจับภาษาต่าง ๆ แบบอัตโนมัติ หากคุณทราบล่วงหน้าว่าภาษาเป็นอะไร (เช่น ทุกเอกสารเป็นรัสเซีย) คุณสามารถเปลี่ยน `Language.Auto` เป็น `Language.Russian` เพื่อเพิ่มประสิทธิภาพ + +### เคล็ดลับการทำ Post‑Processing + +- **ตัดช่องว่างส่วนหัว/ส่วนท้าย**: `result.getText().trim()` +- **ทำให้บรรทัดใหม่เป็นมาตรฐาน**: `result.getText().replace("\r\n", "\n")` +- **ลบอักขระที่ไม่สามารถพิมพ์ได้**: ใช้ regex เช่น `result.getText().replaceAll("[^\\p{Print}]", "")` + +--- + +## จดจำข้อความในภาพด้วยตัวเลือกขั้นสูง (ไม่บังคับ) + +หากต้องการควบคุมที่ละเอียดกว่า Aspose OCR มีคุณสมบัติเพิ่มเติมให้ใช้: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +การปรับแต่งเหล่านี้มีประโยชน์เมื่อคุณต้องจัดการกับเอกสารสแกนที่มีการเอียงหรือคอนทราสต์ต่ำ + +--- + +## สรุปตัวอย่างทำงานเต็มรูปแบบ + +เมื่อรวมทุกอย่างเข้าด้วยกัน โปรแกรมสุดท้ายทำตามลำดับดังนี้: + +1. **ทำ OCR บนรูปภาพ** – สร้าง `OcrEngine` +2. **ใช้ลิขสิทธิ์ Aspose** – ไม่บังคับแต่แนะนำ +3. **โหลดรูปภาพสำหรับ OCR** – ผ่าน `Image.load` +4. **ตั้งค่าการตรวจจับภาษา** – `Language.Auto` เพื่อ **จดจำข้อความในภาพ** อัตโนมัติ +5. **ดึงข้อความจากรูปภาพ** – พิมพ์ผลลัพธ์และจัดการกรณีผลลัพธ์ว่างอย่างราบรื่น + +คุณสามารถคัดลอกบล็อกโค้ดด้านบนไปวางในโครงการ Maven พร้อม dependency นี้ได้: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +รันคำสั่ง `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` แล้วดูข้อความที่จดจำได้แสดงบน console + +--- + +## สรุป + +เราได้แสดงวิธี **ทำ OCR บนรูปภาพ** ด้วย Aspose OCR สำหรับ Java ตั้งแต่การใช้ลิขสิทธิ์ ไปจนถึง **การโหลดรูปภาพสำหรับ OCR**, **การจดจำข้อความในภาพ**, และสุดท้าย **การดึงข้อความจากรูปภาพ** เพื่อนำไปใช้ต่อ ผลลัพธ์ตรงไปตรงมา รองรับหลายภาษาโดยไม่ต้องตั้งค่าเพิ่มเติม และสามารถขยายด้วยตัวเลือกการประมวลผลล่วงหน้าเมื่อจำเป็น + +ต่อไปคุณอาจลองนำผลลัพธ์ OCR ไปสร้างดัชนีการค้นหา, สร้าง PDF พร้อมข้อความที่แปลงแล้ว, หรือทดลองกับฟอร์แมตภาพต่าง ๆ ความเป็นไปได้ไม่มีที่สิ้นสุด และด้วย API ของ Aspose ที่แข็งแกร่ง คุณจะใช้เวลามากกว่าสร้างฟีเจอร์มากกว่าต่อสู้กับข้อจำกัดของ OCR + +มีคำถามหรือเจอกรณีขอบ? แสดงความคิดเห็นด้านล่าง—ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโครงการของคุณ + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..84ad811bd --- /dev/null +++ b/ocr/turkish/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR kullanarak bir görüntüden aranabilir PDF oluşturun. OCR'yi + PDF'ye dönüştürmeyi, görüntüden metin çıkarmayı ve görüntü üzerinde hızlıca OCR + yapmayı öğrenin. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: tr +og_description: Python OCR ile bir görüntüden aranabilir PDF oluşturun. Bu kılavuz, + OCR'yi PDF'ye dönüştürmeyi, görüntüden metin çıkarmayı ve görüntü üzerinde OCR yapmayı + gösterir. +og_title: Python’da Aranabilir PDF Oluşturma – Tam Programlama Rehberi +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Python'da Aranabilir PDF Oluşturma – Tam Adım Adım Rehber +url: /tr/python-java/general/create-searchable-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 Aranabilir PDF Oluşturma – Tam Adım‑Adım Kılavuz + +Tarayıcıdan alınan bir makbuzdan **aranabilir PDF** oluşturmanız gerektiğinde ama nereden başlayacağınızı bilemediğiniz oldu mu? Yalnız değilsiniz—birçok geliştirici, metnin bir resmini gerçekten arayabileceğiniz bir PDF'ye dönüştürmeye çalıştıklarında aynı engelle karşılaşıyor. + +Bu öğreticide, **perform OCR on image** yapmanızı, OCR sonucunu **searchable PDF**'ye dönüştürmenizi ve gerektiğinde ham metni dışa aktarmanızı sağlayan pratik bir çözümü adım adım inceleyeceğiz. Süslü şeyler yok, bugün projenize kopyalayıp yapıştırabileceğiniz çalışan bir örnek. + +## What You’ll Learn + +- Python'da hafif bir OCR motoru nasıl kurulur +- **convert OCR to PDF** adımları ve bunu aranabilir bir belge olarak kaydetme +- **extract text from image** için yöntemler ve sonraki analizler için kullanım +- Görüntü yönlendirme ve büyük dosyalar gibi yaygın tuzaklarla başa çıkma ipuçları +- Kendi kullanım senaryonuza uyarlayabileceğiniz tam, çalıştırılabilir bir betik + +### Prerequisites + +- Makinenizde Python 3.8+ yüklü +- pip ve sanal ortamlar hakkında temel bilgi (isteğe bağlı ama önerilir) +- Açık, makine‑okunabilir metin içeren bir görüntü dosyası (PNG, JPEG vb.) + +Eğer bunlara sahipseniz, başlayalım. + +## Step 1: Install the Required Library + +The code snippet you saw earlier uses a fictional `ocr` package, but the same ideas apply to real‑world libraries such as **EasyOCR**, **pytesseract**, or **pdfminer.six**. For this guide we’ll use **EasyOCR** because it’s pure Python, supports many languages, and returns a handy PDF conversion method via an auxiliary helper. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Sanal bir ortam içinde kurun (`python -m venv venv && source venv/bin/activate`) böylece bağımlılıklarınız düzenli kalır. + +## Step 2: Initialize the OCR Engine – Perform OCR on Image + +Now that the library is ready, we create an OCR engine and tell it to work with English text. This is the first place where we **perform OCR on image**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Why do we need a dedicated reader object? EasyOCR pre‑loads language models, so re‑using the same `reader` for multiple images is far more efficient than re‑initializing it each time. + +## Step 3: Load the Image – Extract Text from Image + +Let’s bring the picture into memory. This step is where we **extract text from image** later, but first we just load it. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +If your image is upside‑down or skewed, consider using Pillow’s `rotate` or `transpose` methods before feeding it to the OCR engine. A quick visual check can save you hours of debugging later. + +## Step 4: Run the OCR Engine and Capture Results + +Here’s the core of the process—sending the image to the OCR engine and getting back structured data. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +The `detail=1` flag gives us bounding boxes, which we’ll need when we later **convert OCR to PDF**. If you only care about raw strings, set `detail=0`. + +## Step 5: Convert OCR Result to a Searchable PDF – Convert OCR to PDF + +EasyOCR doesn’t provide a direct PDF writer, but we can stitch together the PDF ourselves using Pillow and the `reportlab` library. To keep the tutorial lightweight, we’ll use `fpdf2`, which lets us embed the original image and overlay invisible text. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +What just happened? We placed the scanned image as the visible layer, then wrote the recognized words on top using white text that blends into the white background. Search tools still read the hidden layer, so the PDF becomes **searchable** without altering the visual appearance. + +## Step 6: Save the PDF Bytes – Convert Image to PDF + +If you prefer to handle the PDF in memory (e.g., sending it over an API), you can capture the bytes instead of writing directly to disk. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +That line demonstrates the classic **convert image to PDF** workflow: you start with an image, run OCR, overlay text, and finally emit a PDF stream. + +## Step 7: Verify the Result – Quick Checks + +After you run the script, open `receipt_searchable.pdf` in any PDF viewer and try the search box (Ctrl + F). Type a word you know appears in the receipt—if it jumps to the right spot, you’ve successfully **create searchable pdf**! + +If the search fails, double‑check: + +1. The OCR confidence scores (`conf` values). Low confidence may mean the image is blurry. +2. Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. +3. That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers have that option). + +## Full Working Script + +Putting everything together, here’s the complete, ready‑to‑run Python file: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Save this as `searchable_pdf.py`, replace the `YOUR_DIRECTORY` placeholders with real paths, and run: + +```bash +python searchable_pdf.py +``` + +You should see a confirmation message and a brand‑new searchable PDF sitting in your folder. + +## Common Questions & Edge Cases + +**What if the image is in color?** +EasyOCR works with both grayscale and color images, but converting to grayscale (`pil_image.convert("L")`) can sometimes improve accuracy on noisy scans. + +**Can I handle multi‑page PDFs?** +Yes—loop over each page image, run the OCR steps, and append each page to the same `FPDF` object. Just remember to reset the cursor (`self.add_page()`) for each new image. + +**Is there a way to keep the original text layer instead of invisible white text?** +If you need a true “text‑under‑image” PDF (e.g., for accessibility), consider using `pdfminer` or `pikepdf` to embed a hidden text layer with proper PDF tags. That’s more advanced, but the principle remains the same: background image + overlay text. + +**What if OCR confidence is low?** +You can filter out low‑confidence words: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Wrap‑Up – What We Achieved + +We started with a simple image of a receipt, **performed OCR on image**, extracted the recognized strings, and finally **create searchable pdf** that behaves like any professionally scanned document. The process covered every secondary keyword—**convert OCR to PDF**, **extract text from image**, **convert image to PDF**, and **perform OCR on image**—so you now have a reusable toolbox for any similar project. + +### Next Steps + +- Experiment with other languages by passing their ISO codes to `easyocr.Reader(['en', 'es'])`. +- Swap EasyOCR for Tesseract if you need a fully offline solution; the rest of the pipeline stays the same. +- Add OCR confidence visualisation (draw bounding boxes on the image) to debug problematic scans. + +Got a twist you’d like to share? Drop a comment, fork + + +## 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/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [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/turkish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/turkish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..650168951 --- /dev/null +++ b/ocr/turkish/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-06-19 +description: Görsellerden metin çıkarın Python’da basit bir OCR motoru ile. Tarama + görüntülerini metne dönüştürmeyi, resimlerden metin tanımayı ve Python’da görüntü + dosyalarını verimli bir şekilde listelemeyi öğrenin. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: tr +og_description: Python'da hafif bir OCR motoru kullanarak görüntülerden metin çıkarın. + Bu rehber, taranmış görüntüleri metne dönüştürmeyi, fotoğraflardan metin tanımayı + ve birkaç adımda Python ile görüntü dosyalarını listelemeyi gösterir. +og_title: Python ile Görüntülerden Metin Çıkarma – Tam Batch OCR Kılavuzu +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Python ile Görsellerden Metin Çıkarma – Tam Batch OCR Kılavuzu +url: /tr/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python'da Görüntülerden Metin Çıkarma – Tam Batch OCR Kılavuzu + +Görüntülerden **metin çıkarmak** istediğiniz ama nereden başlayacağınızı bilemediğiniz oldu mu? Yalnız değilsiniz—geliştiriciler sürekli taranmış PDF'leri, fotoğraflanmış fişleri veya ekran görüntülerini aranabilir metne dönüştürme zorluğuyla karşılaşıyor. Bu öğreticide, **taran görüntüleri metne dönüştürmeyi**, resimlerden metin tanımayı ve hatta **list image files python**‑stilinde görüntü dosyalarını listelemeyi gösteren eksiksiz, çalıştırmaya hazır bir örnek üzerinden ilerleyeceğiz. Sonunda, bir klasörü tek seferde işleyen yeniden kullanılabilir bir betiğe sahip olacaksınız. + +İhtiyacınız olan her şeyi ele alacağız: gerekli kütüphaneler, her adımın neden önemli olduğu, kenar‑durum yönetimi ve biraz hata ayıklama. Harici belgelere koşmanıza gerek yok; aşağıdaki kod kendi içinde yeterli ve açıklamalar “nasıl” *ve* “neden” sorularını yanıtlıyor. Sevdiğiniz IDE'yi açın ve hemen işe koyulalım. + +--- + +## Ne Oluşturacaksınız + +- Bir OCR motoru başlatın (`ocr` paketini örnek olarak kullanacağız). +- Bir dizini tarayın ve **list image files python**‑stilinde PNG, JPG ve TIFF dosyalarını filtreleyin. +- Bulunan tüm resimler üzerinde bir **batch OCR** işlemi yürütün. +- Her dosya için çıkarılan metni, net bir etiketle yazdırın. + +> **Pro ipucu:** `ocr` kütüphaneniz yüklü değilse, birkaç küçük değişiklikle `pytesseract` ile değiştirebilirsiniz—temel mantık aynı kalır. + +--- + +## Önkoşullar + +- Python 3.8+ (betik f‑string ve tip ipuçları kullanıyor). +- `OcrEngine` ve `recognize_batch` sağlayan bir OCR kütüphanesi. Bu rehberde hayali bir `ocr` paketi varsayıyoruz, ancak desen gerçek kütüphanelerle de çalışır. +- İşlemek istediğiniz görüntü dosyalarını içeren bir klasör (`.png`, `.jpg`, `.tif`). + +--- + +## Adım 1 – Gerekli Modülleri Kurun ve İçe Aktarın + +Öncelikle OCR paketinin mevcut olduğundan emin olun. Gerçek bir kütüphane (ör. `pytesseract`) kullanıyorsanız, içe aktarmayı buna göre değiştirin. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Neden önemli:** `os`'yi içe aktarmak platformlar arası yol yönetimi sağlar, `typing.List` ise IDE otomatik tamamlamasını ve geleceğe dönük uyumluluğu destekler. + +--- + +## Adım 2 – **Extract Text from Images**: OCR Motorunu Başlatın + +Motoru oluşturmak, herhangi bir OCR çalışmasının ilk adımıdır. Ayrıca dili otomatik algılayacak şekilde ayarlıyoruz, böylece motor karışık dildeki belgeleri de işleyebilir. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Açıklama:** Motor oluşturmayı bir fonksiyon içinde kapsüllendirerek kodu modüler tutuyoruz. Daha sonra DPI veya OCR modunu ayarlamanız gerekirse, sadece bu noktayı değiştirmeniz yeterli olur. + +--- + +## Adım 3 – **List Image Files Python**: Dizinden Dosyaları Toplayın + +Şimdi işlemek istediğimiz her resmi bulmamız gerekiyor. Aşağıdaki liste kavraması, yaygın bir “list image files python” kalıbını yansıtıyor. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Kenar durumu yönetimi:** Fonksiyon alt‑klasörleri yok sayar (daha sonra yineleme ekleyebilirsiniz) ve gizli dosyaları otomatik olarak filtreler; çünkü genellikle desteklenen uzantılarla bitmezler. + +--- + +## Adım 4 – **Convert Scanned Images to Text**: Batch OCR Çalıştırın + +Çoğu OCR kütüphanesi, tek tek resim işlemeye göre çok daha hızlı olan bir batch yöntemi sunar. İşte nasıl çağıracağımız: + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Neden batch?** Tüm resimleri bir kerede göndermek, (ör. OCR modelini tekrar tekrar yüklemek) gibi ek yükleri azaltır ve genellikle CPU/GPU kullanımını iyileştirir. + +--- + +## Adım 5 – **Recognize Text from Pictures**: Sonuçları Görüntüleyin + +Son olarak, eşleşen dosya adları ve OCR sonuçları üzerinde döngü kurarak her resim için temiz bir başlık yazdırıyoruz. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **İpucu:** `strip()` OCR'nun sıkça eklediği baştaki/sondaki boşlukları temizler. + +--- + +## Tam Betik – Hepsini Bir Araya Getirin + +Aşağıda eksiksiz, çalıştırılabilir program yer alıyor. `batch_ocr.py` olarak kaydedin ve `python batch_ocr.py ` komutuyla çalıştırın. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Beklenen Çıktı + +Klasörün `invoice1.png` ve `receipt.jpg` içerdiğini varsayarsak, şu şekilde bir çıktı görebilirsiniz: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Her blok net bir şekilde etiketlendiği için, sonraki işlem (ör. veritabanına kaydetme) oldukça basittir. + +--- + +## Yaygın Sorunlarla Baş Etme + +| Issue | Why it Happens | Quick Fix | +|-------|----------------|-----------| +| **No text appears** | OCR language not detected or image is too low‑contrast. | Force a language (`engine.language = ocr.Language.English`) or preprocess images (increase contrast). | +| **Memory error on large batches** | The engine tries to load all images at once. | Split `image_files` into chunks (`batch_size = 20`) and call `recognize_batch` repeatedly. | +| **Unsupported file format** | You added a `.gif` or `.bmp`. | Extend `supported_exts` tuple or convert images to PNG/JPG beforehand. | +| **Unicode garbling** | OCR returns bytes instead of strings. | Ensure the OCR library outputs Unicode (`result.text.decode('utf‑8')` if needed). | + +--- + +## İş Akışını Genişletme + +Artık **extract text from images** yapabildiğinize göre, aşağıdaki adımları değerlendirin: + +- **Export to CSV** – Her dosya adını ve çıkarılan metni analiz için bir tabloya yazın. +- **Parallel processing** – `concurrent.futures.ThreadPoolExecutor` kullanarak birden çok batch'i aynı anda işleyin. +- **Integrate with cloud OCR** – Yerel motoru, daha karmaşık düzenlerde yüksek doğruluk sağlayan Google Vision veya Azure OCR ile değiştirin. +- **Add image preprocessing** – Pillow veya OpenCV gibi kütüphaneler, OCR'dan önce görüntüleri eğme, gürültü azaltma veya eşikleme yaparak sonuçları artırabilir. + +Bu fikirlerin tümü, oluşturduğumuz aynı temel fonksiyonları kullanır; bu yüzden sıfırdan başlamanıza gerek kalmaz. + +--- + +## Sonuç + +Python'da **extract text from images** için eksiksiz bir çözüm üzerinden geçtik; **list image files python**'dan **recognize text from pictures**'a ve sonunda **convert scanned images to text**'a kadar her adımı bir batch içinde ele aldık. Betik kasıtlı olarak basit, ancak daha büyük projeler için (fiş dijitalleştirme, aranabilir arşiv oluşturma veya veri çıkarma hattı) sağlam bir temel sunacak kadar esnek. + +Deneyin, ön işleme adımlarını ayarlayın ve OCR doğruluğunuzun yükseldiğini izleyin. Bir sorunla karşılaşırsanız, “Handling Common Pitfalls” tablosuna göz atın; çoğu sorun küçük bir yapılandırma değişikliğiyle çözülür. + +Bir sonraki meydan okumaya hazır mısınız? `pdf2image` kullanarak PDF‑to‑image dönüşüm adımı ekleyin, ardından bu görüntüleri aynı boru hattına besleyin. OCR ile Python ekosisteminin zengin araçlarını birleştirdiğinizde sınır yoktur. + +İyi kodlamalar, ve metniniz her zaman okunabilir olsun! + +## What Should You Learn Next? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak 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 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/) +- [Extract Text Images – OCR Basics with Aspose.OCR for Java](/ocr/english/java/ocr-basics/) +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/turkish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..3a16f84fc --- /dev/null +++ b/ocr/turkish/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-19 +description: Python OCR kullanarak görüntülerden metin çıkarın. Otomatik dil algılama, + paralel işleme ve toplu tanıma konularını kısa bir öğreticide öğrenin. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: tr +og_description: Python OCR ile görüntülerden metin çıkarın. Bu rehber, otomatik dil + algılamayı, paralel işleme ve toplu tanıma işlemlerini tek bir öğreticide gösterir. +og_title: Python'da Görüntülerden Metin Çıkarma – Tam OCR Rehberi +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python'da Görüntülerden Metin Çıkarma – Tam OCR Rehberi +url: /tr/python-java/general/extract-text-from-images-in-python-full-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python’da Görüntülerden Metin Çıkarma – Tam OCR Rehberi + +Hiç **görüntülerden metin çıkarmayı** manuel olarak her kelimeyi yazarak yapmayı düşündünüz mü? Tek başınıza değilsiniz. İster eski makbuzları dijitalleştiriyor olun, ister aranabilir bir belge arşivi oluşturuyor olun, ya da sadece havalı AI numaralarıyla oynuyor olun, resimlerden metin çekebilmek günümüz Python geliştiricileri için vazgeçilmez bir yetenek. + +Bu öğreticide, popüler bir OCR motoru kullanarak **görüntülerden metin çıkaran** tam çalışır bir örnek üzerinden adım adım ilerleyeceğiz. Otomatik dil algılamayı, hız için paralel işleme ve toplu görüntü tanımını ele alacağız; böylece onlarca dosyayı saniyeler içinde işleyebileceksiniz. Aradığınız şey bu mu? Hadi başlayalım. + +## Öğrenecekleriniz + +- `ocr.OcrEngine` ile OCR motorunu nasıl başlatacağınızı. +- Motorun kendi kendine doğru dili seçmesi için **otomatik dil algılamayı** nasıl etkinleştireceğinizi. +- Özel bir iş parçacığı havuzu ile **paralel işleme OCR** yapılandırmasını. +- Dosya listesi üzerinde **toplu görüntü tanımını** nasıl çalıştıracağınızı. +- Her görüntü için tanınan metni yazdırarak kaydetmeye veya indekslemeye hazır hale getirmeyi. + +Harici bir dokümantasyona ihtiyaç yok—gereken her şey burada ve kod `ocr` paketiyle (kurulum: `pip install ocr`) kutudan çıkar çıkmaz çalışıyor. + +## Önkoşullar + +Başlamadan önce şunların yüklü olduğundan emin olun: + +1. Python 3.8 veya daha yeni bir sürüm. +2. `ocr` paketi (`pip install ocr`). +3. İşlemek istediğiniz PNG (veya JPG) görüntülerin bulunduğu bir klasör. +4. Python fonksiyonları ve döngülerine temel aşinalık. + +Hepsi bu—ağır bağımlılıklar, GPU sihri yok, sadece saf Python. + +![extract text from images example](https://example.com/ocr-demo.png "Screenshot showing extract text from images output") + +*Alt metin: görüntülerden metin çıkarma demosu ekran görüntüsü* + +## Adım 1 – OCR Motorunu Kurun (Anahtar Kelime Eylemde) + +İlk iş: bir OCR motoru örneği oluşturun. `ocr.OcrEngine()` düşünün; bu, işlemin beynidir; karakterleri, satırları ve paragrafları nasıl okuyacağını bilir. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Neden açık bir motor örneğine ihtiyaç duyuyoruz? Çünkü **ocr.OcrEngine kullanımı** dil ayarları, iş parçacığı yönetimi ve daha fazlası üzerinde ince ayar yapmanıza olanak tanır. Tek satırlık yardımcı fonksiyonlara göre **görüntülerden metin çıkarma** konusunda en esnek yoldur. + +## Adım 2 – Motorun Dilleri Otomatik Olarak Algılamasını Sağlayın + +Çoğu OCR kütüphanesi hangi dili arayacağını sizden ister. Tek dilli bir proje için bu sorun olmaz, ancak karışık dilli bir toplu işlemde zahmetlidir. Neyse ki, `ocr` paketi **otomatik dil algılamayı** destekler. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +`engine.language` değerini `ocr.Language.Auto` olarak ayarlamak, motorun her görüntüyü koklayıp uygun dil modelini seçmesini sağlar. Bu küçük satır, uluslararası belgelerle uğraşırken saatler süren manuel yapılandırmayı ortadan kaldırır. + +## Adım 3 – Paralel İşleme OCR ile Hızı Artırın + +Dört ya da daha fazla CPU çekirdeğiniz varsa, neden kullanmayasınız? Motor bir iş parçacığı havuzu oluşturabilir ve birden fazla görüntüyü aynı anda işleyebilir. İşte **paralel işleme OCR** burada devreye girer. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Makinenize göre `4` sayısını istediğiniz gibi ayarlayın. Daha fazla iş parçacığı → daha hızlı toplu çalıştırma, ancak her iş parçacığı bellek tüketir; ortamınıza uygun bir denge bulun. + +## Adım 4 – İşlemek İstediğiniz Görüntüleri Toplayın + +Şimdi dosya yolu listesine ihtiyacımız var. Bu listeyi elle oluşturabilir, bir CSV’den okuyabilir ya da `glob` kullanabilirsiniz. Açıklık olması açısından kısa bir sabit liste tanımlayacağız: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +`YOUR_DIRECTORY` kısmını sisteminizdeki gerçek yol ile değiştirin. Eğer onlarca dosyanız varsa, `glob.glob("*.png")` gibi bir komut işinizi görecektir. + +## Adım 5 – Toplu Görüntü Tanımını Çalıştırın + +İşte öğreticinin kalbi: `files` içindeki her görüntüyü işleyen ve sonuç nesneleri listesi döndüren tek bir çağrı. Bu, büyük ölçekli OCR’u pratik hâle getiren **toplu görüntü tanımı** özelliğidir. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Arka planda motor, daha önce yapılandırdığımız dört işçi iş parçacığına dosyaları dağıtırken aynı zamanda her resim için dili otomatik algılar. Metod, tanınan metin ve meta verileri içeren bir liste döndürür. + +## Adım 6 – Çıkarılan Metni Yazdırın (Ya da Saklayın) + +Son olarak, sonuçlar üzerinde döngü kurup metni ekrana bastırıyoruz. Gerçek bir projede muhtemelen bunu bir veritabanına ya da CSV dosyasına yazarsınız, ancak örnek basit kalması için sadece yazdırıyoruz. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Beklenen çıktı** (kısaltılmış): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Her blok, dosya adını ve OCR‑türetilmiş dizeyi gösterir. Bir görüntü birden fazla dil içeriyorsa, önceki **otomatik dil algılama** adımı sayesinde uygun karakterler görünecektir. + +## İpuçları & Yaygın Tuzaklar + +- **Görüntü kalitesi önemli** – bulanık ya da düşük kontrastlı fotoğraflar çöp sonuç verir. Gerekirse OpenCV (`cv2.threshold`, `cv2.resize`) ile ön işleme yapın. +- **İş parçacığı sayısı vs. I/O** – Görüntüler yavaş bir ağ sürücüsünde bulunuyorsa, daha fazla iş parçacığı fayda sağlamaz. CPU kullanımını `top` ya da **Task Manager** ile izleyin. +- **Unicode yönetimi** – `result.text` bir Unicode dizesidir. Dosyalara yazarken `encoding="utf‑8"` ile açın, aksi takdirde `UnicodeEncodeError` alabilirsiniz. +- **Bellek tüketimi** – Büyük PDF’ler çok RAM tüketebilir. `MemoryError` alırsanız iş parçacığı havuzunu küçültün ya da görüntüleri daha küçük partiler halinde işleyin. + +## Tam Çalışan Betik + +Aşağıda, tartıştığımız tüm adımları içeren, kopyala‑yapıştır‑hazır tam betik yer alıyor. `batch_ocr.py` olarak kaydedin ve `python batch_ocr.py` komutuyla çalıştırın. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Şöyle çalıştırın: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Her görüntü için güzel biçimlendirilmiş bir metin bloğu göreceksiniz; bu da **görüntülerden metin çıkarma** işini ölçekli bir şekilde yapabildiğinizi kanıtlar. + +## Sırada Ne Var? + +Python ile **görüntülerden metin çıkarma** temellerini öğrendinize göre, aşağıdaki konuları keşfetmeyi düşünün: + +- **Post‑işleme**: OCR çıktısını regex ya da doğal dil işleme kütüphaneleriyle temizleyin. +- **PDF dönüşümü**: Çıkarılan metinleri aranabilir PDF’ler oluşturmak için bir PDF jeneratörüne besleyin. +- **Bulut OCR hizmetleri**: Yerel `ocr` sonuçlarını Google Vision veya Azure OCR ile karşılaştırarak kenar‑durum doğruluğunu ölçün. +- **GUI ön yüz**: Kullanıcıların görüntü yükleyip anında çıkarılan metni görebileceği küçük bir Flask ya da FastAPI uygulaması geliştirin. + +Bu konular, yeni kurduğunuz **Python OCR kütüphanesi** temeline dayanır ve hepsi burada kullandığımız **paralel işleme OCR** taktiklerinden faydalanır. + +--- + +*Kodlamanın tadını çıkarın! Herhangi bir sorunla karşılaşırsanız, aşağıya yorum bırakın—OCR inceliklerini birlikte çözebiliriz.* + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve ilgili konuları derinlemesine ele alan tam çalışan kod örnekleri ve adım adım açıklamalar içerir. + +- [Resimden Metin Çıkarma – Aspose OCR ile 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/) +- [Resimden Metin Çıkarma – .NET için Aspose.OCR ile OCR Optimizasyonu](/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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/turkish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..39366e6b9 --- /dev/null +++ b/ocr/turkish/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-06-19 +description: Python'da OCR kullanarak PDF'den metin nasıl çıkarılır – PDF'den metin + çıkarma, görüntüden metin tanıma ve bir OCR Python örneği kapsayan adım adım öğretici. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: tr +og_description: Python'da OCR kullanarak PDF nasıl çıkarılır. PDF'den metin çıkarmayı, + görüntüden metin tanımayı öğrenin ve tam bir OCR Python örneğini görün. +og_title: Python’da OCR ile PDF Metni Nasıl Çıkarılır – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Python’da OCR ile PDF Metni Nasıl Çıkarılır – Tam Kılavuz +url: /tr/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF Metnini OCR ile Python’da Nasıl Çıkarılır – Tam Kılavuz + +Sadece taranmış bir görüntü olduğunda **PDF içeriğini nasıl çıkaracağınızı** hiç merak ettiniz mi? Tek başınıza değilsiniz. Gerçek dünyadaki birçok projede—sözleşmeler, faturalar veya tarihi arşivler gibi—aldığınız PDF seçilebilir metin içermez. İyi haber? Birkaç Python satırı bu yalnızca görüntü sayfalarını aranabilir, düzenlenebilir metne dönüştürebilir. + +Bu öğreticide, bir PDF okuyan, ilk sayfasını görüntü olarak işleyen ve ardından bir OCR motoru kullanarak **PDF'den metin çıkarır** pratik bir **OCR Python örneği** üzerinden ilerleyeceğiz. Sonunda **OCR ile PDF okuma** yöntemini tam olarak öğrenecek, her adımın neden önemli olduğunu anlayacak ve kodu çok sayfalı belgeler veya farklı diller için nasıl uyarlayacağınızı göreceksiniz. + +## Öğrenecekleriniz + +- Python için güvenilir bir OCR kütüphanesini kurun ve yapılandırın. +- PDF sayfalarını OCR için uygun görüntülere dönüştürün. +- **Görüntüden metin tanıma** ve temiz Unicode dizgileri alın. +- Ortak tuzaklar (düşük çözünürlüklü PDF'ler, döndürülmüş sayfalar) ve bunlardan nasıl kaçınılır. +- Betik genişletilerek birden çok sayfa veya toplu işleme desteklenir. + +**Önkoşullar**: Python 3.8+, pip ve sanal ortamlar hakkında temel bir anlayış. Önceden OCR deneyimi gerekmez—sadece takip edin. + +--- + +## ## OCR ile Python’da PDF Metni Nasıl Çıkarılır + +Bu H2 başlığı, anahtar kelimemizi arama motorlarının sevdiği yerde içerir. Hadi doğrudan koda dalalım. + +### Adım 1 – Gerekli Paketleri Kurun + +İlk olarak bir OCR motoruna ihtiyacımız var. Aşağıdaki örnek popüler **ocr** paketini (Tesseract'ın ince bir sarmalayıcısı) kullanıyor. Farklı bir arka uç tercih ederseniz, kavramlar aynı kalır. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Pro ipucu:** Linux'ta ayrıca Tesseract ikili dosyasına ihtiyacınız olacak: `sudo apt-get install tesseract-ocr`. macOS kullanıcıları Homebrew üzerinden alabilir: `brew install tesseract`. + +### Adım 2 – OCR Motorunu Başlatın ve Dili Ayarlayın + +Şimdi motoru çalıştırıp İngilizce karakterleri aramasını söylüyoruz. `ocr.Language.English` ifadesini desteklenen herhangi bir dil kodu ile değiştirebilirsiniz. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Neden önemli:** Dili belirtmek, motorun dil‑spesifik sözlükler ve karakter modelleri uygulayabilmesi sayesinde doğruluğu büyük ölçüde artırır. + +### Adım 3 – PDF Sayfasını Görüntü Olarak Yükleyin + +OCR, PDF nesneleri yerine raster görüntüler üzerinde çalışır. `ocr.Image.from_pdf` yardımcı işlevi seçilen sayfayı bitmap olarak işler. Diğer sayfalar için `page_number` değerini ayarlayın (0‑tabanlı indeksleme). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Köşe durumu:** PDF taranmış görüntüler yerine vektör grafikler içeriyorsa, net bir işleme alabilirsiniz. Düşük çözünürlüklü taramalar için DPI'yi artırmayı düşünün: `ocr.Image.from_pdf(..., dpi=300)`. + +### Adım 4 – İşlenen Görüntüden Metin Tanıma + +İşte **ocr python örneği**nin kalbi. Motor bitmap'i işler ve çıkarılan dizeyi içeren bir nesne döndürür. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +`ocr_result.text` özniteliği, mümkün olduğunda satır sonlarını koruyan düz metin çıktısını tutar. + +### Adım 5 – Çıkarılan Metni Yazdırın veya Saklayın + +Son olarak sonucu çıktılarız. Gerçek bir uygulamada muhtemelen bir dosyaya veya veritabanına yazarsınız. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Betik çalıştırıldığında aşağıdakine benzer bir şey göstermelidir: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Bu, OCR kullanarak tam bir **extract text from pdf** iş akışıdır. + +--- + +## ## Görüntüden Metin Tanıma – Doğruluğu Ayarlama + +Sadece **recognize text from image** (örneğin bir makbuzun JPEG'i) ile ilgileniyorsanız, PDF dönüştürme adımını atlayabilirsiniz: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Daha iyi sonuçlar için ipuçları:** + +- **Ön‑işleme**: görüntüyü gri tonlamaya dönüştürün, eşikleme uygulayın veya eğikliği düzeltin. Pillow bunu kolaylaştırır. +- PDF işleme sırasında **DPI'yi artırın**: daha yüksek çözünürlük OCR motoruna daha fazla detay sağlar. +- Sayfa segmentasyonu için OCR motorunun **konfigürasyonunu etkinleştirin** (`ocr_engine.config = "--psm 6"` tek tip bloklar için). + +## ## OCR ile PDF Okuma – Çoklu Sayfaları İşleme + +Çoğu sözleşme birkaç sayfadan oluşur. Her sayfayı döngüyle işlemek basittir: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Bu fonksiyon **OCR ile PDF okur**, çıktıyı birleştirir ve net bir sayfa sonu işareti ekler. Ardından `full_text`'i bir arama indeksine besleyebilir veya `.txt` dosyası olarak saklayabilirsiniz. + +## ## Yaygın Tuzaklar ve Çözümleri + +| Belirti | Muhtemel Neden | Çözüm | +|---------|----------------|------| +| Bozuk karakterler, çok sayıda `?` | Yanlış dil veya eksik dil veri dosyaları | Doğru Tesseract dil paketini (`tesseract-ocr-`) kurun ve `ocr_engine.language` ayarlayın. | +| Eksik satırlar veya kesik kelimeler | Düşük DPI (150'nin altında) | PDF'i 300 DPI veya daha yüksek (`dpi=300`) renderlayın. | +| Metin döndürülmüş veya ters | Taran sayfa dikey değil | Tanımadan önce `ocr.Image.deskew(page_image)` kullanın. | +| Büyük PDF'lerde yavaş işleme | Sayfalar tek bir iş parçacığında sırayla işleniyor | `concurrent.futures.ThreadPoolExecutor` ile paralelleştirin. | + +## ## OCR Python Örneğini Genişletme + +- **PDF/A'ya dışa aktar**: Çıkarma sonrası metni `reportlab` veya `pypdf2` kullanarak aranabilir bir PDF'e gömebilirsiniz. +- **Dil algılama**: OCR çıktısında `langdetect` kullanarak `ocr_engine.language`'ı dinamik olarak değiştirebilirsiniz. +- **Toplu işleme**: `os.listdir` ile bir dizini dolaşın ve `extract_all_pages` fonksiyonunu her dosyaya uygulayın. + +## ## Beklenen Çıktı ve Doğrulama + +Betik, net bir İngilizce tarama üzerinde çalıştırıldığında, uygun noktalama işaretleriyle temiz bir metin bloğu görmelisiniz. Doğrulamak için: + +1. Birkaç satırı orijinal taranmış görüntüyle karşılaştırmak. +2. Çıktının boş olmadığını kontrol etmek için basit bir kelime sayımı çalıştırmak (`len(ocr_result.text.split())`). +3. İsteğe bağlı olarak, sonucu `pyspellchecker` gibi bir yazım denetleyicisine besleyerek OCR hatalarını tespit etmek. + +## Sonuç + +Geleneksel ayrıştırmanın başarısız olduğu durumlarda **PDF içeriğini nasıl çıkaracağınızı** ele aldık, tam bir **ocr python örneği** gösterdik ve hem tek sayfalı hem çok sayfalı senaryolar için **görüntüden metin tanıma** ve **OCR ile PDF okuma** yöntemlerini açıkladık. Yukarıdaki kod parçacıklarıyla artık herhangi bir taranmış PDF'yi aranabilir, düzenlenebilir metne dönüştürebilirsiniz—artık manuel yeniden yazma yok. + +Sonraki adımlar? Dili İspanyolcaya (`ocr.Language.Spanish`) değiştirin veya doğruluğu artırmak için görüntü ön‑işleme teknikleriyle deney yapın. Bir belge‑yönetim sistemi oluşturuyorsanız, çıkarılan metni Elasticsearch ile indekslemeyi düşünün, böylece ışık hızında arama elde edersiniz. + +Sorularınız mı var ya da tuhaf bir PDF ile mi karşılaştınız? Yorum bırakın, iyi kodlamalar! + +![How to extract PDF using OCR in Python](image.png "How to extract PDF using OCR in Python") + +## 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ı olacak 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/) +- [PDF Metnini Tanıma – Aspose.OCR ile Java için OCR İşlemleri](/ocr/english/java/ocr-operations/) +- [Aspose.OCR kullanarak C# ile görüntü metni çıkarma ve dil seçimi](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/turkish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..95179e834 --- /dev/null +++ b/ocr/turkish/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-06-19 +description: Aspose ile Java’da OCR kullanımını öğrenin. Bu adım adım rehber, otomatik + eğikliği düzeltme, otomatik dil algılama ve metin görüntüsünü kolayca çıkarma konularını + kapsar. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: tr +og_description: 'Aspose ile Java’da OCR nasıl kullanılır: otomatik eğrilik düzeltme, + otomatik dil algılama ve resimlerden metin çıkarma konularını kapsayan tam bir rehber.' +og_title: Aspose ile Java'da OCR Nasıl Kullanılır – Tam Rehber +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Aspose ile Java'da OCR Kullanımı – Tam Rehber +url: /tr/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose ile Java’da OCR Kullanımı – Tam Kılavuz + +Java projesinde **OCR nasıl kullanılır** diye hiç merak ettiniz mi, konfigürasyon yüzünden saçınızı yolmak zorunda kalmadan? Tek başınıza değilsiniz. Birçok geliştirici, özellikle kaynak taramalar eğik olduğunda veya bilinmeyen bir dilde yazıldığında, **görüntüden metin çıkarma** verilerini hızlıca almaya çalışırken bir duvara çarpar. + +Bu öğreticide, **auto deskew images**, **auto language detection** ve tam **ocr image preprocessing** işlem hattını içeren, Aspose ile OCR nasıl kullanılacağını adım adım gösteren bir örnek üzerinden ilerleyeceğiz. Sonunda, tanınan metni konsola yazdıran çalıştırılabilir bir kod parçacığına sahip olacaksınız ve her ayarın neden önemli olduğunu anlayacaksınız. + +> **Ne elde edeceksiniz:** tam, çalıştırılabilir bir Java programı, her satırın açıklamaları, kenar durumlarını ele alma ipuçları ve çözümü toplu işleme veya PDF’lere genişletme fikirleri. + +--- + +## Önkoşullar + +- Java 17 (veya herhangi bir yeni JDK) yüklü ve yapılandırılmış. +- Bağımlılık yönetimi için Maven veya Gradle (Maven koordinatlarını göstereceğiz). +- Aspose OCR for Java lisans dosyası (`Aspose.OCR.Java.lic`). Sadece test ediyorsanız lisans adımını atlayabilirsiniz, ancak ücretsiz deneme bir filigran ekleyecektir. +- Kodun erişebileceği bir yerde konumlandırılmış örnek bir görüntü (`your_image.png`). + +> **Pro tip:** Görüntülerinizi ayrı bir `resources` klasöründe tutun ve sınıf yolu üzerinden yükleyin; bu, farklı işletim sistemlerinde yol‑ile ilgili baş ağrılarını önler. + +## Adım 1: Projeyi Kurun ve Aspose OCR Bağımlılığını Ekleyin + +Yeni bir Maven projesi oluşturun (veya mevcut olanı kullanın) ve `pom.xml` dosyanıza aşağıdakileri ekleyin: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn clean install` komutunu çalıştırarak kütüphaneyi indirin. Gradle tercih ediyorsanız eşdeğeri şudur: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Artık **ocr image preprocessing** sınıfları sınıf yolunuzda. + +## Adım 2: Aspose OCR Lisansınızı Uygulayın (Opsiyonel ama Tavsiye Edilir) + +Bir lisansınız varsa, `main` metodunuzun başında uygulayın. Bu adımı atlamak çalışır, ancak ücretsiz sürüm çıktıya “Demo” filigranı ekler. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Neden önemli:** Lisanslı sürüm kullanım limitlerini kaldırır ve filigranı devre dışı bırakır, size temiz, üretim‑hazır sonuçlar verir. + +## Adım 3: OCR Motoru Örneğini Oluşturun + +Motor, sürecin kalbidir. Örneği oluşturmak, tüm **ocr image preprocessing** seçeneklerine erişim sağlar. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Bu noktada motor hazır, ancak taranmış belgeler için optimal olmayabilecek varsayılan ayarları kullanacaktır. Birkaç ayarı ince ayarlayalım. + +## Adım 4: Daha Temiz Taramalar İçin Auto Deskew Images’ı Etkinleştirin + +Eğik taramalar yaygın bir sıkıntıdır. Aspose, tanımadan önce resmi otomatik olarak düzleştiren bir **auto deskew images** özelliği sunar. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Nasıl çalışır:** Algoritma, metin taban çizgisi açılarını analiz eder ve resmi en olası dik konuma döndürür. Bu, telefonla çekilen fotoğrafların doğruluğunu büyük ölçüde artırır. + +## Adım 5: Auto Language Detection’ı Açın + +Kaynak görüntünün dilini bilmiyorsanız, motorun bunu bulmasına izin verin. Bu, **auto language detection** ayarıdır. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Bunu etkinleştirdiğinizde, Aspose glifleri tarar ve kutudan çıkar çıkmaz 30’dan fazla dili destekleyen en olası dil modelini seçer. + +## Adım 6: Tanımak İstediğiniz Görüntüyü Yükleyin + +Bir görüntüyü diskten, bir URL’den veya bir bayt dizisinden yükleyebilirsiniz. Basitlik açısından yerel bir dosyadan okuyacağız. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **İpucu:** Büyük görüntülerle çalışıyorsanız, işleme süresini çok fazla detay kaybetmeden hızlandırmak için önce `engine.getImagePreprocessing().setResizeFactor(0.5)` ile yeniden örneklemeyi düşünün. + +## Adım 7: OCR Tanıma İşlemini Gerçekleştirin ve Görüntü Metnini Çıkarın + +Şimdi motor sihrini gösteriyor. `recognize` metodu, tanınan metin, güven puanları ve daha fazlasını içeren bir `OcrResult` nesnesi döndürür. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Konsol, resimden çıkarılan düz metni gösterecek – bu, ulaşmak istediğimiz temel **extract text image** sonucudur. + +## Tam Çalışan Örnek + +Aşağıda her şeyi bir araya getiren tam Java sınıfı yer alıyor. `src/main/java/com/example/OcrDemo.java` içine kopyalayıp çalıştırın. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Beklenen Çıktı + +Görüntü temiz bir tarama üzerinde “Hello World” ifadesi içeriyorsa şu çıktıyı görürsünüz: + +``` +=== Recognized Text === +Hello World +``` + +Daha karmaşık belgeler (ör. çok dilli makbuzlar) için çıktı satır sonları ve algılanan dil kodunu içerecektir. + +## Yaygın Tuzaklar & Pro İpuçları + +| Sorun | Neden Oluşur | Çözüm | +|-------|--------------|------| +| **Garbage karakterler** | Görüntü çok karanlık veya gürültülü. | `engine.getImagePreprocessing().setBinarization(true)`'ı etkinleştirin veya kontrastı manuel ayarlayın. | +| **Yanlış dil** | Otomatik algılama karışık‑dilli sayfalarda başarısız olur. | `engine.setLanguage(Language.English)` (veya uygun enum) ayarlayarak belirli bir dili zorlayın. | +| **Yavaş işleme** | Çok yüksek çözünürlüklü görüntüler. | `engine.getImagePreprocessing().setResizeFactor(0.5)` ile küçültün. | +| **Bellek dışı hatalar** | Bir kerede büyük bir görüntü topluluğu yüklendiğinde. | Görüntüleri sırayla işleyin ve her çalıştırmadan sonra `engine.dispose()` çağırın. | + +> **Unutmayın:** OCR motoru yalnızca okuma‑only işlemler için iş parçacığı‑güvenlidir, ancak her iş parçacığı için yeni bir örnek oluşturmak gizli durum hatalarını önler. + +## Çözümü Genişletmek + +Artık **OCR nasıl kullanılır** konusunda bilgi sahibi olduğunuza göre şunları yapmak isteyebilirsiniz: + +1. **PDF’leri İşlemek** – Her PDF sayfasını bir görüntüye (`PdfConverter`) dönüştürün ve aynı işlem hattına besleyin. +2. **Klasörü Toplu İşlemek** – Bir dizindeki dosyalar üzerinde döngü kurun, aynı adımları uygulayın ve sonuçları bir CSV’ye yazın. +3. **Web Servisi ile Entegre Etmek** – OCR mantığını, çok parçalı yüklemeleri kabul eden bir Spring Boot `@RestController` aracılığıyla dışa açın. + +Tüm bu senaryolar, burada oluşturduğumuz aynı **ocr image preprocessing** yapılandırmasını yeniden kullanır. + +## Sonuç + +Java’da Aspose ile **OCR nasıl kullanılır** konusunu baştan sona ele aldık: lisans uygulama, motor oluşturma, **auto deskew images**’ı açma, **auto language detection**’ı etkinleştirme, görüntü yükleme ve sonunda tek bir `System.out.println` ile **extract text image** yapma. Kod tamamen bağımsız, herhangi bir yeni JDK’da çalışır ve doğruluk ile performans için en iyi uygulamaları gösterir. + +Kendi resimlerinizle deneyin—belki taranmış bir sözleşme ya da bir makbuz ekran görüntüsü. Ön‑işleme bayraklarını ayarlayın, farklı dillerle deney yapın ve Aspose’un OCR kütüphanesinin üretim‑düzeyinde metin çıkarımı için neden sağlam bir tercih olduğunu çabucak göreceksiniz. + +Sorularınız mı var ya da sonuçlarınızı paylaşmak mı istiyorsunuz? Aşağıya bir yorum bırakın ya da GitHub’da bana mesaj atın. Mutlu kodlamalar! + +--- + +![Java’da OCR kullanımı örneği](/images/ocr-java-example.png "Java’da OCR Kullanımı – Aspose demo ekran görüntüsü") + + +## Sonraki Öğrenmeniz Gerekenler + + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak 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ı olacak tam çalışan kod örnekleri ve adım adım açıklamalar içerir. + +- [Aspose.OCR Kullanarak Görüntü Metnini Dil ile OCR Yapma](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR Detect Areas Modu ile Java’da Görüntüden Metin Çıkarma](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [OCR Kullanımı - Java için Aspose.OCR ile İleri Teknikler](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/turkish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..a3570e170 --- /dev/null +++ b/ocr/turkish/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR kullanarak Python'da OCR doğruluğunu artırın. OCR dilini nasıl + ayarlayacağınızı, OCR için görüntüyü nasıl yükleyeceğinizi ve özel bir sözlükle + görüntüden metin nasıl çıkarılacağını öğrenin. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: tr +og_description: Python'da OCR doğruluğunu artırmak için OCR dilini ayarlayın, OCR + için bir görüntü yükleyin ve özel bir sözlükle görüntüden metin çıkarın. +og_title: Python'da OCR Doğruluğunu Artırın – Adım Adım Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Python'da OCR Doğruluğunu Artırma – Tam Kılavuz +url: /tr/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python’da OCR Doğruluğunu Artırma – Tam Kılavuz + +Metin taradığınızda garip semboller, ürün kodları ya da marka adları içeriyorsa **OCR doğruluğunu artırmanın** yollarını hiç merak ettiniz mi? Yalnız değilsiniz. Birçok projede varsayılan motor sadece anlamsız karakterler üretir ve bu gerçek bir verimlilik kaybıdır. + +Bu öğreticide, **OCR dilini ayarlama**, **görüntüyü OCR için yükleme**, **görüntü üzerinde OCR gerçekleştirme** ve son olarak **görüntüden metin çıkarma** adımlarını gösteren pratik, uçtan‑uza bir örnek üzerinden ilerleyeceğiz. Ayrıca tanıma oranlarını artıran özel bir sözlük de ekleyeceğiz. Sonunda, herhangi bir Python kod tabanına ekleyebileceğiniz çalıştırmaya hazır bir betiğe sahip olacaksınız. + +## Öğrenecekleriniz + +- PNG dosyasını okuyan Aspose OCR kullanan tam işlevsel bir Python betiği. +- Dil ve özel kelime listesi yapılandırarak **OCR doğruluğunu artırma** yeteneği. +- Her ayarın neden önemli olduğuna dair net açıklamalar ve Latin dışı karakterler gibi kenar durumlarını ele almanın ipuçları. +- Yaygın OCR tuzaklarını gidermek için hızlı bir kontrol listesi. + +### Ön Koşullar + +- Makinenizde yüklü Python 3.8 veya daha yeni bir sürüm. +- `aspose-ocr` paketi (`pip install aspose-ocr` ile kurulur). +- Okumak istediğiniz metni içeren örnek bir görüntü (`technical_doc.png`). +- Python’a temel aşinalık—fantezi bir şey gerekmez. + +> **Pro tip:** Sanal bir ortamda çalışıyorsanız, paketi kurmadan önce ortamı etkinleştirin. Bağımlılıklarınızı düzenli tutar ve sürüm çakışmalarını önler. + +--- + +## Adım 1: Aspose OCR’yi Kurun ve İçe Aktarın + +İlk iş olarak, kütüphaneyi ortamımıza ekleyip ihtiyacımız olan parçaları içe aktaralım. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +`aspose.ocr` ad alanı, OCR sürecinin kalbi olan `OcrEngine` sınıfına erişim sağlar. Burada içe aktarmak, betiğin geri kalanını temiz ve okunabilir tutar. + +--- + +## Adım 2: Bir OCR Motoru Oluşturun ve **OCR Dilini Ayarlayın** + +Dil neden önemlidir? OCR motorları, karakter şekillerini ve kelime kalıplarını tanımak için dile özgü modeller kullanır. Motorunuza İngilizce metin taradığınızı söylerseniz, Kiril alfabindeki karakterleri görmezden gelir ve Latin alfabine odaklanır; bu da **OCR doğruluğunu büyük ölçüde artırır**. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Not:** Aspose OCR 50’den fazla dili destekler. Belgeniz İngilizce değilse `ocr.Language.English` yerine `ocr.Language.Spanish`, `ocr.Language.French` vb. kullanın. + +--- + +## Adım 3: **Doğruluğu Artırmak İçin Özel Sözlük** Tanımlayın + +Faturalarınızda “AsposeOCR” gibi bir kelime ya da “SKU12345” gibi ürün kodları olduğunu hayal edin. Motor bu terimleri bilmediği için yanlış tahminlerde bulunur. Özel bir kelime listesi sağlamak, motora *“Bu dizgiler geçerli—düzeltme yapma.”* demek gibidir. Bu, **OCR doğruluğunu artırma** için hızlı bir kazanımdır. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Bu listeyi bir dosyadan ya da veritabanından da yükleyebilirsiniz; basitlik açısından bir Python listesinde tutmak yeterlidir. + +--- + +## Adım 4: **OCR İçin Görüntüyü Yükleyin** + +Şimdi bir görüntüye ihtiyacımız var. `Image.load` metodu, desteklenen herhangi bir raster formatının (PNG, JPEG, BMP vb.) yolunu kabul eder. Dosya bulunamazsa motor bir istisna fırlatır; bu yüzden buna karşı önlem alacağız. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Bu adımın önemi:** Görüntüyü doğru şekilde yüklemek, motorun analiz etmek istediğiniz tam piksel verileriyle çalışmasını sağlar. Bozuk dosyalar ya da yanlış yollar sıkça hayal kırıklığı yaratır. + +--- + +## Adım 5: **Görüntü Üzerinde OCR Gerçekleştirin** ve Sonuçları Çıkarın + +Motor yapılandırıldı ve görüntü hazır olduğunda, gerçek tanıma tek bir metod çağrısıdır. Sonuç nesnesi ham metni, güven skorlarını ve hatta isterseniz daha sonra kullanabileceğiniz yerleşim bilgilerini içerir. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Metni satır satır **görüntüden metin çıkarma** ihtiyacınız varsa, yeni satır karakterlerine göre bölünebilir: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Adım 6: Çıktıyı Doğrulayın – Gerçekten **OCR Doğruluğunu Artırdı** mı? + +Sonucu yazdıralım ve özel sözlüğümüzün bir fark yaratıp yaratmadığını görelim. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Örnek görüntü için tipik çıktı şöyle görünebilir: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Marka adı, Yunan karakteri ve ürün kodunun tam olarak tanımladığımız gibi göründüğüne dikkat edin. Özel sözlük olmadan motor bunları “Aspose OCR” ya da “SKU 1234” gibi düzeltmeye çalışırdı. + +--- + +## Yaygın Tuzaklar ve Çözüm Önerileri + +| Sorun | Neden Oluşur | Çözüm | +|-------|--------------|------| +| **Çöp karakterler** | Yanlış dil ayarı veya düşük çözünürlüklü görüntü | `engine.language` kaynağın diline eşleştiğinden ve yüksek DPI tarama (300 dpi veya üzeri) kullandığınızdan emin olun. | +| **Özel kelimeler yok sayılıyor** | Sözlük eklenmemiş veya özellik adında yazım hatası | `engine.text_processing.custom_dictionary = …` satırını iki kez kontrol edin. | +| **Dosya bulunamadı** | Yanlış yol veya eksik dosya izinleri | `os.path.abspath()` ile mutlak yolu doğrulayın; betiği uygun izinlerle çalıştırın. | +| **Yavaş işleme** | Büyük görüntüler veya çok sayıda sayfa | Görüntüyü ön‑işleyin (kırp, yeniden boyutlandır) veya `engine.recognize(image, max_threads=4)` ile paralel çalıştırın. | + +--- + +## Daha İleri: **OCR Doğruluğunu Artırmak** İçin Gelişmiş Ayarlar + +1. **Ön‑işleme** – Görüntüyü Aspose OCR’ye göndermeden önce Pillow ile kontrast artırma ya da ikilileştirme uygulayın. +2. **Birden Çok Dil** – `engine.language = ocr.Language.English | ocr.Language.French` ile çift‑dilli tanıma etkinleştirin. +3. **Bölge‑Bazlı OCR** – Sadece belirli bir alan (ör. tablo) gerekiyorsa, gürültüyü azaltmak için önce görüntüyü kırpın. +4. **Güven Skoru Filtreleme** – `result.confidence` her karakter için bir puan verir; düşük güvenilir sonuçları programatik olarak elerken kullanabilirsiniz. + +--- + +## Tam Çalışan Betik + +Aşağıda, tartıştığımız tüm adımları içeren, kopyala‑yapıştır‑hazır betik yer alıyor. `improve_ocr_accuracy.py` adıyla kaydedin ve komut satırından çalıştırın. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Çalıştırın: + +```bash +python improve_ocr_accuracy.py +``` + +Daha önce gösterdiğimiz güzel biçimlendirilmiş çıktıyı göreceksiniz. + +--- + +## Sonuç + +Python’da **OCR doğruluğunu artırmanın** basit bir yolunu şu adımlarla ele aldık: + +1. **OCR dilini** belgenize uygun şekilde ayarlama. +2. **Görüntüyü doğru şekilde** yükleyerek motorun doğru pikselleri görmesini sağlama. +3. **Görüntü üzerinde OCR** tek bir metod çağrısıyla gerçekleştirme. +4. **Görüntüden metin çıkarma** ve sonucu doğrulama. +5. **Özel sözlük** ekleyerek alan‑spesifik terimleri sabitleme. + +Bu, ham fotoğraftan temiz, aranabilir metne kadar tüm süreci, düzenli ve yeniden kullanılabilir bir betikle birleştirir. + +Bir sonraki adım için, görüntü ön‑işleme (kontrast, eğikliği düzeltme) deneyebilir ya da `ocr.Language.English | ocr.Language.German` gibi çok‑dilli bir yapılandırmaya geçebilirsiniz. Aynı prensipler geçerlidir ve **OCR doğruluğunu artırmaya** devam edersiniz. + +Sorularınız veya tuhaf bir kenar durumunuz mu var? Aşağıya yorum bırakın, iyi kodlamalar! + +![improve OCR accuracy + + +## Sonraki Öğrenmeniz Gerekenler + + +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 projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım‑adım açıklamalı tam çalışan kod örnekleri içerir. + +- [Görüntüden Metin Çıkarma – Aspose.OCR for .NET ile OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) +- [Aspose OCR ile Çoklu Dillerde Metin Tanıma](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [OCR Görüntü Tanımasında Eşik Değeri Nasıl Ayarlanır](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/turkish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..85e13a0a8 --- /dev/null +++ b/ocr/turkish/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-19 +description: Python'un OCR kütüphanesini kullanarak görüntüde OCR yapın. Görüntüden + metin algılamayı, JPEG'den metin tanımayı ve taranmış görüntüden metni verimli bir + şekilde çıkarmayı öğrenin. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: tr +og_description: Python ile görüntüde OCR yapın ve taranmış dosyalardan metin çıkarın. + Bu rehber, görüntüleri yükleme, eğrilikleri düzeltme ve metni adım adım tanıma sürecini + size anlatır. +og_title: Python'da Görüntü Üzerinde OCR Yapın – Tam Metin Çıkarma Rehberi +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Python'da Görüntü Üzerinde OCR Yapın – Tam Metin Çıkarma Rehberi +url: /tr/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntüde OCR Yapma – Python’da Tam Metin Çıkarma Kılavuzu + +Hiç **görüntü dosyalarında OCR gerçekleştirmek** istediğinizde kodun çok karmaşık görünmesi nedeniyle takıldınız mı? Tek başınıza değilsiniz. Tarama fişlerini aranabilir PDF’lere dönüştürmek ya da bir veri‑bilim projesi için JPEG’den altyazı çekmek isterken, JPEG ve diğer formatlardan metin tanıma yeteneği, günümüz geliştiricileri için vazgeçilmez bir beceridir. + +Bu öğreticide, **görüntü dosyalarından metin algılamak**, **taralı görüntü belgelerinden metin çıkarmak** ve hatta **OCR için görüntü yüklemek** için sadece birkaç satır kodla çalışan tam bir örnek üzerinden adım adım ilerleyeceğiz. Sonuna geldiğinizde, eksik import’lar ya da “belgelere bakın” gibi belirsiz kısaltmalar olmadan, kendi projelerinize doğrudan ekleyebileceğiniz üretim‑hazır bir snippet elde edeceksiniz. + +## Ne Oluşturacaksınız + +- JPEG (veya desteklenen herhangi bir format) yükleyen, otomatik eğim düzeltmesini (auto‑deskew) etkinleştiren ve tanınan metni ekrana yazdıran küçük bir Python betiği. +- **Neden** her ayarın önemli olduğuna dair açıklamalar, sadece **nasıl** yazılacağına odaklanmadan. +- Çok sayfalı PDF’ler, İngilizce dışı diller ve bulanık taramalar gibi yaygın sorunlarla başa çıkma ipuçları. + +### Önkoşullar + +- Python 3.8+ yüklü (örnek, `pip install ocr-lib` ile temin edilebilen `ocr` paketini kullanıyor – kendi kütüphane adınızı buraya koyun). +- Python fonksiyonları ve sanal ortamlar hakkında temel bilgi. +- İşlemek istediğiniz bir görüntü dosyası (JPEG, PNG, TIFF); örnek olarak `skewed_page.jpg` dosyasını kullanacağız. + +> **Pro ipucu:** Windows kullanıyorsanız, OCR kütüphanesini kurarken izin sorunlarından kaçınmak için terminali Yönetici olarak çalıştırın. + +--- + +## Görüntüde OCR Yapma – Kurulum ve Yapılandırma + +İlk olarak temiz bir OCR motoru örneğine ihtiyacınız var. Bunu, işlemin beyni olarak düşünün; doğru yapılandırma olmadan en keskin görüntü bile anlamsız sonuç verir. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Neden önemli:** `engine.language` ayarı, OCR motorunun beklediği karakter kümesini daraltır ve doğruluğu büyük ölçüde artırır. Bu ayarı atladığınızda motor tahmin yapmaya çalışır ve basit kelimeleri sık sık yanlış okur. + +--- + +## Otomatik Eğimi Düzeltmeyi Etkinleştir – Eğik Taramaları Düzeltme + +Tarama sayfaları nadiren tamamen düz olur. Hafif bir eğim, karakter segmentasyonunu bozabilir ve “Hello” kelimesini “H3llo” hâline getirebilir. `auto_deskew` bayrağı bu işi sizin için halleder. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Köşe durumu:** Görüntülerinizin zaten düz olduğunu biliyorsanız, deskew’i devre dışı bırakmak işleme süresinden birkaç milisaniye kazandırabilir – binlerce sayfayı toplu işte işlerken faydalıdır. + +--- + +## OCR için Görüntü Yükleme – JPEG, PNG, TIFF Desteği + +Şimdi gerçekten **OCR için görüntü yükleme** adımına geçiyoruz. `ocr.Image.load` metodu esnektir; desteklenen herhangi bir raster formatının yolunu kabul eder. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Bu adımın önemi:** Kütüphane dosyayı dahili bir bitmap’e okur, gerekirse renk uzayı dönüşümünü uygular. Bu adımı atlayıp ham bir bayt akışı geçirirseniz `FileNotFoundError` alır ya da daha kötüsü sessizce boş sonuçlar üretir. + +Eğer özellikle **JPEG’den metin tanımak** istiyorsanız, dosya uzantısının `.jpeg` ya da `.jpg` olduğundan emin olun. Aynı çağrı PNG (`.png`) veya TIFF (`.tif`) için de değişiklik yapmadan çalışır. + +--- + +## Görüntüde OCR Yapma – Motoru Çalıştırma + +Motor hazır ve görüntü bellekteyken, **görüntüde OCR yapma** zamanıdır. Bu tek satır, ön‑işleme, segmentasyon, sınıflandırma ve metin birleştirme işlemlerinin tamamını gerçekleştirir. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Arka planda ne oluyor?** +- Motor, deskew dönüşümünü uygular (eğer etkinleştirildiyse). +- Karakterleri tanımlamak için bir sinir ağı ya da Tesseract arka ucunu çalıştırır. +- Son olarak karakterleri kelimelere ve satırlara diker, zengin bir `result` nesnesi döndürür. + +--- + +## Taralı Görüntüden Metin Çıkarma – Sonuçları Görüntüleme + +Son adım, **taralı görüntüden metin çıkarmak** ve ekrana bastırmaktır. `result.text` özelliği, düz‑metin temsilini içerir. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Tipik çıktı şu şekildedir: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +OCR motoru hiçbir karakter bulamazsa, `result.text` boş bir dize olur. Bu durumda görüntü kalitesini tekrar kontrol edin ya da `engine.confidence_threshold` özelliğini (kütüphaneniz destekliyorsa) ayarlamayı düşünün. + +--- + +## Yaygın Varyasyonlarla Baş Etme + +### JPEG vs PNG’den Metin Tanıma + +Her iki format da desteklenir, ancak JPEG sıkıştırması motoru şaşırtabilecek artefaktlar oluşturabilir. Sık sık hatalı tanıma görüyorsanız, JPEG’i önce PNG’ye dönüştürmeyi deneyin: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Çoklu Dillerle Görüntüden Metin Algılama + +Belgeniz İngilizce ve İspanyolca karışıyorsa, çok dilli modu etkinleştirin: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Motor, tanıma sırasında her iki alfabeyi de dikkate alır. + +### Taralı PDF’lerden Metin Çıkarma + +PDF’ler için önce her sayfayı bir görüntüye rasterleştirmeniz gerekir. `pdf2image` gibi kütüphaneler bu işlemi zahmetsiz hâle getirir: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Tam Çalışan Örnek + +Aşağıda, `ocr_demo.py` dosyasına kopyalayıp yapıştırabileceğiniz eksiksiz betik yer alıyor. Hata yönetimi ve yürütme süresini ölçen küçük bir yardımcı fonksiyon içeriyor. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Beklenen çıktı** (temiz bir tarama varsayımıyla): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Sık Sorulan Sorular + +**S: Bunu başsız (headless) bir sunucuda çalıştırabilir miyim?** +C: Kesinlikle. Kütüphane GUI olmadan çalışır; sadece gerekli yerel ikili dosyaların (ör. Tesseract) sunucuda kurulu olduğundan emin olun. + +**S: Görüntü bulanıktaysa ne yapmalıyım?** +C: `engine.recognize` öncesinde bir keskinleştirme filtresi eklemeyi düşünün. Birçok OCR kütüphanesi `image_preprocessing.sharpen = True` seçeneği sunar ya da OpenCV’nin `cv2.GaussianBlur` tersini kullanabilirsiniz. + +**S: Betik toplu işleme (batch) destekliyor mu?** +C: Evet. `perform_ocr` fonksiyonunu bir dosya yolu listesi üzerinde döngüye alarak kullanabilirsiniz, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/turkish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..1465bcf90 --- /dev/null +++ b/ocr/turkish/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Aspose OCR Java kullanarak görüntüde OCR gerçekleştirin. OCR için görüntüyü + nasıl yükleyeceğinizi, Aspose lisansını nasıl kullanacağınızı ve dakikalar içinde + görüntüden metin nasıl çıkarılacağını öğrenin. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: tr +og_description: Aspose OCR Java ile görüntüde OCR gerçekleştirin. Bu rehber, Aspose + lisansını nasıl kullanacağınızı, OCR için görüntüyü nasıl yükleyeceğinizi ve görüntüden + metni verimli bir şekilde nasıl çıkaracağınızı gösterir. +og_title: Aspose OCR Java ile Görüntüde OCR Yapın – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Aspose OCR Java ile Görüntüde OCR Yapın – Tam Adım Adım Kılavuz +url: /tr/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Java ile Görüntü Üzerinde OCR Yapma – Adım Adım Tam Kılavuz + +Hiç **görüntü dosyaları üzerinde OCR** yapmanız gerekti ama hangi kütüphanenin çok fazla yapılandırma gerektirmeden güvenilir sonuçlar vereceğinden emin olamadınız mı? Yalnız değilsiniz. Gerçek dünyadaki birçok projede—pasaport tarama, fatura dijitalleştirme ya da ekran görüntülerinden metin çekme gibi—metin görüntü verisini hızlıca tanıma yeteneği oyunu değiştiren bir özelliktir. + +Bu öğreticide, Aspose OCR for Java kullanarak **görüntü üzerinde OCR** nasıl yapılır, adım adım bir örnek üzerinden göstereceğiz. Aspose lisansınızı uygulamaktan, resmi yüklemeye, motoru çalıştırmaya ve sonunda **görüntüden metin çıkarma** işlemine kadar her şeyi kapsayacağız. Gereksiz ayrıntı yok, sadece kopyalayıp yapıştırabileceğiniz çalışan bir çözüm. + +## Öğrenecekleriniz + +- Java projesinde **Aspose lisansının nasıl kullanılacağını** net bir şekilde anlayacaksınız. +- **OCR için görüntü yükleme** ve motorun dilleri otomatik algılamasını sağlayan kesin kodu elde edeceksiniz. +- **Görüntüdeki metni tanıma** ve **görüntüden metin çıkarma** adımlarını güvenli bir şekilde uygulayacaksınız. +- Yaygın tuzaklar (boş sonuçlar, desteklenmeyen formatlar, bellek sorunları) için ipuçları alacaksınız. + +> **Önkoşullar** – Java 8 ve üzeri, bağımlılık yönetimi için Maven ya da Gradle ve bir Aspose OCR for Java lisans dosyası (ya da değerlendirme modunda çalışabilirsiniz). + +--- + +## Aspose OCR Java ile Görüntü Üzerinde OCR Nasıl Yapılır + +Aşağıda, tüm akışı gösteren tam, çalıştırılabilir bir Java programı yer alıyor. `AsposeOcrDemo.java` olarak kaydedin ve IDE'nizden ya da komut satırından çalıştırın. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Beklenen Konsol Çıktısı + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Programı bir lisans dosyası olmadan çalıştırırsanız, ilk satır sadece değerlendirme modunda olduğunuzu belirtecek, ancak OCR yine de çalışacaktır. + +--- + +## Aspose Lisansını Kurma ve Kullanma + +### Lisansın Önemi Nedir? + +Kütüphaneyi değerlendirme modunda çalıştırmak hızlı testler için uygundur, ancak çıktıya bir filigran ekler ve bir çalıştırmada işleyebileceğiniz sayfa sayısını sınırlar. **Aspose lisansını kullan** adımı bu kısıtlamaları kaldırır ve Aspose’a ücretli bir müşteri olduğunuzu bildirir. + +### Nasıl Edinilir ve Uygulanır? + +1. Aspose mağazasından bir lisans satın alın. +2. `Aspose.OCR.Java.lic` dosyasını indirin. +3. Uygulamanızın okuyabileceği bir yere koyun—genellikle `src/main/resources` klasörü. +4. Yukarıdaki kodda gösterildiği gibi, herhangi bir OCR işleminden önce `new License().setLicense("Aspose.OCR.Java.lic");` çağrısını yapın. + +> **Pro ipucu:** Sunucuya dağıtım yapıyorsanız, `FileNotFoundException` almamak için mutlak bir yol ya da sınıf‑yolu kaynak yükleyici kullanın. + +--- + +## OCR İşleme İçin Görüntü Yükleme + +`Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` satırı, **OCR için görüntü yükleme** adımının kalbidir. Aspose OCR, PNG, JPEG, BMP, TIFF ve hatta çok sayfalı PDF’leri (Aspose.Pdf ile birleştirildiğinde) destekler. + +### Yaygın Tuzaklar + +| Sorun | Belirti | Çözüm | +|-------|---------|------| +| Yanlış dosya yolu | `FileNotFoundException` | Yolu iki kez kontrol edin; OS‑bağımsız ayırıcılar için `Paths.get(...)` kullanın. | +| Desteklenmeyen format | `UnsupportedOperationException` | Görüntüyü yüklemeden önce PNG ya da JPEG’e dönüştürün. | +| Çok büyük görüntü ( > 10 MP) | Bellek yetersizliği hataları | Görüntüyü `java.awt.Image` ile küçülttükten sonra Aspose’a verin. | + +--- + +## Görüntüden Metin Çıkarma ve Sonuçları İşleme + +OCR motoru tamamlandığında, `OcrResult` nesnesi tanınan dizeyi içerir. İşte **görüntüden metin çıkarma** aşaması; bu metni bir veritabanına kaydedebilir, bir arama indeksine besleyebilir ya da bir NLP hattına yönlendirebilirsiniz. + +### Çoklu Dillerle Çalışma + +`engine.setLanguage(Language.Auto)` ayarladığımız için Aspose, dilleri anlık olarak algılamaya çalışır. Dili önceden biliyorsanız (ör. tüm belgeler Rusça), `Language.Auto` yerine `Language.Russian` kullanarak performans artışı elde edebilirsiniz. + +### Son İşlem İpuçları + +- **Boşlukları kırp**: `result.getText().trim()`. +- **Satır sonlarını normalize et**: `result.getText().replace("\r\n", "\n")`. +- **Yazdırılamayan karakterleri kaldır**: `result.getText().replaceAll("[^\\p{Print}]", "")` gibi bir regex kullanın. + +--- + +## Gelişmiş Seçeneklerle Metin Görüntüsü Tanıma (İsteğe Bağlı) + +Daha ince ayar ihtiyacınız varsa, Aspose OCR ek özellikler sunar: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Bu ayarlamalar, eğimli ya da düşük kontrastlı taranmış belgelerle çalışırken oldukça işe yarar. + +--- + +## Tam Çalışan Örnek Özeti + +Her şeyi bir araya getirdiğimizde, final programı şu sırayla çalışır: + +1. **Görüntü üzerinde OCR** – bir `OcrEngine` oluşturularak. +2. **Aspose lisansı kullanma** – isteğe bağlı ama tavsiye edilen. +3. **OCR için görüntü yükleme** – `Image.load` ile. +4. **Dil algılamayı ayarlama** – `Language.Auto` ile **görüntüdeki metni otomatik tanıma**. +5. **Görüntüden metin çıkarma** – sonucu yazdırma, boş yanıtları nazikçe ele alma. + +Aşağıdaki bağımlılık ile bir Maven projesine doğrudan kod bloğunu ekleyebilirsiniz: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +`mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` komutunu çalıştırın ve konsolda tanınan metni izleyin. + +--- + +## Sonuç + +Aspose OCR for Java kullanarak **görüntü dosyaları üzerinde OCR** yapmayı, lisans uygulamaktan **OCR için görüntü yükleme**, **görüntüdeki metni tanıma** ve son olarak **görüntüden metin çıkarma** aşamalarına kadar adım adım gösterdik. Yaklaşım basit, kutudan çıktığı gibi birden çok dili destekliyor ve gerektiğinde gelişmiş ön‑işleme seçenekleriyle genişletilebiliyor. + +Sırada ne var? OCR çıktısını bir arama indeksine besleyin, çıkarılan metinle PDF oluşturun ya da farklı görüntü formatlarıyla deneyler yapın. Olasılıklar sınırsız ve Aspose’un sağlam API’si sayesinde OCR incelikleriyle uğraşmak yerine özellik geliştirmeye daha çok zaman ayıracaksınız. + +Sorularınız mı var ya da bir kenar durumla mı karşılaştınız? Aşağıya yorum bırakın—mutlu kodlamalar! + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve ilgili konuları derinlemesine ele alan örnekler sunar. Her kaynak, adım adım açıklamalarla tam çalışan kod örnekleri içerir, böylece ek API özelliklerini öğrenebilir ve projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [How to extract text from image from URL using Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Convert Image to Text in Java using Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c0d689221 --- /dev/null +++ b/ocr/vietnamese/python-java/general/create-searchable-pdf-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-06-19 +description: Tạo PDF có thể tìm kiếm từ hình ảnh bằng Python OCR. Học cách chuyển + OCR sang PDF, trích xuất văn bản từ hình ảnh và thực hiện OCR trên hình ảnh nhanh + chóng. +draft: false +keywords: +- create searchable pdf +- convert ocr to pdf +- extract text from image +- convert image to pdf +- perform ocr on image +language: vi +og_description: Tạo PDF có thể tìm kiếm từ hình ảnh bằng Python OCR. Hướng dẫn này + chỉ cách chuyển OCR sang PDF, trích xuất văn bản từ hình ảnh và thực hiện OCR trên + hình ảnh. +og_title: Tạo PDF có thể tìm kiếm trong Python – Hướng dẫn lập trình đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + headline: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from an image using Python OCR. Learn to convert + OCR to PDF, extract text from image, and perform OCR on image quickly. + name: Create Searchable PDF in Python – Complete Step‑by‑Step Guide + steps: + - name: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + text: The OCR confidence scores (`conf` values). Low confidence may mean the image + is blurry. + - name: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + text: Bounding box coordinates—sometimes EasyOCR reports them in a different orientation. + - name: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + text: That the PDF viewer isn’t set to “image‑only” mode (rare, but some viewers + have that option). + type: HowTo +tags: +- OCR +- Python +- PDF +- ImageProcessing +title: Tạo PDF có thể tìm kiếm bằng Python – Hướng dẫn chi tiết từng bước +url: /vi/python-java/general/create-searchable-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 >}} + +# Tạo PDF có thể tìm kiếm trong Python – Hướng dẫn đầy đủ từng bước + +Bạn đã bao giờ cần **tạo PDF có thể tìm kiếm** từ một biên lai đã quét nhưng không biết bắt đầu từ đâu chưa? Bạn không đơn độc—nhiều nhà phát triển gặp cùng một rào cản khi họ lần đầu cố gắng chuyển một bức ảnh chứa văn bản thành một PDF mà bạn thực sự có thể tìm kiếm. + +Trong tutorial này chúng ta sẽ đi qua một giải pháp thực tế cho phép bạn **thực hiện OCR trên hình ảnh**, chuyển kết quả OCR thành **PDF có thể tìm kiếm**, và thậm chí trích xuất văn bản thô nếu bạn cần xử lý tiếp. Không có phần thừa, chỉ có một ví dụ hoạt động mà bạn có thể sao chép‑dán vào dự án ngay hôm nay. + +## Những gì bạn sẽ học + +- Cách thiết lập một engine OCR nhẹ trong Python +- Các bước chính xác để **chuyển đổi OCR sang PDF** và lưu nó dưới dạng tài liệu có thể tìm kiếm +- Các cách để **trích xuất văn bản từ hình ảnh** cho phân tích downstream +- Mẹo xử lý các vấn đề thường gặp như hướng ảnh và tệp lớn +- Một script hoàn chỉnh, có thể chạy được mà bạn có thể tùy chỉnh cho trường hợp sử dụng của mình + +### Yêu cầu trước + +- Python 3.8+ đã được cài đặt trên máy của bạn +- Kiến thức cơ bản về pip và môi trường ảo (tùy chọn nhưng được khuyến nghị) +- Một tệp hình ảnh (PNG, JPEG, v.v.) chứa văn bản rõ ràng, có thể máy đọc được + +Nếu bạn đã có những thứ trên, hãy bắt đầu ngay. + +## Bước 1: Cài đặt Thư viện Yêu cầu + +Đoạn mã mẫu bạn đã thấy trước đó sử dụng một gói `ocr` giả tưởng, nhưng cùng một ý tưởng cũng áp dụng cho các thư viện thực tế như **EasyOCR**, **pytesseract**, hoặc **pdfminer.six**. Trong hướng dẫn này chúng ta sẽ dùng **EasyOCR** vì nó thuần Python, hỗ trợ nhiều ngôn ngữ, và cung cấp một phương pháp chuyển PDF tiện lợi thông qua một helper phụ trợ. + +```bash +pip install easyocr pillow +``` + +> **Pro tip:** Cài đặt trong môi trường ảo (`python -m venv venv && source venv/bin/activate`) để giữ các phụ thuộc gọn gàng. + +## Bước 2: Khởi tạo Engine OCR – Thực hiện OCR trên hình ảnh + +Bây giờ thư viện đã sẵn sàng, chúng ta tạo một engine OCR và chỉ định nó làm việc với văn bản tiếng Anh. Đây là nơi đầu tiên chúng ta **thực hiện OCR trên hình ảnh**. + +```python +import easyocr +from PIL import Image +import io + +# Create an EasyOCR reader for English +reader = easyocr.Reader(['en']) # ← performs OCR on image +``` + +Tại sao chúng ta cần một đối tượng reader riêng? EasyOCR tải trước các mô hình ngôn ngữ, vì vậy việc tái sử dụng cùng một `reader` cho nhiều hình ảnh sẽ hiệu quả hơn rất nhiều so với việc khởi tạo lại mỗi lần. + +## Bước 3: Tải hình ảnh – Trích xuất văn bản từ hình ảnh + +Hãy đưa bức ảnh vào bộ nhớ. Bước này là nơi chúng ta **trích xuất văn bản từ hình ảnh** sau này, nhưng trước tiên chúng ta chỉ tải nó lên. + +```python +# Replace with the path to your receipt or scanned document +image_path = "YOUR_DIRECTORY/receipt.png" + +# Open the image with Pillow (helps with format handling) +pil_image = Image.open(image_path).convert("RGB") +``` + +Nếu ảnh của bạn bị lộn ngược hoặc nghiêng, hãy cân nhắc sử dụng các phương thức `rotate` hoặc `transpose` của Pillow trước khi đưa vào engine OCR. Một kiểm tra nhanh bằng mắt có thể tiết kiệm cho bạn hàng giờ gỡ lỗi sau này. + +## Bước 4: Chạy Engine OCR và Ghi nhận Kết quả + +Đây là phần cốt lõi của quy trình—gửi ảnh tới engine OCR và nhận lại dữ liệu có cấu trúc. + +```python +# EasyOCR returns a list of (bbox, text, confidence) tuples +ocr_result = reader.readtext(image_path, detail=1, paragraph=True) +``` + +Cờ `detail=1` cung cấp cho chúng ta các bounding box, mà chúng ta sẽ cần khi sau này **chuyển đổi OCR sang PDF**. Nếu bạn chỉ quan tâm tới chuỗi thô, hãy đặt `detail=0`. + +## Bước 5: Chuyển đổi Kết quả OCR thành PDF có thể tìm kiếm – Chuyển đổi OCR sang PDF + +EasyOCR không cung cấp một trình ghi PDF trực tiếp, nhưng chúng ta có thể tự ghép PDF bằng Pillow và thư viện `reportlab`. Để tutorial nhẹ, chúng ta sẽ dùng `fpdf2`, cho phép nhúng ảnh gốc và phủ lên văn bản vô hình. + +```bash +pip install fpdf2 +``` + +```python +from fpdf import FPDF + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + # Set invisible text style + self.set_text_color(255, 255, 255) # white on white background + self.set_font("Helvetica", size=12) + + for bbox, text, conf in ocr_data: + # bbox = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] + x_min = min(point[0] for point in bbox) + y_min = min(point[1] for point in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +# Create PDF instance with the original image as background +pdf = SearchablePDF(image_path) + +# Add invisible OCR text on top of the image +pdf.add_ocr_text(ocr_result) + +# Save the searchable PDF +output_path = "YOUR_DIRECTORY/receipt_searchable.pdf" +pdf.output(output_path) +``` + +Điều gì vừa xảy ra? Chúng ta đặt ảnh đã quét làm lớp hiển thị, sau đó viết các từ đã nhận dạng lên trên bằng văn bản màu trắng hòa vào nền trắng. Các công cụ tìm kiếm vẫn đọc được lớp ẩn, vì vậy PDF trở nên **có thể tìm kiếm** mà không thay đổi giao diện hình ảnh. + +## Bước 6: Lưu Dữ liệu PDF – Chuyển đổi Hình ảnh sang PDF + +Nếu bạn muốn xử lý PDF trong bộ nhớ (ví dụ, gửi qua API), bạn có thể lấy dữ liệu byte thay vì ghi trực tiếp ra đĩa. + +```python +pdf_bytes = pdf.output(dest='S').encode('latin1') # returns a byte string + +# Example: write bytes to a file (same as Step 5 but shows the conversion) +with open(output_path, "wb") as f: + f.write(pdf_bytes) +``` + +Dòng này minh họa quy trình truyền thống **chuyển đổi hình ảnh sang PDF**: bạn bắt đầu với một ảnh, chạy OCR, phủ văn bản, và cuối cùng xuất ra một luồng PDF. + +## Bước 7: Xác minh Kết quả – Kiểm tra Nhanh + +Sau khi chạy script, mở `receipt_searchable.pdf` trong bất kỳ trình xem PDF nào và thử hộp tìm kiếm (Ctrl + F). Gõ một từ bạn biết có trong biên lai—nếu nó nhảy đến vị trí đúng, bạn đã **tạo PDF có thể tìm kiếm** thành công! + +Nếu tìm kiếm thất bại, hãy kiểm tra lại: + +1. Điểm tin cậy OCR (`conf`). Điểm thấp có thể nghĩa là ảnh mờ. +2. Tọa độ bounding box—đôi khi EasyOCR báo chúng theo hướng khác. +3. Trình xem PDF không được đặt ở chế độ “chỉ ảnh” (hiếm, nhưng một số trình có tùy chọn này). + +## Kịch bản Hoạt động Đầy đủ + +Kết hợp mọi thứ lại, đây là file Python hoàn chỉnh, sẵn sàng chạy: + +```python +# searchable_pdf.py +import easyocr +from PIL import Image +from fpdf import FPDF + +# ---------- Configuration ---------- +IMAGE_PATH = "YOUR_DIRECTORY/receipt.png" +OUTPUT_PDF = "YOUR_DIRECTORY/receipt_searchable.pdf" +# ---------------------------------- + +class SearchablePDF(FPDF): + def __init__(self, image_path): + super().__init__() + self.add_page() + # Fit the image to the page size + self.image(image_path, x=0, y=0, w=self.w, h=self.h) + + def add_ocr_text(self, ocr_data): + self.set_text_color(255, 255, 255) # invisible white text + self.set_font("Helvetica", size=12) + for bbox, text, conf in ocr_data: + x_min = min(p[0] for p in bbox) + y_min = min(p[1] for p in bbox) + self.set_xy(x_min, y_min) + self.cell(0, 0, txt=text, border=0) + +def main(): + # 1️⃣ Initialize OCR engine – perform OCR on image + reader = easyocr.Reader(['en']) + + # 2️⃣ Load the image – extract text from image later + pil_image = Image.open(IMAGE_PATH).convert("RGB") + + # 3️⃣ Run OCR and capture results + ocr_result = reader.readtext(IMAGE_PATH, detail=1, paragraph=True) + + # 4️⃣ Convert OCR result to searchable PDF – convert OCR to PDF + pdf = SearchablePDF(IMAGE_PATH) + pdf.add_ocr_text(ocr_result) + + # 5️⃣ Save the PDF – convert image to PDF (or keep bytes in memory) + pdf.output(OUTPUT_PDF) + print(f"✅ Searchable PDF saved to {OUTPUT_PDF}") + +if __name__ == "__main__": + main() +``` + +Lưu file này dưới tên `searchable_pdf.py`, thay thế các placeholder `YOUR_DIRECTORY` bằng đường dẫn thực tế, và chạy: + +```bash +python searchable_pdf.py +``` + +Bạn sẽ thấy thông báo xác nhận và một PDF có thể tìm kiếm mới xuất hiện trong thư mục của mình. + +## Câu hỏi Thường gặp & Trường hợp Đặc biệt + +**Nếu ảnh là màu thì sao?** +EasyOCR hoạt động với cả ảnh xám và màu, nhưng chuyển sang xám (`pil_image.convert("L")`) đôi khi cải thiện độ chính xác trên các bản quét nhiễu. + +**Tôi có thể xử lý PDF đa trang không?** +Có—lặp qua mỗi ảnh trang, chạy các bước OCR, và thêm mỗi trang vào cùng một đối tượng `FPDF`. Chỉ cần nhớ đặt lại con trỏ (`self.add_page()`) cho mỗi ảnh mới. + +**Có cách nào giữ lớp văn bản gốc thay vì văn bản trắng vô hình không?** +Nếu bạn cần một PDF “văn bản‑dưới‑ảnh” thực sự (ví dụ, cho khả năng truy cập), hãy cân nhắc dùng `pdfminer` hoặc `pikepdf` để nhúng lớp văn bản ẩn với các thẻ PDF thích hợp. Đây là kỹ thuật nâng cao, nhưng nguyên tắc vẫn giống: ảnh nền + phủ văn bản. + +**Nếu độ tin cậy OCR thấp thì sao?** +Bạn có thể lọc bỏ các từ có độ tin cậy thấp: + +```python +filtered = [item for item in ocr_result if item[2] > 0.8] # keep >80% confidence +pdf.add_ocr_text(filtered) +``` + +## Tổng kết – Những gì chúng ta đã đạt được + +Chúng ta bắt đầu với một ảnh biên lai đơn giản, **thực hiện OCR trên hình ảnh**, trích xuất các chuỗi đã nhận dạng, và cuối cùng **tạo PDF có thể tìm kiếm** hoạt động như bất kỳ tài liệu quét chuyên nghiệp nào. Quy trình đã bao phủ mọi từ khóa phụ—**chuyển đổi OCR sang PDF**, **trích xuất văn bản từ hình ảnh**, **chuyển đổi hình ảnh sang PDF**, và **thực hiện OCR trên hình ảnh**—do đó bạn giờ có một bộ công cụ tái sử dụng cho bất kỳ dự án tương tự nào. + +### Các bước Tiếp theo + +- Thử nghiệm với các ngôn ngữ khác bằng cách truyền mã ISO của chúng vào `easyocr.Reader(['en', 'es'])`. +- Thay EasyOCR bằng Tesseract nếu bạn cần một giải pháp hoàn toàn offline; phần còn lại của pipeline vẫn giữ nguyên. +- Thêm trực quan hoá độ tin cậy OCR (vẽ bounding box lên ảnh) để gỡ lỗi các bản quét có vấn đề. + +Bạn có một cách tiếp cận mới muốn chia sẻ? Hãy để lại bình luận, fork + +## 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ụ 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 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/) +- [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/) +- [Cách OCR Hình ảnh – Thực hiện OCR trên Hình ảnh trong Nhận dạng Ả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/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md b/ocr/vietnamese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md new file mode 100644 index 000000000..21eadb573 --- /dev/null +++ b/ocr/vietnamese/python-java/general/extract-text-from-images-in-python-full-batch-ocr-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-06-19 +description: Trích xuất văn bản từ hình ảnh trong Python bằng một công cụ OCR đơn + giản. Tìm hiểu cách chuyển đổi hình ảnh đã quét thành văn bản, nhận dạng văn bản + từ ảnh, và liệt kê các tệp hình ảnh trong Python một cách hiệu quả. +draft: false +keywords: +- extract text from images +- convert scanned images to text +- recognize text from pictures +- list image files python +language: vi +og_description: Trích xuất văn bản từ hình ảnh trong Python bằng một công cụ OCR nhẹ. + Hướng dẫn này chỉ cho bạn cách chuyển đổi hình ảnh đã quét thành văn bản, nhận dạng + văn bản từ ảnh, và liệt kê các tệp hình ảnh trong Python chỉ trong vài bước. +og_title: Trích xuất văn bản từ hình ảnh bằng Python – Hướng dẫn OCR toàn bộ theo + lô +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Extract text from images in Python with a simple OCR engine. Learn + how to convert scanned images to text, recognize text from pictures, and list + image files python efficiently. + headline: Extract Text from Images in Python – Full Batch OCR Guide + type: TechArticle +tags: +- Python +- OCR +- Image Processing +title: Trích xuất văn bản từ hình ảnh trong Python – Hướng dẫn OCR hàng loạt đầy đủ +url: /vi/python-java/general/extract-text-from-images-in-python-full-batch-ocr-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 trong Python – Hướng dẫn OCR hàng loạt đầy đủ + +Bạn đã bao giờ cần **trích xuất văn bản từ hình ảnh** nhưng không biết bắt đầu từ đâu? Bạn không đơn độc—các nhà phát triển luôn phải đối mặt với thách thức chuyển đổi các tệp PDF đã quét, biên lai chụp ảnh, hoặc ảnh chụp màn hình thành văn bản có thể tìm kiếm. Trong hướng dẫn này, chúng tôi sẽ đi qua một ví dụ hoàn chỉnh, sẵn sàng chạy, cho thấy cách **chuyển đổi hình ảnh đã quét thành văn bản**, nhận dạng văn bản từ ảnh, và thậm chí **liệt kê các tệp hình ảnh theo kiểu python**. Khi kết thúc, bạn sẽ có một script có thể tái sử dụng để xử lý toàn bộ thư mục chỉ trong một lần. + +Chúng tôi sẽ bao phủ mọi thứ bạn cần: các thư viện bắt buộc, lý do mỗi bước quan trọng, xử lý các trường hợp biên, và một chút khắc phục sự cố. Không cần phải chạy theo tài liệu bên ngoài; mã dưới đây là tự chứa, và các giải thích trả lời cả “cách làm” *và* “tại sao”. Hãy mở IDE yêu thích của bạn, và bắt đầu thôi. + +--- + +## Những gì bạn sẽ xây dựng + +- Khởi tạo một engine OCR (chúng tôi sẽ dùng gói `ocr` để minh họa). +- Quét một thư mục và **liệt kê các tệp hình ảnh theo kiểu python**, lọc PNG, JPG và TIFF. +- Thực hiện một thao tác **OCR hàng loạt** trên tất cả các ảnh đã tìm được. +- In ra văn bản đã trích xuất cho mỗi tệp, được gắn nhãn rõ ràng. + +> **Mẹo chuyên nghiệp:** Nếu bạn chưa cài đặt thư viện `ocr`, bạn có thể thay thế bằng `pytesseract` với một vài thay đổi nhỏ—logic cốt lõi vẫn giữ nguyên. + +--- + +## Yêu cầu trước + +- Python 3.8+ (script sử dụng f‑strings và type hints). +- Một thư viện OCR cung cấp một `OcrEngine` với `recognize_batch`. Trong hướng dẫn này chúng tôi giả định một gói `ocr` hư cấu, nhưng mẫu này hoạt động với các thư viện thực. +- Một thư mục chứa các tệp hình ảnh bạn muốn xử lý (`.png`, `.jpg`, `.tif`). + +--- + +## Bước 1 – Cài đặt & Nhập các mô-đun cần thiết + +Đầu tiên, hãy chắc chắn rằng gói OCR đã sẵn sàng. Nếu bạn đang dùng một thư viện thực như `pytesseract`, hãy thay đổi phần import cho phù hợp. + +```python +# Install the fictional OCR package (skip if using pytesseract) +# pip install ocr-package + +import os +import ocr # <-- replace with your actual OCR library +from typing import List +``` + +> **Tại sao điều này quan trọng:** Việc import `os` cung cấp khả năng xử lý đường dẫn đa nền tảng, trong khi `typing.List` giúp IDE tự hoàn thành và chuẩn bị cho tương lai. + +--- + +## Bước 2 – **Extract Text from Images**: Khởi tạo Engine OCR + +Việc tạo engine là bước đầu tiên cho bất kỳ công việc OCR nào. Chúng tôi cũng đặt ngôn ngữ tự động phát hiện để engine có thể xử lý tài liệu đa ngôn ngữ. + +```python +def create_engine() -> ocr.OcrEngine: + """ + Initializes the OCR engine with automatic language detection. + Returns: + An instance of ocr.OcrEngine ready for batch processing. + """ + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # Auto‑detect language + return engine +``` + +> **Giải thích:** Bằng cách đóng gói việc tạo engine trong một hàm, chúng ta giữ cho mã có tính mô-đun. Nếu sau này bạn cần tinh chỉnh DPI hoặc chế độ OCR, chỉ cần chỉnh sửa một chỗ duy nhất. + +--- + +## Bước 3 – **List Image Files Python**: Thu thập tệp từ một thư mục + +Bây giờ chúng ta cần xác định mọi ảnh muốn xử lý. List comprehension dưới đây phản ánh một mẫu “list image files python” phổ biến. + +```python +def get_image_files(input_dir: str) -> List[str]: + """ + Scans `input_dir` and returns a list of absolute paths + for files ending with .png, .jpg, or .tif (case‑insensitive). + """ + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] +``` + +> **Xử lý trường hợp biên:** Hàm này bỏ qua các thư mục con (bạn có thể thêm đệ quy sau) và tự động lọc các tệp ẩn vì chúng thường không kết thúc bằng các phần mở rộng được hỗ trợ. + +--- + +## Bước 4 – **Convert Scanned Images to Text**: Chạy OCR hàng loạt + +Hầu hết các thư viện OCR cung cấp một phương thức batch nhanh hơn rất nhiều so với xử lý từng ảnh một. Đây là cách chúng ta gọi nó. + +```python +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + """ + Sends a list of image file paths to the OCR engine for batch recognition. + Returns a list of OcrResult objects, preserving order. + """ + # The fictional `recognize_batch` returns a list of results matching input order + return engine.recognize_batch(image_paths) +``` + +> **Tại sao batch?** Gửi tất cả ảnh cùng một lúc giảm tải (ví dụ: tải lại mô hình OCR nhiều lần) và thường mang lại hiệu suất CPU/GPU tốt hơn. + +--- + +## Bước 5 – **Recognize Text from Pictures**: Hiển thị kết quả + +Cuối cùng, chúng ta lặp qua các cặp tên tệp và kết quả OCR, in ra tiêu đề sạch sẽ cho mỗi ảnh. + +```python +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + """ + Prints the extracted text for each image, prefixed with the file name. + """ + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + # Some OCR engines store the plain text in a `.text` attribute + print(result.text.strip()) + print() # Blank line for readability +``` + +> **Mẹo:** `strip()` loại bỏ khoảng trắng đầu/cuối mà OCR thường thêm vào. + +--- + +## Script đầy đủ – Kết hợp tất cả lại + +Dưới đây là chương trình hoàn chỉnh, có thể chạy được. Lưu lại dưới tên `batch_ocr.py` và chạy `python batch_ocr.py `. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script – extracts text from images in a given folder. +Usage: python batch_ocr.py /path/to/images +""" + +import sys +import os +import ocr # Replace with your OCR library if different +from typing import List + +def create_engine() -> ocr.OcrEngine: + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto + return engine + +def get_image_files(input_dir: str) -> List[str]: + supported_exts = ('.png', '.jpg', '.jpeg', '.tif', '.tiff') + return [ + os.path.join(input_dir, f) + for f in os.listdir(input_dir) + if f.lower().endswith(supported_exts) + ] + +def run_batch_ocr(engine: ocr.OcrEngine, image_paths: List[str]) -> List[ocr.OcrResult]: + return engine.recognize_batch(image_paths) + +def display_results(image_paths: List[str], ocr_results: List[ocr.OcrResult]) -> None: + for file_path, result in zip(image_paths, ocr_results): + print(f"--- {os.path.basename(file_path)} ---") + print(result.text.strip()) + print() + +def main() -> None: + if len(sys.argv) != 2: + print("Usage: python batch_ocr.py ") + sys.exit(1) + + input_dir = sys.argv[1] + + if not os.path.isdir(input_dir): + print(f"Error: '{input_dir}' is not a valid directory.") + sys.exit(1) + + engine = create_engine() + image_files = get_image_files(input_dir) + + if not image_files: + print("No supported image files found in the directory.") + sys.exit(0) + + ocr_results = run_batch_ocr(engine, image_files) + display_results(image_files, ocr_results) + +if __name__ == "__main__": + main() +``` + +### Kết quả mong đợi + +Giả sử thư mục chứa `invoice1.png` và `receipt.jpg`, bạn có thể thấy: + +``` +--- invoice1.png --- +Invoice #12345 +Date: 2024‑04‑01 +Total: $256.78 + +--- receipt.jpg --- +Store: Coffee Corner +Item: Latte +Price: $4.50 +``` + +Mỗi khối đều được gắn nhãn rõ ràng, giúp việc xử lý tiếp theo (ví dụ: lưu vào cơ sở dữ liệu) trở nên đơn giản. + +--- + +## Xử lý các vấn đề thường gặp + +| Vấn đề | Tại sao xảy ra | Giải pháp nhanh | +|-------|----------------|-----------------| +| **Không xuất hiện văn bản** | Ngôn ngữ OCR không được phát hiện hoặc ảnh có độ tương phản quá thấp. | Buộc ngôn ngữ (`engine.language = ocr.Language.English`) hoặc tiền xử lý ảnh (tăng độ tương phản). | +| **Lỗi bộ nhớ khi batch lớn** | Engine cố gắng tải tất cả ảnh cùng lúc. | Chia `image_files` thành các khối (`batch_size = 20`) và gọi `recognize_batch` liên tục. | +| **Định dạng tệp không được hỗ trợ** | Bạn đã thêm `.gif` hoặc `.bmp`. | Mở rộng tuple `supported_exts` hoặc chuyển đổi ảnh sang PNG/JPG trước. | +| **Ký tự Unicode bị lỗi** | OCR trả về bytes thay vì string. | Đảm bảo thư viện OCR xuất Unicode (`result.text.decode('utf‑8')` nếu cần). | + +--- + +## Mở rộng quy trình làm việc + +Bây giờ bạn đã có thể **trích xuất văn bản từ hình ảnh**, hãy xem xét các bước tiếp theo: + +- **Xuất ra CSV** – Ghi mỗi tên tệp và văn bản đã trích xuất vào bảng tính để phân tích. +- **Xử lý song song** – Sử dụng `concurrent.futures.ThreadPoolExecutor` để xử lý nhiều batch đồng thời. +- **Tích hợp OCR đám mây** – Thay engine cục bộ bằng Google Vision hoặc Azure OCR để đạt độ chính xác cao hơn trên các bố cục phức tạp. +- **Thêm tiền xử lý ảnh** – Các thư viện như Pillow hoặc OpenCV có thể chỉnh góc, giảm nhiễu, hoặc ngưỡng ảnh trước khi OCR, nâng cao kết quả. + +Tất cả các ý tưởng này đều sử dụng cùng các hàm cốt lõi mà chúng ta đã xây dựng, vì vậy bạn không cần bắt đầu từ đầu. + +--- + +## Kết luận + +Chúng tôi vừa đi qua một giải pháp hoàn chỉnh để **trích xuất văn bản từ hình ảnh** trong Python, bao phủ mọi thứ từ **list image files python** đến **recognize text from pictures** và cuối cùng là **convert scanned images to text** trong một batch gọn gàng. Script được thiết kế đơn giản nhưng đủ linh hoạt để làm nền tảng cho các dự án lớn hơn—cho dù bạn đang số hoá biên lai, xây dựng kho lưu trữ có thể tìm kiếm, hay vận hành một pipeline trích xuất dữ liệu. + +Hãy thử chạy, tinh chỉnh các bước tiền xử lý, và quan sát độ chính xác OCR của bạn tăng lên. Nếu gặp khó khăn, hãy quay lại bảng “Xử lý các vấn đề thường gặp”; hầu hết các vấn đề đều được giải quyết bằng một thay đổi cấu hình nhỏ. + +Sẵn sàng cho thử thách tiếp theo? Hãy thêm bước chuyển PDF sang ảnh bằng `pdf2image`, rồi đưa các ảnh này trực tiếp vào cùng pipeline. Khi kết hợp OCR với hệ sinh thái phong phú của Python, không gì là không thể. + +Chúc lập trình vui vẻ, và hy vọng văn bản của bạn luôn rõ ràng! + +## 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, kèm theo giải thích từng bước để giúp bạn thành thạo 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 chi tiết](/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 – Cơ bản OCR với Aspose.OCR cho Java](/ocr/english/java/ocr-basics/) +- [Cách trích xuất văn bản từ hình ảnh qua URL bằng Aspose.OCR cho Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) + +{{< /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-in-python-full-ocr-guide/_index.md b/ocr/vietnamese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md new file mode 100644 index 000000000..8f1b81e3c --- /dev/null +++ b/ocr/vietnamese/python-java/general/extract-text-from-images-in-python-full-ocr-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-06-19 +description: Trích xuất văn bản từ hình ảnh bằng Python OCR. Học cách phát hiện ngôn + ngữ tự động, xử lý song song và nhận dạng hàng loạt trong một hướng dẫn ngắn gọn. +draft: false +keywords: +- extract text from images +- Python OCR library +- automatic language detection +- parallel processing OCR +- batch image recognition +- ocr.OcrEngine usage +language: vi +og_description: Trích xuất văn bản từ hình ảnh bằng Python OCR. Bài hướng dẫn này + trình bày việc phát hiện ngôn ngữ tự động, xử lý song song và nhận dạng hàng loạt + trong một hướng dẫn duy nhất. +og_title: Trích xuất văn bản từ hình ảnh trong Python – Hướng dẫn OCR đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + headline: extract text from images in Python – Full OCR Guide + type: TechArticle +- description: extract text from images using Python OCR. Learn automatic language + detection, parallel processing, and batch recognition in a concise tutorial. + name: extract text from images in Python – Full OCR Guide + steps: + - name: Python 3.8 or newer installed. + text: Python 3.8 or newer installed. + - name: The `ocr` package (`pip install ocr`). + text: The `ocr` package (`pip install ocr`). + - name: A folder of PNG (or JPG) images you want to process. + text: A folder of PNG (or JPG) images you want to process. + - name: Basic familiarity with Python functions and loops. + text: Basic familiarity with Python functions and loops. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Trích xuất văn bản từ hình ảnh bằng Python – Hướng dẫn OCR đầy đủ +url: /vi/python-java/general/extract-text-from-images-in-python-full-ocr-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 trong Python – Hướng dẫn OCR toàn diện + +Bạn đã bao giờ tự hỏi làm sao **trích xuất văn bản từ hình ảnh** mà không phải gõ lại từng từ chưa? Bạn không phải là người duy nhất. Dù bạn đang số hoá các hoá đơn cũ, xây dựng một kho lưu trữ tài liệu có thể tìm kiếm, hay chỉ đơn giản là thử nghiệm các thủ thuật AI thú vị, khả năng lấy văn bản từ ảnh là kỹ năng cần có cho bất kỳ lập trình viên Python nào ngày nay. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ hoàn chỉnh, có thể chạy ngay, **trích xuất văn bản từ hình ảnh** bằng một engine OCR phổ biến. Chúng ta sẽ đề cập đến phát hiện ngôn ngữ tự động, xử lý song song để tăng tốc, và nhận dạng ảnh theo lô để bạn có thể xử lý hàng chục tệp trong vài giây. Nghe có vẻ phù hợp? Hãy bắt đầu. + +## Những gì bạn sẽ học + +- Cách khởi tạo engine OCR với `ocr.OcrEngine`. +- Kích hoạt **phát hiện ngôn ngữ tự động** để engine tự chọn ngôn ngữ phù hợp. +- Cấu hình **OCR xử lý song song** với một thread pool tùy chỉnh. +- Thực hiện **nhận dạng ảnh theo lô** trên danh sách tệp. +- In ra văn bản đã nhận dạng cho mỗi ảnh, sẵn sàng để lưu hoặc lập chỉ mục. + +Không cần tài liệu bên ngoài—tất cả những gì bạn cần đều có ở đây, và mã hoạt động ngay với package `ocr` (cài đặt bằng `pip install ocr`). + +## Điều kiện tiên quyết + +Trước khi bắt đầu, hãy chắc chắn bạn đã có: + +1. Python 3.8 hoặc mới hơn được cài đặt. +2. Package `ocr` (`pip install ocr`). +3. Một thư mục chứa các ảnh PNG (hoặc JPG) bạn muốn xử lý. +4. Kiến thức cơ bản về hàm và vòng lặp trong Python. + +Đó là tất cả—không có phụ thuộc nặng, không cần GPU, chỉ cần Python thuần. + +![trích xuất văn bản từ hình ảnh ví dụ](https://example.com/ocr-demo.png "Ảnh chụp màn hình hiển thị kết quả trích xuất văn bản từ hình ảnh") + +*Alt text: ảnh chụp màn hình demo trích xuất văn bản từ hình ảnh* + +## Bước 1 – Thiết lập Engine OCR (Từ khóa chính trong hành động) + +Điều đầu tiên cần làm: tạo một instance của engine OCR. Hãy nghĩ `ocr.OcrEngine()` như bộ não của toàn bộ quá trình; nó biết cách đọc ký tự, dòng và đoạn văn. + +```python +import ocr + +# Step 1: Create an OCR engine instance +engine = ocr.OcrEngine() +``` + +Tại sao chúng ta cần một engine rõ ràng? Bởi vì **sử dụng ocr.OcrEngine** cho phép bạn kiểm soát chi tiết các thiết lập ngôn ngữ, luồng xử lý và hơn thế nữa. Đây là cách linh hoạt nhất để **trích xuất văn bản từ hình ảnh** so với các helper một dòng. + +## Bước 2 – Để Engine Tự Động Phát Hiện Ngôn Ngữ + +Hầu hết các thư viện OCR yêu cầu bạn chỉ định ngôn ngữ cần tìm. Điều này ổn với dự án một ngôn ngữ, nhưng gây phiền toái khi xử lý lô đa ngôn ngữ. May mắn là package `ocr` hỗ trợ **phát hiện ngôn ngữ tự động**. + +```python +# Step 2: Enable automatic language detection +engine.language = ocr.Language.Auto +``` + +Đặt `engine.language` thành `ocr.Language.Auto` sẽ khiến engine tự sniff mỗi ảnh và chọn mô hình ngôn ngữ phù hợp. Dòng lệnh ngắn này tiết kiệm cho bạn hàng giờ cấu hình thủ công khi làm việc với tài liệu quốc tế. + +## Bước 3 – Tăng Tốc Độ với OCR Xử Lý Song Song + +Nếu máy bạn có bốn lõi CPU trở lên, tại sao không tận dụng chúng? Engine có thể khởi tạo một thread pool, cho phép xử lý nhiều ảnh đồng thời. Đây là lúc **OCR xử lý song song** tỏa sáng. + +```python +# Step 3: Enable parallel processing with four worker threads +engine.set_thread_pool_size(4) +``` + +Bạn có thể điều chỉnh số `4` tùy theo máy. Nhiều thread → chạy lô nhanh hơn, nhưng nhớ mỗi thread tiêu tốn bộ nhớ, vì vậy hãy tìm điểm cân bằng phù hợp với môi trường của bạn. + +## Bước 4 – Thu Thập Các Ảnh Cần Xử Lý + +Bây giờ chúng ta cần một danh sách các đường dẫn tệp. Bạn có thể tạo danh sách này thủ công, đọc từ CSV, hoặc dùng `glob`. Để minh bạch, chúng ta sẽ hard‑code một danh sách ngắn: + +```python +# Step 4: Prepare a list of image files to be recognized +files = [ + "YOUR_DIRECTORY/doc1.png", + "YOUR_DIRECTORY/doc2.png", + "YOUR_DIRECTORY/doc3.png", + "YOUR_DIRECTORY/doc4.png" +] +``` + +Thay `YOUR_DIRECTORY` bằng đường dẫn thực tế trên hệ thống của bạn. Nếu có hàng chục tệp, một lệnh nhanh `glob.glob("*.png")` sẽ làm phần việc nặng. + +## Bước 5 – Thực Hiện Nhận Dạng Ảnh Theo Lô + +Đây là phần cốt lõi của tutorial: một lời gọi duy nhất xử lý mọi ảnh trong `files` và trả về danh sách các đối tượng kết quả. Đây là tính năng **nhận dạng ảnh theo lô** giúp OCR quy mô lớn trở nên thực tiễn. + +```python +# Step 5: Perform batch recognition on all images +results = engine.recognize_batch(files) +``` + +Ở phía sau, engine phân phối mỗi tệp cho bốn worker thread mà chúng ta đã cấu hình trước, đồng thời tự động phát hiện ngôn ngữ cho từng ảnh. Phương thức trả về một danh sách, mỗi phần tử chứa văn bản đã nhận dạng và siêu dữ liệu liên quan. + +## Bước 6 – In (hoặc Lưu) Văn Bản Đã Trích Xuất + +Cuối cùng, chúng ta lặp qua các kết quả và in ra văn bản. Trong dự án thực tế, bạn có thể ghi chúng vào cơ sở dữ liệu hoặc file CSV, nhưng việc in ra giúp ví dụ đơn giản hơn. + +```python +# Step 6: Output the recognized text for each image +for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") +``` + +**Kết quả mong đợi** (rút gọn để ngắn gọn): + +``` +--- +File: YOUR_DIRECTORY/doc1.png +Extracted Text: +Invoice #12345 +Date: 2024‑03‑15 +Total: $250.00 +--- +``` + +Mỗi khối hiển thị tên tệp theo sau là chuỗi ký tự được OCR tạo ra. Nếu một ảnh chứa nhiều ngôn ngữ, bạn sẽ thấy các ký tự tương ứng xuất hiện nhờ bước **phát hiện ngôn ngữ tự động** ở trên. + +## Mẹo chuyên nghiệp & Những lỗi thường gặp + +- **Chất lượng ảnh quan trọng** – ảnh mờ hoặc độ tương phản thấp sẽ cho ra kết quả rác. Hãy tiền xử lý bằng OpenCV (`cv2.threshold`, `cv2.resize`) nếu cần. +- **Số lượng thread vs. I/O** – Nếu ảnh của bạn nằm trên ổ mạng chậm, việc tăng thread có thể không giúp gì. Theo dõi mức sử dụng CPU bằng `top` hoặc `Task Manager`. +- **Xử lý Unicode** – `result.text` là chuỗi Unicode. Khi ghi ra file, mở chúng với `encoding="utf‑8"` để tránh lỗi `UnicodeEncodeError`. +- **Tiêu thụ bộ nhớ** – PDF lớn có thể tiêu tốn nhiều RAM. Nếu gặp `MemoryError`, giảm kích thước thread pool hoặc xử lý ảnh theo các khối nhỏ hơn. + +## Script Hoàn Chỉnh + +Dưới đây là script đầy đủ, sẵn sàng copy‑paste, tích hợp mọi bước chúng ta đã thảo luận. Lưu lại dưới tên `batch_ocr.py` và chạy `python batch_ocr.py`. + +```python +#!/usr/bin/env python3 +""" +Batch OCR script to extract text from images using the ocr package. +Features: +- Automatic language detection +- Parallel processing with configurable thread pool +- Simple batch API for multiple files +""" + +import ocr +import os +import sys + +def main(image_dir: str, workers: int = 4): + # Verify directory exists + if not os.path.isdir(image_dir): + print(f"Error: Directory '{image_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + # Build list of PNG/JPG files + supported_ext = (".png", ".jpg", ".jpeg", ".tif", ".tiff") + files = [ + os.path.join(image_dir, f) + for f in os.listdir(image_dir) + if f.lower().endswith(supported_ext) + ] + + if not files: + print("No supported image files found in the directory.", file=sys.stderr) + sys.exit(1) + + # Initialize OCR engine + engine = ocr.OcrEngine() + engine.language = ocr.Language.Auto # automatic language detection + engine.set_thread_pool_size(workers) # parallel processing OCR + + # Perform batch recognition + print(f"Processing {len(files)} files with {workers} workers...") + results = engine.recognize_batch(files) + + # Output results + for result in results: + print("---") + print(f"File: {result.file_path}") + print("Extracted Text:") + print(result.text.strip()) + print("---\n") + +if __name__ == "__main__": + # Example usage: python batch_ocr.py ./my_images 4 + if len(sys.argv) < 2: + print("Usage: python batch_ocr.py [worker_count]") + sys.exit(1) + + directory = sys.argv[1] + worker_count = int(sys.argv[2]) if len(sys.argv) > 2 else 4 + main(directory, worker_count) +``` + +Chạy như sau: + +```bash +python batch_ocr.py ./my_images 4 +``` + +Bạn sẽ thấy một khối văn bản được định dạng đẹp cho mỗi ảnh, chứng minh rằng bạn có thể **trích xuất văn bản từ hình ảnh** ở quy mô lớn. + +## Tiếp Theo? + +Sau khi đã nắm vững các kiến thức cơ bản về **trích xuất văn bản từ hình ảnh** bằng Python, bạn có thể khám phá: + +- **Xử lý hậu kỳ**: làm sạch đầu ra OCR bằng regex hoặc các thư viện ngôn ngữ tự nhiên. +- **Chuyển PDF**: đưa các chuỗi đã trích xuất vào công cụ tạo PDF để có PDF có thể tìm kiếm. +- **Dịch vụ OCR đám mây**: so sánh kết quả `ocr` nội bộ với Google Vision hoặc Azure OCR để đạt độ chính xác cao hơn trong các trường hợp đặc biệt. +- **Giao diện GUI**: xây dựng một ứng dụng Flask hoặc FastAPI nhỏ cho phép người dùng tải ảnh lên và ngay lập tức xem văn bản đã trích xuất. + +Mỗi chủ đề này đều dựa trên nền tảng **thư viện OCR Python** mà bạn vừa thiết lập, và đều hưởng lợi từ các thủ thuật **OCR xử lý song song** mà chúng ta đã dùng. + +--- + +*Chúc bạn lập trình vui! Nếu gặp bất kỳ khó khăn nào, hãy để lại bình luận bên dưới—tôi luôn sẵn sàng hỗ trợ giải quyết các vấn đề liên quan đến OCR.* + +## 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 mã nguồn hoạt động đầy đủ cùng các 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. + +- [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 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/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md b/ocr/vietnamese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md new file mode 100644 index 000000000..4640d9945 --- /dev/null +++ b/ocr/vietnamese/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-06-19 +description: Cách trích xuất PDF bằng OCR trong Python – hướng dẫn từng bước bao gồm + trích xuất văn bản từ PDF, nhận dạng văn bản từ hình ảnh và ví dụ OCR bằng Python. +draft: false +keywords: +- how to extract pdf +- extract text from pdf +- recognize text from image +- ocr python example +- read pdf with ocr +language: vi +og_description: Cách trích xuất PDF bằng OCR trong Python. Học cách trích xuất văn + bản từ PDF, nhận dạng văn bản từ hình ảnh và xem một ví dụ hoàn chỉnh về OCR trong + Python. +og_title: Cách Trích Xuất Văn Bản PDF bằng OCR trong Python – Hướng Dẫn Đầy Đủ +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + headline: How to Extract PDF Text with OCR in Python – Complete Guide + type: TechArticle +- description: How to extract PDF using OCR in Python – step‑by‑step tutorial covering + extract text from PDF, recognize text from image, and an OCR Python example. + name: How to Extract PDF Text with OCR in Python – Complete Guide + steps: + - name: – Install the Required Packages + text: First, we need an OCR engine. The example below uses the popular **ocr** + package (a thin wrapper around Tesseract). If you prefer a different backend, + the concepts stay the same. + - name: – Initialize the OCR Engine and Set Language + text: Now we spin up the engine and tell it to look for English characters. You + can swap `ocr.Language.English` for any supported language code. + - name: – Load a PDF Page as an Image + text: OCR works on raster images, not PDF objects. The `ocr.Image.from_pdf` helper + renders the chosen page to a bitmap. Adjust `page_number` for other pages (0‑based + indexing). + - name: – Recognize Text from the Rendered Image + text: Here’s the heart of the **ocr python example**. The engine processes the + bitmap and returns an object containing the extracted string. + - name: – Print or Store the Extracted Text + text: Finally, we output the result. In a real application you’d probably write + to a file or a database. + type: HowTo +tags: +- OCR +- Python +- PDF +- Text Extraction +title: Cách Trích Xuất Văn Bản PDF Bằng OCR Trong Python – Hướng Dẫn Toàn Diện +url: /vi/python-java/general/how-to-extract-pdf-text-with-ocr-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Trích Xuất Văn Bản PDF bằng OCR trong Python – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi **cách trích xuất PDF** khi tệp chỉ là một hình ảnh quét chưa? Bạn không phải là người duy nhất. Trong nhiều dự án thực tế—như hợp đồng, hoá đơn, hoặc lưu trữ lịch sử—PDF bạn nhận được không có văn bản có thể chọn được. Tin tốt? Chỉ vài dòng Python có thể biến những trang chỉ có hình ảnh thành văn bản có thể tìm kiếm và chỉnh sửa. + +Trong hướng dẫn này, chúng ta sẽ đi qua một **ví dụ OCR Python** thực tế, đọc một PDF, chuyển trang đầu tiên thành hình ảnh, và sau đó **trích xuất văn bản từ PDF** bằng một công cụ OCR. Khi kết thúc, bạn sẽ biết chính xác cách **đọc PDF với OCR**, lý do mỗi bước quan trọng, và cách điều chỉnh mã cho tài liệu đa trang hoặc các ngôn ngữ khác. + +## Những Điều Bạn Sẽ Học + +- Cài đặt và thiết lập một thư viện OCR đáng tin cậy cho Python. +- Chuyển các trang PDF thành hình ảnh phù hợp cho OCR. +- **Nhận dạng văn bản từ hình ảnh** và lấy các chuỗi Unicode sạch. +- Những khó khăn thường gặp (PDF độ phân giải thấp, trang bị xoay) và cách tránh chúng. +- Mở rộng script để xử lý nhiều trang hoặc xử lý hàng loạt. + +**Yêu cầu trước**: Python 3.8+, pip, và hiểu biết cơ bản về môi trường ảo. Không cần kinh nghiệm OCR trước—chỉ cần làm theo. + +--- + +## ## Cách Trích Xuất Văn Bản PDF bằng OCR trong Python + +Tiêu đề H2 này chứa từ khóa chính của chúng ta ngay nơi các công cụ tìm kiếm thích thấy. Hãy đi thẳng vào mã. + +### Bước 1 – Cài Đặt Các Gói Yêu Cầu + +Đầu tiên, chúng ta cần một công cụ OCR. Ví dụ dưới đây sử dụng gói **ocr** phổ biến (một lớp bao bọc mỏng quanh Tesseract). Nếu bạn thích backend khác, các khái niệm vẫn giống. + +```bash +# Create a fresh virtual environment (optional but recommended) +python -m venv venv +source venv/bin/activate # Windows: venv\Scripts\activate + +# Install the OCR wrapper and Pillow for image handling +pip install ocr pillow +``` + +> **Mẹo chuyên nghiệp:** Trên Linux, bạn cũng cần binary Tesseract: `sudo apt-get install tesseract-ocr`. Người dùng macOS có thể cài qua Homebrew: `brew install tesseract`. + +### Bước 2 – Khởi Tạo Công Cụ OCR và Đặt Ngôn Ngữ + +Bây giờ chúng ta khởi động công cụ và yêu cầu nó tìm các ký tự tiếng Anh. Bạn có thể thay `ocr.Language.English` bằng bất kỳ mã ngôn ngữ nào được hỗ trợ. + +```python +import ocr + +# Step 1: Create an OCR engine and set the language to English +ocr_engine = ocr.OcrEngine() +ocr_engine.language = ocr.Language.English +``` + +**Tại sao điều này quan trọng:** Đặt ngôn ngữ sẽ cải thiện độ chính xác đáng kể vì công cụ có thể áp dụng các từ điển và mô hình ký tự riêng cho ngôn ngữ. + +### Bước 3 – Tải Trang PDF Thành Hình Ảnh + +OCR hoạt động trên ảnh raster, không phải các đối tượng PDF. Hàm trợ giúp `ocr.Image.from_pdf` chuyển trang đã chọn thành bitmap. Điều chỉnh `page_number` cho các trang khác (đánh số bắt đầu từ 0). + +```python +# Step 2: Load the first page of the PDF as an image +pdf_file_path = "YOUR_DIRECTORY/contract.pdf" +page_image = ocr.Image.from_pdf(pdf_file_path, page_number=1) +``` + +> **Trường hợp đặc biệt:** Nếu PDF chứa đồ họa vector thay vì hình ảnh quét, bạn có thể nhận được bản render sắc nét. Đối với các bản quét độ phân giải thấp, hãy cân nhắc tăng DPI: `ocr.Image.from_pdf(..., dpi=300)`. + +### Bước 4 – Nhận Dạng Văn Bản Từ Hình Ảnh Đã Render + +Đây là phần cốt lõi của **ví dụ ocr python**. Công cụ xử lý bitmap và trả về một đối tượng chứa chuỗi đã trích xuất. + +```python +# Step 3: Recognize text from the rendered page image +ocr_result = ocr_engine.recognize(page_image) +``` + +Thuộc tính `ocr_result.text` chứa đầu ra văn bản thuần, giữ lại các ngắt dòng khi có thể. + +### Bước 5 – In Hoặc Lưu Văn Bản Đã Trích Xuất + +Cuối cùng, chúng ta xuất kết quả. Trong một ứng dụng thực tế, bạn có thể ghi vào tệp hoặc cơ sở dữ liệu. + +```python +# Step 4: Print the extracted text +print(ocr_result.text) +``` + +Chạy script sẽ hiển thị một cái gì đó giống như: + +``` +THIS AGREEMENT is made on the 1st day of January 2024... +``` + +Đó là quy trình **trích xuất văn bản từ pdf** hoàn chỉnh bằng OCR. + +--- + +## ## Nhận Dạng Văn Bản Từ Hình Ảnh – Tinh Chỉnh Độ Chính Xác + +Nếu bạn chỉ quan tâm đến **nhận dạng văn bản từ hình ảnh** (ví dụ, một JPEG của biên lai), bạn có thể bỏ qua bước chuyển đổi PDF: + +```python +image_path = "receipt.jpg" +page_image = ocr.Image.from_file(image_path) # Directly load an image +ocr_result = ocr_engine.recognize(page_image) +print(ocr_result.text) +``` + +**Mẹo để có kết quả tốt hơn:** + +- **Tiền xử lý** ảnh: chuyển sang thang độ xám, áp dụng ngưỡng, hoặc chỉnh nghiêng. Pillow giúp việc này dễ dàng. +- **Tăng DPI** khi render PDF: độ phân giải cao hơn cung cấp nhiều chi tiết cho công cụ OCR. +- **Bật cấu hình của công cụ OCR** cho phân đoạn trang (`ocr_engine.config = "--psm 6"` cho các khối đồng nhất). + +## ## Đọc PDF với OCR – Xử Lý Nhiều Trang + +Hầu hết các hợp đồng có nhiều trang. Lặp qua mỗi trang là rất đơn giản: + +```python +def extract_all_pages(pdf_path): + all_text = [] + for i in range(ocr.Image.pdf_page_count(pdf_path)): + img = ocr.Image.from_pdf(pdf_path, page_number=i) + result = ocr_engine.recognize(img) + all_text.append(result.text) + return "\n--- PAGE BREAK ---\n".join(all_text) + +full_text = extract_all_pages("YOUR_DIRECTORY/contract.pdf") +print(full_text) +``` + +Hàm này **đọc PDF với OCR**, nối các đầu ra lại và chèn một dấu phân trang rõ ràng. Bạn có thể đưa `full_text` vào chỉ mục tìm kiếm hoặc lưu thành tệp `.txt`. + +## ## Những Rủi Ro Thường Gặp và Cách Khắc Phục + +| Triệu chứng | Nguyên nhân có thể | Cách khắc phục | +|------------|-------------------|----------------| +| Ký tự lộn xộn, nhiều `?` | Ngôn ngữ sai hoặc thiếu tệp dữ liệu ngôn ngữ | Cài đặt gói ngôn ngữ Tesseract đúng (`tesseract-ocr-`) và đặt `ocr_engine.language`. | +| Thiếu dòng hoặc từ bị cắt ngắn | DPI thấp (dưới 150) | Render PDF ở 300 DPI hoặc cao hơn (`dpi=300`). | +| Văn bản bị xoay hoặc ngược | Trang quét không thẳng đứng | Sử dụng `ocr.Image.deskew(page_image)` trước khi nhận dạng. | +| Xử lý chậm trên PDF lớn | Xử lý các trang tuần tự trên một luồng | Song song hoá với `concurrent.futures.ThreadPoolExecutor`. | + +## ## Mở Rộng Ví Dụ OCR Python + +- **Xuất ra PDF/A**: Sau khi trích xuất, bạn có thể nhúng văn bản trở lại PDF có thể tìm kiếm bằng `reportlab` hoặc `pypdf2`. +- **Phát hiện ngôn ngữ**: Sử dụng `langdetect` trên đầu ra OCR để chuyển `ocr_engine.language` một cách động. +- **Xử lý hàng loạt**: Duyệt thư mục bằng `os.listdir` và áp dụng `extract_all_pages` cho mỗi tệp. + +## ## Kết Quả Mong Đợi và Kiểm Tra + +Khi bạn chạy script trên một bản quét tiếng Anh rõ ràng, bạn sẽ thấy một khối văn bản sạch sẽ với dấu câu đúng. Kiểm tra bằng cách: + +1. So sánh một vài dòng với hình ảnh quét gốc. +2. Chạy đếm từ đơn giản (`len(ocr_result.text.split())`) để đảm bảo đầu ra không rỗng. +3. Tùy chọn, đưa kết quả vào bộ kiểm tra chính tả như `pyspellchecker` để phát hiện lỗi OCR. + +## Kết Luận + +Chúng tôi đã trình bày **cách trích xuất PDF** khi việc phân tích truyền thống thất bại, minh họa một **ví dụ ocr python** đầy đủ, và giải thích cách **nhận dạng văn bản từ hình ảnh** và **đọc PDF với OCR** cho cả trường hợp một trang và đa trang. Với các đoạn mã trên, bạn có thể chuyển bất kỳ PDF quét nào thành văn bản có thể tìm kiếm và chỉnh sửa—không còn phải gõ lại thủ công. + +Bước tiếp theo? Hãy thử đổi ngôn ngữ sang tiếng Tây Ban Nha (`ocr.Language.Spanish`) hoặc thử nghiệm các kỹ thuật tiền xử lý ảnh để tăng độ chính xác. Nếu bạn đang xây dựng hệ thống quản lý tài liệu, hãy cân nhắc lập chỉ mục văn bản đã trích xuất bằng Elasticsearch để tìm kiếm siêu nhanh. + +Có câu hỏi hoặc gặp PDF lạ? Hãy để lại bình luận, và chúc bạn lập trình vui vẻ! + +![Cách trích xuất PDF bằng OCR trong Python](image.png "Cách trích xuất PDF bằng OCR trong Python") + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao phủ 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ạt động đầy đủ 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 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/) +- [Nhận Dạng Văn Bản PDF – Các Hoạt Động OCR với Aspose.OCR cho Java](/ocr/english/java/ocr-operations/) +- [Trích Xuất Văn Bản Hình Ả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/) + +{{< /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-use-ocr-in-java-with-aspose-complete-guide/_index.md b/ocr/vietnamese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md new file mode 100644 index 000000000..bfe5fe12f --- /dev/null +++ b/ocr/vietnamese/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-19 +description: Học cách sử dụng OCR trong Java với Aspose. Hướng dẫn từng bước này bao + gồm tự động chỉnh nghiêng ảnh, tự động phát hiện ngôn ngữ và dễ dàng trích xuất + văn bản từ hình ảnh. +draft: false +keywords: +- how to use OCR +- auto language detection +- extract text image +- auto deskew images +- ocr image preprocessing +language: vi +og_description: 'Cách sử dụng OCR trong Java với Aspose: hướng dẫn đầy đủ bao gồm + tự động chỉnh nghiêng ảnh, tự động phát hiện ngôn ngữ và trích xuất văn bản từ hình + ảnh.' +og_title: Cách sử dụng OCR trong Java với Aspose – Hướng dẫn toàn diện +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + headline: How to Use OCR in Java with Aspose – Complete Guide + type: TechArticle +- description: Learn how to use OCR in Java with Aspose. This step‑by‑step guide covers + auto deskew images, auto language detection, and extract text image easily. + name: How to Use OCR in Java with Aspose – Complete Guide + steps: + - name: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + text: '**Process PDFs** – Convert each PDF page to an image (`PdfConverter`) then + feed it to the same pipeline.' + - name: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + text: '**Batch process a folder** – Loop through files in a directory, applying + the same steps, and write results to a CSV.' + - name: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + text: '**Integrate with a web service** – Expose the OCR logic via a Spring Boot + `@RestController` that accepts multipart uploads.' + type: HowTo +tags: +- OCR +- Java +- Aspose +- Image Processing +title: Cách sử dụng OCR trong Java với Aspose – Hướng dẫn toàn diện +url: /vi/python-java/general/how-to-use-ocr-in-java-with-aspose-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Sử Dụng OCR trong Java với Aspose – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi **cách sử dụng OCR** trong một dự án Java mà không phải đau đầu vì cấu hình chưa? Bạn không phải là người duy nhất. Nhiều lập trình viên gặp khó khăn khi cần **trích xuất văn bản từ hình ảnh** một cách nhanh chóng, đặc biệt khi các bản quét nguồn bị nghiêng hoặc viết bằng ngôn ngữ không quen thuộc. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ thực hành cho thấy cách sử dụng OCR với Aspose, bao gồm **tự động chỉnh nghiêng ảnh**, **tự động phát hiện ngôn ngữ**, và toàn bộ **pipeline tiền xử lý ảnh OCR**. Khi hoàn thành, bạn sẽ có một đoạn mã sẵn sàng chạy, in ra văn bản đã nhận dạng trên console, và hiểu tại sao mỗi thiết lập lại quan trọng. + +> **Bạn sẽ nhận được:** một chương trình Java hoàn chỉnh, có thể chạy được, giải thích từng dòng mã, mẹo xử lý các trường hợp đặc biệt, và ý tưởng mở rộng giải pháp để xử lý hàng loạt hoặc PDF. + +--- + +## Các Điều Kiện Cần Thiết + +- Java 17 (hoặc bất kỳ JDK hiện đại nào) đã được cài đặt và cấu hình. +- Maven hoặc Gradle để quản lý phụ thuộc (chúng tôi sẽ trình bày ví dụ với Maven). +- Tệp giấy phép Aspose OCR for Java (`Aspose.OCR.Java.lic`). Nếu bạn chỉ muốn thử nghiệm, có thể bỏ qua bước cấp giấy phép, nhưng phiên bản dùng thử sẽ thêm watermark. +- Một hình ảnh mẫu (`your_image.png`) được đặt ở vị trí mà mã có thể truy cập. + +> **Mẹo chuyên nghiệp:** lưu các hình ảnh trong một thư mục `resources` riêng và tải chúng qua classpath; cách này tránh các rắc rối về đường dẫn trên các hệ điều hành khác nhau. + +--- + +## Bước 1: Thiết Lập Dự Án và Thêm Phụ Thuộc Aspose OCR + +Tạo một dự án Maven mới (hoặc sử dụng dự án hiện có) và thêm phần sau vào `pom.xml` của bạn: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Chạy `mvn clean install` để tải thư viện. Nếu bạn thích Gradle, tương đương là: + +```gradle +implementation 'com.aspose:aspose-ocr:23.12' +``` + +Bây giờ bạn đã có các lớp **ocr image preprocessing** trên classpath. + +--- + +## Bước 2: Áp Dụng Giấy Phép Aspose OCR (Tùy Chọn nhưng Được Khuyến Khích) + +Nếu bạn có giấy phép, hãy áp dụng nó ngay trong phương thức `main` của bạn. Bỏ qua bước này vẫn được, nhưng phiên bản miễn phí sẽ dán watermark “Demo” lên kết quả. + +```java +// Apply your Aspose OCR license (skip if you don't have one) +ocr.License license = new ocr.License(); +license.setLicense("Aspose.OCR.Java.lic"); +``` + +> **Tại sao lại quan trọng:** Phiên bản có giấy phép loại bỏ giới hạn sử dụng và tắt watermark, cho bạn kết quả sạch sẽ, sẵn sàng cho môi trường production. + +--- + +## Bước 3: Tạo Đối Tượng OCR Engine + +Engine là trung tâm của quá trình. Khi khởi tạo, bạn sẽ có quyền truy cập vào tất cả các tùy chọn **ocr image preprocessing**. + +```java +// Step 3: Create an OCR engine instance +ocr.OcrEngine engine = new ocr.OcrEngine(); +``` + +Lúc này engine đã sẵn sàng, nhưng nó sẽ dùng các thiết lập mặc định có thể không tối ưu cho tài liệu quét. Hãy tinh chỉnh một vài thiết lập. + +--- + +## Bước 4: Bật Tự Động Chỉnh Nghiêng Ảnh (Auto Deskew Images) Để Có Ảnh Sạch Hơn + +Các bản quét nghiêng là một vấn đề phổ biến. Aspose cung cấp tính năng **auto deskew images** tự động làm thẳng ảnh trước khi nhận dạng. + +```java +// Enable auto deskew to correct tilted images +engine.getImagePreprocessing().setAutoDeskew(true); +``` + +> **Cách hoạt động:** Thuật toán phân tích góc đường cơ sở của văn bản và xoay ảnh về hướng thẳng đứng có khả năng nhất. Điều này cải thiện đáng kể độ chính xác cho các bức ảnh chụp bằng điện thoại. + +--- + +## Bước 5: Bật Tự Động Phát Hiện Ngôn Ngữ + +Nếu bạn không biết ngôn ngữ của ảnh nguồn, hãy để engine tự tìm ra. Đây là thiết lập **auto language detection**. + +```java +// Let the engine detect the language automatically +engine.setLanguage(ocr.Language.Auto); +``` + +Khi bật tính năng này, Aspose sẽ quét các glyph và chọn mô hình ngôn ngữ có khả năng nhất, hỗ trợ hơn 30 ngôn ngữ ngay từ đầu. + +--- + +## Bước 6: Tải Ảnh Muốn Nhận Dạng + +Bạn có thể tải ảnh từ đĩa, URL, hoặc thậm chí một mảng byte. Để đơn giản, chúng ta sẽ đọc từ tệp cục bộ. + +```java +// Load the image you want to recognize +ocr.Image image = ocr.Image.load("src/main/resources/your_image.png"); +``` + +> **Mẹo:** Nếu bạn đang xử lý các ảnh lớn, hãy cân nhắc giảm độ phân giải trước bằng `engine.getImagePreprocessing().setResizeFactor(0.5)` để tăng tốc mà không mất quá nhiều chi tiết. + +--- + +## Bước 7: Thực Hiện Nhận Dạng OCR và Trích Xuất Văn Bản Ảnh + +Bây giờ engine sẽ thực hiện phép màu của nó. Phương thức `recognize` trả về một đối tượng `OcrResult` chứa văn bản đã nhận dạng, điểm tin cậy, và các thông tin khác. + +```java +// Perform OCR recognition +ocr.OcrResult result = engine.recognize(image); + +// Output the recognized text +System.out.println(result.getText()); +``` + +Console sẽ hiển thị văn bản thuần túy được trích xuất từ ảnh — đây là kết quả **extract text image** mà chúng ta hướng tới. + +--- + +## Ví Dụ Hoàn Chỉnh + +Dưới đây là lớp Java đầy đủ liên kết mọi thứ lại với nhau. Sao chép‑dán vào `src/main/java/com/example/OcrDemo.java` và chạy. + +```java +package com.example; + +import com.aspose.ocr.*; + +public class OcrDemo { + public static void main(String[] args) { + // ----- Step 1: Apply license (optional) ----- + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); + } catch (Exception e) { + System.out.println("License not found, continuing in demo mode."); + } + + // ----- Step 2: Create OCR engine ----- + OcrEngine engine = new OcrEngine(); + + // ----- Step 3: Enable auto deskew images ----- + engine.getImagePreprocessing().setAutoDeskew(true); + + // ----- Step 4: Enable auto language detection ----- + engine.setLanguage(Language.Auto); + + // ----- Step 5: Load the image ----- + Image image = Image.load("src/main/resources/your_image.png"); + + // ----- Step 6: Recognize and extract text image ----- + OcrResult result = engine.recognize(image); + + // ----- Step 7: Print the result ----- + System.out.println("=== Recognized Text ==="); + System.out.println(result.getText()); + } +} +``` + +### Kết Quả Dự Kiến + +Nếu ảnh chứa cụm từ “Hello World” trên một bản quét sạch, bạn sẽ thấy: + +``` +=== Recognized Text === +Hello World +``` + +Đối với các tài liệu phức tạp hơn (ví dụ: biên lai đa ngôn ngữ), kết quả sẽ bao gồm các dấu xuống dòng và mã ngôn ngữ được phát hiện. + +--- + +## Những Sai Lầm Thường Gặp & Mẹo Chuyên Nghiệp + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|-------------|----------------| +| **Ký tự rác** | Ảnh quá tối hoặc nhiễu. | Bật `engine.getImagePreprocessing().setBinarization(true)` hoặc điều chỉnh độ tương phản thủ công. | +| **Ngôn ngữ sai** | Phát hiện tự động thất bại trên trang đa ngôn ngữ. | Đặt `engine.setLanguage(Language.English)` (hoặc enum phù hợp) để buộc một ngôn ngữ cụ thể. | +| **Xử lý chậm** | Ảnh có độ phân giải rất cao. | Giảm kích thước với `engine.getImagePreprocessing().setResizeFactor(0.5)`. | +| **Lỗi hết bộ nhớ** | Tải quá nhiều ảnh cùng lúc. | Xử lý ảnh tuần tự và gọi `engine.dispose()` sau mỗi lần chạy. | + +> **Nhớ:** Engine OCR an toàn với đa luồng cho các thao tác chỉ đọc, nhưng tạo một instance mới cho mỗi luồng sẽ tránh các lỗi trạng thái ẩn. + +--- + +## Mở Rộng Giải Pháp + +Bây giờ bạn đã biết **cách sử dụng OCR** với Aspose, bạn có thể muốn: + +1. **Xử lý PDF** – Chuyển mỗi trang PDF thành ảnh (`PdfConverter`) rồi đưa vào cùng pipeline. +2. **Xử lý hàng loạt thư mục** – Duyệt các tệp trong một thư mục, áp dụng các bước tương tự, và ghi kết quả ra CSV. +3. **Tích hợp với dịch vụ web** – Phơi bày logic OCR qua một `@RestController` của Spring Boot nhận tải lên multipart. + +Tất cả các kịch bản trên đều tái sử dụng cùng cấu hình **ocr image preprocessing** mà chúng ta đã xây dựng. + +--- + +## Kết Luận + +Chúng ta đã bao quát **cách sử dụng OCR** trong Java với Aspose từ đầu đến cuối: áp dụng giấy phép, tạo engine, bật **auto deskew images**, kích hoạt **auto language detection**, tải ảnh, và cuối cùng **extract text image** bằng một dòng `System.out.println`. Mã nguồn hoàn toàn tự chứa, chạy trên bất kỳ JDK hiện đại nào, và minh họa các thực tiễn tốt nhất về độ chính xác và hiệu suất. + +Hãy thử với những bức ảnh của riêng bạn — có thể là hợp đồng đã quét hoặc ảnh chụp biên lai. Điều chỉnh các flag tiền xử lý, thử nghiệm các ngôn ngữ khác nhau, và bạn sẽ nhanh chóng thấy tại sao thư viện OCR của Aspose là lựa chọn vững chắc cho việc trích xuất văn bản ở mức production. + +Có câu hỏi hoặc muốn chia sẻ kết quả? Để lại bình luận bên dưới hoặc nhắn tin cho tôi trên GitHub. Chúc lập trình vui! + +--- + +![How to use OCR in Java example](/images/ocr-java-example.png "How to use OCR in Java – Aspose demo screenshot") + + +## 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 mã mẫu đầy đủ với các 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. + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [How to Use OCR - Advanced Techniques with Aspose.OCR for Java](/ocr/english/java/advanced-ocr-techniques/) + +{{< /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/improve-ocr-accuracy-in-python-complete-guide/_index.md b/ocr/vietnamese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md new file mode 100644 index 000000000..7ace0c39a --- /dev/null +++ b/ocr/vietnamese/python-java/general/improve-ocr-accuracy-in-python-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-06-19 +description: Cải thiện độ chính xác OCR trong Python bằng Aspose OCR. Tìm hiểu cách + thiết lập ngôn ngữ OCR, tải ảnh để OCR và trích xuất văn bản từ ảnh bằng từ điển + tùy chỉnh. +draft: false +keywords: +- improve OCR accuracy +- extract text from image +- perform OCR on image +- load image for OCR +- set OCR language +language: vi +og_description: Cải thiện độ chính xác OCR trong Python bằng cách thiết lập ngôn ngữ + OCR, tải ảnh để OCR và trích xuất văn bản từ ảnh bằng từ điển tùy chỉnh. +og_title: Cải thiện độ chính xác OCR trong Python – Hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + headline: Improve OCR Accuracy in Python – Complete Guide + type: TechArticle +- description: Improve OCR accuracy in Python using Aspose OCR. Learn how to set OCR + language, load image for OCR, and extract text from image with a custom dictionary. + name: Improve OCR Accuracy in Python – Complete Guide + steps: + - name: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + text: '**Pre‑processing** – Apply contrast enhancement or binarization with Pillow + before feeding the image to Aspose OCR.' + - name: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + text: '**Multiple Languages** – Set `engine.language = ocr.Language.English | + ocr.Language.French` to enable bilingual recognition.' + - name: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + text: '**Region‑Based OCR** – If you only need a specific area (e.g., a table), + crop the image first to reduce noise.' + - name: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + text: '**Confidence Filtering** – `result.confidence` gives a per‑character score; + you can discard low‑confidence results programmatically.' + - name: '**Setting the OCR language** to match your document.' + text: '**Setting the OCR language** to match your document.' + - name: '**Loading the image correctly** so the engine sees the right pixels.' + text: '**Loading the image correctly** so the engine sees the right pixels.' + - name: '**Performing OCR on the image** with a single method call.' + text: '**Performing OCR on the image** with a single method call.' + - name: '**Extracting text from the image** and confirming the result.' + text: '**Extracting text from the image** and confirming the result.' + - name: '**Adding a custom dictionary** to lock in domain‑specific terms.' + text: '**Adding a custom dictionary** to lock in domain‑specific terms.' + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Cải thiện độ chính xác OCR trong Python – Hướng dẫn toàn diện +url: /vi/python-java/general/improve-ocr-accuracy-in-python-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cải Thiện Độ Chính Xác OCR trong Python – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi làm sao **cải thiện độ chính xác OCR** khi văn bản bạn quét chứa các ký hiệu lạ, mã sản phẩm, hay tên thương hiệu chưa? Bạn không đơn độc. Trong nhiều dự án, engine mặc định chỉ đưa ra những ký tự vô nghĩa, và đó là một nguyên nhân gây giảm năng suất nghiêm trọng. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ thực tế, từ đầu đến cuối, cho thấy cách **đặt ngôn ngữ OCR**, **tải ảnh cho OCR**, **thực hiện OCR trên ảnh**, và cuối cùng **trích xuất văn bản từ ảnh** với một từ điển tùy chỉnh giúp tăng tỷ lệ nhận dạng. Khi kết thúc, bạn sẽ có một script sẵn sàng chạy mà có thể đưa vào bất kỳ dự án Python nào. + +## Những Điều Bạn Sẽ Nhận Được + +- Một script Python hoạt động đầy đủ, sử dụng Aspose OCR để đọc file PNG. +- Khả năng **cải thiện độ chính xác OCR** bằng cách cấu hình ngôn ngữ và danh sách từ tùy chỉnh. +- Giải thích rõ ràng tại sao mỗi thiết lập quan trọng, cùng các mẹo xử lý các trường hợp đặc biệt như ký tự không phải Latin. +- Một danh sách kiểm tra nhanh để khắc phục các vấn đề thường gặp trong OCR. + +### Yêu Cầu Trước + +- Python 3.8 hoặc mới hơn đã được cài đặt trên máy của bạn. +- Gói `aspose-ocr` (cài đặt bằng `pip install aspose-ocr`). +- Một hình mẫu (`technical_doc.png`) chứa văn bản bạn muốn đọc. +- Kiến thức cơ bản về Python—không cần gì phức tạp. + +> **Pro tip:** Nếu bạn đang làm việc trong môi trường ảo, hãy kích hoạt nó trước khi cài đặt gói. Điều này giúp quản lý phụ thuộc gọn gàng và tránh xung đột phiên bản. + +--- + +## Bước 1: Cài Đặt và Nhập Aspose OCR + +Đầu tiên, hãy đưa thư viện vào môi trường và nhập các thành phần cần thiết. + +```python +# Install the package (run this once in your terminal) +# pip install aspose-ocr + +import aspose.ocr as ocr +``` + +Namespace `aspose.ocr` cung cấp lớp `OcrEngine`, là trái tim của quá trình OCR. Việc nhập nó ở đây giúp phần còn lại của script sạch sẽ và dễ đọc. + +--- + +## Bước 2: Tạo OCR Engine và **Đặt Ngôn Ngữ OCR** + +Tại sao ngôn ngữ lại quan trọng? Các engine OCR dựa vào các mô hình ngôn ngữ riêng để nhận dạng hình dạng ký tự và mẫu từ. Nếu bạn thông báo cho engine rằng bạn đang quét văn bản tiếng Anh, nó sẽ bỏ qua các glyph Cyrillic và tập trung vào bảng chữ cái Latin, từ đó **cải thiện độ chính xác OCR** một cách đáng kể. + +```python +# Step 2: Initialize the OCR engine +engine = ocr.OcrEngine() + +# Set the recognition language to English (you can pick other languages too) +engine.language = ocr.Language.English +``` + +> **Lưu ý:** Aspose OCR hỗ trợ hơn 50 ngôn ngữ. Thay `ocr.Language.English` bằng `ocr.Language.Spanish`, `ocr.Language.French`, v.v., nếu tài liệu của bạn không phải tiếng Anh. + +--- + +## Bước 3: Định Nghĩa **Từ Điển Tùy Chỉnh** để Tăng Độ Chính Xác + +Hãy tưởng tượng bạn đang quét các hoá đơn chứa từ “AsposeOCR” hoặc các mã sản phẩm như “SKU12345”. Engine không biết những thuật ngữ này, nên sẽ đoán sai. Cung cấp một danh sách từ tùy chỉnh cho engine biết, *“Hey, những chuỗi này là hợp lệ—đừng cố gắng sửa chúng.”* Đó là cách nhanh để **cải thiện độ chính xác OCR**. + +```python +# Step 3: Create a list of domain‑specific words +custom_word_list = [ + "AsposeOCR", # brand name + "InvoiceID", # field label + "SKU12345", # product code + "β‑cell" # Greek character example +] + +# Attach the custom dictionary to the engine +engine.text_processing.custom_dictionary = custom_word_list +``` + +Bạn có thể tải danh sách này từ file hoặc cơ sở dữ liệu nếu có hàng trăm mục—đơn giản chỉ cần giữ chúng trong một list Python. + +--- + +## Bước 4: **Tải Ảnh cho OCR** + +Bây giờ chúng ta cần một ảnh. Phương thức `Image.load` chấp nhận đường dẫn tới bất kỳ định dạng raster nào được hỗ trợ (PNG, JPEG, BMP, v.v.). Nếu không tìm thấy file, engine sẽ ném ra ngoại lệ, vì vậy chúng ta sẽ bảo vệ trước trường hợp này. + +```python +import os + +image_path = "YOUR_DIRECTORY/technical_doc.png" + +if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + +# Step 4: Load the image into memory +image = ocr.Image.load(image_path) +``` + +> **Tại sao bước này quan trọng:** Việc tải ảnh đúng cách đảm bảo engine làm việc với dữ liệu pixel chính xác mà bạn muốn phân tích. Các file hỏng hoặc đường dẫn sai là nguồn gây bực bội phổ biến. + +--- + +## Bước 5: **Thực Hiện OCR trên Ảnh** và Trích Xuất Kết Quả + +Với engine đã được cấu hình và ảnh đã sẵn sàng, việc nhận dạng thực sự chỉ là một lời gọi phương thức. Đối tượng kết quả chứa văn bản thô, điểm tin cậy, và thậm chí thông tin bố cục nếu bạn cần sau này. + +```python +# Step 5: Run OCR +result = engine.recognize(image) + +# The recognized text is stored in result.text +recognized_text = result.text +``` + +Nếu bạn muốn **trích xuất văn bản từ ảnh** từng dòng, có thể tách bằng ký tự xuống dòng: + +```python +lines = recognized_text.splitlines() +for idx, line in enumerate(lines, start=1): + print(f"{idx:02d}: {line}") +``` + +--- + +## Bước 6: Kiểm Tra Kết Quả – Nó Thực Sự **Cải Thiện Độ Chính Xác OCR** Không? + +Hãy in ra kết quả và xem từ điển tùy chỉnh của chúng ta có tạo ra sự khác biệt không. + +```python +print("\n--- OCR Output ---") +print(recognized_text) +``` + +Kết quả điển hình cho ảnh mẫu có thể trông như sau: + +``` +--- OCR Output --- +InvoiceID: 2023‑07‑15 +Customer: AsposeOCR Ltd. +Product: β‑cell Therapy Kit +SKU: SKU12345 +``` + +Chú ý cách tên thương hiệu, ký tự Hy Lạp, và mã sản phẩm xuất hiện đúng như chúng ta đã định nghĩa. Nếu không có từ điển tùy chỉnh, engine sẽ cố “sửa” chúng, thường cho ra kết quả như “Aspose OCR” hoặc “SKU 1234”. + +--- + +## Những Cạm Bẫy Thường Gặp & Cách Khắc Phục + +| Vấn Đề | Nguyên Nhân | Giải Pháp | +|-------|-------------|----------| +| **Ký tự rác** | Đặt ngôn ngữ sai hoặc ảnh độ phân giải thấp | Đảm bảo `engine.language` khớp với ngôn ngữ nguồn và sử dụng ảnh scan DPI cao (300 dpi hoặc hơn). | +| **Từ tùy chỉnh bị bỏ qua** | Từ điển chưa được gắn hoặc tên thuộc tính bị lỗi chính tả | Kiểm tra lại `engine.text_processing.custom_dictionary = …`. | +| **File không tìm thấy** | Đường dẫn sai hoặc thiếu quyền truy cập | Dùng `os.path.abspath()` để xác nhận đường dẫn tuyệt đối; chạy script với quyền phù hợp. | +| **Xử lý chậm** | Ảnh lớn hoặc nhiều trang | Tiền xử lý ảnh (cắt, thay đổi kích thước) hoặc dùng `engine.recognize(image, max_threads=4)` để song song. | + +--- + +## Đi Tiếp: Tinh Chỉnh Nâng Cao để **Cải Thiện Độ Chính Xác OCR** + +1. **Tiền xử lý** – Áp dụng tăng độ tương phản hoặc nhị phân hoá bằng Pillow trước khi đưa ảnh vào Aspose OCR. +2. **Nhiều Ngôn Ngữ** – Đặt `engine.language = ocr.Language.English | ocr.Language.French` để bật nhận dạng song ngữ. +3. **OCR Theo Vùng** – Nếu chỉ cần một khu vực cụ thể (ví dụ: bảng), hãy cắt ảnh trước để giảm nhiễu. +4. **Lọc Tin Cậy** – `result.confidence` cung cấp điểm tin cậy cho từng ký tự; bạn có thể loại bỏ các kết quả có độ tin cậy thấp bằng mã. + +--- + +## Script Hoàn Chỉnh + +Dưới đây là script đầy đủ, sẵn sàng sao chép‑dán. Lưu lại dưới tên `improve_ocr_accuracy.py` và chạy từ dòng lệnh. + +```python +# improve_ocr_accuracy.py +# Complete example that shows how to improve OCR accuracy with Aspose OCR in Python. + +import os +import aspose.ocr as ocr + +def main(): + # ---------- Step 1: Initialize engine and set language ---------- + engine = ocr.OcrEngine() + engine.language = ocr.Language.English # set OCR language + + # ---------- Step 2: Attach custom dictionary ---------- + custom_word_list = [ + "AsposeOCR", + "InvoiceID", + "SKU12345", + "β‑cell" + ] + engine.text_processing.custom_dictionary = custom_word_list + + # ---------- Step 3: Load the image ---------- + image_path = "YOUR_DIRECTORY/technical_doc.png" + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + image = ocr.Image.load(image_path) # load image for OCR + + # ---------- Step 4: Perform OCR ---------- + result = engine.recognize(image) # perform OCR on image + recognized_text = result.text + + # ---------- Step 5: Output the recognized text ---------- + print("\n--- OCR Output ---") + print(recognized_text) + + # Optional: print line numbers for easier debugging + print("\n--- Line‑by‑Line View ---") + for idx, line in enumerate(recognized_text.splitlines(), start=1): + print(f"{idx:02d}: {line}") + +if __name__ == "__main__": + main() +``` + +Chạy script: + +```bash +python improve_ocr_accuracy.py +``` + +Bạn sẽ thấy đầu ra được định dạng đẹp như chúng tôi đã trình bày ở trên. + +--- + +## Kết Luận + +Chúng ta vừa khám phá một cách đơn giản để **cải thiện độ chính xác OCR** trong Python bằng cách: + +1. **Đặt ngôn ngữ OCR** phù hợp với tài liệu của bạn. +2. **Tải ảnh đúng cách** để engine nhận được pixel chính xác. +3. **Thực hiện OCR trên ảnh** chỉ với một lời gọi phương thức. +4. **Trích xuất văn bản từ ảnh** và xác nhận kết quả. +5. **Thêm từ điển tùy chỉnh** để giữ lại các thuật ngữ chuyên ngành. + +Đó là toàn bộ quy trình—from hình ảnh thô đến văn bản sạch, có thể tìm kiếm—được gói gọn trong một script tái sử dụng. + +Nếu bạn muốn thử thách tiếp theo, hãy thử nghiệm với tiền xử lý ảnh (tăng độ tương phản, chỉnh góc) hoặc chuyển sang cấu hình đa ngôn ngữ bằng `ocr.Language.English | ocr.Language.German`. Các nguyên tắc vẫn áp dụng, và bạn sẽ tiếp tục **cải thiện độ chính xác OCR** trên nhiều loại tài liệu hơn. + +Có câu hỏi hay trường hợp đặc biệt nào? Để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +![improve OCR accuracy + + +## 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ụ code hoàn chỉnh cùng hướng dẫn 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 – 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/) +- [How to Set Threshold Value in OCR Image Recognition](/ocr/english/net/ocr-settings/set-threshold-value/) + +{{< /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/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md b/ocr/vietnamese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md new file mode 100644 index 000000000..4ecdf78c3 --- /dev/null +++ b/ocr/vietnamese/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/_index.md @@ -0,0 +1,306 @@ +--- +category: general +date: 2026-06-19 +description: Thực hiện OCR trên hình ảnh bằng thư viện OCR của Python. Tìm hiểu cách + phát hiện văn bản từ hình ảnh, nhận dạng văn bản từ JPEG và trích xuất văn bản từ + ảnh quét một cách hiệu quả. +draft: false +keywords: +- perform OCR on image +- recognize text from jpeg +- detect text from image +- extract text from scanned image +- load image for OCR +language: vi +og_description: Thực hiện OCR trên hình ảnh bằng Python và trích xuất văn bản từ các + tệp quét. Hướng dẫn này sẽ đưa bạn qua các bước tải hình ảnh, chỉnh nghiêng và nhận + dạng văn bản từng bước. +og_title: Thực hiện OCR trên hình ảnh bằng Python – Hướng dẫn trích xuất toàn bộ văn + bản +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + headline: Perform OCR on Image in Python – Full Text Extraction Guide + type: TechArticle +- description: Perform OCR on image using Python's ocr library. Learn how to detect + text from image, recognize text from jpeg, and extract text from scanned image + efficiently. + name: Perform OCR on Image in Python – Full Text Extraction Guide + steps: + - name: Prerequisites + text: '- Python 3.8+ installed (the example uses the `ocr` package available via + `pip install ocr-lib` – replace with your actual library name). - Basic familiarity + with Python functions and virtual environments. - An image file (JPEG, PNG, + TIFF) you want to process; we’ll use `skewed_page.jpg` as a placeh' + - name: Recognize Text from JPEG vs PNG + text: 'Both formats are supported, but JPEG compression can introduce artifacts + that confuse the engine. If you notice frequent mis‑recognitions, try converting + the JPEG to PNG first:' + - name: Detect Text from Image with Multiple Languages + text: 'If your document mixes English and Spanish, set a multilingual mode:' + - name: Extract Text from Scanned PDFs + text: 'For PDFs, you need to rasterize each page into an image first. Libraries + like `pdf2image` make this painless:' + type: HowTo +- questions: + - answer: Absolutely. The library works without a GUI; just ensure the necessary + native binaries (e.g., Tesseract) are installed on the server. + question: Can I run this on a headless server? + - answer: Consider adding a sharpening filter before `engine.recognize`. Many OCR + libraries expose `image_preprocessing.sharpen = True` or you can use OpenCV’s + `cv2.GaussianBlur` in reverse. + question: What if the image is blurry? + - answer: 'Yes. Wrap `perform_ocr` in a loop over a list of file paths, ## 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 image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + - [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) + + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container + >}} {{< /blocks/products/pf/main-wrap-class >}} {{< blocks/products/products-backtop-button + >}}' + question: Does the script support batch processing? + type: FAQPage +tags: +- OCR +- Python +- Image Processing +- Text Extraction +title: Thực hiện OCR trên hình ảnh bằng Python – Hướng dẫn trích xuất toàn bộ văn + bản +url: /vi/python-java/general/perform-ocr-on-image-in-python-full-text-extraction-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Thực hiện OCR trên hình ảnh bằng Python – Hướng dẫn trích xuất văn bản đầy đủ + +Bạn đã bao giờ cần **thực hiện OCR trên các tệp hình ảnh** nhưng gặp khó khăn vì mã nguồn quá khó hiểu? Bạn không phải là người duy nhất. Dù bạn đang chuyển một đống biên lai đã quét thành PDF có thể tìm kiếm được hay lấy chú thích từ một tệp JPEG cho dự án khoa học dữ liệu, khả năng nhận dạng văn bản từ JPEG và các định dạng khác là kỹ năng không thể thiếu đối với bất kỳ nhà phát triển nào ngày nay. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ hoàn chỉnh, có thể chạy ngay, cho bạn thấy cách **phát hiện văn bản từ các tệp hình ảnh**, **trích xuất văn bản từ tài liệu hình ảnh đã quét**, và thậm chí **tải hình ảnh cho OCR** chỉ trong vài dòng mã. Khi kết thúc, bạn sẽ có một đoạn mã sẵn sàng cho môi trường production mà có thể chèn vào dự án của mình—không thiếu import, không có các “xem tài liệu” mơ hồ. + +## Những gì bạn sẽ xây dựng + +- Một script Python nhỏ tạo một engine OCR, bật tính năng tự động cân chỉnh (auto‑deskew), tải một JPEG (hoặc bất kỳ định dạng nào được hỗ trợ), và in ra văn bản đã nhận dạng. +- Giải thích **tại sao** mỗi thiết lập quan trọng, không chỉ **cách** viết nó. +- Mẹo xử lý PDF đa trang, ngôn ngữ không phải tiếng Anh, và các lỗi thường gặp như ảnh mờ. + +### Yêu cầu trước + +- Python 3.8+ đã được cài đặt (ví dụ sử dụng gói `ocr` có sẵn qua `pip install ocr-lib` – thay thế bằng tên thư viện thực tế của bạn). +- Kiến thức cơ bản về hàm Python và môi trường ảo. +- Một tệp hình ảnh (JPEG, PNG, TIFF) mà bạn muốn xử lý; chúng tôi sẽ dùng `skewed_page.jpg` làm ví dụ. + +> **Mẹo chuyên nghiệp:** Nếu bạn đang dùng Windows, chạy terminal với quyền Administrator khi cài đặt thư viện OCR để tránh các lỗi quyền truy cập. + +--- + +## Thực hiện OCR trên hình ảnh – Cài đặt và cấu hình + +Điều đầu tiên bạn cần là một thể hiện engine OCR sạch sẽ. Hãy nghĩ nó như bộ não của toàn bộ quá trình; nếu không cấu hình đúng, ngay cả hình ảnh sắc nét nhất cũng sẽ trả về kết quả vô nghĩa. + +```python +# Step 1: Import the OCR library and create an engine +import ocr + +engine = ocr.OcrEngine() +# Set the recognition language – English works for most cases +engine.language = ocr.Language.English +``` + +**Tại sao điều này quan trọng:** +Cài đặt `engine.language` giúp thu hẹp bộ ký tự mà engine OCR mong đợi, từ đó tăng độ chính xác đáng kể. Nếu bỏ qua, engine sẽ phải đoán, thường xuyên nhận dạng sai các từ đơn giản. + +--- + +## Bật tính năng tự động cân chỉnh – Sửa các ảnh quét nghiêng + +Các trang được quét hiếm khi hoàn toàn thẳng. Một góc nghiêng nhẹ có thể làm sai lệch việc phân đoạn ký tự, biến “Hello” thành “H3llo”. Cờ `auto_deskew` sẽ thực hiện công việc nặng này cho bạn. + +```python +# Step 2: Turn on automatic deskew to straighten tilted images +engine.image_preprocessing.auto_deskew = True +``` + +**Trường hợp đặc biệt:** Nếu bạn biết các ảnh của mình đã thẳng, việc tắt deskew có thể giảm vài mili giây thời gian xử lý—rất hữu ích khi xử lý hàng ngàn trang trong một batch job. + +--- + +## Tải hình ảnh cho OCR – Hỗ trợ JPEG, PNG, TIFF + +Bây giờ chúng ta thực sự **tải hình ảnh cho OCR**. Phương thức `ocr.Image.load` rất linh hoạt; nó chấp nhận đường dẫn tới bất kỳ định dạng raster nào được hỗ trợ. + +```python +# Step 3: Load the image you want to analyze +image_path = "YOUR_DIRECTORY/skewed_page.jpg" +image = ocr.Image.load(image_path) +``` + +> **Tại sao bước này quan trọng:** Thư viện đọc tệp vào một bitmap nội bộ, thực hiện bất kỳ chuyển đổi không gian màu nào cần thiết. Bỏ qua bước này và truyền một luồng byte thô sẽ gây ra `FileNotFoundError` hoặc, tệ hơn, trả về kết quả rỗng mà không có cảnh báo. + +Nếu bạn cần **nhận dạng văn bản từ các tệp JPEG** cụ thể, chỉ cần đảm bảo phần mở rộng tệp là `.jpeg` hoặc `.jpg`. Lệnh gọi tương tự cũng hoạt động với PNG (`.png`) hoặc TIFF (`.tif`) mà không cần thay đổi. + +--- + +## Thực hiện OCR trên hình ảnh – Chạy engine + +Với engine đã được chuẩn bị và hình ảnh đã ở trong bộ nhớ, đã đến lúc **thực hiện OCR trên hình ảnh**. Dòng lệnh duy nhất này thực hiện toàn bộ công việc: tiền xử lý, phân đoạn, phân loại và ghép văn bản. + +```python +# Step 4: Run OCR and capture the result object +result = engine.recognize(image) +``` + +**Bên trong engine đang làm gì?** +- Engine áp dụng phép biến đổi deskew (nếu được bật). +- Nó chạy một mạng nơ-ron hoặc backend Tesseract để nhận dạng ký tự. +- Cuối cùng, nó ghép các ký tự thành từ và dòng, trả về một đối tượng `result` phong phú. + +--- + +## Trích xuất văn bản từ hình ảnh đã quét – Xuất kết quả + +Bước cuối cùng là **trích xuất văn bản từ hình ảnh đã quét** và hiển thị nó. Thuộc tính `result.text` chứa phiên bản văn bản thuần. + +```python +# Step 5: Print the detected text to the console +print("Detected text:") +print(result.text) +``` + +Kết quả thường trông như sau: + +``` +Detected text: +Invoice #12345 +Date: 2023‑09‑01 +Total: $1,234.56 +Thank you for your business! +``` + +Nếu engine OCR không tìm thấy ký tự nào, `result.text` sẽ là một chuỗi rỗng. Trong trường hợp đó, hãy kiểm tra lại chất lượng ảnh hoặc cân nhắc điều chỉnh thuộc tính `engine.confidence_threshold` (nếu thư viện của bạn hỗ trợ). + +--- + +## Xử lý các biến thể phổ biến + +### Nhận dạng văn bản từ JPEG so với PNG + +Cả hai định dạng đều được hỗ trợ, nhưng nén JPEG có thể tạo ra các artefact làm rối engine. Nếu bạn gặp nhiều lỗi nhận dạng, hãy thử chuyển JPEG sang PNG trước: + +```python +from PIL import Image +Image.open(image_path).save("temp.png", format="PNG") +image = ocr.Image.load("temp.png") +``` + +### Phát hiện văn bản từ hình ảnh với nhiều ngôn ngữ + +Nếu tài liệu của bạn chứa cả tiếng Anh và tiếng Tây Ban Nha, hãy bật chế độ đa ngôn ngữ: + +```python +engine.language = ocr.Language.English | ocr.Language.Spanish +``` + +Engine sẽ cân nhắc cả hai bảng chữ cái trong quá trình nhận dạng. + +### Trích xuất văn bản từ PDF đã quét + +Đối với PDF, bạn cần raster hoá mỗi trang thành hình ảnh trước. Các thư viện như `pdf2image` giúp việc này trở nên đơn giản: + +```python +from pdf2image import convert_from_path + +pages = convert_from_path("document.pdf", dpi=300) +for i, page_image in enumerate(pages): + image = ocr.Image.from_pil(page_image) # assuming the library accepts a PIL image + result = engine.recognize(image) + print(f"Page {i+1} text:") + print(result.text) +``` + +--- + +## Ví dụ hoàn chỉnh + +Dưới đây là script đầy đủ mà bạn có thể sao chép‑dán vào tệp `ocr_demo.py`. Nó bao gồm xử lý lỗi và một helper nhỏ để đo thời gian thực thi. + +```python +import ocr +import time +import sys +from pathlib import Path + +def perform_ocr(image_path: str) -> str: + """ + Perform OCR on a given image file and return the extracted text. + Handles auto‑deskew and basic error reporting. + """ + if not Path(image_path).exists(): + sys.exit(f"❌ Error: File not found – {image_path}") + + engine = ocr.OcrEngine() + engine.language = ocr.Language.English + engine.image_preprocessing.auto_deskew = True + + try: + image = ocr.Image.load(image_path) + except Exception as e: + sys.exit(f"❌ Failed to load image: {e}") + + start = time.time() + result = engine.recognize(image) + elapsed = time.time() - start + + if not result.text.strip(): + print("⚠️ No text detected. Try a higher‑resolution image or adjust preprocessing.") + else: + print(f"✅ OCR completed in {elapsed:.2f}s") + print("Detected text:") + print(result.text) + + return result.text + +if __name__ == "__main__": + # Replace with the path to your JPEG/PNG/TIFF file + perform_ocr("YOUR_DIRECTORY/skewed_page.jpg") +``` + +**Kết quả mong đợi** (giả sử ảnh quét rõ ràng): + +``` +✅ OCR completed in 0.87s +Detected text: +Lorem ipsum dolor sit amet, +consectetur adipiscing elit. +``` + +--- + +## Câu hỏi thường gặp + +**H: Tôi có thể chạy script này trên máy chủ không có giao diện (headless) không?** +Đ: Hoàn toàn có thể. Thư viện hoạt động mà không cần GUI; chỉ cần đảm bảo các binary gốc cần thiết (ví dụ, Tesseract) đã được cài đặt trên máy chủ. + +**H: Nếu ảnh bị mờ thì sao?** +Đ: Hãy cân nhắc thêm bộ lọc làm nét trước khi gọi `engine.recognize`. Nhiều thư viện OCR cung cấp `image_preprocessing.sharpen = True` hoặc bạn có thể dùng `cv2.GaussianBlur` của OpenCV theo hướng ngược lại. + +**H: Script có hỗ trợ xử lý hàng loạt không?** +Đ: Có. Đơn giản gói `perform_ocr` trong một vòng lặp qua danh sách các đường dẫn tệp, + +{{< /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/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md b/ocr/vietnamese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md new file mode 100644 index 000000000..5d5695ccd --- /dev/null +++ b/ocr/vietnamese/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-19 +description: Thực hiện OCR trên hình ảnh bằng Aspose OCR Java. Tìm hiểu cách tải hình + ảnh để OCR, sử dụng giấy phép Aspose và trích xuất văn bản từ hình ảnh trong vài + phút. +draft: false +keywords: +- perform ocr on image +- extract text from image +- recognize text image +- use aspose license +- load image for ocr +language: vi +og_description: Thực hiện OCR trên hình ảnh bằng Aspose OCR Java. Hướng dẫn này chỉ + cách sử dụng giấy phép Aspose, tải hình ảnh để OCR và trích xuất văn bản từ hình + ảnh một cách hiệu quả. +og_title: Thực hiện OCR trên hình ảnh với Aspose OCR Java – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + headline: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR Java. Learn how to load image + for OCR, use Aspose license, and extract text from image in minutes. + name: Perform OCR on Image with Aspose OCR Java – Complete Step‑by‑Step Guide + steps: + - name: Expected Console Output + text: '``` Aspose OCR license applied successfully. Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png + === OCR RESULT === Hello World! Привет мир! ```' + - name: Why a License Matters + text: Running the library in evaluation mode is fine for quick tests, but it adds + a watermark to the output and limits the number of pages you can process per + run. Applying the **use aspose license** step removes these restrictions and + signals to Aspose that you’re a paying customer. + - name: How to Obtain and Apply It + text: 1. Purchase a license from the Aspose store. 2. Download the `Aspose.OCR.Java.lic` + file. 3. Place it somewhere your application can read—commonly the `src/main/resources` + folder. 4. Call `new License().setLicense("Aspose.OCR.Java.lic");` before any + OCR work, as shown in the code above. + - name: Common Pitfalls + text: '| Issue | Symptom | Fix | |-------|---------|-----| | Wrong file path | + `FileNotFoundException` | Double‑check the path; use `Paths.get(...)` for OS‑independent + separators. | | Unsupported format | `UnsupportedOperationException` | Convert + the image to PNG or JPEG before loading. | | Huge image ( > ' + - name: Dealing with Multiple Languages + text: Because we set `engine.setLanguage(Language.Auto)`, Aspose will attempt + to detect languages on‑the‑fly. If you know the language in advance (e.g., all + documents are Russian), you can replace `Language.Auto` with `Language.Russian` + for a performance boost. + - name: Post‑Processing Tips + text: "- **Trim whitespace**: `result.getText().trim()`. - **Normalize line endings**: + `result.getText().replace(\"\r\n\", \"\n\")`. - **Remove non‑printable characters**: + use a regex like `result.getText().replaceAll(\"[^\\p{Print}]\", \"\")`." + type: HowTo +tags: +- Aspose OCR +- Java +- Image Processing +title: Thực hiện OCR trên hình ảnh với Aspose OCR Java – Hướng dẫn chi tiết từng bước +url: /vi/python-java/general/perform-ocr-on-image-with-aspose-ocr-java-complete-step-by-s/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Thực hiện OCR trên hình ảnh với Aspose OCR Java – Hướng dẫn chi tiết từng bước + +Bạn đã bao giờ cần **thực hiện OCR trên hình ảnh** nhưng không chắc thư viện nào sẽ cho kết quả đáng tin cậy mà không cần cấu hình phức tạp? Bạn không phải là người duy nhất. Trong nhiều dự án thực tế—như quét hộ chiếu, số hoá hoá đơn, hoặc trích xuất văn bản từ ảnh chụp màn hình—khả năng nhận dạng nhanh chóng dữ liệu văn bản trong hình ảnh là một yếu tố quyết định. + +Trong tutorial này chúng ta sẽ thực hành một ví dụ thực tế cho thấy cách **thực hiện OCR trên hình ảnh** bằng Aspose OCR cho Java. Chúng ta sẽ bao phủ mọi thứ từ việc áp dụng giấy phép Aspose đến tải ảnh, chạy engine, và cuối cùng **trích xuất văn bản từ hình ảnh** để bạn có thể sử dụng ở các bước tiếp theo. Không có phần thừa, chỉ có giải pháp hoạt động mà bạn có thể sao chép‑dán. + +## Những gì bạn sẽ nhận được + +- Một cái nhìn rõ ràng về cách **sử dụng giấy phép Aspose** trong dự án Java. +- Mã chính xác cần để **tải hình ảnh cho OCR** và cho phép engine tự động phát hiện ngôn ngữ. +- Hướng dẫn từng bước để **nhận dạng nội dung văn bản trong hình ảnh** và **trích xuất văn bản từ hình ảnh** một cách an toàn. +- Mẹo xử lý các vấn đề thường gặp (kết quả rỗng, định dạng không được hỗ trợ và vấn đề bộ nhớ). + +> **Yêu cầu trước** – Java 8 hoặc mới hơn, Maven hoặc Gradle để quản lý phụ thuộc, và file giấy phép Aspose OCR cho Java (hoặc bạn có thể chạy ở chế độ đánh giá). + +--- + +## Cách thực hiện OCR trên hình ảnh với Aspose OCR Java + +Dưới đây là chương trình Java đầy đủ, sẵn sàng chạy, minh họa toàn bộ quy trình. Lưu nó dưới tên `AsposeOcrDemo.java` và chạy từ IDE hoặc dòng lệnh của bạn. + +```java +import com.aspose.ocr.*; +import com.aspose.ocr.License; + +/** + * Demonstrates how to perform OCR on an image using Aspose OCR for Java. + * This example shows: + * • Applying an Aspose license (or skipping for evaluation) + * • Loading an image for OCR + * • Setting automatic language detection + * • Recognizing the image and extracting the detected text + */ +public class AsposeOcrDemo { + + public static void main(String[] args) { + // ------------------------------------------------- + // Step 1: Apply your Aspose OCR license (optional) + // ------------------------------------------------- + // If you have a license file, uncomment the next two lines. + // This removes the evaluation watermark and lifts usage limits. + try { + License license = new License(); + license.setLicense("Aspose.OCR.Java.lic"); // <-- use aspose license + System.out.println("Aspose OCR license applied successfully."); + } catch (Exception ex) { + // In evaluation mode we simply continue without a license. + System.out.println("License not found – running in evaluation mode."); + } + + // ------------------------------------------------- + // Step 2: Create an OCR engine instance + // ------------------------------------------------- + OcrEngine engine = new OcrEngine(); + + // ------------------------------------------------- + // Step 3: Set language detection to automatic + // ------------------------------------------------- + engine.setLanguage(Language.Auto); // <-- recognize text image automatically + + // ------------------------------------------------- + // Step 4: Load the image you want to recognize + // ------------------------------------------------- + // Replace the path with the location of your test picture. + // This demonstrates the “load image for OCR” step. + String imagePath = "YOUR_DIRECTORY/mixed_latin_cyrillic.png"; + Image image = Image.load(imagePath); + System.out.println("Image loaded from: " + imagePath); + + // ------------------------------------------------- + // Step 5: Perform OCR and output the recognized text + // ------------------------------------------------- + OcrResult result = engine.recognize(image); + if (result != null && result.getText() != null && !result.getText().isEmpty()) { + System.out.println("=== OCR RESULT ==="); + System.out.println(result.getText()); // <-- extract text from image + } else { + System.out.println("No text was recognized. Check image quality or language settings."); + } + } +} +``` + +### Kết quả dự kiến trên console + +``` +Aspose OCR license applied successfully. +Image loaded from: YOUR_DIRECTORY/mixed_latin_cyrillic.png +=== OCR RESULT === +Hello World! +Привет мир! +``` + +Nếu bạn chạy chương trình mà không có file giấy phép, dòng đầu tiên sẽ chỉ thông báo bạn đang ở chế độ đánh giá, nhưng OCR vẫn hoạt động. + +--- + +## Cài đặt và sử dụng giấy phép Aspose + +### Tại sao giấy phép lại quan trọng + +Chạy thư viện ở chế độ đánh giá là ổn cho các thử nghiệm nhanh, nhưng nó sẽ thêm watermark vào kết quả và giới hạn số trang bạn có thể xử lý mỗi lần. Thực hiện bước **sử dụng giấy phép Aspose** sẽ loại bỏ các hạn chế này và thông báo cho Aspose rằng bạn là khách hàng trả phí. + +### Cách lấy và áp dụng giấy phép + +1. Mua giấy phép từ cửa hàng Aspose. +2. Tải file `Aspose.OCR.Java.lic`. +3. Đặt nó ở vị trí mà ứng dụng của bạn có thể đọc—thông thường là thư mục `src/main/resources`. +4. Gọi `new License().setLicense("Aspose.OCR.Java.lic");` trước khi thực hiện bất kỳ công việc OCR nào, như trong mã ở trên. + +> **Mẹo chuyên nghiệp:** Nếu bạn triển khai lên server, sử dụng đường dẫn tuyệt đối hoặc bộ tải tài nguyên class‑path để tránh `FileNotFoundException`. + +--- + +## Tải hình ảnh để xử lý OCR + +Dòng `Image.load("YOUR_DIRECTORY/mixed_latin_cyrillic.png")` là phần cốt lõi của bước **tải hình ảnh cho OCR**. Aspose OCR hỗ trợ nhiều định dạng: PNG, JPEG, BMP, TIFF, và thậm chí PDF đa trang (khi kết hợp với Aspose.Pdf). + +### Các vấn đề thường gặp + +| Vấn đề | Triệu chứng | Giải pháp | +|-------|-------------|-----------| +| Sai đường dẫn tệp | `FileNotFoundException` | Kiểm tra lại đường dẫn; sử dụng `Paths.get(...)` để có dấu phân tách độc lập với hệ điều hành. | +| Định dạng không được hỗ trợ | `UnsupportedOperationException` | Chuyển đổi hình ảnh sang PNG hoặc JPEG trước khi tải. | +| Hình ảnh quá lớn ( > 10 MP) | Lỗi thiếu bộ nhớ | Giảm kích thước hình ảnh bằng `java.awt.Image` trước khi đưa vào Aspose. | + +--- + +## Trích xuất văn bản từ hình ảnh và xử lý kết quả + +Khi engine OCR hoàn thành, đối tượng `OcrResult` chứa chuỗi đã nhận dạng. Đây là nơi chúng ta **trích xuất văn bản từ hình ảnh** để xử lý tiếp—lưu vào cơ sở dữ liệu, đưa vào chỉ mục tìm kiếm, hoặc truyền cho pipeline NLP downstream. + +### Xử lý đa ngôn ngữ + +Vì chúng ta đã đặt `engine.setLanguage(Language.Auto)`, Aspose sẽ cố gắng phát hiện ngôn ngữ tự động. Nếu bạn biết trước ngôn ngữ (ví dụ: tất cả tài liệu đều là tiếng Nga), bạn có thể thay `Language.Auto` bằng `Language.Russian` để tăng hiệu năng. + +### Mẹo xử lý hậu kỳ + +- **Xóa khoảng trắng thừa**: `result.getText().trim()`. +- **Chuẩn hoá ký tự xuống dòng**: `result.getText().replace("\r\n", "\n")`. +- **Loại bỏ ký tự không hiển thị**: sử dụng regex như `result.getText().replaceAll("[^\\p{Print}]", "")`. + +--- + +## Nhận dạng văn bản trong hình ảnh với các tùy chọn nâng cao (Tùy chọn) + +Nếu bạn cần kiểm soát chi tiết hơn, Aspose OCR cung cấp các thuộc tính bổ sung: + +```java +engine.getImagePreprocessingOptions().setDeskew(true); // correct tilted text +engine.getImagePreprocessingOptions().setContrast(1.2f); // boost faint characters +engine.getRecognitionOptions().setExtractAreas(true); // get bounding boxes +``` + +Những điều chỉnh này hữu ích khi bạn làm việc với tài liệu quét bị lệch hoặc độ tương phản thấp. + +--- + +## Tóm tắt ví dụ hoàn chỉnh + +Kết hợp mọi thứ lại, chương trình cuối cùng thực hiện các bước sau theo thứ tự: + +1. **Thực hiện OCR trên hình ảnh** – bằng cách tạo một `OcrEngine`. +2. **Sử dụng giấy phép Aspose** – tùy chọn nhưng được khuyến nghị. +3. **Tải hình ảnh cho OCR** – thông qua `Image.load`. +4. **Cài đặt phát hiện ngôn ngữ** – `Language.Auto` để **nhận dạng nội dung văn bản trong hình ảnh** tự động. +5. **Trích xuất văn bản từ hình ảnh** – in kết quả, xử lý các phản hồi rỗng một cách nhẹ nhàng. + +Bạn có thể sao chép khối mã trên trực tiếp vào dự án Maven với phụ thuộc sau: + +```xml + + com.aspose + aspose-ocr + 23.12 + +``` + +Chạy `mvn compile exec:java -Dexec.mainClass="AsposeOcrDemo"` và quan sát console hiển thị văn bản đã nhận dạng. + +--- + +## Kết luận + +Chúng tôi vừa cho bạn thấy cách **thực hiện OCR trên hình ảnh** bằng Aspose OCR cho Java, từ việc áp dụng giấy phép đến **tải hình ảnh cho OCR**, **nhận dạng nội dung văn bản trong hình ảnh**, và cuối cùng **trích xuất văn bản từ hình ảnh** để sử dụng downstream. Cách tiếp cận này đơn giản, hoạt động với nhiều ngôn ngữ ngay từ đầu, và có thể mở rộng với các tùy chọn tiền xử lý nâng cao khi cần. + +Tiếp theo bạn có thể làm gì? Thử đưa đầu ra OCR vào chỉ mục tìm kiếm, tạo PDF với văn bản đã trích xuất, hoặc thử nghiệm các định dạng hình ảnh khác. Khả năng là vô hạn, và với API mạnh mẽ của Aspose, bạn sẽ dành nhiều thời gian hơn cho việc xây dựng tính năng hơn là đấu tranh với các vấn đề OCR. + +Có câu hỏi hoặc gặp trường hợp khó xử? Để lại bình luận bên dưới—chúc bạn lập trình vui vẻ! + +## 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 mã mẫu đầy đủ 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 trích xuất văn bản từ hình ảnh từ URL bằng Aspose.OCR cho Java](/ocr/english/java/advanced-ocr-techniques/perform-ocr-image-from-url/) +- [Chuyển đổi hình ảnh thành văn bản trong Java bằng Aspose.OCR BufferedImage](/ocr/english/java/advanced-ocr-techniques/perform-ocr-buffered-image/) +- [Trích xuất văn bản từ hình ảnh Java với chế độ Detect Areas của Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) + +{{< /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