diff --git a/ocr/arabic/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/arabic/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..242ad7f54 --- /dev/null +++ b/ocr/arabic/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: دورة تعليمية عن OCR غير المتزامن تُظهر كيفية استخدام Aspose OCR في بايثون + مع asyncio لاستخراج النص من الصور بسرعة. تعلم تنفيذ OCR غير المتزامن خطوة بخطوة. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: ar +og_description: يُرشدك البرنامج التعليمي لـ OCR غير المتزامن إلى كيفية استخدام Aspose + OCR في بايثون مع asyncio لاستخراج نص الصور بكفاءة. +og_title: دليل OCR غير المتزامن – Python asyncio مع Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: دليل OCR غير المتزامن – Python asyncio مع Aspose OCR +url: /ar/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# دليل OCR غير المتزامن – Python asyncio مع Aspose OCR + +هل تساءلت يوماً كيف تشغّل التعرف الضوئي على الحروف دون حجب تطبيقك؟ في **دليل OCR غير المتزامن** ستشاهد ذلك بالضبط — استخراج نص غير حابِس للـ thread باستخدام `asyncio` في بايثون ومكتبة Aspose OCR. + +إذا كنت عالقاً في انتظار معالجة صورة ثقيلة، فإن هذا الدليل يقدّم لك حلاً غير متزامنًا نظيفًا يبقي حلقة الأحداث تعمل بسلاسة. + +في الأقسام التالية سنغطي كل ما تحتاجه: تثبيت المكتبة، إعداد مساعد غير متزامن، معالجة النتيجة، وحتى نصيحة سريعة لتوسيع المعالجة إلى عدة صور. بنهاية الدليل ستتمكن من إضافة **دليل OCR غير المتزامن** إلى أي مشروع بايثون يستخدم `asyncio` بالفعل. + +## ما الذي ستحتاجه + +قبل أن نبدأ، تأكد من وجود ما يلي: + +* Python 3.9+ (واجهة `asyncio` التي نستخدمها مستقرة منذ 3.7) +* رخصة Aspose OCR سارية أو نسخة تجريبية مجانية (المكتبة مكتوبة ببايثون خالص، لا تحتاج إلى ملفات ثنائية) +* ملف صورة صغير (`.jpg`، `.png`، إلخ) تريد قراءته – احفظه في مجلد معروف + +لا توجد أدوات خارجية أخرى مطلوبة؛ كل شيء يعمل ببايثون خالص. + +## الخطوة 1: تثبيت حزمة Aspose OCR + +أولاً، احصل على حزمة Aspose OCR من PyPI. افتح الطرفية ونفّذ: + +```bash +pip install aspose-ocr +``` + +> **نصيحة احترافية:** إذا كنت تعمل داخل بيئة افتراضية (مستحسن جدًا)، فعّلها أولاً. هذا يحافظ على عزل الاعتمادات ويتجنب تعارض الإصدارات. + +## الخطوة 2: تهيئة محرك OCR بشكل غير متزامن + +قلب **دليل OCR غير المتزامن** هو دالة مساعدة غير متزامنة. تُنشئ كائن `OcrEngine`، تُحمّل صورة، ثم تستدعي `recognize_async()`. المحرك نفسه متزامن، لكن طريقة الـ wrapper تُعيد كائنًا قابلًا للانتظار، مما يسمح لحلقة الأحداث بالبقاء مستجيبة. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**لماذا نفعل ذلك بهذه الطريقة:** +*إنشاء المحرك داخل الدالة المساعدة يضمن أمان الخيوط إذا قررت تشغيل عدة مهام OCR متوازية لاحقًا. كلمة المفتاح `await` تُعيد التحكم إلى حلقة الأحداث بينما تُجرى المعالجة الثقيلة في مجموعة الخيوط الداخلية للمكتبة.* + +## الخطوة 3: تشغيل المساعدة من دالة `async` رئيسية + +الآن نحتاج إلى coroutine صغير يُدعى `main()` يستدعي `async_ocr()` ويطبع النتيجة. هذا يعكس نقطة الدخول النموذجية لسكريبت `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**ماذا يحدث خلف الكواليس؟** +`asyncio.run()` ينشئ حلقة أحداث جديدة، يجدول `main()`، ويغلق الحلقة بنظافة عندما تنتهي `main()`. هذا النمط هو الطريقة الموصى بها لبدء البرامج غير المتزامنة في بايثون 3.7+. + +## الخطوة 4: اختبار السكريبت الكامل + +احفظ الكتلتين البرمجيتين أعلاه في ملف واحد، مثلاً `async_ocr_demo.py`. شغّله من سطر الأوامر: + +```bash +python async_ocr_demo.py +``` + +إذا تم الإعداد بشكل صحيح، يجب أن ترى شيئًا مثل: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +المخرجات الدقيقة ستعتمد على محتوى `photo.jpg`. النقطة الأساسية هي أن السكريبت ينتهي بسرعة، حتى وإن كانت الصورة كبيرة، لأن عمل OCR يحدث في الخلفية. + +## الخطوة 5: التوسيع – معالجة عدة صور بشكل متزامن + +سؤال شائع يتبع ذلك هو: *"هل يمكنني تنفيذ OCR على دفعة من الملفات دون إطلاق عملية جديدة لكل واحدة؟"* الجواب نعم. لأن مساعدنا غير متزامن بالكامل، يمكننا جمع عدة coroutines باستخدام `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**لماذا يعمل هذا:** `asyncio.gather()` يجدول جميع مهام OCR مرة واحدة. مكتبة Aspose OCR لا تزال تستخدم مجموعة خيوطها الخاصة، لكن من منظور بايثون يبقى كل شيء غير حابِس، مما يتيح لك معالجة عشرات الصور في الوقت الذي تستغرقه مكالمة متزامنة واحدة. + +## الخطوة 6: معالجة الأخطاء بلطف + +عند التعامل مع ملفات خارجية، ستواجه حتماً ملفات مفقودة، صور تالفة، أو مشاكل رخصة. احطّ استدعاء OCR بكتلة `try/except` للحفاظ على حلقة الأحداث حية: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +الآن يمكن لـ `batch_ocr()` استدعاء `safe_async_ocr` بدلاً من ذلك، مما يضمن أن ملفًا سيئًا واحدًا لا يوقف الدفعة بأكملها. + +## نظرة بصرية + +![مخطط دليل OCR غير المتزامن](async-ocr-diagram.png){alt="مخطط تدفق دليل OCR غير المتزامن يوضح مساعد async_ocr، حلقة الأحداث، ومحرك Aspose OCR"} + +المخطط أعلاه يوضح التدفق: حلقة الأحداث → `async_ocr` → `OcrEngine` → الخيط الخلفي → النتيجة تعود إلى الحلقة. + +## الأخطاء الشائعة وكيفية تجنّبها + +| المشكلة | لماذا تحدث | الحل | +|---------|------------|------| +| **إدخال/إخراج حابِس داخل المساعدة** | استخدام `open()` دون `await` يسبب حجب الحلقة. | استخدم `aiofiles` لقراءة الملفات، أو دع `engine.load_image` يتولى ذلك (إنه غير حابِس بالفعل). | +| **إعادة استخدام نفس `OcrEngine` عبر coroutines** | المحرك غير آمن للـ thread؛ الاستدعاءات المتزامنة قد تفسد الحالة. | أنشئ محركًا جديدًا داخل كل استدعاء `async_ocr` (كما هو موضح). | +| **غياب الرخصة** | Aspose OCR يرمي استثناءً متعلقًا بالرخصة أثناء التشغيل. | سجّل رخصتك مبكرًا (`OcrEngine.set_license("license.json")`). | +| **صور كبيرة تسبب ارتفاعًا في استهلاك الذاكرة** | المكتبة تحمل الصورة بالكامل في الذاكرة. | قلل أبعاد الصور قبل OCR إذا كانت الذاكرة تشكل قلقًا. | + +## ملخص: ما أنجزناه + +في هذا **دليل OCR غير المتزامن** قمنا بـ: + +1. تثبيت مكتبة Aspose OCR. +2. بناء مساعد `async_ocr` يُجري التعرف دون حجب. +3. تشغيل المساعد من نقطة دخول `asyncio` نظيفة. +4. توضيح المعالجة الدفعة باستخدام `asyncio.gather`. +5. إضافة معالجة الأخطاء ونصائح أفضل الممارسات. + +كل ذلك ببايثون خالص، لذا يمكنك دمجه في خادم ويب، أداة سطر أوامر، أو خط أنابيب بيانات دون إعادة كتابة الكود غير المتزامن الموجود. + +## الخطوات التالية والمواضيع ذات الصلة + +* **معالجة الصور مسبقًا بشكل غير متزامن** – استخدم `aiohttp` لتنزيل الصور بشكل متزامن قبل OCR. +* **تخزين نتائج OCR** – اجمع هذا الدليل مع برنامج تشغيل قاعدة بيانات غير متزامن مثل `asyncpg` لـ PostgreSQL. +* **تحسين الأداء** – جرّب `engine.recognize_async(max_threads=4)` إذا كانت المكتبة توفر هذا الخيار. +* **محركات OCR بديلة** – قارن Aspose OCR مع أغطية Tesseract غير المتزامنة لتحليل التكلفة والفائدة. + +لا تتردد في التجربة: جرّب معالجة ملفات PDF، عدّل إعدادات اللغة، أو اربط النتائج مع chatbot. السماء هي الحد عندما يكون لديك أساس صلب لـ **دليل OCR غير المتزامن**. + +برمجة سعيدة، ولتكن استخراج النصوص سريعًا دائمًا! + +## ماذا يجب أن تتعلمه بعد ذلك؟ + +- [استخراج النص من صورة باستخدام Aspose OCR – دليل خطوة بخطوة](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [دليل Aspose OCR – التعرف الضوئي على الحروف](/ocr/english/) +- [كيفية تنفيذ OCR لنص الصورة مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/arabic/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..1a1f5b7ff --- /dev/null +++ b/ocr/arabic/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: اكتشاف اللغة التلقائي في OCR أصبح سهلًا. تعلّم كيفية تحميل صورة OCR، + وتفعيل اكتشاف اللغة التلقائي، والتعرف على نص الصورة في بضع خطوات فقط. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: ar +og_description: اكتشاف اللغة تلقائيًا في OCR أصبح سهلًا. اتبع هذا الدليل خطوة بخطوة + لتمكين اكتشاف اللغة التلقائي، وتحميل OCR للصورة، والتعرف على نص الصورة. +og_title: اكتشاف اللغة تلقائيًا باستخدام OCR – دليل بايثون الكامل +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: الكشف التلقائي عن اللغة باستخدام OCR – دليل بايثون الكامل +url: /ar/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# الكشف التلقائي عن اللغة باستخدام OCR – دليل بايثون كامل + +هل تساءلت يوماً كيف تجعل محرك OCR *يخمن* لغة المستند الممسوح ضوئياً دون أن تخبره بما يبحث عنه؟ هذا بالضبط ما يفعله **الكشف التلقائي عن اللغة**، وهو تغيير جذري عندما تتعامل مع ملفات PDF متعددة اللغات، أو صور لعلامات الشوارع، أو أي صورة تمزج بين خطوط مختلفة. + +في هذا الدرس سنستعرض مثالاً عملياً يوضح لك كيفية **تمكين الكشف التلقائي عن اللغة**، **تحميل OCR للصورة**، و**التعرف على نص الصورة** باستخدام واجهة برمجة تطبيقات على نمط بايثون. في النهاية ستحصل على سكريبت مستقل يطبع كل من رمز اللغة المكتشفة والنص المستخرج—دون الحاجة لتحديد اللغة يدوياً. + +## ما ستتعلمه + +- كيفية إنشاء كائن محرك OCR وتفعيل **الكشف التلقائي عن اللغة**. +- الخطوات الدقيقة **لتحميل OCR للصورة** من القرص. +- كيفية استدعاء طريقة `recognize()` للمحرك والحصول على نتيجة تتضمن رمز اللغة. +- نصائح للتعامل مع الحالات الخاصة مثل الصور منخفضة الدقة أو الخطوط غير المدعومة. + +لا تحتاج إلى خبرة سابقة في OCR متعدد اللغات؛ فقط إعداد بسيط لبايثون وملف صورة. + +--- + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من وجود ما يلي: + +1. تثبيت Python 3.8+ (أي نسخة حديثة تعمل). +2. مكتبة OCR التي توفر `OcrEngine`، `LanguageAutoDetectMode`، إلخ – في هذا الدليل سنفترض حزمة افتراضية تسمى `myocr`. ثبّتها باستخدام: + + ```bash + pip install myocr + ``` + +3. ملف صورة (`multilingual_sample.png`) يحتوي على نص على الأقل بلغتين مختلفتين. +4. قليل من الفضول—إذا لم تتعامل مع OCR من قبل، لا تقلق؛ الكود بسيط ومباشر. + +--- + +## الخطوة 1: تمكين الكشف التلقائي عن اللغة + +أول شيء عليك فعله هو إخبار المحرك بأنه يجب أن *يكتشف* اللغة بنفسه. هنا يأتي دور علم **الكشف التلقائي عن اللغة**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **لماذا هذا مهم:** +> عندما يتم ضبط `AUTO_DETECT`، يقوم المحرك بتشغيل مصنف لغة خفيف الوزن على الصورة قبل أن يبدأ التعرف الثقيل على الأحرف. هذا يعني أنك لا تحتاج إلى تخمين ما إذا كان النص إنجليزياً، روسياً، فرنسياً، أو أي تركيبة أخرى. سيختار المحرك تلقائياً نموذج اللغة الأنسب لكل منطقة من الصورة. + +--- + +## الخطوة 2: تحميل OCR للصورة + +الآن بعد أن علم المحرك أنه يجب أن يكتشف اللغات تلقائياً، نحتاج إلى تزويده بشيء يعمل عليه. خطوة **تحميل OCR للصورة** تقرأ البت ماب وتجهز المخازن الداخلية. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **نصيحة احترافية:** +> إذا كانت صورتك أكبر من 300 dpi، فكر في تقليل حجمها إلى حوالي 150‑200 dpi. التفاصيل الزائدة قد تُبطئ مرحلة الكشف عن اللغة دون تحسين الدقة. + +--- + +## الخطوة 3: التعرف على نص الصورة + +مع الصورة في الذاكرة وتفعيل الكشف عن اللغة، الخطوة الأخيرة هي طلب من المحرك **التعرف على نص الصورة**. هذه الدعوة الواحدة تقوم بكل العمل الشاق. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` هو كائن يحتوي عادةً على خاصيتين على الأقل: + +| الخاصية | الوصف | +|-----------|-------------| +| `language` | رمز ISO‑639‑1 للغة المكتشفة (مثال: `"en"` للإنجليزية). | +| `text` | النص المستخرج من الصورة كـ plain‑text. | + +--- + +## الخطوة 4: استرجاع اللغة المكتشفة والنص المستخرج + +الآن نطبع ما اكتشفه المحرك. هذا يوضح قدرة **detect language OCR** عملياً. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**نموذج المخرجات** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **ماذا لو أعاد المحرك `None`؟** +> عادةً ما يعني ذلك أن الصورة غير واضحة أو أن النص صغير جداً (< 8 pt). حاول زيادة التباين أو استخدام مصدر بدقة أعلى. + +--- + +## مثال كامل يعمل (تمكين الكشف التلقائي عن اللغة من البداية إلى النهاية) + +بجمع كل ما سبق، إليك سكريبت جاهز للتنفيذ يغطي **تمكين الكشف التلقائي عن اللغة**، **تحميل OCR للصورة**، **التعرف على نص الصورة**، و**الكشف عن اللغة** في خطوة واحدة. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +احفظه باسم `automatic_language_detection_ocr.py`، استبدل `YOUR_DIRECTORY` بالمجلد الذي يحتوي على ملف PNG، ثم شغّله: + +```bash +python automatic_language_detection_ocr.py +``` + +ستظهر لك رمز اللغة متبوعاً بالنص المستخرج، تماماً كما في مثال المخرجات أعلاه. + +--- + +## التعامل مع الحالات الشائعة + +| الحالة | الحل المقترح | +|-----------|----------------| +| **صورة ذات دقة منخفضة جداً** (أقل من 100 dpi) | قم بزيادة الدقة باستخدام مرشح بيكوبك قبل التحميل، أو اطلب مصدرًا بدقة أعلى. | +| **خطوط مختلطة في صورة واحدة** (مثال: إنجليزي + سيريلي) | عادةً ما يقسم المحرك الصفحة إلى مناطق؛ إذا لاحظت أخطاء في الكشف، اضبط `engine.enable_region_split = True`. | +| **لغة غير مدعومة** | تأكد أن مكتبة OCR تتضمن حزمة لغة للخط الذي تحتاجه؛ قد تحتاج إلى تحميل نماذج إضافية. | +| **معالجة دفعات كبيرة** | أنشئ المحرك مرة واحدة، ثم أعد استخدامه عبر عدة دورات `load_image` / `recognize` لتجنب تحميل النماذج مراراً. | + +--- + +## نظرة بصرية عامة + +![مثال على الكشف التلقائي للغة](https://example.com/auto-lang-detect.png "الكشف التلقائي عن اللغة") + +*النص البديل:* مثال على الكشف التلقائي للغة يُظهر رمز اللغة المكتشف والنص المتعدد اللغات المستخرج. + +--- + +## الخلاصة + +لقد غطينا الآن **الكشف التلقائي عن اللغة** من البداية إلى النهاية—إنشاء المحرك، تفعيل الكشف التلقائي، تحميل صورة للـ OCR، التعرف على النص، وأخيراً استرجاع اللغة المكتشفة. يتيح لك هذا التدفق المتكامل معالجة المستندات متعددة اللغات دون الحاجة لتكوين نماذج اللغة يدوياً في كل مرة. + +إذا كنت مستعداً للانتقال إلى مستوى أعلى، فكر في: + +- **معالجة دفعات** مئات الصور باستخدام حلقة تعيد استخدام نفس كائن `OcrEngine`. +- **معالجة ما بعد الاستخراج** للنص باستخدام مدقق إملائي أو محلل لغوي مخصص. +- **دمج** السكريبت في خدمة ويب تستقبل تحميلات المستخدم وتعيد JSON يحتوي على حقلي `language` و `text`. + +لا تتردد في تجربة صيغ صور مختلفة (`.jpg`, `.tif`) وملاحظة كيف تتغير دقة الكشف. هل لديك أسئلة أو صورة صعبة لا تُقرأ؟ اترك تعليقاً أدناه—برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..93aa60fc2 --- /dev/null +++ b/ocr/arabic/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-31 +description: تعلم كيفية تحويل الصور إلى نص باستخدام بايثون مع سكريبت تحويل الصور إلى + نص بالجملة. استخرج النص من الصور الممسوحة ضوئياً باستخدام Aspose.OCR في دقائق. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: ar +og_description: تحويل الصور إلى نص باستخدام بايثون فورًا. يوضح هذا الدليل تحويل الصور + إلى نص بشكل جماعي وكيفية التعرف على النص من الصور الممسوحة ضوئيًا باستخدام Aspose.OCR. +og_title: تحويل الصور إلى نص بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: تحويل الصور إلى نص بايثون – دليل كامل خطوة بخطوة +url: /ar/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل الصور إلى نص بايثون – دليل شامل خطوة‑بخطوة + +هل تساءلت يومًا كيف **convert images to text python** دون البحث عن عشرات المكتبات؟ لست وحدك. سواء كنت تقوم برقمنة الإيصالات القديمة، أو استخراج البيانات من الفواتير الممسوحة ضوئيًا، أو بناء أرشيف PDF قابل للبحث، فإن تحويل الصور إلى ملفات نصية عادية هو مهمة يومية للعديد من المطورين. + +في هذا الدرس سنستعرض خط أنابيب **bulk image to text conversion** يتعرف على النص من الصور الممسوحة، ويحفظ كل نتيجة كملف `.txt` منفصل، وكل ذلك ببضع أسطر من بايثون فقط. لا حاجة للبحث عن واجهات برمجة تطبيقات غامضة—Aspose.OCR يتولى الجزء الأكبر، وسنوضح لك بالضبط كيفية ربطه. + +## ما ستتعلمه + +- كيفية تثبيت وتكوين حزمة Aspose.OCR للبايثون. +- الكود الدقيق المطلوب **convert images to text python** باستخدام `BatchOcrEngine`. +- نصائح للتعامل مع المشكلات الشائعة مثل الصيغ غير المدعومة أو الملفات التالفة. +- طرق للتحقق من أن خطوة **recognize text from scanned images** نجحت فعليًا. + +بنهاية هذا الدليل ستحصل على سكريبت جاهز للتنفيذ يمكنه معالجة آلاف الصور دفعة واحدة—مثالي لأي سيناريو معالجة دفعات. + +## المتطلبات المسبقة + +- Python 3.8+ مثبت على جهازك. +- مجلد يحتوي على ملفات صور (PNG, JPEG, TIFF, إلخ) تريد تحويلها إلى نص. +- حساب Aspose Cloud نشط أو ترخيص تجريبي مجاني (الطبقة المجانية كافية للاختبار). + +إذا كان لديك كل ذلك، لنبدأ. + +--- + +## الخطوة 1 – إعداد بيئة بايثون + +قبل أن نكتب أي كود OCR، تأكد من أنك تعمل داخل بيئة افتراضية نظيفة. هذا يعزل الاعتمادات ويمنع تعارض الإصدارات. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **نصيحة احترافية:** حافظ على تنظيم دليل المشروع—أنشئ مجلدًا فرعيًا باسم `ocr_project` وضع السكريبت هناك. سيسهل ذلك التعامل مع المسارات لاحقًا. + +## الخطوة 2 – تثبيت Aspose.OCR للبايثون + +Aspose.OCR مكتبة تجارية، لكنها تُوزَّع بحزمة wheel مجانية على نمط NuGet يمكنك سحبها من PyPI. نفّذ الأمر التالي داخل البيئة الافتراضية المُفعَّلة: + +```bash +pip install aspose-ocr +``` + +إذا واجهت خطأ في الصلاحيات، أضف العلامة `--user` أو نفّذ الأمر باستخدام `sudo` (Linux/macOS فقط). بعد التثبيت يجب أن ترى شيئًا مشابهًا لـ: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **لماذا Aspose؟** على عكس العديد من أدوات OCR المفتوحة، يدعم Aspose.OCR **bulk image to text conversion** مباشرةً ويتعامل مع مجموعة واسعة من صيغ الصور دون إعداد إضافي. كما يوفر فئة `BatchOcrEngine` التي تجعل مهمة “convert images to text python” عملية سطر واحد. + +## الخطوة 3 – تحويل الصور إلى نص بايثون باستخدام Batch OCR + +الآن نصل إلى جوهر الدرس. السكريبت التالي قابل للتنفيذ بالكامل ويقوم بـ: + +1. استيراد فئات محرك OCR. +2. إنشاء كائن `BatchOcrEngine`. +3. توجيه المحرك إلى مجلد إدخال يحتوي على الصور. +4. تحديد مجلد إخراج لكتابة كل ملف نصي مستخرج. +5. تشغيل طريقة `recognize()` التي **recognize text from scanned images** واحدة تلو الأخرى. + +احفظ ما يلي باسم `batch_ocr.py` داخل مجلد مشروعك: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### كيف يعمل + +- **`BatchOcrEngine`** يلف فئة `OcrEngine` العادية لكنه يضيف تنسيقًا على مستوى المجلد، وهو ما تحتاجه تمامًا عندما تريد **convert images to text python** على نطاق واسع. +- خاصية `input_folder` تخبر المحرك أين يبحث عن الصور المصدرية. يقوم تلقائيًا بمسح الدليل وتحديد كل ملف مدعوم. +- خاصية `output_folder` تحدد أين تُحفظ كل ملفات `.txt`. يطابق المحرك اسم الملف الأصلي، فمثلاً `receipt1.png` يصبح `receipt1.txt`. +- استدعاء `recognize()` يُشغِّل الحلقة الداخلية التي تُحمِّل كل صورة، تُجري OCR، وتكتب النتيجة. الطريقة تُبقي التنفيذ محجوزًا حتى تُعالج جميع الملفات، مما يسهل ربط إجراءات أخرى (مثل ضغط مجلد الإخراج). + +#### النتيجة المتوقعة + +عند تشغيل السكريبت: + +```bash +python batch_ocr.py +``` + +ستظهر لك: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +داخل `output_texts` ستجد ملف نصي عادي لكل صورة. افتح أيًا منها بمحرر نص وسترى نتيجة OCR الخام—عادةً ما تكون تقريبًا قريبًا من النص المطبوع الأصلي. + +## الخطوة 4 – التحقق من النتائج ومعالجة الأخطاء + +حتى أفضل محركات OCR قد تتعثر مع مسحات منخفضة الدقة أو صفحات مائلة بشدة. إليك طريقة سريعة للتحقق من صحة المخرجات وتسجيل أي فشل. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**لماذا نضيف هذا؟** +- يلتقط الحالات التي ينتج فيها المحرك سلسلة فارغة صامتًا (شائع مع الصور غير القابلة للقراءة). +- يمنحك قائمة بالملفات الإشكالية لتفحصها يدويًا أو تعيد تشغيلها بإعدادات مختلفة (مثل زيادة خيارات `OcrEngine.preprocess`). + +### الحالات الخاصة والتعديلات + +| الحالة | الحل المقترح | +|-----------|----------------| +| الصور مدارة بزاوية 90° | اضبط `batch_engine.ocr_engine.rotation_correction = True`. | +| لغات مختلطة (إنجليزي + فرنسي) | استخدم `batch_engine.ocr_engine.language = "eng+fra"` قبل `recognize()`. | +| ملفات PDF ضخمة تم تحويلها إلى صور أولًا | قسّم ملفات PDF إلى صور صفحة واحدة، ثم مرّر المجلد إلى المحرك الدفعي. | +| أخطاء الذاكرة في دفعات كبيرة جدًا | عالج مجلدات فرعية أصغر بشكل متسلسل، أو زد `batch_engine.max_memory_usage`. | + +## الخطوة 5 – أتمتة سير العمل بالكامل (اختياري) + +إذا كنت تحتاج لتشغيل هذا التحويل كل ليلة، غلف السكريبت بملف شل بسيط أو ملف دفعي Windows، وجدوله باستخدام `cron` (Linux/macOS) أو Task Scheduler (Windows). إليك مثالًا بسيطًا لملف `run_ocr.sh` للأنظمة الشبيهة بـ Unix: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +اجعل الملف قابلًا للتنفيذ (`chmod +x run_ocr.sh`) وأضف إدخالًا إلى cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +سيقوم هذا بتشغيل التحويل كل يوم في الساعة 2 صباحًا ويسجل أي مخرجات للمراجعة لاحقًا. + +--- + +## الخلاصة + +أصبح لديك الآن طريقة مثبتة وجاهزة للإنتاج **convert images to text python** باستخدام `BatchOcrEngine` من Aspose.OCR. يتعامل السكريبت مع **bulk image to text conversion**، يكتب كل نتيجة إلى ملف مخصص، ويتضمن خطوات تحقق لضمان أنك فعليًا **recognize text from scanned images** بشكل صحيح. + +من هنا يمكنك: + +- تجربة إعدادات OCR مختلفة (حزم اللغات، تصحيح الميل، تقليل الضوضاء). +- تمرير النص المُولد إلى فهرس بحث مثل Elasticsearch للبحث النصي الفوري. +- دمج هذا الخط الأنابيب مع أدوات تحويل PDF لمعالجة ملفات PDF الممسوحة ضوئيًا دفعة واحدة. + +هل لديك أسئلة، أو لاحظت مشكلة مع نوع ملف معين؟ اترك تعليقًا أدناه، ولنحلها معًا. برمجة سعيدة، ونتمنى أن تكون عمليات OCR سريعة وخالية من الأخطاء! + +## ماذا تتعلم بعد ذلك؟ + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..cbba956e8 --- /dev/null +++ b/ocr/arabic/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: إنشاء كائن الترخيص في بايثون وتكوين مسار الترخيص بسهولة. تعلم كيفية إعداد + ترخيص Aspose OCR مع أمثلة شفرة واضحة. +draft: false +keywords: +- create license instance +- configure license path +language: ar +og_description: إنشاء كائن الترخيص في بايثون وتكوين مسار الترخيص فورًا. اتبع هذا الدليل + لتفعيل Aspose OCR بثقة. +og_title: إنشاء مثيل ترخيص في بايثون – دليل الإعداد الكامل +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: إنشاء كائن الترخيص في بايثون – دليل خطوة بخطوة +url: /ar/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء كائن الترخيص في بايثون – دليل الإعداد الكامل + +هل تحتاج إلى **create license instance** لـ Aspose OCR في بايثون؟ أنت في المكان الصحيح. في هذا الدرس سنوضح لك أيضًا كيفية **configure license path** حتى يعرف SDK أين يجد ملف `.lic` الخاص بك. + +إذا سبق لك أن جلست أمام سكريبت فارغ وتتساءل لماذا محرك OCR يشتكي من منتج غير مرخص، فأنت لست وحدك. الحل عادةً يكون بضع أسطر من الشيفرة—بمجرد أن تعرف بالضبط أين تضعها. بنهاية هذا الدليل ستحصل على بيئة Aspose OCR مرخصة بالكامل جاهزة للتعرف على النصوص، الصور، وملفات PDF دون أي مشاكل. + +## ما ستتعلمه + +- كيفية **create license instance** باستخدام حزمة `asposeocr`. +- الطريقة الصحيحة لـ **configure license path** لكل من بيئة التطوير والإنتاج. +- المشكلات الشائعة (ملف مفقود، أذونات غير صحيحة) وكيفية تجنبها. +- سكريبت كامل قابل للتنفيذ يمكنك إضافته إلى أي مشروع. + +لا يلزمك أي خبرة سابقة مع Aspose OCR، فقط تثبيت Python 3 يعمل وملف ترخيص صالح. + +--- + +## الخطوة 1: تثبيت حزمة Aspose OCR للبايثون + +قبل أن نتمكن من **create license instance**، يجب أن تكون المكتبة موجودة. افتح الطرفية ونفّذ الأمر التالي: + +```bash +pip install aspose-ocr +``` + +> **نصيحة احترافية:** إذا كنت تستخدم بيئة افتراضية (مستحسن جدًا)، فعّلها أولًا. هذا يحافظ على تنظيم الاعتمادات ويمنع تعارض الإصدارات. + +## الخطوة 2: استيراد فئة الترخيص + +الآن بعد أن أصبح SDK متاحًا، يجب أن تكون السطر الأول في سكريبتك هو استيراد فئة `License`. هذه هي الكائن الذي سنستخدمه لـ **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +لماذا نستوردها فورًا؟ لأن كائن `License` يجب أن يُنشأ **قبل** أي استدعاءات OCR؛ وإلا سيظهر خطأ ترخيص في اللحظة التي تحاول فيها معالجة صورة. + +## الخطوة 3: إنشاء كائن الترخيص + +هذه هي اللحظة التي انتظرتها—فعليًا **create license instance**. إنها سطر واحد، لكن السياق المحيط مهم. + +```python +# Step 3: Create a License instance +license = License() +``` + +المتغير `license` الآن يحمل كائنًا يتحكم في جميع سلوكيات الترخيص لعملية بايثون الحالية. فكر فيه كحارس البوابة الذي يخبر Aspose OCR، “أنا أمتلك الحق في التشغيل”. + +## الخطوة 4: ضبط مسار الترخيص + +مع وجود الكائن، نحتاج إلى توجيهه إلى ملف `.lic` الخاص بنا. هنا يأتي دور **configure license path**. استبدل العنصر النائب بالمسار المطلق لملف الترخيص الخاص بك. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +بعض النقاط التي يجب ملاحظتها: + +1. **السلاسل الخام (`r"…"`)** تمنع تفسير الشرطات المائلة العكسية كحروف هروب في نظام Windows. +2. استخدم **مسارًا مطلقًا** لتجنب الالتباس عندما يُشغل السكريبت من دليل عمل مختلف. +3. إذا كنت تفضّل مسارًا نسبيًا (مثلاً عند تضمين الترخيص مع مشروعك)، تأكد أن القاعدة النسبية هي موقع السكريبت، وليس دليل الصدفة الحالي. + +### معالجة الملفات المفقودة + +إذا كان المسار خاطئًا أو الملف غير قابل للقراءة، سيُطلق `set_license` استثناءً. غلف الاستدعاء داخل كتلة `try/except` لتقديم رسالة خطأ ودية: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +هذا المقتطف **configures license path** بأمان ويخبرك بالضبط ما الخطأ—دون أي تتبعات غامضة. + +## الخطوة 5: التحقق من أن الترخيص فعال + +فحص سريع يوفّر ساعات من التصحيح لاحقًا. بعد أن تستدعي `set_license`، جرّب عملية OCR بسيطة. إذا كان الترخيص صالحًا، سيعالج SDK الصورة دون إلقاء خطأ ترخيص. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +إذا رأيت النص المُعرّف يُطبع، مبروك—لقد نجحت في **create license instance** و**configure license path**. إذا حصلت على استثناء ترخيص، تحقق مرة أخرى من المسار وأذونات الملف. + +## الحالات الخاصة وأفضل الممارسات + +| الحالة | ما يجب فعله | +|-----------|------------| +| **ملف الترخيص موجود على مشاركة شبكة** | اربط المشاركة بحرف محرك أقراص أو استخدم مسار UNC (`\\server\share\license.lic`). تأكد أن عملية بايثون لديها صلاحية القراءة. | +| **التشغيل داخل حاوية Docker** | انسخ ملف `.lic` إلى الصورة وأشر إليه بمسار مطلق مثل `/app/license/Aspose.OCR.Java.lic`. | +| **وجود عدة مفسرات بايثون** (مثل بيئات conda) | ثبّت ملف الترخيص مرة واحدة لكل بيئة أو احتفظ به في موقع مركزي ووجه كل مفسر إليه. | +| **ملف الترخيص مفقود وقت التشغيل** | انتقل إلى وضع تجريبي (إن كان مدعومًا) أو أوقف التنفيذ برسالة سجل واضحة. | + +### الأخطاء الشائعة + +- **استخدام الشرطات المائلة الأمامية على Windows** – بايثون يقبلها، لكن بعض إصدارات SDK القديمة قد تفسّرها خطأ. استخدم السلاسل الخام أو الشرطات المائلة المزدوجة. +- **نسيان استيراد `License`** – سيتعطل السكريبت مع `NameError`. استورد دائمًا قبل إنشاء الكائن. +- **استدعاء `set_license` بعد طرق OCR** – SDK يتحقق من الترخيص عند أول استخدام، لذا اضبط المسار **أولًا**. + +## مثال كامل يعمل + +فيما يلي سكريبت كامل يربط كل شيء معًا. احفظه باسم `ocr_setup.py` وشغّله من سطر الأوامر. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**الناتج المتوقع** (مع صورة صالحة): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +إذا تعذر العثور على ملف الترخيص، ستظهر لك رسالة خطأ واضحة بدلًا من استثناء “License not found” الغامض. + +--- + +## الخلاصة + +أنت الآن تعرف بالضبط كيف **create license instance** في بايثون و**configure license path** لـ Aspose OCR SDK. الخطوات بسيطة: ثبّت الحزمة، استورد `License`, أنشئ الكائن، وجهه إلى ملف `.lic` الخاص بك، وتحقق باستخدام اختبار OCR صغير. + +مع هذه المعرفة يمكنك دمج قدرات OCR في خدمات الويب، التطبيقات المكتبية، أو خطوط الأنابيب الآلية دون الوقوع في أخطاء الترخيص. بعد ذلك، فكر في استكشاف إعدادات OCR المتقدمة—حزم اللغات، معالجة الصور مسبقًا، أو المعالجة الدفعية—كل منها يبني على الأساس الصلب الذي أنشأته الآن. + +هل لديك أسئلة حول النشر، Docker، أو التعامل مع تراخيص متعددة؟ اترك تعليقًا، ونتمنى لك برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..6fc1d2118 --- /dev/null +++ b/ocr/arabic/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: إنشاء ملف PDF قابل للبحث من الصور الممسوحة ضوئياً باستخدام Python OCR. + تعلم كيفية تحويل PDF من صورة ممسوحة ضوئياً، وتحويل TIFF إلى PDF، وإضافة طبقة نص + OCR في دقائق. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: ar +og_description: إنشاء ملف PDF قابل للبحث على الفور. يوضح هذا الدليل كيفية تشغيل OCR، + تحويل ملف PDF الممسوح ضوئياً، وإضافة طبقة نص OCR باستخدام سكريبت بايثون واحد. +og_title: إنشاء ملف PDF قابل للبحث باستخدام بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: إنشاء ملف PDF قابل للبحث باستخدام بايثون – دليل خطوة بخطوة +url: /ar/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء PDF قابل للبحث باستخدام بايثون – دليل خطوة بخطوة + +هل تساءلت يومًا كيف تُنشئ **PDF قابل للبحث** من صفحة ممسوحة ضوئيًا دون الحاجة إلى التعامل مع عشرات الأدوات؟ لست وحدك. في العديد من سير عمل المكاتب، يتم وضع ملف TIFF أو JPEG ممسوح على محرك مشاركة، ويتعين على الشخص التالي نسخ‑لصق النص يدويًا—مما يسبب الألم، الأخطاء، وإضاعة الوقت. + +في هذا الدرس سنستعرض حلًا برمجيًا نظيفًا يتيح لك **تحويل PDF صورة ممسوحة**، **تحويل TIFF إلى PDF**، و**إضافة طبقة نص OCR** في خطوة واحدة. بنهاية الدرس ستحصل على سكربت جاهز للاستخدام يقوم بتشغيل OCR، يدمج النص المخفي، ويُنتج PDF قابل للبحث يمكنك فهرسته، البحث فيه، أو مشاركته بثقة. + +## ما ستحتاجه + +- Python 3.9+ (أي نسخة حديثة تعمل) +- حزم `aspose-ocr` و `aspose-pdf` (تثبيتها عبر `pip install aspose-ocr aspose-pdf`) +- ملف صورة ممسوحة (`.tif`, `.png`, `.jpg`, أو حتى صفحة PDF تحتوي على صورة فقط) +- كمية معتدلة من الذاكرة RAM (محرك OCR خفيف؛ حتى اللاب توب يتعامل معه) + +> **نصيحة احترافية:** إذا كنت تستخدم Windows، أسهل طريقة للحصول على الحزم هي تشغيل الأمر في نافذة PowerShell مرتفعة الصلاحيات. + +```bash +pip install aspose-ocr aspose-pdf +``` + +الآن بعد أن انتهينا من المتطلبات المسبقة، دعنا نغوص في الكود. + +## الخطوة 1: إنشاء مثيل محرك OCR – *create searchable pdf* + +أول شيء نفعله هو تشغيل محرك OCR. فكر فيه كالعقل الذي سيقرأ كل بكسل ويحوّله إلى أحرف. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **لماذا هذا مهم:** تهيئة المحرك مرة واحدة فقط يحافظ على انخفاض استهلاك الذاكرة. إذا قمت باستدعاء `OcrEngine()` داخل حلقة لكل صفحة، ستنفد الموارد سريعًا. + +## الخطوة 2: تحميل الصورة الممسوحة – *convert tiff to pdf* & *convert scanned image pdf* + +بعد ذلك، وجه المحرك إلى الملف الذي تريد معالجته. الـ API يقبل أي صورة نقطية، لذا فإن TIFF يعمل بنفس كفاءة JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +إذا كان لديك ملف PDF يحتوي فقط على صورة ممسوحة، يمكنك ما زال استخدام `load_image` لأن Aspose سيستخرج الصفحة الأولى تلقائيًا. + +## الخطوة 3: إعداد خيارات حفظ PDF – *add OCR text layer* + +هنا نقوم بتكوين شكل الـ PDF النهائي. العلامة الحاسمة هي `create_searchable_pdf`؛ ضبطها على `True` يخبر المكتبة بدمج طبقة نص غير مرئية تعكس المحتوى البصري. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **ما تفعله طبقة النص:** عندما تفتح الملف الناتج في Adobe Reader وتحاول تحديد النص، ستظهر الأحرف المخفية. محركات البحث يمكنها أيضًا فهرستها—مثالي للامتثال أو الأرشفة. + +## الخطوة 4: تشغيل OCR والحفظ – *how to run OCR* في استدعاء واحد + +الآن يحدث السحر. استدعاء طريقة واحدة يشغّل محرك التعرف ويكتب PDF القابل للبحث على القرص. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +طريقة `recognize` تُعيد كائن حالة يمكنك فحصه للبحث عن أخطاء، لكن في معظم السيناريوهات البسيطة يكون الاستدعاء أعلاه كافيًا. + +### النتيجة المتوقعة + +تشغيل السكربت يطبع: + +``` +PDF saved as searchable PDF. +``` + +إذا فتحت `scanned_page_searchable.pdf` ستلاحظ أنك تستطيع تحديد النص، نسخه‑لصقه، وحتى إجراء بحث `Ctrl+F`. هذا هو ما يميز سير عمل **create searchable pdf**. + +## السكربت الكامل القابل للتشغيل + +فيما يلي السكربت الكامل الجاهز للتنفيذ. فقط استبدل مسارات العناصر النائبة بمواقع ملفاتك الفعلية. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +احفظه باسم `create_searchable_pdf.py` ثم نفّذه: + +```bash +python create_searchable_pdf.py +``` + +## أسئلة شائعة وحالات خاصة + +### 1️⃣ هل يمكنني معالجة ملفات PDF متعددة الصفحات؟ + +نعم. استخدم `ocr_engine.load_image("file.pdf")` ثم كرّر عبر كل صفحة باستخدام `ocr_engine.recognize(pdf_save_options, page_number)`. المكتبة ستولد PDF قابل للبحث متعدد الصفحات تلقائيًا. + +### 2️⃣ ماذا لو كان ملف المصدر TIFF عالي الدقة (300 dpi+)؟ + +كلما ارتفعت DPI زادت دقة OCR لكن استهلاك الذاكرة يصبح أكبر. إذا واجهت `MemoryError`، قلل حجم الصورة أولًا: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ كيف أغيّر لغة OCR؟ + +عيّن خاصية `language` على المحرك قبل تحميل الصورة: + +```python +ocr_engine.language = "fra" # French +``` + +قائمة كاملة بأكواد اللغات المدعومة موجودة في وثائق Aspose. + +### 4️⃣ ماذا لو أردت الحفاظ على جودة الصورة الأصلية؟ + +فئة `PdfSaveOptions` تحتوي على خاصية `compression`. اضبطها على `PdfCompression.None` للحفاظ على بيانات الصورة النقطية كما هي تمامًا. + +```python +pdf_save_options.compression = "None" +``` + +## نصائح للنشر في بيئات الإنتاج + +- **معالجة دفعات:** غلف المنطق الأساسي في دالة تستقبل قائمة مسارات ملفات. سجّل كل نجاح/فشل في ملف CSV لتتبع التدقيق. +- **التوازي:** استخدم `concurrent.futures.ThreadPoolExecutor` لتشغيل OCR على عدة نوى. فقط تذكّر أن كل خيط يحتاج إلى مثيل `OcrEngine` خاص به. +- **الأمان:** إذا كنت تتعامل مع مستندات حساسة، شغّل السكربت في بيئة معزولة واحذف الملفات المؤقتة فور الانتهاء من المعالجة. + +## الخلاصة + +أنت الآن تعرف كيف **تنشئ ملفات PDF قابلة للبحث** من صور ممسوحة باستخدام سكربت بايثون مختصر. من خلال تهيئة محرك OCR، تحميل TIFF (أو أي صورة نقطية)، تكوين `PdfSaveOptions` لإ **add OCR text layer**، وأخيرًا استدعاء `recognize`، يصبح خط أنابيب **convert scanned image pdf** و **convert TIFF to PDF** أمرًا واحدًا قابلًا للتكرار. + +ما الخطوات التالية؟ جرّب ربط هذا السكربت بمراقب ملفات بحيث أي مسح جديد يُسقط في مجلد يتحول تلقائيًا إلى PDF قابل للبحث. أو جرب لغات OCR مختلفة لدعم أرشيفات متعددة اللغات. السماء هي الحد عندما تجمع بين OCR وإنشاء PDF. + +هل لديك أسئلة إضافية حول **how to run OCR** بلغات أو أطر أخرى؟ اترك تعليقًا أدناه، ونتمنى لك برمجة سعيدة! + +![مخطط يوضح التدفق من الصورة الممسوحة → محرك OCR → PDF قابل للبحث (create searchable pdf)](searchable-pdf-flow.png "مخطط تدفق إنشاء PDF قابل للبحث") + +## ماذا يجب أن تتعلم بعد ذلك؟ + +- [كيفية التعرف الضوئي على النص في PDF باستخدام .NET مع Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [تحويل الصور إلى PDF C# – حفظ نتيجة OCR متعددة الصفحات](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [كيفية التعرف الضوئي على نص الصورة مع اللغة باستخدام Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/arabic/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..99cd09f02 --- /dev/null +++ b/ocr/arabic/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: حسّن دقة التعرف الضوئي على الأحرف (OCR) باستخدام بايثون عبر معالجة الصور + مسبقًا للتعرف الضوئي على الأحرف. تعلّم كيفية استخراج النص من ملفات الصور، والتعرف + على النص من ملفات PNG، وتعزيز النتائج. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: ar +og_description: حسّن دقة التعرف الضوئي على الأحرف في بايثون من خلال تطبيق معالجة مسبقة + للصور للنص. اتبع هذا الدليل لاستخراج النص من ملفات الصور والتعرف على النص من ملفات + PNG بسهولة. +og_title: تحسين دقة التعرف الضوئي على الأحرف في بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: تحسين دقة التعرف الضوئي على الأحرف في بايثون – دليل كامل خطوة بخطوة +url: /ar/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحسين دقة OCR في بايثون – دليل خطوة بخطوة كامل + +هل حاولت يومًا **تحسين دقة OCR** ولكنك حصلت على مخرجات مشوشة؟ لست وحدك. يواجه معظم المطورين صعوبة عندما تكون الصورة الأصلية مليئة بالضوضاء، مائلة، أو ذات تباين منخفض ببساطة. الخبر السار؟ مجموعة من حيل ما قبل المعالجة يمكنها تحويل لقطة شاشة غير واضحة إلى نص نظيف يمكن للآلة قراءته. + +في هذا البرنامج التعليمي سنستعرض مثالًا واقعيًا **يعالج صورة لـ OCR**، يشغل محرك التعرف، وأخيرًا **يستخرج النص من الصورة** — تحديدًا PNG. بنهاية الدليل ستعرف بالضبط كيف **تتعرف على النص من PNG** بمعدل نجاح أعلى، وستحصل على مقتطف كود قابل لإعادة الاستخدام يمكنك إدراجه في أي مشروع. + +## ما ستتعلمه + +- لماذا تعد معالجة الصورة مهمة لمحركات OCR +- أي أوضاع ما قبل المعالجة (إزالة الضوضاء، تصحيح الميل) تعطي أكبر تحسين +- كيفية تكوين كائن `OcrEngine` في بايثون +- السكريبت الكامل القابل للتنفيذ الذي **يستخرج النص من الصورة** +- نصائح للتعامل مع الحالات الخاصة مثل المسحات المدوّرة أو الصور منخفضة الدقة + +لا تحتاج إلى مكتبات خارجية غير SDK الخاص بـ OCR، لكنك ستحتاج إلى Python 3.8+ وصورة PNG تريد قراءتها. + +--- + +![مخطط يوضح خطوات تحسين دقة OCR في بايثون](image.png "مخطط تحسين تدفق عمل دقة OCR") + +*Alt text: مخطط يوضح خطوات تحسين دقة OCR ومعالجة ما قبل المعالجة وخطوات التعرف.* + +## المتطلبات المسبقة + +- Python 3.8 أو أحدث مثبت +- الوصول إلى SDK الخاص بـ OCR الذي يوفر `OcrEngine`، `OcrEngineSettings`، و `ImagePreprocessMode` (الكود أدناه يستخدم API عام؛ استبدله بفئات البائع إذا لزم الأمر) +- صورة PNG (`input.png`) موجودة في مجلد يمكنك الإشارة إليه + +إذا كنت تستخدم بيئة افتراضية، فعّلها الآن—ليس هناك شيء معقد، فقط `python -m venv venv && source venv/bin/activate`. + +--- + +## الخطوة 1: إنشاء كائن محرك OCR – ابدأ تحسين دقة OCR + +الأول الذي تحتاجه هو كائن محرك OCR. فكر فيه كالعقل الذي سيقرأ البكسلات لاحقًا ويُخرج الأحرف. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +لماذا هذا مهم: بدون محرك لا يمكنك تطبيق أي معالجة مسبقة، وستُرسل الصورة الخام مباشرة إلى المُعرّف—عادةً ما يكون ذلك أسوأ سيناريو للدقة. + +--- + +## الخطوة 2: تحميل ملف PNG المستهدف – تهيئة البيئة لتعرف النص من PNG + +الآن نخبر المحرك أي ملف سيعمل عليه. PNG غير مضغوط، وهذا يمنحنا ميزة صغيرة على JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +إذا كانت الصورة موجودة في مكان آخر، فقط عدّل المسار. المحرك يقبل أي صيغة مدعومة، لكن PNG غالبًا ما يحافظ على التفاصيل الدقيقة اللازمة لحواف الأحرف الواضحة. + +--- + +## الخطوة 3: تكوين ما قبل المعالجة – معالجة الصورة لـ OCR + +هنا يحدث السحر. نُنشئ كائن إعدادات، نفعّل إزالة الضوضاء لمسح البقع، ونُشغّل تصحيح الميل بحيث يُستقيم النص المائل تلقائيًا. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### لماذا إزالة الضوضاء + تصحيح الميل؟ + +- **إزالة الضوضاء**: الضوضاء العشوائية في البكسلات تُربك خوارزميات مطابقة الأنماط. إزالتها تُحسّن حدة الحروف. +- **تصحيح الميل**: حتى ميل قدره درجتين يمكن أن يُخفض درجات الثقة بشكل كبير. تصحيح الميل يُعيد محاذاة الخط الأساسي، مما يسمح للمُعرّف بمطابقة الخطوط بشكل أكثر موثوقية. + +يمكنك تجربة علامات إضافية (مثل `ImagePreprocessMode.CONTRAST_ENHANCE`) إذا كانت صورك داكنة جدًا. عادةً ما تُدرج وثائق SDK جميع الأوضاع المتاحة. + +--- + +## الخطوة 4: تطبيق الإعدادات على المحرك – ربط ما قبل المعالجة بـ OCR + +نُعيّن كائن الإعدادات إلى المحرك حتى يستخدم التحويلات التي عرّفناها في عملية التعرف التالية. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +إذا تخطيت هذه الخطوة، سيعود المحرك إلى الإعدادات الافتراضية (غالبًا “بدون معالجة مسبقة”)، وستلاحظ **انخفاض دقة OCR**. + +--- + +## الخطوة 5: تشغيل عملية التعرف – استخراج النص من الصورة + +مع كل شيء موصول، نطلب من المحرك الآن أداء مهمته. الاستدعاء متزامن، ويُعيد كائن نتيجة يحتوي على السلسلة المعترف بها. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +خلف الكواليس، يقوم المحرك الآن بـ: + +1. تحميل PNG إلى الذاكرة +2. تطبيق إزالة الضوضاء وتصحيح الميل بناءً على إعداداتنا +3. تشغيل الشبكة العصبية أو مطابقة الأنماط الكلاسيكية +4. تجميع الناتج في `recognition_result` + +--- + +## الخطوة 6: إخراج النص المعترف به – تحقق من التحسين + +لنطبع السلسلة المستخرجة. في تطبيق حقيقي قد تكتبها إلى ملف، قاعدة بيانات، أو تمرّرها إلى خدمة أخرى. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### النتيجة المتوقعة + +إذا كانت الصورة تحتوي على الجملة “Hello, OCR World!” يجب أن ترى: + +``` +Hello, OCR World! +``` + +لاحظ أن النص نظيف—بدون رموز عشوائية أو أحرف مكسورة. هذا هو نتيجة **معالجة الصورة المناسبة للنص**. + +--- + +## نصائح احترافية وحالات خاصة + +| الحالة | ما الذي يجب تعديله | السبب | +|-----------|----------------|-----| +| PNG منخفض الدقة جدًا (≤ 72 dpi) | أضف `ImagePreprocessMode.SUPER_RESOLUTION` إذا كان متاحًا | التكبير يمكن أن يمنح المُعرّف المزيد من البكسلات للعمل معها | +| النص مدوّر > 5° | زد من تحمل تصحيح الميل أو قم بتدوير يدوي باستخدام `Pillow` قبل تمريره للمحرك | الزوايا الشديدة أحيانًا تتجاوز تصحيح الميل التلقائي | +| نمط خلفية كثيف | فعّل `ImagePreprocessMode.BACKGROUND_REMOVAL` | يزيل الفوضى غير النصية التي قد تُقرأ خطأ | +| مستند متعدد اللغات | عيّن `ocr_engine.language = "eng+spa"` (أو ما شابه) | يختار المحرك مجموعة الأحرف الصحيحة، مما يحسّن الدقة العامة | + +تذكر، **تحسين دقة OCR** ليس حلًا واحدًا يناسب الجميع؛ قد تحتاج إلى تعديل علامات ما قبل المعالجة وفقًا لمجموعتك الخاصة من البيانات. + +--- + +## السكريبت الكامل – جاهز للنسخ واللصق + +فيما يلي المثال الكامل القابل للتنفيذ الذي يدمج كل خطوة ناقشناها. احفظه باسم `improve_ocr_accuracy.py` وشغّله باستخدام `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +شغّله، راقب وحدة التحكم، وسترى نتيجة **استخراج النص من الصورة** فورًا. إذا بدت النتيجة غير صحيحة، عدّل علامات `preprocess_mode` كما هو موضح في جدول “نصائح احترافية”. + +--- + +## الخلاصة + +لقد استعرضنا وصفة عملية **لتحسين دقة OCR** باستخدام بايثون. من خلال إنشاء `OcrEngine`، تحميل PNG، **معالجة الصورة لـ OCR**، وأخيرًا **التعرف على النص من PNG**، يمكنك استخراج النص من ملفات الصورة حتى عندما لا تكون المصدر مثاليًا. + +ما الخطوة التالية؟ جرّب معالجة مجموعة من الصور داخل حلقة، خزن كل نتيجة في CSV، أو جرّب أوضاع معالجة إضافية مثل تحسين التباين. نفس النمط يعمل مع ملفات PDF، الإيصالات الممسوحة، أو الملاحظات المكتوبة بخط اليد—فقط غير الإدخال واضبط الإعدادات. + +هل لديك أسئلة حول نوع صورة معين أو تريد معرفة كيفية دمج هذا في خدمة ويب؟ اترك تعليقًا، وسنستكشف تلك السيناريوهات معًا. برمجة سعيدة، ولتكن نتائج OCR دائمًا واضحة كالكريستال! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +- [استخراج النص من الصورة باستخدام Aspose OCR – دليل خطوة بخطوة](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [استخراج النص من الصورة – تحسين OCR باستخدام Aspose.OCR لـ .NET](/ocr/english/net/ocr-optimization/) +- [كيفية استخراج النص من الصورة عن طريق إعداد المستطيلات في OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/arabic/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..f8c58a268 --- /dev/null +++ b/ocr/arabic/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: تعلم كيفية استخدام منطقة الاهتمام في OCR لتحميل الصورة للـ OCR واستخراج + النص من المستطيل، وهو مثالي للتعرف على المبلغ في الفاتورة. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: ar +og_description: إتقان منطقة الاهتمام في OCR لتحميل الصورة للـ OCR، استخراج النص من + المستطيل والتعرف على النص من الفاتورة في دليل واحد. +og_title: منطقة الاهتمام في OCR – دليل بايثون خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: منطقة الاهتمام في OCR – استخراج النص من مستطيل باستخدام بايثون +url: /ar/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – استخراج النص من مستطيل في بايثون + +هل تساءلت يومًا كيف تقوم بـ **ocr region of interest** لجزء محدد من فاتورة ممسوحة ضوئيًا دون إطعام الصفحة بأكملها إلى المحرك؟ لست أول من يحدق في إيصال غير واضح ويفكر، “كيف أستخرج المبلغ الذي يقع في أسفل اليمين؟” الخبر السار هو أنك تستطيع إخبار مكتبة OCR بالضبط أين تبحث، مما يزيد السرعة والدقة بشكل كبير. + +في هذا الدليل سنستعرض مثالًا كاملاً وقابلًا للتنفيذ يوضح لك كيفية **load image for OCR**، تعريف **region of interest**، ثم **extract text from rectangle** وأخيرًا **recognize text from invoice** للإجابة على سؤال “كيفية استخراج المبلغ”. لا مراجع غامضة—فقط كود ملموس، شروحات واضحة، وبعض النصائح الاحترافية التي كنت تتمنى معرفتها مبكرًا. + +--- + +## ما ستبنيه + +بنهاية هذا البرنامج التعليمي ستحصل على سكريبت بايثون صغير يقوم بـ: + +1. تحميل صورة فاتورة من القرص. +2. وضع مستطيل ROI حيث يوجد المبلغ الإجمالي. +3. تشغيل OCR داخل ذلك الـ ROI فقط. +4. طباعة سلسلة المبلغ المنقحة. + +كل هذا يعمل مع أي مكتبة OCR تدعم الـ ROI—سنستخدم هنا حزمة خيالية تمثيلية `SimpleOCR` تشبه الأدوات الشهيرة مثل Tesseract أو EasyOCR. يمكنك استبدالها بسهولة؛ المفاهيم تبقى نفسها. + +--- + +## المتطلبات المسبقة + +- تثبيت Python 3.8+ (`python --version` يجب أن يظهر ≥3.8). +- حزمة OCR قابلة للتثبيت عبر pip (مثال: `pip install simpleocr`). +- صورة فاتورة (PNG أو JPEG) موجودة في مجلد يمكنك الإشارة إليه. +- إلمام أساسي بدوال وفئات بايثون (لا شيء معقد). + +إذا كان لديك كل ذلك، رائع—لنبدأ. إذا لم يكن، احصل على الصورة أولًا؛ باقي الخطوات مستقلة عن محتوى الملف الفعلي. + +--- + +## الخطوة 1: Load Image for OCR + +أول شيء يحتاجه أي سير عمل OCR هو صورة نقطية للقراءة منها. معظم المكتبات توفر طريقة بسيطة `load_image` تقبل مسار الملف. إليك الطريقة مع محرك `SimpleOCR` الخاص بنا: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **نصيحة احترافية:** استخدم مسارات مطلقة أو `os.path.join` لتجنب مفاجآت “الملف غير موجود” عند تشغيل السكريبت من دليل عمل مختلف. + +--- + +## الخطوة 2: Define OCR Region of Interest + +بدلاً من السماح للمحرك بمسح الصفحة بأكملها، نخبره *بالضبط* أين يقع المبلغ. هذه هي خطوة **ocr region of interest**، وهي المفتاح لاستخراج موثوق، خاصة عندما يحتوي المستند على رؤوس أو تذييلات صاخبة. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +لماذا هذه الأرقام؟ `x` و `y` هما إزاحة بالبكسل من الزاوية العلوية اليسرى، بينما `width` و `height` يحددان حجم الصندوق. إذا لم تكن متأكدًا، افتح الصورة في أي محرر، فعّل المسطرة، وسجل الإحداثيات. العديد من بيئات التطوير تسمح لك بطباعة موضع المؤشر أثناء التحويم. + +--- + +## الخطوة 3: Extract Text from Rectangle + +الآن بعد ضبط الـ ROI، نطلب من المحرك **recognize text from invoice** لكن مقيدًا بالمستطيل الذي أضفناه. تُعيد الدالة كائن نتيجة يحتوي عادةً على السلسلة الخام، درجات الثقة، وأحيانًا إطارات الحدود. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +خلف الكواليس، `recognize()` يمر على كل ROI، يقتطع تلك القطعة، يشغل نموذج OCR، ويجمع النتائج معًا. لهذا السبب تعريف منطقة **extract text from rectangle** ضيقة يمكن أن يوفر ثوانٍ من وقت المعالجة للوظائف الدفعية. + +--- + +## الخطوة 4: How to Extract Amount – Clean the Output + +OCR ليس مثاليًا؛ ستحصل غالبًا على مسافات زائدة، أسطر جديدة، أو حتى أحرف مخطئة (مثل “S” بدلًا من “5”). `strip()` سريع وبعض التعبيرات النمطية الصغيرة عادةً ما تحل المشكلة للقيم المالية. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **لماذا هذا مهم:** إذا كنت تخطط لإدخال المبلغ في قاعدة بيانات أو بوابة دفع، تحتاج إلى تنسيق متوقع. إزالة الفراغات وتصفية الأحرف غير الرقمية يمنع الأخطاء في المراحل اللاحقة. + +--- + +## الخطوة 5: Recognize Text from Invoice – Full Script + +بدمج كل ما سبق، إليك السكريبت الكامل الجاهز للتنفيذ. احفظه باسم `extract_amount.py` وشغّله باستخدام `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### النتيجة المتوقعة + +``` +Amount: 1,245.67 +``` + +إذا كان الـ ROI غير محاذٍ بشكل صحيح، قد ترى شيئًا مثل `Amount: 1245.6S`—لاحظ الـ “S” الزائدة. عدّل إحداثيات المستطيل وأعد التشغيل حتى تصبح النتيجة نظيفة. + +--- + +## المشكلات الشائعة وحالات الحافة + +| المشكلة | السبب | الحل | +|--------|-------|------| +| **ROI صغير جدًا** | يتم قطع نص المبلغ، مما يؤدي إلى تعرّف جزئي. | زِد `width`/`height` بنحو 10‑20 % وأعد الاختبار. | +| **دقة DPI غير صحيحة** | المسحات منخفضة الدقة (≤150 dpi) تقلل من دقة OCR. | أعد تحجيم الصورة إلى 300 dpi قبل التحميل، أو اطلب من الماسح دقة أعلى. | +| **عملات متعددة** | التعبير النمطي يلتقط أول مجموعة رقمية، قد تكون رقم الفاتورة. | حسّن التعبير النمطي للبحث عن رموز العملة (`$`, `€`, `£`) قبل الأرقام. | +| **فواتير مائلة** | محركات OCR تفترض نصًا عموديًا؛ الصفحات المائلة تعطل التعرف. | طبّق تصحيح دوران (`ocr_engine.rotate(90)`) قبل إضافة ROI. | +| **ضوضاء في الخلفية** | الظلال أو الختم يربك النموذج. | عالج مسبقًا باستخدام عتبة بسيطة (`cv2.threshold`) أو مرشح إزالة الضوضاء. | + +معالجة هذه الحالات مبكرًا توفر لك ساعات من التصحيح لاحقًا. + +--- + +## نصائح احترافية للمشاريع الواقعية + +- **معالجة دفعات:** حلق عبر مجلد الفواتير، احسب ROI ديناميكيًا (مثلاً بناءً على اكتشاف القالب)، وخزن النتائج في CSV. +- **مطابقة القوالب:** إذا كنت تتعامل مع عدة تخطيطات فواتير، احتفظ بخريطة JSON من `template_id → إحداثيات ROI`. غيّر ROI بناءً على مصنف تخطيط سريع. +- **التنفيذ المتوازي:** استخدم `concurrent.futures.ThreadPoolExecutor` لتشغيل عدة مثيلات OCR متزامنًا—مفيد لخطوط الأنابيب الخلفية ذات الحجم الكبير. +- **تصفية الثقة:** معظم نتائج OCR تشمل درجة ثقة. تجاهل النتائج التي تقل عن عتبة (مثال: 85 %) وضع علامة عليها للمراجعة اليدوية. + +--- + +## الخلاصة + +غطّينا كل ما تحتاجه للقيام بـ **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, وأخيرًا **recognize text from invoice** للإجابة على سؤال **how to extract amount** الشائع. السكريبت صغير، لكنه مرن بما يكفي للتكيف مع صيغ مستندات مختلفة، لغات متعددة، ومزودي OCR مختلفين. + +الآن بعد أن أتقنت الأساسيات، فكر في توسيع سير العمل: أضف مسح الباركود، دمج مع محلل PDF، أو إرسال المبلغ المستخرج إلى واجهة برمجة تطبيقات محاسبة. السماء هي الحد، ومع ROI معرف جيدًا ستحصل دائمًا على نتائج أسرع وأنظف. + +إذا واجهت أي صعوبة، اترك تعليقًا أدناه—نتمنى لك OCR موفق! + +![مثال على منطقة الاهتمام في OCR](https://example.com/ocr_roi_example.png "مثال على منطقة الاهتمام في OCR") + + +## ماذا يجب أن تتعلم بعد ذلك؟ + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/chinese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..efd1a6617 --- /dev/null +++ b/ocr/chinese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-31 +description: 异步 OCR 教程,展示如何在 Python 中使用 Aspose OCR 与 asyncio 实现快速图像文字提取。学习一步一步的异步 + OCR 实现。 +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: zh +og_description: 异步 OCR 教程将指导您在 Python 中使用 asyncio 与 Aspose OCR,实现高效的图像文字提取。 +og_title: 异步 OCR 教程 – 使用 Aspose OCR 的 Python asyncio +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: 异步 OCR 教程 – Python asyncio 与 Aspose OCR +url: /zh/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 异步 OCR 教程 – Python asyncio 与 Aspose OCR + +是否曾想过如何在不阻塞应用的情况下运行光学字符识别?在本 **async OCR tutorial** 中,你将看到正是如此——使用 Python 的 `asyncio` 和 Aspose OCR 库进行非阻塞的文本提取。 + +如果你一直在等待处理大型图像而卡住了,本指南为你提供了一个简洁的异步解决方案,让你的事件循环保持活跃。 + +在接下来的章节中,我们将覆盖所有必需内容:安装库、构建异步助手、处理结果,甚至还有一个快速的多图像扩展技巧。完成后,你就可以将 **async OCR tutorial** 嵌入任何已经使用 `asyncio` 的 Python 项目中。 + +## 你需要的准备 + +* Python 3.9+(我们使用的 `asyncio` API 从 3.7 起已稳定) +* 有效的 Aspose OCR 许可证或免费试用版(该库纯 Python,无本地二进制) +* 一个你想读取的小图像文件(`.jpg`、`.png` 等)——请放在已知文件夹中 + +不需要其他外部工具;所有操作均在纯 Python 中运行。 + +## 步骤 1:安装 Aspose OCR 包 + +首先,从 PyPI 获取 Aspose OCR 包。打开终端并运行: + +```bash +pip install aspose-ocr +``` + +> **专业提示:** 如果你在虚拟环境中工作(强烈推荐),请先激活它。这可以保持依赖隔离,避免版本冲突。 + +## 步骤 2:异步初始化 OCR 引擎 + +我们 **async OCR tutorial** 的核心是一个异步助手函数。它创建 `OcrEngine` 实例,加载图像,然后调用 `recognize_async()`。引擎本身是同步的,但包装方法返回一个可 await 的对象,使事件循环保持响应。 + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**我们这样做的原因:** +*在助手函数内部创建引擎可确保线程安全,以防以后并行运行多个 OCR 任务。`await` 关键字在繁重工作在库内部线程池中进行时,将控制权交还给事件循环。* + +## 步骤 3:从异步主函数驱动助手 + +现在我们需要一个小型的 `main()` 协程来调用 `async_ocr()` 并打印结果。这与 `asyncio` 脚本的典型入口点相呼应。 + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**内部发生了什么?** +`asyncio.run()` 会创建一个全新的事件循环,调度 `main()`,并在 `main()` 完成后干净地关闭循环。这是 Python 3.7+ 中启动异步程序的推荐模式。 + +## 步骤 4:测试完整脚本 + +将上述两个代码块保存到同一个文件,例如 `async_ocr_demo.py`。在命令行运行它: + +```bash +python async_ocr_demo.py +``` + +如果一切设置正确,你应该会看到类似如下的输出: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +具体输出取决于 `photo.jpg` 的内容。关键是脚本能够快速结束,即使图像很大,因为 OCR 工作在后台进行。 + +## 步骤 5:扩展——并发处理多个图像 + +一个常见的后续问题是,*“我能否在不为每个文件启动新进程的情况下批量 OCR 吗?”* 当然可以。因为我们的助手是完全异步的,我们可以使用 `asyncio.gather()` 收集多个协程: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**为什么可行:** `asyncio.gather()` 会一次性调度所有 OCR 任务。底层的 Aspose OCR 库仍然使用自己的线程池,但从 Python 的角度看,一切保持非阻塞,使你能够在单次同步调用所需时间内处理数十张图像。 + +## 步骤 6:优雅地处理错误 + +在处理外部文件时,你不可避免会遇到文件缺失、图像损坏或许可证问题。将 OCR 调用包装在 `try/except` 块中,以保持事件循环存活: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +现在 `batch_ocr()` 可以改为调用 `safe_async_ocr`,确保单个错误文件不会导致整个批次中止。 + +## 可视化概览 + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial flowchart showing async_ocr helper, event loop, and Aspose OCR engine"} + +上图可视化了流程:事件循环 → `async_ocr` → `OcrEngine` → 后台线程 → 结果返回循环。 + +## 常见陷阱及规避方法 + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **助手内部的阻塞 I/O** | 意外地使用未加 `await` 的 `open()` 会阻塞循环。 | 使用 `aiofiles` 读取文件,或让 `engine.load_image` 处理(它已经是非阻塞的)。 | +| **在多个协程中复用单个 `OcrEngine`** | 该引擎不是线程安全的;并发调用可能导致状态损坏。 | 在每次 `async_ocr` 调用中实例化全新的引擎(如示例所示)。 | +| **缺少许可证** | Aspose OCR 在运行时抛出与许可证相关的异常。 | 提前注册许可证 (`OcrEngine.set_license("license.json")`). | +| **大图像导致内存激增** | 库会将整张图像加载到内存中。 | 如果内存是问题,先对图像进行降采样后再 OCR。 | + +## 回顾:我们实现了什么 + +在本 **async OCR tutorial** 中,我们: + +1. 安装了 Aspose OCR 库。 +2. 构建了一个 `async_ocr` 助手,实现非阻塞识别。 +3. 从干净的 `asyncio` 入口点运行该助手。 +4. 演示了使用 `asyncio.gather` 的批处理。 +5. 添加了错误处理和最佳实践提示。 + +所有这些都是纯 Python 实现,你可以将其直接嵌入 Web 服务器、CLI 工具或数据管道,而无需重写已有的异步代码。 + +## 下一步及相关主题 + +* **异步图像预处理** – 使用 `aiohttp` 并发下载图像后再进行 OCR。 +* **存储 OCR 结果** – 将本教程与异步数据库驱动如 `asyncpg`(PostgreSQL)结合。 +* **性能调优** – 如库提供此选项,可尝试 `engine.recognize_async(max_threads=4)`。 +* **替代 OCR 引擎** – 将 Aspose OCR 与 Tesseract 的异步包装进行成本效益比较。 + +随意尝试:尝试输入 PDF、调整语言设置,或将结果接入聊天机器人。一旦拥有坚实的 **async OCR tutorial** 基础,想象力就是唯一限制。 + +祝编码愉快,愿你的文本提取始终快速! + +## 接下来你应该学习什么? + +- [使用 Aspose OCR 从图像提取文本 – 步骤指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR 教程 – 光学字符识别](/ocr/english/) +- [使用 Aspose.OCR 按语言 OCR 图像文本](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/chinese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..c4c63c32e --- /dev/null +++ b/ocr/chinese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: 在 OCR 中轻松实现自动语言检测。了解如何加载图像 OCR、启用自动语言检测,并仅需几步即可识别文本图像。 +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: zh +og_description: OCR 中的自动语言检测变得轻松。请按照本分步教程启用自动语言检测、加载图像 OCR 并识别文本图像。 +og_title: 使用 OCR 的自动语言检测——完整 Python 指南 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: 使用 OCR 的自动语言检测——完整 Python 指南 +url: /zh/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 自动语言检测与 OCR – 完整 Python 指南 + +有没有想过让 OCR 引擎在不告诉它要找什么的情况下自行“猜测”扫描文档的语言?这正是 **自动语言检测** 的作用,在处理多语言 PDF、街道标志照片或任何混合文字的图像时,它简直是个游戏规则改变者。 + +在本教程中,我们将通过一个实战示例,展示如何 **启用自动语言检测**、**加载图像 OCR**,以及 **识别文本图像**,使用类似 Python 的 API。完成后,你将拥有一个独立脚本,能够打印出检测到的语言代码和提取的文本——无需手动设置语言。 + +## 你将学到 + +- 如何创建 OCR 引擎实例并打开 **自动语言检测**。 +- 从磁盘 **加载图像 OCR** 的完整步骤。 +- 如何调用引擎的 `recognize()` 方法并获取包含语言代码的结果。 +- 处理低分辨率图像或不受支持脚本等边缘情况的技巧。 + +不需要任何多语言 OCR 的先验经验,只要有基本的 Python 环境和一张图像文件即可。 + +--- + +## 前置条件 + +在开始之前,请确保你已经具备: + +1. 已安装 Python 3.8+(任意近期版本均可)。 +2. 提供 `OcrEngine`、`LanguageAutoDetectMode` 等类的 OCR 库——本指南假设使用名为 `myocr` 的虚构包。使用以下命令安装: + + ```bash + pip install myocr + ``` + +3. 一张包含至少两种语言文字的图像文件(`multilingual_sample.png`)。 +4. 一点好奇心——即使你从未接触过 OCR,也无需担心,代码刻意写得非常直观。 + +--- + +## 步骤 1:启用自动语言检测 + +首先需要告诉引擎它应该自行**判断**语言。这时 **自动语言检测** 标志就派上用场了。 + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **为什么重要:** +> 当 `AUTO_DETECT` 被设置后,引擎会在进行重量级字符识别之前,对图像运行一个轻量级语言分类器。这意味着你不必猜测文本是英文、俄文、法文或它们的任意组合。引擎会自动为图像的每个区域挑选最合适的语言模型。 + +--- + +## 步骤 2:加载图像 OCR + +现在引擎已经知道需要自动检测语言,我们需要给它提供待处理的图像。**加载图像 OCR** 步骤会读取位图并准备内部缓冲区。 + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **小技巧:** +> 如果你的图像分辨率高于 300 dpi,建议将其下采样至约 150‑200 dpi。过多的细节实际上会 **减慢** 语言检测阶段的速度,却并不会提升准确度。 + +--- + +## 步骤 3:识别图像中的文本 + +图像已在内存中且语言检测已开启,最后一步是让引擎 **识别文本图像**。一次调用即可完成所有繁重工作。 + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` 是一个对象,通常至少包含以下两个属性: + +| 属性 | 描述 | +|-----------|-------------| +| `language` | 检测到的语言的 ISO‑639‑1 代码(例如 `"en"` 表示英文)。 | +| `text` | 图像的纯文本转录内容。 | + +--- + +## 步骤 4:获取检测到的语言和提取的文本 + +现在只需打印出引擎发现的内容,即可演示 **detect language OCR** 功能。 + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**示例输出** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **如果引擎返回 `None`,该怎么办?** +> 通常意味着图像过于模糊或文字太小(< 8 pt)。尝试提高对比度或使用更高分辨率的源图像。 + +--- + +## 完整工作示例(端到端启用自动语言检测) + +将所有步骤整合在一起,下面是一个可直接运行的脚本,涵盖 **启用自动语言检测**、**加载图像 OCR**、**识别文本图像** 与 **检测语言 OCR**。 + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +将其保存为 `automatic_language_detection_ocr.py`,将 `YOUR_DIRECTORY` 替换为存放 PNG 的文件夹路径,然后运行: + +```bash +python automatic_language_detection_ocr.py +``` + +你应该会看到语言代码以及提取的文本,正如上面的示例输出所示。 + +--- + +## 常见边缘情况处理 + +| 情形 | 建议解决方案 | +|-----------|----------------| +| **极低分辨率图像**(低于 100 dpi) | 使用双三次过滤器放大后再加载,或获取更高分辨率的源图像。 | +| **单张图像中混合多种脚本**(如英文 + 西里尔文) | 引擎通常会将页面划分为多个区域;如果出现误检,可设置 `engine.enable_region_split = True`。 | +| **不受支持的语言** | 确认 OCR 库是否已包含该脚本的语言包;可能需要下载额外模型。 | +| **大批量处理** | 只初始化一次引擎,然后在多个 `load_image` / `recognize` 循环中复用,以避免重复加载模型。 | + +--- + +## 可视化概览 + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt text:* 自动语言检测示例输出,显示检测到的语言代码和提取的多语言文本。 + +--- + +## 结论 + +我们已经完整演示了 **自动语言检测** 的全流程——创建引擎、启用自动语言检测、加载图像进行 OCR、识别文本,最后获取检测到的语言。此端到端流程让你在处理多语言文档时,无需每次手动配置语言模型。 + +如果想进一步深入,可以考虑: + +- **批量** 处理数百张图像,使用循环复用同一个 `OcrEngine` 实例。 +- **后处理** 提取的文本,例如使用拼写检查器或针对特定语言的分词器。 +- **集成** 脚本到 Web 服务,接受用户上传并返回包含 `language` 与 `text` 字段的 JSON。 + +欢迎尝试不同的图像格式(`.jpg`、`.tif`),观察检测准确率的变化。如有疑问或遇到顽固的图像无法读取,欢迎在下方留言——祝编码愉快! + +## 接下来你可以学习什么? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..22fd4d53c --- /dev/null +++ b/ocr/chinese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-31 +description: 学习如何使用批量图像转文本脚本在 Python 中将图像转换为文本。使用 Aspose.OCR 在几分钟内识别扫描图像中的文本。 +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: zh +og_description: 使用 Python 即时将图像转换为文本。本指南展示批量图像转文本转换以及如何使用 Aspose.OCR 从扫描图像中识别文本。 +og_title: 将图像转换为文本 Python – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: 将图像转换为文本(Python)——完整逐步指南 +url: /zh/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将图像转换为文本(Python) – 完整分步指南 + +有没有想过如何 **convert images to text python** 而不需要搜索数十个库?你并不是唯一的。无论是数字化旧收据、从扫描的发票中提取数据,还是构建可搜索的 PDF 档案,将图片转换为纯文本文件都是许多开发者的日常工作。 + +在本教程中,我们将演示一个 **bulk image to text conversion** 流程,该流程能够识别扫描图像中的文本,将每个结果保存为单独的 `.txt` 文件,并且只需几行 Python 代码即可完成。无需为晦涩的 API 四处寻找——Aspose.OCR 完成繁重的工作,我们将向您展示如何正确使用它。 + +## 您将学到的内容 + +- 如何安装和配置 Aspose.OCR for Python 包。 +- 使用 `BatchOcrEngine` 进行 **convert images to text python** 的确切代码。 +- 处理常见陷阱(如不受支持的格式或损坏的文件)的技巧。 +- 验证 **recognize text from scanned images** 步骤实际成功的方法。 + +阅读完本指南后,您将拥有一个可直接运行的脚本,能够一次性处理成千上万的图像——非常适合任何批处理场景。 + +## 前提条件 + +- 在机器上已安装 Python 3.8+。 +- 一个包含图像文件(PNG、JPEG、TIFF 等)的文件夹,您希望将其转换为文本。 +- 有效的 Aspose Cloud 账户或免费试用许可证(免费层已足以进行测试)。 + +如果您已具备上述条件,让我们开始吧。 + +--- + +## 第一步 – 设置 Python 环境 + +在编写任何 OCR 代码之前,请确保您在一个干净的虚拟环境中工作。这可以隔离依赖并防止版本冲突。 + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **专业提示:** 保持项目目录整洁——创建一个名为 `ocr_project` 的子文件夹并将脚本放入其中。这会让后续的路径处理变得轻而易举。 + +## 第二步 – 安装 Aspose.OCR for Python + +Aspose.OCR 是商业库,但它提供了一个可从 PyPI 获取的免费 NuGet 风格的 wheel 包。请在已激活的虚拟环境中运行以下命令: + +```bash +pip install aspose-ocr +``` + +如果遇到权限错误,请添加 `--user` 标志或使用 `sudo` 运行该命令(仅限 Linux/macOS)。安装完成后,您应该会看到类似如下的输出: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **为什么选择 Aspose?** 与许多开源 OCR 工具不同,Aspose.OCR 开箱即支持 **bulk image to text conversion**,并且能够在无需额外配置的情况下处理多种图像格式。它还提供了 `BatchOcrEngine` 类,使得 “convert images to text python” 任务只需一行代码即可完成。 + +## 第三步 – 使用批量 OCR 将图像转换为文本(Python) + +现在进入教程的核心。下面是一个可直接运行的脚本,它会: + +1. 导入 OCR 引擎类。 +2. 实例化一个 `BatchOcrEngine`。 +3. 将引擎指向包含图像的输入文件夹。 +4. 指定引擎将每个提取的文本文件写入输出文件夹。 +5. 调用 `recognize()` 方法,逐个 **recognize text from scanned images**。 + +将以下内容保存为项目文件夹中的 `batch_ocr.py`: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### 工作原理 + +- **`BatchOcrEngine`** 包装了普通的 `OcrEngine`,并添加了文件夹级别的编排功能,这正是批量 **convert images to text python** 时所需的。 +- `input_folder` 属性告诉引擎在哪里查找源图像。它会自动扫描目录并排队所有受支持的文件类型。 +- `output_folder` 属性决定每个 `.txt` 文件的存放位置。引擎会保持原始文件名的对应关系,例如 `receipt1.png` 会生成 `receipt1.txt`。 +- 调用 `recognize()` 会触发内部循环,加载每张图像、执行 OCR 并写入结果。该方法会阻塞直至所有文件处理完毕,便于后续操作(例如压缩输出文件夹)。 + +#### 预期输出 + +运行脚本时: + +```bash +python batch_ocr.py +``` + +您应该会看到: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +在 `output_texts` 中,您会找到每张图像对应的纯文本文件。使用文本编辑器打开任意文件,您将看到原始 OCR 结果——通常与原始印刷文本非常接近。 + +## 第四步 – 验证结果并处理错误 + +即使是最好的 OCR 引擎,也可能在低分辨率扫描或严重倾斜的页面上出现错误。以下是一种快速检查输出并记录任何失败的方法。 + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**为什么要添加此代码?** +- 它可以捕获引擎静默生成空字符串的情况(在不可读的图像中很常见)。 +- 它会提供问题文件列表,方便您手动检查或使用不同设置重新运行(例如,增加 `OcrEngine.preprocess` 选项)。 + +### 边缘情况与调整 + +| 情况 | 建议解决方案 | +|-----------|----------------| +| 图像旋转了 90° | 设置 `batch_engine.ocr_engine.rotation_correction = True`。 | +| 混合语言(英语 + 法语) | 在调用 `recognize()` 之前使用 `batch_engine.ocr_engine.language = "eng+fra"`。 | +| 先将大型 PDF 转换为图像 | 将 PDF 拆分为单页图像,然后将文件夹提供给批处理引擎。 | +| 在超大批次上出现内存错误 | 顺序处理较小的子文件夹,或增加 `batch_engine.max_memory_usage`。 | + +## 第五步 – 自动化整个工作流(可选) + +如果您需要每天夜间运行此转换,可将脚本包装在简单的 shell 或 Windows 批处理文件中,并使用 `cron`(Linux/macOS)或任务计划程序(Windows)进行调度。以下是适用于类 Unix 系统的最小化 `run_ocr.sh`: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +使其可执行(`chmod +x run_ocr.sh`),并添加 cron 条目: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +这将在每天凌晨 2 点运行转换,并记录所有输出以供后续查看。 + +--- + +## 结论 + +您现在拥有一种经过验证、可投入生产的方式,使用 Aspose.OCR 的 `BatchOcrEngine` **convert images to text python**。该脚本能够处理 **bulk image to text conversion**,优雅地将每个结果写入专属文件,并包含验证步骤,以确保您能够正确 **recognize text from scanned images**。 + +接下来您可以: + +- 尝试不同的 OCR 设置(语言包、去倾斜、降噪)。 +- 将生成的文本导入 Elasticsearch 等搜索索引,实现即时全文搜索。 +- 将此流水线与 PDF 转换工具结合,一次性处理扫描的 PDF。 + +有任何问题,或发现某种文件类型出现异常?请在下方留言,我们一起排查。祝编码愉快,愿您的 OCR 运行快速且无错误! + +## 接下来您可以学习什么? + +- [使用 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 提取图像文本(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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..31e558bf9 --- /dev/null +++ b/ocr/chinese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: 在 Python 中创建许可证实例并轻松配置许可证路径。通过清晰的代码示例学习如何设置 Aspose OCR 许可证。 +draft: false +keywords: +- create license instance +- configure license path +language: zh +og_description: 在 Python 中创建许可证实例并立即配置许可证路径。按照本教程,自信地激活 Aspose OCR。 +og_title: 在 Python 中创建许可证实例 – 完整设置指南 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: 在 Python 中创建许可证实例 – 步骤指南 +url: /zh/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中创建 License 实例 – 完整设置指南 + +需要为 Aspose OCR 在 Python 中 **创建 license 实例** 吗?您来对地方了。在本教程中,我们还会展示如何 **配置 license 路径**,让 SDK 知道 `.lic` 文件所在的位置。 + +如果您曾经盯着空白脚本发愁,为什么 OCR 引擎总是抱怨未授权产品,您并不孤单。通常只需几行代码——只要把它们放在正确的位置。阅读完本指南后,您将拥有一个完整授权的 Aspose OCR 环境,能够顺畅地识别文本、图像和 PDF。 + +## 您将学到的内容 + +- 如何使用 `asposeocr` 包 **创建 license 实例**。 +- 在开发和生产环境中 **配置 license 路径** 的正确方式。 +- 常见陷阱(文件缺失、权限错误)以及如何避免。 +- 一个完整、可直接运行的脚本,您可以将其放入任何项目中。 + +无需任何 Aspose OCR 经验,只需一套可用的 Python 3 环境和一份有效的 license 文件。 + +--- + +## 步骤 1:安装 Aspose OCR Python 包 + +在我们能够 **创建 license 实例** 之前,必须先安装库本身。打开终端并运行: + +```bash +pip install aspose-ocr +``` + +> **小贴士:** 如果您使用虚拟环境(强烈推荐),请先激活它。这可以保持依赖整洁,防止版本冲突。 + +## 步骤 2:导入 License 类 + +SDK 已就绪后,脚本的第一行应导入 `License` 类。这是我们用来 **创建 license 实例** 的对象。 + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +为什么要立即导入?因为必须在任何 OCR 调用 **之前** 实例化 `License` 对象;否则 SDK 在您尝试处理图像时会抛出授权错误。 + +## 步骤 3:创建 License 实例 + +下面就是您一直在等待的时刻——实际 **创建 license 实例**。这只是一行代码,但上下文很重要。 + +```python +# Step 3: Create a License instance +license = License() +``` + +变量 `license` 现在持有一个对象,控制当前 Python 进程的所有授权行为。可以把它想象成守门员,告诉 Aspose OCR:“嘿,我有运行的权限。” + +## 步骤 4:配置 License 路径 + +实例准备好后,需要指向我们的 `.lic` 文件。这时 **配置 license 路径** 就派上用场了。将占位符替换为 license 文件的绝对路径。 + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +需要注意的几点: + +1. **原始字符串 (`r"…"`)** 可防止 Windows 上的反斜杠被解释为转义字符。 +2. 使用 **绝对路径** 可避免脚本从不同工作目录启动时产生混淆。 +3. 如果您倾向使用相对路径(例如将 license 与项目一起打包),请确保相对基准是脚本所在位置,而不是当前 shell 目录。 + +### 处理文件缺失 + +如果路径错误或文件不可读,`set_license` 会抛出异常。将调用包装在 `try/except` 块中,以提供友好的错误信息: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +此代码段 **安全地配置 license 路径**,并明确告诉您出错的原因——不再出现神秘的堆栈跟踪。 + +## 步骤 5:验证 License 已激活 + +一次快速的检查可以为后续调试节省数小时。调用 `set_license` 后,尝试执行一个简单的 OCR 操作。如果 license 有效,SDK 将处理图像而不会抛出授权错误。 + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +如果看到识别出的文本被打印出来,恭喜您——已经成功 **create license instance** 并 **configure license path**。如果出现授权异常,请再次检查路径和文件权限。 + +## 边缘情况与最佳实践 + +| 情况 | 处理方式 | +|-----------|------------| +| **License 文件位于网络共享** | 将共享映射到驱动器字母或使用 UNC 路径 (`\\server\share\license.lic`)。确保 Python 进程拥有读取权限。 | +| **在 Docker 容器内运行** | 将 `.lic` 文件复制到镜像中,并使用绝对路径如 `/app/license/Aspose.OCR.Java.lic` 引用。 | +| **多个 Python 解释器**(如 conda 环境) | 每个环境安装一次 license 文件,或保留在中心位置并让每个解释器指向它。 | +| **运行时缺少 License 文件** | 优雅地回退到试用模式(如果支持),或以清晰的日志信息中止。 | + +### 常见陷阱 + +- **在 Windows 上使用正斜杠** – Python 能接受,但某些旧版 SDK 可能会误解。请使用原始字符串或双反斜杠。 +- **忘记导入 `License`** – 脚本会因 `NameError` 而崩溃。实例化前务必先导入。 +- **在 OCR 方法之后才调用 `set_license`** – SDK 会在首次使用时检查授权,因此必须 **先** 设置路径。 + +## 完整可运行示例 + +下面是一段完整脚本,演示了所有步骤的整合。将其保存为 `ocr_setup.py` 并在命令行运行。 + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**预期输出**(假设图像有效): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +如果找不到 license 文件,您将看到明确的错误信息,而不是晦涩的 “License not found” 异常。 + +--- + +## 结论 + +现在您已经掌握了在 Python 中 **create license instance** 并 **configure license path** 的全部流程。步骤简明:安装包、导入 `License`、实例化、指向 `.lic` 文件,最后通过小型 OCR 测试验证。 + +有了这些知识,您可以将 OCR 功能嵌入 Web 服务、桌面应用或自动化流水线,而不会再被授权错误卡住。接下来,您可以探索更高级的 OCR 设置——语言包、图像预处理或批量处理——这些都建立在您刚刚搭建的坚实基础之上。 + +对部署、Docker 或多 license 处理有疑问?欢迎留言,祝编码愉快! + +## 接下来您可以学习什么? + +- [Aspose OCR 教程 – 光学字符识别](/ocr/english/) +- [如何在 Java 中设置 License 并验证 Aspose.OCR License](/ocr/english/java/ocr-basics/set-license/) +- [如何使用 Aspose.OCR 进行语言选择的图像文字 OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..9d8f6e143 --- /dev/null +++ b/ocr/chinese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: 使用 Python OCR 将扫描图像创建可搜索的 PDF。学习如何将扫描的图像 PDF 转换、将 TIFF 转换为 PDF,并在几分钟内添加 + OCR 文本层。 +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: zh +og_description: 即时创建可搜索的 PDF。本指南展示如何使用单个 Python 脚本运行 OCR、转换扫描的图像 PDF 并添加 OCR 文本层。 +og_title: 使用Python创建可搜索的PDF – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: 使用 Python 创建可搜索 PDF – 步骤指南 +url: /zh/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Python 创建可搜索 PDF – 步骤指南 + +是否曾想过 **从扫描页创建可搜索 PDF** 而不需要使用大量工具?你并不孤单。在许多办公流程中,扫描的 TIFF 或 JPEG 会被放到共享磁盘,下一位同事只能手动复制‑粘贴文本——既痛苦又容易出错,还浪费时间。 + +在本教程中,我们将逐步演示一种简洁的编程解决方案,让你一次性 **转换扫描图像 PDF**、**将 TIFF 转为 PDF**,并 **添加 OCR 文本层**。完成后,你将拥有一个可直接使用的脚本,能够运行 OCR、嵌入隐藏文本,并生成可索引、可搜索或可放心分享的 PDF。 + +## 所需环境 + +- Python 3.9+(任意近期版本均可) +- `aspose-ocr` 与 `aspose-pdf` 包(通过 `pip install aspose-ocr aspose-pdf` 安装) +- 一个扫描图像文件(`.tif`、`.png`、`.jpg`,或仅包含图像的 PDF 页面) +- 适量的内存(OCR 引擎轻量,即使是笔记本也能胜任) + +> **小贴士:** 如果你使用 Windows,最简便的获取这些包的方式是在提升权限的 PowerShell 窗口中运行上述命令。 + +```bash +pip install aspose-ocr aspose-pdf +``` + +现在前置条件已经完成,让我们进入代码部分。 + +## 步骤 1:创建 OCR 引擎实例 – *create searchable pdf* + +首先我们实例化 OCR 引擎。可以把它想象成读取每个像素并转换为字符的大脑。 + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **为什么重要:** 只初始化一次引擎可以保持内存占用低。如果在循环中对每页都调用 `OcrEngine()`,很快就会耗尽资源。 + +## 步骤 2:加载扫描图像 – *convert tiff to pdf* & *convert scanned image pdf* + +接下来,将引擎指向你想要处理的文件。API 接受任何光栅图像,因此 TIFF 与 JPEG 同样适用。 + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +如果你手头有仅包含扫描图像的 PDF,也可以使用 `load_image`,因为 Aspose 会自动提取第一页。 + +## 步骤 3:准备 PDF 保存选项 – *add OCR text layer* + +这里我们配置最终 PDF 的保存方式。关键标志是 `create_searchable_pdf`;将其设为 `True` 即告诉库嵌入一个与可视内容对应的不可见文本层。 + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **文本层的作用:** 当你在 Adobe Reader 中打开生成的文件并尝试选取文本时,会看到隐藏的字符。搜索引擎也能索引这些字符——非常适合合规或归档需求。 + +## 步骤 4:运行 OCR 并保存 – *how to run OCR* in a single call + +魔法时刻到来。一次方法调用即可运行识别引擎并将可搜索 PDF 写入磁盘。 + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize` 方法返回一个状态对象,可用于检查错误,但在大多数直接场景下,上面的简单调用已经足够。 + +### 预期输出 + +运行脚本后会打印: + +``` +PDF saved as searchable PDF. +``` + +如果打开 `scanned_page_searchable.pdf`,你会发现可以选取文本、复制‑粘贴,甚至使用 `Ctrl+F` 搜索。这正是 **create searchable pdf** 工作流的标志。 + +## 完整可运行脚本 + +下面是完整的、可直接运行的脚本。只需将占位路径替换为实际文件位置。 + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +将其保存为 `create_searchable_pdf.py` 并执行: + +```bash +python create_searchable_pdf.py +``` + +## 常见问题与边缘情况 + +### 1️⃣ 能处理多页 PDF 吗? + +可以。使用 `ocr_engine.load_image("file.pdf")`,然后在循环中对每页调用 `ocr_engine.recognize(pdf_save_options, page_number)`。库会自动生成多页可搜索 PDF。 + +### 2️⃣ 如果源文件是高分辨率 TIFF(300 dpi 以上)怎么办? + +更高的 DPI 能提升 OCR 准确度,但也会占用更多内存。如果出现 `MemoryError`,请先对图像进行降采样: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ 如何更改 OCR 的语言? + +在加载图像之前,设置引擎的 `language` 属性: + +```python +ocr_engine.language = "fra" # French +``` + +完整的语言代码列表请参阅 Aspose 文档。 + +### 4️⃣ 如果需要保持原始图像质量怎么办? + +`PdfSaveOptions` 类提供 `compression` 属性。将其设为 `PdfCompression.None` 即可完整保留光栅数据。 + +```python +pdf_save_options.compression = "None" +``` + +## 生产环境部署建议 + +- **批量处理:** 将核心逻辑封装为接受文件路径列表的函数。将每次成功/失败记录到 CSV,以便审计。 +- **并行化:** 使用 `concurrent.futures.ThreadPoolExecutor` 在多核上并行运行 OCR。记住每个线程需要独立的 `OcrEngine` 实例。 +- **安全性:** 若处理敏感文档,请在沙箱环境中运行脚本,并在处理完毕后立即删除临时文件。 + +## 结论 + +现在你已经掌握了使用简洁的 Python 脚本 **create searchable pdf** 的完整方法。通过初始化 OCR 引擎、加载 TIFF(或任意光栅图像)、配置 `PdfSaveOptions` 以 **add OCR text layer**,最后调用 `recognize`,整个 **convert scanned image pdf** 与 **convert TIFF to PDF** 流程即可变成一次可重复执行的命令。 + +下一步?尝试将此脚本与文件监视器结合,使任何新扫描文件一放入文件夹就自动生成可搜索 PDF。或尝试不同的 OCR 语言,以支持多语言档案。当 OCR 与 PDF 生成相结合时,可能性无限。 + +对 **how to run OCR** 在其他语言或框架中的实现还有疑问?欢迎在下方留言,祝编码愉快! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## 接下来该学习什么? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/chinese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7a07f3026 --- /dev/null +++ b/ocr/chinese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-31 +description: 通过使用 Python 对图像进行预处理,提高 OCR 的准确性。学习如何从图像文件中提取文本,识别 PNG 中的文字,并提升识别效果。 +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: zh +og_description: 通过对文本进行图像预处理,在 Python 中提升 OCR 准确率。按照本指南轻松从图像文件中提取文本并识别 PNG 中的文字。 +og_title: 在Python中提升OCR准确率 – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 在 Python 中提升 OCR 准确率 – 完整的逐步指南 +url: /zh/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 提升 Python 中 OCR 准确率 – 完整分步指南 + +是否曾尝试 **提升 OCR 准确率**,却得到一堆乱码?你并不孤单。大多数开发者在原始图像噪声大、倾斜或对比度低时都会碰壁。好消息是:只需几招预处理技巧,就能把模糊的截图变成干净、机器可读的文本。 + +在本教程中,我们将通过一个真实案例 **对图像进行 OCR 预处理**,运行识别引擎,最后 **从图像中提取文本**——具体以 PNG 为例。完成后,你将掌握如何 **从 PNG 中识别文本**,并拥有一段可在任意项目中直接使用的代码片段。 + +## 你将学到 + +- 为什么图像预处理对 OCR 引擎至关重要 +- 哪些预处理模式(去噪、去倾斜)能带来最大提升 +- 如何在 Python 中配置 `OcrEngine` 实例 +- 完整可运行的脚本,**从图像文件中提取文本** +- 处理旋转扫描或低分辨率图片等边缘情况的技巧 + +无需除 OCR SDK 之外的外部库,但你需要 Python 3.8+ 和一张待读取的 PNG 图像。 + +--- + +![提升 Python 中 OCR 准确率的步骤示意图](image.png "提升 OCR 准确率工作流") + +*Alt text: 展示预处理和识别步骤的提升 OCR 准确率工作流示意图。* + +## 前置条件 + +- 已安装 Python 3.8 或更高版本 +- 可使用提供 `OcrEngine`、`OcrEngineSettings` 与 `ImagePreprocessMode` 的 OCR SDK(下面的代码使用通用 API;如有需要请替换为你的供应商类) +- 将 PNG 图像(`input.png`)放在可引用的文件夹中 + +如果你使用虚拟环境,请立即激活——不需要花哨操作,只需 `python -m venv venv && source venv/bin/activate`。 + +--- + +## 步骤 1:创建 OCR 引擎实例 – 开始提升 OCR 准确率 + +首先需要一个 OCR 引擎对象。它相当于大脑,后续会读取像素并输出字符。 + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +为什么重要:没有引擎就无法进行任何预处理,原始图像会直接喂给识别器——这通常是准确率最差的情况。 + +--- + +## 步骤 2:加载目标 PNG – 为从 PNG 中识别文本做好准备 + +现在告诉引擎要处理的文件。PNG 是无损格式,天然比 JPEG 多了一点优势。 + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +如果图像位于其他位置,只需调整路径即可。引擎支持任何受支持的格式,但 PNG 往往能保留字符边缘的细节。 + +--- + +## 步骤 3:配置预处理 – 为 OCR 预处理图像 + +魔法就在这里。我们创建一个设置对象,开启去噪以去除斑点,并打开去倾斜,使倾斜的文字自动校正。 + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### 为什么同时使用去噪 + 去倾斜? + +- **去噪**:随机像素噪声会干扰模式匹配算法。去除噪声后字母更清晰。 +- **去倾斜**:即使是 2 度的倾斜也会显著降低置信度分数。去倾斜会对齐基线,让识别器更可靠地匹配字体。 + +如果你的图像特别暗,可以尝试额外的标志(例如 `ImagePreprocessMode.CONTRAST_ENHANCE`)。SDK 文档通常会列出所有可用模式。 + +--- + +## 步骤 4:将设置应用到引擎 – 把预处理绑定到 OCR + +将设置对象分配给引擎,这样下一次识别时就会使用我们刚定义的转换。 + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +如果跳过此步骤,引擎会回退到默认(通常是“无预处理”),导致 **OCR 准确率下降**。 + +--- + +## 步骤 5:运行识别过程 – 从图像中提取文本 + +所有准备就绪后,终于可以让引擎工作了。此调用是同步的,返回一个包含识别字符串的结果对象。 + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +在幕后,引擎会: + +1. 将 PNG 加载到内存 +2. 根据我们的设置执行去噪和去倾斜 +3. 运行神经网络或经典模式匹配器 +4. 将输出封装进 `recognition_result` + +--- + +## 步骤 6:输出识别文本 – 验证提升效果 + +打印提取的字符串。在真实应用中,你可能会把它写入文件、数据库,或传递给其他服务。 + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### 预期输出 + +如果图像中包含句子 “Hello, OCR World!” 应该会看到: + +``` +Hello, OCR World! +``` + +可以看到文本干净整洁——没有杂散符号或破碎字符。这正是 **图像预处理用于文本** 的效果。 + +--- + +## 专业技巧 & 边缘情况 + +| 场景 | 调整方式 | 原因 | +|-----------|----------------|-----| +| 非常低分辨率的 PNG (≤ 72 dpi) | 如有可用,添加 `ImagePreprocessMode.SUPER_RESOLUTION` | 上采样可以为识别器提供更多像素 | +| 文本旋转 > 5° | 增大去倾斜容差或在喂给引擎前使用 `Pillow` 手动旋转 | 极端角度有时会绕过自动去倾斜 | +| 背景图案繁杂 | 启用 `ImagePreprocessMode.BACKGROUND_REMOVAL` | 去除非文本杂乱,防止误读 | +| 多语言文档 | 设置 `ocr_engine.language = "eng+spa"`(或类似) | 引擎选择正确的字符集,提高整体准确率 | + +记住,**提升 OCR 准确率** 并非一刀切;你可能需要针对特定数据集反复调试预处理标志。 + +--- + +## 完整脚本 – 直接复制粘贴 + +下面是完整、可运行的示例,涵盖了我们讨论的每一步。将其保存为 `improve_ocr_accuracy.py`,然后使用 `python improve_ocr_accuracy.py` 执行。 + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +运行后观察控制台,你会立即看到 **从图像中提取文本** 的结果。如果输出不理想,按 “专业技巧” 表中的说明调整 `preprocess_mode` 标志。 + +--- + +## 结论 + +我们刚刚演示了使用 Python **提升 OCR 准确率** 的实用配方。通过创建 `OcrEngine`、加载 PNG、**为 OCR 预处理图像**,以及最终 **从 PNG 中识别文本**,即使源图像并不完美,也能可靠地 **从图像文件中提取文本**。 + +接下来可以尝试将一批图像放入循环处理、将每个结果存入 CSV,或实验对比度增强等额外预处理模式。相同的模式同样适用于 PDF、扫描收据或手写笔记——只需更换输入并相应调整设置。 + +对特定图像类型有疑问,或想了解如何将其集成到 Web 服务中?欢迎留言,我们一起探讨。祝编码愉快,愿你的 OCR 结果永远晶莹剔透! + +## 接下来该学习什么? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/chinese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..ee2a93e1a --- /dev/null +++ b/ocr/chinese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-31 +description: 了解如何使用 OCR 感兴趣区域加载图像进行 OCR,并从矩形中提取文本,完美适用于识别发票上的金额。 +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: zh +og_description: 掌握 OCR 感兴趣区域,加载图像进行 OCR,从矩形中提取文本,并在单个教程中识别发票文本。 +og_title: OCR感兴趣区域 – Python逐步指南 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR感兴趣区域 – 在Python中从矩形提取文本 +url: /zh/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 感兴趣区域 – 在 Python 中从矩形提取文本 + +有没有想过如何 **ocr region of interest** 扫描发票的特定部分,而不必将整页输入引擎?你并不是第一个盯着模糊收据并思考“如何提取位于右下角的金额?”的人。好消息是,你可以告诉 OCR 库确切的查找位置,从而显著提升速度和准确性。 + +在本指南中,我们将通过一个完整、可运行的示例,展示如何 **load image for OCR**、定义 **region of interest**,然后 **extract text from rectangle**,最终 **recognize text from invoice**,并回答经典的“如何提取金额”问题。没有模糊的引用——只有具体的代码、清晰的解释,以及一些你希望早些知道的专业技巧。 + +--- + +## 你将构建的内容 + +通过本教程的学习,你将拥有一个小型的 Python 脚本,能够: + +1. 从磁盘加载发票图像。 +2. 标记总金额所在的矩形 ROI。 +3. 仅在该 ROI 内运行 OCR。 +4. 打印清理后的金额字符串。 + +所有这些都适用于任何支持 ROI 的 OCR 库——这里我们使用一个虚构但具代表性的 `SimpleOCR` 包,它模拟了 Tesseract 或 EasyOCR 等流行工具。随意替换它;概念保持不变。 + +--- + +## 前置条件 + +- 已安装 Python 3.8+(`python --version` 应显示 ≥3.8)。 +- 可通过 pip 安装的 OCR 包(例如 `pip install simpleocr`)。 +- 放置在可引用文件夹中的发票图像(PNG 或 JPEG)。 +- 对 Python 函数和类有基本了解(无需高级技巧)。 + +如果你已经具备这些,太好了——让我们开始吧。如果没有,先获取图像;其余步骤与实际文件内容无关。 + +--- + +## 步骤 1:加载用于 OCR 的图像 + +任何 OCR 工作流的第一步都是需要一个位图作为读取来源。大多数库提供一个接受文件路径的简单 `load_image` 方法。下面是使用我们的 `SimpleOCR` 引擎的做法: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **专业提示:** 使用绝对路径或 `os.path.join`,以避免在从不同工作目录运行脚本时出现 “file not found” 的意外。 + +--- + +## 步骤 2:定义 OCR 感兴趣区域 + +我们不让引擎扫描整页,而是明确告诉它金额所在的*确切*位置。这一步是 **ocr region of interest**,是实现可靠提取的关键,尤其当文档包含嘈杂的页眉或页脚时。 + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +为什么是这些数字?`x` 和 `y` 是相对于左上角的像素偏移,而 `width` 和 `height` 描述了框的尺寸。如果不确定,可以在任意编辑器中打开图像,启用标尺并记录坐标。许多 IDE 甚至在悬停时显示光标位置。 + +--- + +## 步骤 3:从矩形提取文本 + +现在 ROI 已设置,我们让引擎 **recognize text from invoice**,但仅限于我们刚刚添加的矩形。该调用返回一个结果对象,通常包含原始字符串、置信度分数,有时还有边界框。 + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +在内部,`recognize()` 会遍历每个 ROI,裁剪相应区域,运行 OCR 模型,并将结果拼接起来。这就是为什么定义一个紧凑的 **extract text from rectangle** 区域可以为批处理作业节省数秒的原因。 + +--- + +## 步骤 4:如何提取金额 – 清理输出 + +OCR 并非完美;你经常会得到多余的空格、换行,甚至误读的字符(比如 “S” 与 “5”)。快速使用 `strip()` 加上一个小正则表达式通常即可处理货币值。 + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **为何重要:** 如果你打算将金额写入数据库或支付网关,需要一个可预测的格式。去除空白并过滤非数字字符可以防止后续错误。 + +--- + +## 步骤 5:识别发票文本 – 完整脚本 + +将所有步骤整合在一起,下面是完整的可直接运行的脚本。将其保存为 `extract_amount.py` 并执行 `python extract_amount.py`。 + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### 预期输出 + +``` +Amount: 1,245.67 +``` + +如果 ROI 对齐不正确,你可能会看到类似 `Amount: 1245.6S` 的输出——注意多余的 “S”。调整矩形坐标并重新运行,直至输出整洁。 + +--- + +## 常见陷阱与边缘情况 + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI 太小** | 金额文本被裁剪,导致识别不完整。 | 将 `width`/`height` 扩大约 10‑20 % 并重新测试。 | +| **DPI 不正确** | 低分辨率扫描(≤150 dpi)降低 OCR 准确度。 | 在加载前将图像重新采样至 300 dpi,或让扫描仪使用更高 DPI。 | +| **多种货币** | 正则表达式匹配到第一个数字组,可能是发票号。 | 优化正则,使其在数字前查找货币符号(`$`, `€`, `£`)。 | +| **发票旋转** | OCR 引擎假设文本是正向的,旋转的页面会导致识别失败。 | 在添加 ROI 前使用旋转校正(`ocr_engine.rotate(90)`)。 | +| **背景噪声** | 阴影或印章会干扰模型。 | 使用简单阈值预处理(`cv2.threshold`)或去噪滤波。 | + +提前处理这些边缘情况可以为你节省后续数小时的调试时间。 + +--- + +## 实际项目的专业技巧 + +- **批量处理:**遍历发票文件夹,动态计算 ROI(例如基于模板检测),并将结果存入 CSV。 +- **模板匹配:**如果处理多种发票布局,维护一个 `template_id → ROI coordinates` 的 JSON 映射。根据快速布局分类器切换 ROI。 +- **并行执行:**使用 `concurrent.futures.ThreadPoolExecutor` 并发运行多个 OCR 实例——适用于高吞吐量的后台流水线。 +- **置信度过滤:**大多数 OCR 结果包含置信度分数。丢弃低于阈值(如 85 %)的结果,并标记为手动复审。 + +--- + +## 结论 + +我们已经覆盖了实现 **ocr region of interest**、**load image for OCR**、**extract text from rectangle**,以及最终 **recognize text from invoice**,以回答经典的 **how to extract amount** 问题所需的全部内容。该脚本简洁但足够灵活,可适配不同的文档格式、语言和 OCR 后端。 + +既然你已经掌握了基础,考虑扩展工作流:添加条形码扫描、集成 PDF 解析器,或将提取的金额推送到会计 API。无限可能,而通过明确定义的 ROI,你始终能获得更快、更清晰的结果。 + +如果遇到问题,请在下方留言——祝你 OCR 愉快! + +![OCR 感兴趣区域示例](https://example.com/ocr_roi_example.png "OCR 感兴趣区域示例") + +## 接下来你应该学习什么? + +- [通过在 OCR 中准备矩形来提取图像文本](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [使用 Aspose.OCR 检测区域模式在 Java 中提取图像文本](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [提取图像文本 – 使用 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/czech/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/czech/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..2255b1a92 --- /dev/null +++ b/ocr/czech/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Asynchronní OCR tutoriál ukazující, jak použít Aspose OCR v Pythonu s + asyncio pro rychlé získávání textu z obrázků. Naučte se krok za krokem implementaci + asynchronního OCR. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: cs +og_description: Asynchronní OCR tutoriál vás provede používáním Aspose OCR v Pythonu + s asyncio pro efektivní extrakci textu z obrázků. +og_title: Asynchronní OCR tutoriál – Python asyncio s Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Asynchronní OCR tutoriál – Python asyncio s Aspose OCR +url: /cs/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR tutoriál – Python asyncio s Aspose OCR + +Už jste se někdy zamysleli, jak spustit rozpoznávání znaků (OCR) bez blokování vaší aplikace? V **async OCR tutoriálu** uvidíte přesně to – neblokující extrakci textu pomocí `asyncio` v Pythonu a knihovny Aspose OCR. + +Pokud jste se zasekli čekáním, až se zpracuje těžký obrázek, tento průvodce vám poskytne čisté asynchronní řešení, které udržuje vaši smyčku událostí v chodu. + +V následujících sekcích pokryjeme vše, co potřebujete: instalaci knihovny, vytvoření asynchronního pomocníka, zpracování výsledku a dokonce rychlou tip na škálování na více obrázků. Na konci budete schopni vložit **async OCR tutoriál** do jakéhokoli Python projektu, který již používá `asyncio`. + +## Co budete potřebovat + +* Python 3.9+ (API `asyncio`, které používáme, je stabilní od verze 3.7) +* Aktivní licence Aspose OCR nebo bezplatná zkušební verze (knihovna je čistě Python, bez nativních binárek) +* Malý soubor obrázku (`.jpg`, `.png`, atd.), který chcete načíst – uložte jej do známé složky + +Žádné další externí nástroje nejsou vyžadovány; vše běží v čistém Pythonu. + +## Krok 1: Instalace balíčku Aspose OCR + +Nejprve získáme balíček Aspose OCR z PyPI. Otevřete terminál a spusťte: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Pokud pracujete ve virtuálním prostředí (vřele doporučeno), nejprve jej aktivujte. Tím se izolují závislosti a předejdete konfliktům verzí. + +## Krok 2: Asynchronní inicializace OCR enginu + +Srdcem našeho **async OCR tutoriálu** je asynchronní pomocná funkce. Vytvoří instanci `OcrEngine`, načte obrázek a následně zavolá `recognize_async()`. Engine samotný je synchronní, ale metoda wrapper vrací awaitable, což umožňuje smyčce událostí zůstat responzivní. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Proč to děláme tímto způsobem:** +*Vytvoření enginu uvnitř pomocníka zajišťuje bezpečnost vláken, pokud později spustíte mnoho OCR úloh paralelně. Klíčové slovo `await` předá kontrolu zpět smyčce událostí, zatímco těžká práce probíhá v interním vláknovém poolu knihovny.* + +## Krok 3: Použití pomocníka z asynchronní hlavní funkce + +Nyní potřebujeme malý coroutine `main()`, který zavolá `async_ocr()` a vytiskne výsledek. Toto odráží typický vstupní bod pro skript `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Co se děje pod kapotou?** +`asyncio.run()` vytvoří novou smyčku událostí, naplánuje `main()` a po dokončení `main()` smyčku čistě ukončí. Tento vzor je doporučený způsob, jak spouštět asynchronní programy v Pythonu 3.7+. + +## Krok 4: Otestování kompletního skriptu + +Uložte oba výše uvedené bloky kódu do jediného souboru, např. `async_ocr_demo.py`. Spusťte jej z příkazové řádky: + +```bash +python async_ocr_demo.py +``` + +Pokud je vše nastaveno správně, měli byste vidět něco jako: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Přesný výstup bude záviset na obsahu souboru `photo.jpg`. Klíčové je, že skript skončí rychle, i když je obrázek velký, protože OCR práce probíhá na pozadí. + +## Krok 5: Škálování – Zpracování více obrázků souběžně + +Často kladená otázka je: *„Mohu OCRovat dávku souborů, aniž bych spouštěl nový proces pro každý?“* Rozhodně. Protože je náš pomocník plně asynchronní, můžeme shromáždit mnoho coroutine pomocí `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Proč to funguje:** `asyncio.gather()` naplánuje všechny OCR úlohy najednou. Podkladová knihovna Aspose OCR stále používá svůj vlastní thread pool, ale z pohledu Pythonu vše zůstává neblokující, což vám umožní zpracovat desítky obrázků během času, který by zabral jeden synchronní hovor. + +## Krok 6: Elegantní zpracování chyb + +Když pracujete s externími soubory, nevyhnutelně narazíte na chybějící soubory, poškozené obrázky nebo problémy s licencí. Zabalte OCR volání do bloku `try/except`, aby smyčka událostí zůstala aktivní: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Nyní `batch_ocr()` může místo toho volat `safe_async_ocr`, což zajistí, že jedna špatná položka neukončí celou dávku. + +## Vizualizace + +![Diagram async OCR tutoriálu](async-ocr-diagram.png){alt="Diagram toku async OCR tutoriálu zobrazující pomocníka async_ocr, smyčku událostí a engine Aspose OCR"} + +Diagram výše vizualizuje tok: smyčka událostí → `async_ocr` → `OcrEngine` → vlákno na pozadí → výsledek zpět do smyčky. + +## Časté úskalí a jak se jim vyhnout + +| Úskalí | Proč k tomu dochází | Řešení | +|--------|---------------------|--------| +| **Blocking I/O uvnitř pomocníka** | Náhodné použití `open()` bez `await` může blokovat smyčku. | Použijte `aiofiles` pro čtení souborů, nebo nechte `engine.load_image` to zvládnout (už je neblokující). | +| **Znovupoužití jediného `OcrEngine` napříč coroutine** | Engine není thread‑safe; souběžné volání může poškodit stav. | Vytvořte nový engine uvnitř každého volání `async_ocr` (jak je ukázáno). | +| **Chybějící licence** | Aspose OCR vyhodí výjimku související s licencí za běhu. | Zaregistrujte licenci co nejdříve (`OcrEngine.set_license("license.json")`). | +| **Velké obrázky způsobující špičky paměti** | Knihovna načítá celý obrázek do RAM. | Před OCR zmenšete rozlišení obrázků, pokud je paměť problémem. | + +## Shrnutí: Co jsme dosáhli + +V tomto **async OCR tutoriálu** jsme: + +1. Nainstalovali knihovnu Aspose OCR. +2. Vytvořili pomocnou funkci `async_ocr`, která provádí rozpoznání bez blokování. +3. Spustili pomocníka z čistého vstupního bodu `asyncio`. +4. Ukázali dávkové zpracování pomocí `asyncio.gather`. +5. Přidali zpracování chyb a tipy na nejlepší postupy. + +Vše je čistý Python, takže jej můžete vložit do webového serveru, CLI nástroje nebo datového pipeline bez nutnosti přepisovat existující asynchronní kód. + +## Další kroky a související témata + +* **Asynchronní předzpracování obrázků** – použijte `aiohttp` pro souběžné stahování obrázků před OCR. +* **Ukládání OCR výsledků** – zkombinujte tento tutoriál s asynchronním databázovým driverem jako `asyncpg` pro PostgreSQL. +* **Ladění výkonu** – experimentujte s `engine.recognize_async(max_threads=4)`, pokud knihovna takovou možnost nabízí. +* **Alternativní OCR enginy** – porovnejte Aspose OCR s async obaly Tesseractu pro analýzu nákladů a přínosů. + +Neváhejte experimentovat: zkuste zpracovávat PDF, upravit nastavení jazyka nebo napojit výsledky do chatbotu. Možnosti jsou neomezené, jakmile máte solidní **async OCR tutoriál** základ. + +Šťastné kódování a ať je vaše extrakce textu vždy rychlá! + +## Co byste se měli naučit dál? + +- [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/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/czech/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..92c38f664 --- /dev/null +++ b/ocr/czech/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Automatické rozpoznávání jazyka v OCR je snadné. Naučte se, jak načíst + obrázek pro OCR, povolit automatické rozpoznávání jazyka a rozpoznat text na obrázku + během několika kroků. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: cs +og_description: Automatické rozpoznání jazyka v OCR je snadné. Postupujte podle tohoto + krok‑za‑krokem návodu, abyste povolili automatické rozpoznání jazyka, načetli obrázek + pro OCR a rozpoznali text na obrázku. +og_title: Automatické rozpoznávání jazyka pomocí OCR – Kompletní průvodce Pythonem +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatické rozpoznávání jazyka pomocí OCR – Kompletní průvodce Pythonem +url: /cs/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatické rozpoznávání jazyka pomocí OCR – Kompletní průvodce v Pythonu + +Už jste se někdy zamýšleli, jak nechat OCR engine *uhádnout* jazyk naskenovaného dokumentu, aniž byste mu říkali, co má hledat? Přesně to dělá **automatické rozpoznávání jazyka** a představuje revoluci, když pracujete s vícejazyčnými PDF, fotografiemi pouličních značek nebo jakýmkoli obrázkem, který kombinuje různé písmo. + +V tomto tutoriálu projdeme praktickým příkladem, který vám ukáže, jak **povolit automatické rozpoznávání jazyka**, **načíst OCR obrázku** a **rozpoznat text z obrázku** pomocí API ve stylu Pythonu. Na konci budete mít samostatný skript, který vypíše jak detekovaný kód jazyka, tak extrahovaný text – bez nutnosti ručního nastavení jazyka. + +## Co se naučíte + +- Jak vytvořit instanci OCR engine a zapnout **automatické rozpoznávání jazyka**. +- Přesné kroky k **načtení OCR obrázku** z disku. +- Jak zavolat metodu `recognize()` engine a získat výsledek, který obsahuje kód jazyka. +- Tipy pro zvládání okrajových případů, jako jsou nízké rozlišení nebo nepodporované písmo. + +Předchozí zkušenosti s vícejazyčným OCR nejsou potřeba; stačí základní nastavení Pythonu a soubor s obrázkem. + +--- + +## Požadavky + +Než se pustíme do práce, ujistěte se, že máte: + +1. Nainstalovaný Python 3.8+ (funguje jakákoli novější verze). +2. OCR knihovnu, která poskytuje `OcrEngine`, `LanguageAutoDetectMode` atd. – pro tento návod předpokládáme hypotetický balíček nazvaný `myocr`. Nainstalujte jej pomocí: + + ```bash + pip install myocr + ``` + +3. Soubor s obrázkem (`multilingual_sample.png`), který obsahuje text alespoň ve dvou různých jazycích. +4. Trochu zvědavosti – pokud jste s OCR nikdy nepracovali, nebojte se; kód je úmyslně jednoduchý. + +--- + +## Krok 1: Povolení automatického rozpoznávání jazyka + +První věc, kterou musíte udělat, je říct engine, aby *sám* zjistil jazyk. Zde vstupuje do hry příznak **automatického rozpoznávání jazyka**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Proč je to důležité:** +> Když je nastaven `AUTO_DETECT`, engine spustí lehký klasifikátor jazyka na obrázku před tím, než se zapojí těžkopádné rozpoznávání znaků. To znamená, že nemusíte hádat, zda je text anglický, ruský, francouzský nebo jakákoliv jejich kombinace. Engine automaticky vybere nejlepší jazykový model pro každou oblast obrázku. + +--- + +## Krok 2: Načtení OCR obrázku + +Nyní, když engine ví, že má automaticky detekovat jazyky, musíme mu poskytnout něco, na čem může pracovat. Krok **načíst OCR obrázku** načte bitmapu a připraví interní buffery. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Tip:** +> Pokud je váš obrázek větší než 300 dpi, zvažte jeho zmenšení na přibližně 150‑200 dpi. Příliš mnoho detailů může ve skutečnosti *zpomalení* fázi detekce jazyka, aniž by zlepšilo přesnost. + +--- + +## Krok 3: Rozpoznání textu z obrázku + +S obrázkem v paměti a zapnutým detekováním jazyka je posledním krokem požádat engine o **rozpoznání textu z obrázku**. Toto jediné volání provede veškerou těžkou práci. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` je objekt, který typicky obsahuje alespoň dva atributy: + +| Atribut | Popis | +|-----------|-------------| +| `language` | Kód ISO‑639‑1 detekovaného jazyka (např. `"en"` pro angličtinu). | +| `text` | Přepis textu z obrázku v prostém textu. | + +--- + +## Krok 4: Získání detekovaného jazyka a extrahovaného textu + +Nyní jednoduše vytiskneme, co engine objevil. Tím demonstrujeme funkci **detect language OCR** v praxi. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Ukázkový výstup** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Co když engine vrátí `None`?** +> To obvykle znamená, že obrázek je příliš rozmazaný nebo je text příliš malý (< 8 pt). Zkuste zvýšit kontrast nebo použít zdroj s vyšším rozlišením. + +--- + +## Kompletní funkční příklad (Povolení automatického rozpoznávání jazyka od začátku do konce) + +Sestavením všech částí získáte připravený skript, který pokrývá **povolení automatického rozpoznávání jazyka**, **načtení OCR obrázku**, **rozpoznání textu z obrázku** a **detekci jazyka OCR** najednou. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Uložte tento soubor jako `automatic_language_detection_ocr.py`, nahraďte `YOUR_DIRECTORY` složkou, kde máte PNG, a spusťte: + +```bash +python automatic_language_detection_ocr.py +``` + +Měli byste vidět kód jazyka následovaný extrahovaným textem, stejně jako v ukázkovém výstupu výše. + +--- + +## Řešení běžných okrajových případů + +| Situace | Doporučené řešení | +|-----------|----------------| +| **Velmi nízké rozlišení obrázku** (méně než 100 dpi) | Zvětšete jej pomocí bikubického filtru před načtením, nebo požádejte o zdroj s vyšším rozlišením. | +| **Smíšené písmo v jednom obrázku** (např. angličtina + cyrilice) | Engine obvykle rozdělí stránku na regiony; pokud zaznamenáte chybné detekce, nastavte `engine.enable_region_split = True`. | +| **Nepodporovaný jazyk** | Ověřte, že OCR knihovna obsahuje jazykový balíček pro požadované písmo; možná bude potřeba stáhnout další modely. | +| **Zpracování velkých dávek** | Inicializujte engine jednou a poté jej znovu použijte pro více cyklů `load_image` / `recognize`, abyste se vyhnuli opakovanému načítání modelů. | + +--- + +## Vizualizace + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt text:* automatický příklad výstupu rozpoznávání jazyka zobrazující detekovaný kód jazyka a extrahovaný vícejazyčný text. + +--- + +## Závěr + +Právě jsme prošli **automatickým rozpoznáváním jazyka** od začátku do konce – vytvoření engine, povolení automatického rozpoznávání jazyka, načtení obrázku pro OCR, rozpoznání textu a nakonec získání detekovaného jazyka. Tento end‑to‑end tok vám umožní zpracovávat vícejazyčné dokumenty bez nutnosti ruční konfigurace jazykových modelů při každém použití. + +Pokud chcete jít dál, zvažte: + +- **Batching** stovek obrázků pomocí smyčky, která znovu používá stejnou instanci `OcrEngine`. +- **Post‑processing** extrahovaného textu pomocí kontroloru pravopisu nebo jazykově specifického tokenizéru. +- **Integraci** skriptu do webové služby, která přijímá nahrané soubory a vrací JSON s poli `language` a `text`. + +Nebojte se experimentovat s různými formáty obrázků (`.jpg`, `.tif`) a sledovat, jak se mění přesnost detekce. Máte otázky nebo obtížný obrázek, který se nechce přečíst? Zanechte komentář níže – šťastné kódování! + +## Co byste se měli naučit dál? + +- [Jak provést OCR textu na obrázku s jazykem pomocí Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [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/) +- [Rozpoznat text z obrázku pomocí Aspose OCR pro více jazyků](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/czech/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ac60e3c25 --- /dev/null +++ b/ocr/czech/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Naučte se, jak převádět obrázky na text v Pythonu pomocí skriptu pro + hromadný převod obrázků na text. Rozpoznávejte text ze skenovaných obrázků pomocí + Aspose.OCR během několika minut. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: cs +og_description: Okamžitě převádějte obrázky na text v Pythonu. Tento průvodce ukazuje + hromadný převod obrázků na text a jak rozpoznat text ze skenovaných obrázků pomocí + Aspose.OCR. +og_title: Převod obrázků na text v Pythonu – kompletní tutoriál +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Převod obrázků na text v Pythonu – Kompletní průvodce krok za krokem +url: /cs/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod obrázků na text v Pythonu – Kompletní průvodce krok za krokem + +Už jste se někdy zamysleli, jak **convert images to text python** bez hledání desítek knihoven? Nejste v tom sami. Ať už digitalizujete staré účtenky, získáváte data ze skenovaných faktur nebo budujete prohledávatelný archiv PDF, převod obrázků na prosté textové soubory je každodenní práce mnoha vývojářů. + +V tomto tutoriálu projdeme **bulk image to text conversion** pipeline, která rozpozná text ze skenovaných obrázků, uloží každý výsledek jako samostatný soubor `.txt` a vše to zvládne jen s několika řádky Pythonu. Žádné hledání neznámých API—Aspose.OCR udělá těžkou práci a my vám ukážeme, jak to přesně nastavit. + +## Co se naučíte + +- Jak nainstalovat a nakonfigurovat balíček Aspose.OCR pro Python. +- Přesný kód potřebný k **convert images to text python** pomocí `BatchOcrEngine`. +- Tipy, jak řešit běžné problémy, jako jsou nepodporované formáty nebo poškozené soubory. +- Způsoby, jak ověřit, že krok **recognize text from scanned images** byl úspěšný. + +Na konci tohoto průvodce budete mít připravený skript, který dokáže zpracovat tisíce obrázků najednou—ideální pro jakýkoli scénář hromadného zpracování. + +## Požadavky + +- Python 3.8+ nainstalovaný na vašem počítači. +- Složka s obrazovými soubory (PNG, JPEG, TIFF atd.), které chcete převést na text. +- Aktivní účet Aspose Cloud nebo bezplatná zkušební licence (bezplatná úroveň stačí pro testování). + +Pokud to máte, pojďme na to. + +--- + +## Krok 1 – Nastavte své Python prostředí + +Než začneme psát jakýkoli OCR kód, ujistěte se, že pracujete v čistém virtuálním prostředí. To izoluje závislosti a zabraňuje konfliktům verzí. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Tip:** Udržujte adresář projektu přehledný—vytvořte podsložku nazvanou `ocr_project` a umístěte do ní skript. To později usnadní práci s cestami. + +## Krok 2 – Nainstalujte Aspose.OCR pro Python + +Aspose.OCR je komerční knihovna, ale je distribuována s bezplatným NuGet‑style wheel, který můžete stáhnout z PyPI. Spusťte následující příkaz v aktivovaném virtuálním prostředí: + +```bash +pip install aspose-ocr +``` + +Pokud narazíte na chybu oprávnění, přidejte příznak `--user` nebo spusťte příkaz s `sudo` (pouze Linux/macOS). Po instalaci byste měli vidět něco jako: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Proč Aspose?** Na rozdíl od mnoha open‑source OCR nástrojů, Aspose.OCR podporuje **bulk image to text conversion** hned z krabice a zvládá širokou škálu formátů obrázků bez další konfigurace. Také nabízí třídu `BatchOcrEngine`, která úkol “convert images to text python” provede jedním řádkem. + +## Krok 3 – Převod obrázků na text v Pythonu pomocí Batch OCR + +Nyní k jádru tutoriálu. Níže je plně spustitelný skript, který: + +1. Importuje třídy OCR enginu. +2. Vytvoří instanci `BatchOcrEngine`. +3. Ukáže enginu vstupní složku s obrázky. +4. Nasměruje engine, aby zapisoval každý extrahovaný textový soubor do výstupní složky. +5. Spustí metodu `recognize()`, která **recognize text from scanned images** po jednom. + +Uložte následující jako `batch_ocr.py` ve své projektové složce: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Jak to funguje + +- **`BatchOcrEngine`** obaluje běžný `OcrEngine`, ale přidává orchestraci na úrovni složek, což je přesně to, co potřebujete, když chcete **convert images to text python** hromadně. +- Vlastnost `input_folder` říká engine, kde hledat zdrojové obrázky. Automaticky prohledá adresář a zařadí každý podporovaný typ souboru. +- Vlastnost `output_folder` určuje, kam se uloží každý soubor `.txt`. Engine zachovává původní název souboru, takže `receipt1.png` se stane `receipt1.txt`. +- Volání `recognize()` spustí interní smyčku, která načte každý obrázek, provede OCR a zapíše výsledek. Metoda blokuje, dokud nejsou zpracovány všechny soubory, což usnadňuje řetězení dalších akcí (např. zipnout výstupní složku). + +#### Očekávaný výstup + +Když spustíte skript: + +```bash +python batch_ocr.py +``` + +Měli byste vidět: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Uvnitř `output_texts` najdete prostý textový soubor pro každý obrázek. Otevřete kterýkoli z nich v textovém editoru a uvidíte surový OCR výsledek—obvykle blízkou aproximaci původního tištěného textu. + +## Krok 4 – Ověřte výsledky a ošetřete chyby + +I ty nejlepší OCR enginy mohou selhat u nízkokvalitních skenů nebo silně nakloněných stránek. Zde je rychlý způsob, jak prověřit výstup a zaznamenat případné selhání. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Proč to přidat?** +- Zachytí případy, kdy engine tiše vygeneroval prázdný řetězec (běžné u nečitelnych obrázků). +- Poskytne vám seznam problematických souborů, abyste je mohli ručně zkontrolovat nebo spustit znovu s jiným nastavením (např. zvýšit možnosti `OcrEngine.preprocess`). + +### Okrajové případy a úpravy + +| Situace | Navrhované řešení | +|-----------|----------------| +| Obrázky jsou otočeny o 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Smíšené jazyky (angličtina + francouzština) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Obrovské PDF nejprve převedené na obrázky | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Chyby paměti při velmi velkých dávkách | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Krok 5 – Automatizujte celý workflow (volitelné) + +Pokud potřebujete spouštět tento převod každou noc, zabalte skript do jednoduchého shellu nebo Windows batch souboru a naplánujte jej pomocí `cron` (Linux/macOS) nebo Task Scheduler (Windows). Zde je minimální `run_ocr.sh` pro Unix‑like systémy: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Udělejte jej spustitelným (`chmod +x run_ocr.sh`) a přidejte cron záznam: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +To spustí převod každý den v 2 AM a zaznamená veškerý výstup pro pozdější kontrolu. + +--- + +## Závěr + +Nyní máte osvědčenou, připravenou pro produkci metodu k **convert images to text python** pomocí `BatchOcrEngine` z Aspose.OCR. Skript zvládá **bulk image to text conversion**, elegantně zapisuje každý výsledek do samostatného souboru a obsahuje ověřovací kroky, aby bylo jisté, že skutečně **recognize text from scanned images** správně. + +Odtud můžete: + +- Experimentovat s různými OCR nastaveními (jazykové balíčky, deskew, redukce šumu). +- Poslat vygenerovaný text do vyhledávacího indexu jako Elasticsearch pro okamžité full‑textové vyhledávání. +- Kombinovat tento pipeline s nástroji pro konverzi PDF, aby se skenované PDF zpracovaly najednou. + +Máte otázky nebo jste narazili na problém s konkrétním typem souboru? Zanechte komentář níže a pojďme to společně vyřešit. Šťastné programování a ať jsou vaše OCR běhy rychlé a bez chyb! + +## Co byste se měli naučit dál? + +- [Extrahovat text z obrázku pomocí Aspose OCR – Průvodce krok za krokem](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrahovat text z obrázků pomocí OCR operace na složkách](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/czech/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..e28a7a9b3 --- /dev/null +++ b/ocr/czech/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Vytvořte instanci licence v Pythonu a snadno nakonfigurujte cestu k licenci. + Naučte se, jak nastavit licencování Aspose OCR pomocí jasných ukázek kódu. +draft: false +keywords: +- create license instance +- configure license path +language: cs +og_description: Vytvořte instanci licence v Pythonu a okamžitě nastavte cestu k licenci. + Postupujte podle tohoto tutoriálu a s jistotou aktivujte Aspose OCR. +og_title: Vytvoření licenční instance v Pythonu – Kompletní průvodce nastavením +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Vytvoření licenční instance v Pythonu – krok za krokem +url: /cs/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření instance licence v Pythonu – Kompletní průvodce nastavením + +Potřebujete **vytvořit instanci licence** pro Aspose OCR v Pythonu? Jste na správném místě. V tomto tutoriálu vám také ukážeme, jak **nastavit cestu k licenci** tak, aby SDK vědělo, kde najít váš soubor `.lic`. + +Pokud jste někdy zírali na prázdný skript a přemýšleli, proč OCR engine stále stěžuje na nelicencovaný produkt, nejste sami. Oprava je obvykle jen pár řádků kódu – jakmile přesně víte, kam je vložit. Na konci tohoto průvodce budete mít plně licencované prostředí Aspose OCR připravené rozpoznávat text, obrázky a PDF bez problémů. + +## Co se naučíte + +- Jak **vytvořit instanci licence** pomocí balíčku `asposeocr`. +- Správný způsob, jak **nastavit cestu k licenci** pro vývoj i produkci. +- Běžné úskalí (chybějící soubor, špatná oprávnění) a jak se jim vyhnout. +- Kompletní spustitelný skript, který můžete vložit do libovolného projektu. + +Předchozí zkušenost s Aspose OCR není vyžadována, stačí funkční instalace Python 3 a platný licenční soubor. + +--- + +## Krok 1: Instalace balíčku Aspose OCR pro Python + +Než budeme moci **vytvořit instanci licence**, musí být knihovna nainstalována. Otevřete terminál a spusťte: + +```bash +pip install aspose-ocr +``` + +> **Tip:** Pokud používáte virtuální prostředí (vysoce doporučeno), nejprve jej aktivujte. To udrží vaše závislosti přehledné a zabrání konfliktům verzí. + +## Krok 2: Import třídy License + +Jakmile je SDK k dispozici, první řádek vašeho skriptu by měl importovat třídu `License`. Tento objekt použijeme k **vytvoření instance licence**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Proč jej importovat hned? Protože objekt `License` musí být vytvořen **před** jakýmkoli voláním OCR; jinak SDK vyhodí licenční chybu v okamžiku, kdy se pokusíte zpracovat obrázek. + +## Krok 3: Vytvoření instance licence + +Tady je okamžik, na který jste čekali – skutečně **vytvořit instanci licence**. Je to jediný řádek, ale okolní kontext má význam. + +```python +# Step 3: Create a License instance +license = License() +``` + +Proměnná `license` nyní obsahuje objekt, který řídí veškeré licenční chování pro aktuální proces Pythonu. Představte si ji jako strážce, který říká Aspose OCR: „Hej, mám právo běžet.“ + +## Krok 4: Nastavení cesty k licenci + +S připravenou instancí musíme nasměrovat na náš soubor `.lic`. Zde vstupuje do hry **nastavení cesty k licenci**. Nahraďte zástupný text absolutní cestou k vašemu licenčnímu souboru. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Několik věcí, na které je třeba dát pozor: + +1. **Raw strings (`r"…"`)** zabraňují tomu, aby zpětná lomítka byla na Windows interpretována jako escape znaky. +2. Použijte **absolutní cestu**, aby nedošlo k záměně, když je skript spuštěn z jiného pracovního adresáře. +3. Pokud dáváte přednost relativní cestě (např. při balení licence s projektem), ujistěte se, že relativní základ je umístění skriptu, nikoli aktuální adresář shellu. + +### Ošetření chybějících souborů + +Pokud je cesta špatná nebo je soubor nečitelný, `set_license` vyvolá výjimku. Zabalte volání do bloku `try/except`, aby se zobrazila přátelská chybová zpráva: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Tento úryvek **bezpečně nastavuje cestu k licenci** a řekne vám přesně, co se pokazilo – žádné tajemné stack trace. + +## Krok 5: Ověření, že licence je aktivní + +Rychlá kontrola rozumu ušetří hodiny ladění později. Po zavolání `set_license` vyzkoušejte jednoduchou OCR operaci. Pokud je licence platná, SDK zpracuje obrázek bez vyhození licenční chyby. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Pokud se vám vytiskne rozpoznaný text, gratulujeme – úspěšně jste **vytvořili instanci licence** a **nastavili cestu k licenci**. Pokud obdržíte licenční výjimku, zkontrolujte znovu cestu a oprávnění k souboru. + +## Okrajové případy a osvědčené postupy + +| Situace | Co dělat | +|-----------|------------| +| **Licenční soubor je na síťovém sdílení** | Přiřaďte sdílení k písmenku jednotky nebo použijte UNC cestu (`\\server\share\license.lic`). Zajistěte, aby proces Python měl přístup ke čtení. | +| **Běh uvnitř Docker kontejneru** | Zkopírujte soubor `.lic` do obrazu a odkažte na něj pomocí absolutní cesty, např. `/app/license/Aspose.OCR.Java.lic`. | +| **Více Python interpreterů** (např. conda envs) | Nainstalujte licenční soubor jednou pro každé prostředí nebo udržujte centrální umístění a nasměrujte každý interpreter na něj. | +| **Licenční soubor chybí za běhu** | Elegantně přejděte do zkušebního režimu (pokud je podporován) nebo ukončete s jasnou logovací zprávou. | + +### Běžné úskalí + +- **Používání lomítek (`/`) na Windows** – Python je akceptuje, ale některé starší verze SDK je mohou špatně interpretovat. Držte se raw stringů nebo dvojitých zpětných lomítek. +- **Zapomněli jste importovat `License`** – Skript spadne s `NameError`. Vždy importujte před vytvořením instance. +- **Volání `set_license` po OCR metodách** – SDK kontroluje licenci při prvním použití, takže cestu nastavte **jako první**. + +## Kompletní funkční příklad + +Níže je kompletní skript, který spojuje vše dohromady. Uložte jej jako `ocr_setup.py` a spusťte z příkazové řádky. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Očekávaný výstup** (při platném obrázku): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Pokud se licenční soubor nepodaří najít, uvidíte jasnou chybovou zprávu místo kryptické výjimky „License not found“. + +--- + +## Závěr + +Nyní přesně víte, jak **vytvořit instanci licence** v Pythonu a **nastavit cestu k licenci** pro Aspose OCR SDK. Kroky jsou jednoduché: nainstalujte balíček, importujte `License`, vytvořte jeho instanci, nasměrujte ji na váš soubor `.lic` a ověřte pomocí malého OCR testu. + +S tímto know-how můžete vložit OCR funkce do webových služeb, desktopových aplikací nebo automatizovaných pipeline, aniž byste narazili na licenční chyby. Dále můžete zkoumat pokročilá nastavení OCR – jazykové balíčky, předzpracování obrázků nebo dávkové zpracování – která staví na pevné základně, kterou jste právě vytvořili. + +Máte otázky ohledně nasazení, Dockeru nebo správy více licencí? Zanechte komentář a šťastné programování! + +## Co byste se měli naučit dál? + +- [Aspose OCR tutoriál – optické rozpoznávání znaků](/ocr/english/) +- [Jak nastavit licenci a ověřit Aspose.OCR licenci v Javě](/ocr/english/java/ocr-basics/set-license/) +- [Jak provést OCR textu z obrázku s jazykem pomocí Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/czech/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..3a99a25de --- /dev/null +++ b/ocr/czech/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Vytvořte prohledávatelný PDF ze skenovaných obrázků pomocí Python OCR. + Naučte se, jak převést PDF se skenovaným obrázkem, převést TIFF na PDF a během několika + minut přidat OCR textovou vrstvu. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: cs +og_description: Vytvořte okamžitě prohledávatelný PDF. Tento průvodce ukazuje, jak + spustit OCR, převést naskenovaný PDF obrázek a přidat OCR textovou vrstvu pomocí + jediného Python skriptu. +og_title: Vytvořte prohledávatelný PDF pomocí Pythonu – kompletní tutoriál +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Vytvořte prohledávatelný PDF pomocí Pythonu – krok za krokem +url: /cs/python-java/general/create-searchable-pdf-with-python-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 pomocí Pythonu – krok za krokem + +Už jste se někdy zamýšleli, jak **vytvořit prohledávatelné PDF** ze skenované stránky, aniž byste museli balit desítky nástrojů? Nejste v tom sami. V mnoha kancelářských pracovních postupech se naskenovaný TIFF nebo JPEG uloží na sdílený disk a další osoba musí text ručně kopírovat a vkládat – bolestivé, náchylné k chybám a ztrátě času. + +V tomto tutoriálu projdeme čistým, programovým řešením, které vám umožní **převést skenovaný obrázek PDF**, **převést TIFF do PDF** a **přidat OCR textovou vrstvu** najednou. Na konci budete mít připravený skript, který spustí OCR, vloží skrytý text a vytvoří prohledávatelné PDF, které můžete indexovat, vyhledávat nebo sdílet s jistotou. + +## Co budete potřebovat + +- Python 3.9+ (jakákoli novější verze funguje) +- balíčky `aspose-ocr` a `aspose-pdf` (instalované pomocí `pip install aspose-ocr aspose-pdf`) +- Naskenovaný obrázek (`.tif`, `.png`, `.jpg` nebo i PDF stránka, která je jen obrázek) +- Mírné množství RAM (OCR engine je nenáročný; i notebook to zvládne) + +> **Tip:** Pokud používáte Windows, nejjednodušší způsob, jak získat balíčky, je spustit příkaz v oprávněném PowerShell okně. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Nyní, když jsou předpoklady za sebou, ponořme se do kódu. + +## Krok 1: Vytvoření instance OCR engine – *create searchable pdf* + +První věc, kterou uděláme, je spuštění OCR engine. Představte si ho jako mozek, který přečte každý pixel a přemění jej na znaky. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Proč je to důležité:** Inicializace engine jen jednou udržuje nízkou spotřebu paměti. Kdybyste volali `OcrEngine()` uvnitř smyčky pro každou stránku, rychle byste vyčerpali zdroje. + +## Krok 2: Načtení skenovaného obrázku – *convert tiff to pdf* & *convert scanned image pdf* + +Dále nasměrujte engine na soubor, který chcete zpracovat. API přijímá libovolný rastrový obrázek, takže TIFF funguje stejně dobře jako JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Pokud máte PDF, které obsahuje jen skenovaný obrázek, můžete stále použít `load_image`, protože Aspose automaticky extrahuje první stránku. + +## Krok 3: Příprava možností uložení PDF – *add OCR text layer* + +Zde konfigurujeme, jak má finální PDF vypadat. Klíčovým příznakem je `create_searchable_pdf`; nastavení na `True` říká knihovně, aby vložila neviditelnou textovou vrstvu, která odráží vizuální obsah. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Co textová vrstva dělá:** Když otevřete výsledný soubor v Adobe Reader a pokusíte se vybrat text, uvidíte skryté znaky. Vyhledávače je také mohou indexovat – ideální pro soulad nebo archivaci. + +## Krok 4: Spuštění OCR a uložení – *how to run OCR* v jediném volání + +Nyní se děje magie. Jedno volání metody spustí rozpoznávací engine a zapíše prohledávatelné PDF na disk. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Metoda `recognize` vrací objekt stavu, který můžete zkontrolovat na chyby, ale pro většinu jednoduchých scénářů je výše uvedené volání dostačující. + +### Očekávaný výstup + +Spuštění skriptu vypíše: + +``` +PDF saved as searchable PDF. +``` + +Pokud otevřete `scanned_page_searchable.pdf`, všimnete si, že můžete vybrat text, zkopírovat ho a dokonce provést hledání `Ctrl+F`. To je znak workflow **create searchable pdf**. + +## Kompletní funkční skript + +Níže je kompletní, připravený ke spuštění skript. Stačí nahradit zástupné cesty skutečnými umístěními souborů. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Uložte tento soubor jako `create_searchable_pdf.py` a spusťte: + +```bash +python create_searchable_pdf.py +``` + +## Často kladené otázky a okrajové případy + +### 1️⃣ Můžu zpracovávat vícestránkové PDF? + +Ano. Použijte `ocr_engine.load_image("file.pdf")` a poté projděte každou stránku pomocí `ocr_engine.recognize(pdf_save_options, page_number)`. Knihovna automaticky vygeneruje vícestránkové prohledávatelné PDF. + +### 2️⃣ Co když je můj zdrojový soubor vysoké rozlišení TIFF (300 dpi+)? + +Vyšší DPI poskytuje lepší přesnost OCR, ale také vyšší spotřebu paměti. Pokud narazíte na `MemoryError`, nejprve zmenšete velikost obrázku: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Jak změním jazyk OCR? + +Nastavte vlastnost `language` na engine před načtením obrázku: + +```python +ocr_engine.language = "fra" # French +``` + +Úplný seznam podporovaných jazykových kódů najdete v dokumentaci Aspose. + +### 4️⃣ Co když potřebuji zachovat původní kvalitu obrázku? + +Třída `PdfSaveOptions` má vlastnost `compression`. Nastavte ji na `PdfCompression.None`, aby se rasterová data zachovala přesně tak, jak byla. + +```python +pdf_save_options.compression = "None" +``` + +## Tipy pro nasazení v produkčním prostředí + +- **Dávkové zpracování:** Zabalte hlavní logiku do funkce, která přijímá seznam cest k souborům. Každý úspěch/neúspěch zaznamenejte do CSV pro auditní stopy. +- **Paralelizace:** Použijte `concurrent.futures.ThreadPoolExecutor` k běhu OCR na více jádrech. Pamatujte, že každý vláken potřebuje svou vlastní instanci `OcrEngine`. +- **Bezpečnost:** Pokud pracujete s citlivými dokumenty, spusťte skript v sandboxovaném prostředí a po zpracování okamžitě odstraňte dočasné soubory. + +## Závěr + +Nyní víte, jak **vytvořit prohledávatelné PDF** soubory ze skenovaných obrázků pomocí stručného Python skriptu. Inicializací OCR engine, načtením TIFF (nebo libovolného rastrového souboru), konfigurací `PdfSaveOptions` pro **add OCR text layer** a nakonec voláním `recognize` se celý pipeline **convert scanned image pdf** a **convert TIFF to PDF** promění v jediný, opakovatelný příkaz. + +Další kroky? Zkuste propojit tento skript s monitorovacím nástrojem, aby se jakýkoli nový sken přetáhlý do složky automaticky stal prohledávatelným. Nebo experimentujte s různými jazyky OCR pro podporu vícejazykových archivů. Možnosti jsou neomezené, když spojíte OCR s generováním PDF. + +Máte další otázky ohledně **how to run OCR** v jiných jazycích nebo rámcích? Zanechte komentář níže a šťastné programování! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## Co byste se měli naučit dál? + +- [Jak provést OCR PDF v .NET s Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Převod obrázků do PDF C# – Uložení vícestránkového OCR výsledku](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Jak provést OCR textu z obrázku s jazykem pomocí Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/czech/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f5c064dc8 --- /dev/null +++ b/ocr/czech/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-31 +description: Zlepšete přesnost OCR pomocí Pythonu předzpracováním obrázků pro OCR. + Naučte se, jak extrahovat text z obrazových souborů, rozpoznávat text z PNG a zvýšit + výsledky. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: cs +og_description: Zvyšte přesnost OCR v Pythonu pomocí předzpracování obrazu pro text. + Postupujte podle tohoto návodu a snadno extrahujte text z obrazových souborů a rozpoznávejte + text z PNG. +og_title: Zlepšete přesnost OCR v Pythonu – kompletní tutoriál +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Zlepšete přesnost OCR v Pythonu – Kompletní krok‑za‑krokem průvodce +url: /cs/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-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í krok‑za‑krokem průvodce + +Už jste se někdy pokusili **zlepšit přesnost OCR**, ale výstup byl jen nesrozumitelný? Nejste v tom sami. Většina vývojářů narazí na problém, když je surový obrázek šumivý, nakřivo nebo prostě jen málo kontrastní. Dobrá zpráva? Několik triků pro předzpracování může proměnit rozmazaný snímek obrazovky v čistý, strojově čitelný text. + +V tomto tutoriálu projdeme reálný příklad, který **předzpracuje obrázek pro OCR**, spustí rozpoznávací engine a nakonec **extrahuje text z obrázku** – konkrétně z PNG. Na konci přesně vědět, jak **rozpoznat text z PNG** s vyšší úspěšností, a budete mít znovupoužitelný úryvek kódu, který můžete vložit do jakéhokoli projektu. + +## Co se naučíte + +- Proč je předzpracování obrazu důležité pro OCR enginy +- Které režimy předzpracování (odšumění, korekce sklonu) přinášejí největší zlepšení +- Jak nakonfigurovat instanci `OcrEngine` v Pythonu +- Kompletní spustitelný skript, který **extrahuje text z obrázku** +- Tipy pro řešení okrajových případů, jako jsou otočené skeny nebo obrázky s nízkým rozlišením + +Kromě OCR SDK nejsou potřeba žádné externí knihovny, ale budete potřebovat Python 3.8+ a PNG obrázek, který chcete přečíst. + +--- + +![Diagram ukazující kroky ke zlepšení přesnosti OCR v Pythonu](image.png "Pracovní postup ke zlepšení přesnosti OCR") + +*Alt text: diagram pracovního postupu ke zlepšení přesnosti OCR, ilustrující kroky předzpracování a rozpoznání.* + +## Požadavky + +- Python 3.8 nebo novější nainstalovaný +- Přístup k OCR SDK, který poskytuje `OcrEngine`, `OcrEngineSettings` a `ImagePreprocessMode` (níže uvedený kód používá obecné API; v případě potřeby jej nahraďte třídami vašeho dodavatele) +- PNG obrázek (`input.png`) umístěný ve složce, na kterou můžete odkazovat + +Pokud používáte virtuální prostředí, aktivujte jej nyní – nic složitého, jen `python -m venv venv && source venv/bin/activate`. + +--- + +## Krok 1: Vytvořte instanci OCR Engine – Začněte zlepšovat přesnost OCR + +První, co potřebujete, je objekt OCR engine. Představte si ho jako mozek, který později přečte pixely a vygeneruje znaky. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Proč je to důležité: bez enginu nemůžete použít žádné předzpracování a surový obrázek bude předán přímo rozpoznávači – obvykle nejhorší scénář pro přesnost. + +--- + +## Krok 2: Načtěte cílový PNG – Připravte podmínky pro rozpoznání textu z PNG + +Nyní řekneme enginu, který soubor má zpracovat. PNG je bezztrátový, což nám už dává malou výhodu oproti JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Pokud je obrázek někde jinde, stačí upravit cestu. Engine přijímá jakýkoli podporovaný formát, ale PNG často zachovává jemné detaily potřebné pro ostré hrany znaků. + +--- + +## Krok 3: Nakonfigurujte předzpracování – Předzpracujte obrázek pro OCR + +Zde se děje kouzlo. Vytvoříme objekt nastavení, povolíme odšumění, aby se odstranily šmouhy, a zapneme korekci sklonu, aby se šikmý text automaticky narovnal. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Proč odšumění + korekce sklonu? + +- **Denoise**: Náhodný šum pixelů mate algoritmy pro porovnávání vzorů. Jeho odstranění zaostří písmena. +- **Deskew**: Už 2‑stupňový náklon může dramaticky snížit skóre důvěry. Korekce sklonu zarovná základní linii, což umožní rozpoznávači spolehlivěji porovnávat fonty. + +Můžete experimentovat s dalšími příznaky (např. `ImagePreprocessMode.CONTRAST_ENHANCE`), pokud jsou vaše obrázky zvláště tmavé. Dokumentace SDK obvykle uvádí všechny dostupné režimy. + +--- + +## Krok 4: Aplikujte nastavení na engine – Propojte předzpracování s OCR + +Přiřaďte objekt nastavení enginu, aby další spuštění rozpoznávání použilo transformace, které jsme právě definovali. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Pokud tento krok přeskočíte, engine se vrátí k výchozímu nastavení (často „žádné předzpracování“) a uvidíte **nižší přesnost OCR**. + +--- + +## Krok 5: Spusťte proces rozpoznávání – Extrahujte text z obrázku + +Po nastavení všeho, konečně požádáme engine, aby udělal svou práci. Volání je synchronní a vrací objekt výsledku, který obsahuje rozpoznaný řetězec. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +V pozadí engine nyní: +1. Načte PNG do paměti +2. Aplikuje odšumění a korekci sklonu podle našich nastavení +3. Spustí neuronovou síť nebo klasický porovnávač vzorů +4. Zabalí výstup do `recognition_result` + +--- + +## Krok 6: Vypište rozpoznaný text – Ověřte zlepšení + +Vytiskněme extrahovaný řetězec. Ve skutečné aplikaci jej můžete zapsat do souboru, databáze nebo předat dalšímu servisu. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Očekávaný výstup + +Pokud obrázek obsahuje větu „Hello, OCR World!“, měli byste vidět: + +``` +Hello, OCR World! +``` + +Všimněte si, že text je čistý – žádné cizí symboly ani poškozené znaky. To je výsledek správného **předzpracování obrazu pro text**. + +--- + +## Pro tipy a okrajové případy + +| Situace | Co upravit | Proč | +|-----------|----------------|-----| +| Velmi nízké rozlišení PNG (≤ 72 dpi) | Přidejte `ImagePreprocessMode.SUPER_RESOLUTION`, pokud je k dispozici | Upsampling může poskytnout rozpoznávači více pixelů ke zpracování | +| Text je otočen > 5° | Zvyšte toleranci korekce sklonu nebo ručně otočte pomocí `Pillow` před předáním enginu | Extrémní úhly někdy obejdou automatickou korekci sklonu | +| Silné vzory na pozadí | Povolte `ImagePreprocessMode.BACKGROUND_REMOVAL` | Odstraní ne‑textové rušení, které by jinak bylo špatně přečteno | +| Vícejazyčný dokument | Nastavte `ocr_engine.language = "eng+spa"` (nebo podobně) | Engine vybere správnou znakovou sadu, čímž zlepší celkovou přesnost | + +Pamatujte, **zlepšení přesnosti OCR** není univerzální řešení; možná budete muset iterovat s příznaky předzpracování pro váš konkrétní dataset. + +--- + +## Kompletní skript – připravený ke kopírování a vložení + +Níže je kompletní, spustitelný příklad, který zahrnuje všechny kroky, o kterých jsme mluvili. Uložte jej jako `improve_ocr_accuracy.py` a spusťte pomocí `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Spusťte jej, sledujte konzoli a okamžitě uvidíte výsledek **extrahování textu z obrázku**. Pokud výstup vypadá špatně, upravte příznaky `preprocess_mode` podle tabulky „Pro tipy“. + +--- + +## Závěr + +Právě jsme prošli praktický návod, jak **zlepšit přesnost OCR** pomocí Pythonu. Vytvořením `OcrEngine`, načtením PNG, **předzpracováním obrázku pro OCR** a nakonec **rozpoznáním textu z PNG** můžete spolehlivě **extrahovat text z obrázku**, i když zdroj není dokonalý. + +Další kroky? Zkuste zpracovat dávku obrázků ve smyčce, uložit každý výsledek do CSV, nebo experimentovat s dalšími režimy předzpracování, jako je zvýšení kontrastu. Stejný postup funguje pro PDF, naskenované účtenky nebo ručně psané poznámky – stačí vyměnit vstup a upravit nastavení. + +Máte otázky ohledně konkrétního typu obrázku nebo chcete vědět, jak to integrovat do webové služby? Zanechte komentář a společně prozkoumáme tyto scénáře. Šťastné kódování a ať jsou vaše OCR výsledky vždy průzračně čisté! + +## Co byste se měli naučit dál? + +- [Extrahovat text z obrázku s 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ázku – Optimalizace OCR s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) +- [Jak extrahovat text z obrázku přípravou obdélníků v OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/czech/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..d89aa017f --- /dev/null +++ b/ocr/czech/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-31 +description: Naučte se, jak použít oblast zájmu OCR k načtení obrázku pro OCR a extrahování + textu z obdélníku, ideální pro rozpoznání částky na faktuře. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: cs +og_description: Ovládněte oblast zájmu OCR pro načtení obrázku, extrahujte text z + obdélníku a rozpoznávejte text z faktury v jednom tutoriálu. +og_title: OCR oblast zájmu – krok za krokem průvodce v Pythonu +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR oblast zájmu – extrahovat text z obdélníku v Pythonu +url: /cs/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR oblast zájmu – Extrahování textu z obdélníku v Pythonu + +Už jste se někdy zamýšleli, jak **ocr region of interest** konkrétní část naskenované faktury, aniž byste do enginu nahrávali celou stránku? Nejste první, kdo se dívá na rozmazaný účtenku a přemýšlí: “Jak získat částku, která je někde v pravém dolním rohu?” Dobrou zprávou je, že můžete OCR knihovně přesně říct, kde má hledat, což dramaticky zvyšuje jak rychlost, tak přesnost. + +V tomto průvodci projdeme kompletním, spustitelným příkladem, který vám ukáže, jak **load image for OCR**, definovat **region of interest**, a pak **extract text from rectangle**, abyste nakonec **recognize text from invoice** a odpověděli na klasickou otázku „jak extrahovat částku“. Žádné vágní odkazy – jen konkrétní kód, jasná vysvětlení a několik tipů, které byste si přáli vědět dříve. + +--- + +## Co si vytvoříte + +Na konci tohoto tutoriálu budete mít malý Python skript, který: + +1. Načte obrázek faktury z disku. +2. Označí obdélníkovou ROI, kde se nachází celková částka. +3. Spustí OCR pouze uvnitř této ROI. +4. Vytiskne vyčištěný řetězec částky. + +Vše funguje s libovolnou OCR knihovnou, která podporuje ROI – zde použijeme fiktivní, ale reprezentativní balíček `SimpleOCR`, který napodobuje populární nástroje jako Tesseract nebo EasyOCR. Klidně jej zaměňte; koncepty zůstávají stejné. + +## Požadavky + +- Python 3.8+ nainstalovaný (`python --version` by měl ukazovat ≥3.8). +- Pip‑instalovatelný OCR balíček (např. `pip install simpleocr`). +- Obrázek faktury (PNG nebo JPEG) umístěný ve složce, na kterou můžete odkazovat. +- Základní znalost funkcí a tříd v Pythonu (nic složitého). + +Pokud už to máte, skvělé – ponořme se dál. Pokud ne, nejprve stáhněte obrázek; zbytek kroků je nezávislý na skutečném obsahu souboru. + +## Krok 1: Načtení obrázku pro OCR + +První věc, kterou jakýkoli OCR workflow potřebuje, je bitmapa, ze které může číst. Většina knihoven poskytuje jednoduchou metodu `load_image`, která přijímá cestu k souboru. Zde je, jak to udělat s naším `SimpleOCR` enginem: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Používejte absolutní cesty nebo `os.path.join`, abyste se vyhnuli překvapením typu „soubor nenalezen“ při spouštění skriptu z jiného pracovního adresáře. + +## Krok 2: Definování OCR oblasti zájmu + +Místo toho, aby engine skenoval celou stránku, řekneme mu *přesně*, kde se částka nachází. Toto je krok **ocr region of interest** a je klíčem k spolehlivému extrahování, zejména když dokument obsahuje šumivé hlavičky nebo patičky. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Proč tyto čísla? `x` a `y` jsou pixelové offsety od levého horního rohu, zatímco `width` a `height` popisují velikost boxu. Pokud si nejste jisti, otevřete obrázek v libovolném editoru, zapněte pravítko a poznamenejte si souřadnice. Mnoho IDE dokonce umožňuje zobrazit pozici kurzoru při najetí. + +## Krok 3: Extrahování textu z obdélníku + +Nyní, když je ROI nastavená, požádáme engine o **recognize text from invoice**, ale omezený na obdélník, který jsme právě přidali. Volání vrací objekt výsledku, který typicky obsahuje surový řetězec, skóre důvěry a někdy i ohraničující boxy. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Za scénou `recognize()` iteruje přes každou ROI, ořízne daný výřez, spustí OCR model a spojí výsledky dohromady. Proto definování úzké **extract text from rectangle** oblasti může ušetřit sekundy při zpracování dávkových úloh. + +## Krok 4: Jak extrahovat částku – vyčistit výstup + +OCR není dokonalé; často získáte nadbytečné mezery, konce řádků nebo dokonce špatně přečtené znaky (např. “S” místo “5”). Rychlé `strip()` a malý regex obvykle stačí pro peněžní hodnoty. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Proč je to důležité:** Pokud plánujete částku vložit do databáze nebo platební brány, potřebujete předvídatelný formát. Odstranění bílých znaků a filtrování ne‑číselných znaků zabraňuje chybám v dalším zpracování. + +## Krok 5: Rozpoznání textu z faktury – Kompletní skript + +Sestavíme vše dohromady, zde je kompletní, připravený ke spuštění skript. Uložte jej jako `extract_amount.py` a spusťte `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Očekávaný výstup + +``` +Amount: 1,245.67 +``` + +Pokud je ROI špatně zarovnaná, můžete vidět něco jako `Amount: 1245.6S` – všimněte si nadbytečného “S”. Upravit souřadnice obdélníku a znovu spustit, dokud výstup nebude čistý. + +## Běžné problémy a okrajové případy + +| Problém | Proč k tomu dochází | Řešení | +|---------|----------------------|--------| +| **ROI příliš malý** | Text částky je oříznutý, což vede k částečnému rozpoznání. | Zvětšete `width`/`height` o ~10‑20 % a znovu otestujte. | +| **Nesprávné DPI** | Nízké rozlišení skenů (≤150 dpi) snižuje přesnost OCR. | Převzorkujte obrázek na 300 dpi před načtením, nebo požádejte skener o vyšší DPI. | +| **Více měn** | Regex vybere první číselnou skupinu, která může být číslem faktury. | Upravte regex tak, aby hledal měnové symboly (`$`, `€`, `£`) před číslicemi. | +| **Otočené faktury** | OCR enginy předpokládají svislý text; otočené stránky narušují rozpoznání. | Aplikujte korekci rotace (`ocr_engine.rotate(90)`) před přidáním ROI. | +| **Šum na pozadí** | Stíny nebo razítka zmatení model. | Předzpracujte jednoduchým prahem (`cv2.threshold`) nebo použijte filtr na odstranění šumu. | + +Řešení těchto okrajových případů včas vám ušetří hodiny ladění později. + +## Pro tipy pro reálné projekty + +- **Batch Processing:** Procházejte složku s fakturami, dynamicky vypočítejte ROI (např. na základě detekce šablony) a uložte výsledky do CSV. +- **Template Matching:** Pokud pracujete s několika rozvrženími faktur, udržujte JSON mapu `template_id → ROI coordinates`. Přepínejte ROI podle rychlého klasifikátoru rozvržení. +- **Parallel Execution:** Použijte `concurrent.futures.ThreadPoolExecutor` k souběžnému spuštění více OCR instancí – skvělé pro vysokovýkonné back‑office pipeline. +- **Confidence Filtering:** Většina OCR výsledků obsahuje skóre důvěry. Odmítněte výsledky pod určitým prahem (např. 85 %) a označte je k ruční kontrole. + +## Závěr + +Probrali jsme vše, co potřebujete k **ocr region of interest**, **load image for OCR**, **extract text from rectangle** a nakonec **recognize text from invoice**, abyste odpověděli na klasickou otázku **how to extract amount**. Skript je kompaktní, ale dostatečně flexibilní, aby se přizpůsobil různým formátům dokumentů, jazykům i OCR backendům. + +Nyní, když ovládáte základy, zvažte rozšíření workflow: přidejte skenování čárových kódů, integraci s PDF parserem nebo odeslání extrahované částky do účetního API. Možnosti jsou neomezené a s dobře definovanou ROI získáte vždy rychlejší a čistší výsledky. + +Pokud narazíte na problém, zanechte komentář níže – šťastné OCRování! + +![příklad oblasti zájmu OCR](https://example.com/ocr_roi_example.png "příklad oblasti zájmu OCR") + + +## Co byste se měli naučit dál? + +- [Jak extrahovat text z obrázku přípravou obdélníků v OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extrahování textu z obrázku v Javě s Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Extrahování textu z obrázku – OCR optimalizace s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/dutch/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..bd4991fd2 --- /dev/null +++ b/ocr/dutch/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Async OCR‑tutorial die laat zien hoe je Aspose OCR in Python met asyncio + gebruikt voor snelle tekstextractie uit afbeeldingen. Leer stap‑voor‑stap asynchrone + OCR‑implementatie. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: nl +og_description: De async OCR-tutorial leidt je door het gebruik van Aspose OCR in + Python met asyncio voor efficiënte tekstextractie uit afbeeldingen. +og_title: Async OCR-tutorial – Python asyncio met Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Async OCR‑tutorial – Python asyncio met Aspose OCR +url: /nl/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR Tutorial – Python asyncio met Aspose OCR + +Heb je je ooit afgevraagd hoe je optische tekenherkenning kunt uitvoeren zonder je app te blokkeren? In een **async OCR tutorial** zie je precies dat—niet‑blokkerende tekstanalyse met Python’s `asyncio` en de Aspose OCR‑bibliotheek. + +Als je vastzat in het wachten op de verwerking van een zware afbeelding, biedt deze gids een nette, asynchrone oplossing die je event‑loop soepel laat draaien. + +In de volgende secties behandelen we alles wat je nodig hebt: de bibliotheek installeren, een asynchrone helper opzetten, het resultaat afhandelen, en zelfs een snelle tip voor het schalen naar meerdere afbeeldingen. Aan het einde kun je een **async OCR tutorial** in elk Python‑project dat al `asyncio` gebruikt, plaatsen. + +## Wat je nodig hebt + +Voordat we beginnen, zorg dat je het volgende hebt: + +* Python 3.9+ (de `asyncio`‑API die we gebruiken is stabiel vanaf 3.7) +* Een actieve Aspose OCR‑licentie of een gratis proefversie (de bibliotheek is pure‑Python, zonder native binaries) +* Een klein afbeeldingsbestand (`.jpg`, `.png`, enz.) dat je wilt lezen – bewaar het in een bekende map + +Geen andere externe tools zijn vereist; alles draait in pure Python. + +## Stap 1: Installeer het Aspose OCR‑pakket + +Allereerst, haal het Aspose OCR‑pakket op van PyPI. Open een terminal en voer uit: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Als je binnen een virtuele omgeving werkt (sterk aanbevolen), activeer deze eerst. Zo blijven afhankelijkheden geïsoleerd en voorkom je versieconflicten. + +## Stap 2: Initialiseert de OCR‑engine asynchroon + +Het hart van onze **async OCR tutorial** is een asynchrone helper‑functie. Deze maakt een `OcrEngine`‑instance, laadt een afbeelding, en roept vervolgens `recognize_async()` aan. De engine zelf is synchroon, maar de wrapper‑methode retourneert een awaitable, waardoor de event‑loop responsief blijft. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Waarom we het op deze manier doen:** +*Het aanmaken van de engine binnen de helper zorgt voor thread‑veiligheid als je later veel OCR‑taken parallel wilt uitvoeren. Het `await`‑keyword geeft de controle terug aan de event‑loop terwijl het zware werk in de interne thread‑pool van de bibliotheek plaatsvindt.* + +## Stap 3: Roep de helper aan vanuit een async‑main‑functie + +Nu hebben we een kleine `main()`‑coroutine nodig die `async_ocr()` aanroept en het resultaat afdrukt. Dit weerspiegelt het typische entry‑point voor een `asyncio`‑script. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Wat gebeurt er onder de motorkap?** +`asyncio.run()` maakt een frisse event‑loop, plant `main()` in, en sluit de loop netjes af zodra `main()` klaar is. Dit patroon is de aanbevolen manier om asynchrone programma’s te starten in Python 3.7+. + +## Stap 4: Test het volledige script + +Sla de twee code‑blokken hierboven op in één bestand, bijvoorbeeld `async_ocr_demo.py`. Voer het uit vanaf de commandoregel: + +```bash +python async_ocr_demo.py +``` + +Als alles correct is ingesteld, zie je iets als: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +De exacte output hangt af van de inhoud van `photo.jpg`. Het belangrijkste is dat het script snel eindigt, zelfs bij een grote afbeelding, omdat het OCR‑werk op de achtergrond plaatsvindt. + +## Stap 5: Schalen – Verwerk meerdere afbeeldingen gelijktijdig + +Een veelgestelde vervolg‑vraag is: *“Kan ik een batch bestanden OCR‑en zonder voor elk een nieuw proces te starten?”* Absoluut. Omdat onze helper volledig asynchroon is, kunnen we veel coroutines verzamelen met `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Waarom dit werkt:** `asyncio.gather()` plant alle OCR‑taken tegelijk. De onderliggende Aspose OCR‑bibliotheek gebruikt nog steeds zijn eigen thread‑pool, maar vanuit Python‑perspectief blijft alles niet‑blokkerend, zodat je tientallen afbeeldingen kunt verwerken in de tijd die een enkele synchrone oproep zou kosten. + +## Stap 6: Fouten netjes afhandelen + +Wanneer je met externe bestanden werkt, kom je onvermijdelijk ontbrekende bestanden, corrupte afbeeldingen of licentie‑problemen tegen. Om de event‑loop levend te houden, wikkel je de OCR‑aanroep in een `try/except`‑blok: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Nu kan `batch_ocr()` `safe_async_ocr` aanroepen, waardoor één slechte file niet de hele batch laat afbreken. + +## Visueel overzicht + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial stroomdiagram dat async_ocr helper, event loop en Aspose OCR engine toont"} + +Het diagram hierboven visualiseert de stroom: de event‑loop → `async_ocr` → `OcrEngine` → achtergrond‑thread → resultaat terug naar de loop. + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|--------------------|----------| +| **Blocking I/O binnen de helper** | Per ongeluk `open()` gebruiken zonder `await` blokkeert de loop. | Gebruik `aiofiles` voor bestandslezingen, of laat `engine.load_image` het doen (dat is al niet‑blokkerend). | +| **Herhaaldelijk gebruiken van één `OcrEngine` in coroutines** | De engine is niet thread‑safe; gelijktijdige aanroepen kunnen de staat corrupt maken. | Maak binnen elke `async_ocr`‑call een verse engine aan (zoals getoond). | +| **Ontbrekende licentie** | Aspose OCR gooit een licentie‑gerelateerde exceptie tijdens runtime. | Registreer je licentie vroeg (`OcrEngine.set_license("license.json")`). | +| **Grote afbeeldingen veroorzaken geheugenpieken** | De bibliotheek laadt de volledige afbeelding in RAM. | Schaal afbeeldingen eerst down voordat je OCR toepast als geheugen een zorg is. | + +## Samenvatting: Wat we hebben bereikt + +In deze **async OCR tutorial** hebben we: + +1. Het Aspose OCR‑pakket geïnstalleerd. +2. Een `async_ocr`‑helper gebouwd die herkenning uitvoert zonder te blokkeren. +3. De helper aangeroepen vanuit een nette `asyncio`‑entry‑point. +4. Batch‑verwerking gedemonstreerd met `asyncio.gather`. +5. Foutafhandeling en best‑practice‑tips toegevoegd. + +Alles is pure Python, dus je kunt het in een web‑server, een CLI‑tool of een data‑pipeline stoppen zonder bestaande async‑code te herschrijven. + +## Volgende stappen & gerelateerde onderwerpen + +* **Asynchrone afbeelding‑preprocessing** – gebruik `aiohttp` om afbeeldingen gelijktijdig te downloaden vóór OCR. +* **OCR‑resultaten opslaan** – combineer deze tutorial met een async database‑driver zoals `asyncpg` voor PostgreSQL. +* **Prestatie‑optimalisatie** – experimenteer met `engine.recognize_async(max_threads=4)` als de bibliotheek zo’n optie biedt. +* **Alternatieve OCR‑engines** – vergelijk Aspose OCR met de async‑wrappers van Tesseract voor een kosten‑batenanalyse. + +Voel je vrij om te experimenteren: probeer PDF’s te verwerken, pas taalinstellingen aan, of koppel de resultaten aan een chatbot. De mogelijkheden zijn eindeloos zodra je een solide **async OCR tutorial**‑basis hebt. + +Happy coding, en moge je tekstanalyse altijd snel gaan! + + +## Wat moet je hierna leren? + +- [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/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/dutch/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..4051453f5 --- /dev/null +++ b/ocr/dutch/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Automatische taaldetectie in OCR eenvoudig gemaakt. Leer hoe je afbeelding‑OCR + laadt, automatische taaldetectie inschakelt en tekst in een afbeelding herkent in + slechts een paar stappen. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: nl +og_description: Automatische taalherkenning in OCR eenvoudig gemaakt. Volg deze stapsgewijze + tutorial om automatische taaldetectie in te schakelen, afbeelding‑OCR te laden en + tekst in een afbeelding te herkennen. +og_title: Automatische taaldetectie met OCR – Complete Python-gids +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatische taaldetectie met OCR – Complete Python‑gids +url: /nl/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatische Taalherkenning met OCR – Complete Python Gids + +Heb je je ooit afgevraagd hoe je een OCR‑engine *laat raden* welke taal een gescand document heeft zonder dat je het vertelt waar het op moet letten? Dat is precies wat **automatische taalherkenning** doet, en het is een echte game‑changer wanneer je werkt met meertalige PDF‑bestanden, foto’s van verkeersborden, of elke afbeelding die verschillende schriftsoorten combineert. + +In deze tutorial lopen we een praktische voorbeeld stap voor stap door dat laat zien hoe je **automatische taalherkenning inschakelt**, **image OCR laadt**, en **tekst uit afbeelding herkent** met een Python‑achtige API. Aan het einde heb je een zelfstandige script die zowel de gedetecteerde taalcodes als de geëxtraheerde tekst afdrukt — zonder handmatige taalinstellingen. + +## Wat je zult leren + +- Hoe je een OCR‑engine‑instantie maakt en **automatische taalherkenning** inschakelt. +- De exacte stappen om **image OCR** van schijf te **laden**. +- Hoe je de `recognize()`‑methode van de engine aanroept en een resultaat terugkrijgt dat de taalcodes bevat. +- Tips voor het omgaan met randgevallen zoals afbeeldingen met lage resolutie of niet‑ondersteunde scripts. + +Ervaring met meertalige OCR is niet vereist; alleen een basis Python‑installatie en een afbeeldingsbestand. + +--- + +## Vereisten + +Before we dive in, make sure you have: + +1. Python 3.8+ geïnstalleerd (elke recente versie werkt). +2. De OCR‑bibliotheek die `OcrEngine`, `LanguageAutoDetectMode`, enz. levert – voor deze gids gaan we uit van een hypothetisch pakket genaamd `myocr`. Installeer het met: + + ```bash + pip install myocr + ``` + +3. Een afbeeldingsbestand (`multilingual_sample.png`) dat tekst bevat in ten minste twee verschillende talen. +4. Een beetje nieuwsgierigheid—als je nog nooit met OCR hebt gewerkt, maak je geen zorgen; de code is opzettelijk eenvoudig. + +--- + +## Stap 1: Automatische Taalherkenning inschakelen + +Het eerste dat je moet doen is de engine vertellen dat hij zelf de taal moet *bepalen*. Hier komt de **automatische taalherkenning**‑vlag in beeld. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Waarom dit belangrijk is:** +> Wanneer `AUTO_DETECT` is ingesteld, voert de engine een lichtgewicht taalclassificator uit op de afbeelding voordat de zware tekenherkenning start. Dat betekent dat je niet hoeft te raden of de tekst Engels, Russisch, Frans of een combinatie daarvan is. De engine kiest automatisch het beste taamodel voor elk gebied van de afbeelding. + +--- + +## Stap 2: Image OCR Laden + +Nu de engine weet dat hij automatisch talen moet detecteren, moeten we hem iets geven om op te werken. De **load image OCR** stap leest de bitmap en bereidt interne buffers voor. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro tip:** +> Als je afbeelding groter is dan 300 dpi, overweeg dan om deze te verkleinen naar ongeveer 150‑200 dpi. Te veel detail kan de taalherkenningsfase zelfs *vertragen* zonder de nauwkeurigheid te verbeteren. + +--- + +## Stap 3: Tekst uit afbeelding herkennen + +Met de afbeelding in het geheugen en taalherkenning ingeschakeld, is het laatste stap om de engine te vragen **tekst uit afbeelding te herkennen**. Deze enkele aanroep doet al het zware werk. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` is een object dat typisch minstens twee attributen bevat: + +| Attribuut | Beschrijving | +|-----------|--------------| +| `language` | ISO‑639‑1 code van de gedetecteerde taal (bijv. `"en"` voor Engels). | +| `text` | De platte‑tekst transcriptie van de afbeelding. | + +--- + +## Stap 4: Gedetecteerde taal en geëxtraheerde tekst ophalen + +Nu printen we simpelweg wat de engine heeft ontdekt. Dit toont de **detect language OCR**‑functionaliteit in actie. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Voorbeeldoutput** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Wat als de engine `None` retourneert?** +> Dat betekent meestal dat de afbeelding te onscherp is of de tekst te klein (< 8 pt). Probeer het contrast te verhogen of een bron met hogere resolutie te gebruiken. + +--- + +## Volledig Werkend Voorbeeld (Automatische Taalherkenning van Begin tot Eind inschakelen) + +Alles samengevoegd, hier is een kant‑klaar script dat **automatische taalherkenning inschakelt**, **image OCR laadt**, **tekst uit afbeelding herkent**, en **detect language OCR** in één keer uitvoert. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Sla dit op als `automatic_language_detection_ocr.py`, vervang `YOUR_DIRECTORY` door de map die je PNG bevat, en voer uit: + +```bash +python automatic_language_detection_ocr.py +``` + +Je zou de taalcodes moeten zien gevolgd door de geëxtraheerde tekst, net als de voorbeeldoutput hierboven. + +--- + +## Veelvoorkomende Randgevallen Afhandelen + +| Situatie | Aanbevolen oplossing | +|----------|----------------------| +| **Zeer lage resolutie afbeelding** (onder 100 dpi) | Schaal op met een bicubische filter vóór het laden, of vraag een bron met hogere resolutie. | +| **Gemengde scripts in één afbeelding** (bijv. Engels + Cyrillisch) | De engine splitst meestal de pagina in regio's; als je verkeerde detecties ziet, zet `engine.enable_region_split = True`. | +| **Niet‑ondersteunde taal** | Controleer of de OCR‑bibliotheek een taalpakket voor het benodigde script bevat; je moet mogelijk extra modellen downloaden. | +| **Grote batchverwerking** | Initialiseert de engine één keer, en hergebruik deze voor meerdere `load_image` / `recognize` cycli om herhaald laden van modellen te vermijden. | + +--- + +## Visueel Overzicht + +![automatische taalherkenning voorbeeldoutput](https://example.com/auto-lang-detect.png "automatische taalherkenning") + +*Alt‑tekst:* automatische taalherkenning voorbeeldoutput die gedetecteerde taalcodes en geëxtraheerde meertalige tekst toont. + +--- + +## Conclusie + +We hebben zojuist **automatische taalherkenning** van begin tot eind behandeld — het maken van de engine, het inschakelen van automatische taalherkenning, het laden van een afbeelding voor OCR, het herkennen van de tekst, en uiteindelijk het ophalen van de gedetecteerde taal. Deze end‑to‑end workflow laat je meertalige documenten verwerken zonder elke keer handmatig taalmodellen te configureren. + +Als je dit verder wilt uitbreiden, overweeg dan: + +- **Batchverwerking** van honderden afbeeldingen met een lus die dezelfde `OcrEngine`‑instantie hergebruikt. +- **Post‑processing** van de geëxtraheerde tekst met een spellingscontrole of taalspecifieke tokenizer. +- **Integreren** van het script in een webservice die gebruikersuploads accepteert en JSON teruggeeft met `language` en `text` velden. + +Voel je vrij om te experimenteren met verschillende afbeeldingsformaten (`.jpg`, `.tif`) en te zien hoe de detectienauwkeurigheid verandert. Heb je vragen of een lastig beeld dat niet gelezen wil worden? Laat een reactie achter — happy coding! + +## Wat moet je hierna leren? + +- [Hoe OCR-beeldtekst met taal te gebruiken met Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Afbeeldingstekst extraheren C# met taalkeuze met Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [tekst uit afbeelding herkennen met Aspose OCR voor meerdere talen](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f3c9d309f --- /dev/null +++ b/ocr/dutch/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Leer hoe je afbeeldingen naar tekst kunt converteren met Python met een + bulk afbeelding‑naar‑tekst conversiescript. Herken tekst uit gescande afbeeldingen + met Aspose.OCR in enkele minuten. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: nl +og_description: Converteer afbeeldingen direct naar tekst met Python. Deze gids toont + bulkconversie van afbeeldingen naar tekst en hoe je tekst uit gescande afbeeldingen + herkent met Aspose.OCR. +og_title: Afbeeldingen omzetten naar tekst met Python – Volledige tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Afbeeldingen naar Tekst Converteren met Python – Complete Stapsgewijze Gids +url: /nl/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Afbeeldingen naar Tekst Converteren Python – Complete Stapsgewijze Gids + +Heb je je ooit afgevraagd hoe je **afbeeldingen naar tekst python** kunt converteren zonder tientallen bibliotheken te hoeven doorzoeken? Je bent niet de enige. Of je nu oude bonnen digitaliseert, gegevens uit gescande facturen haalt, of een doorzoekbaar archief van PDF‑bestanden wilt opbouwen, het omzetten van afbeeldingen naar platte‑tekstbestanden is een dagelijkse klus voor veel ontwikkelaars. + +In deze tutorial lopen we een **bulk image to text conversion**‑pipeline door die tekst herkent in gescande afbeeldingen, elk resultaat opslaat als een individueel `.txt`‑bestand, en dat alles doet met slechts een paar regels Python. Geen mysterie‑shopping voor obscure API’s—Aspose.OCR doet het zware werk, en we laten je precies zien hoe je het moet aansluiten. + +## Wat je gaat leren + +- Hoe je het Aspose.OCR for Python‑pakket installeert en configureert. +- De exacte code die nodig is om **afbeeldingen naar tekst python** te **convert images to text python** met behulp van de `BatchOcrEngine`. +- Tips voor het omgaan met veelvoorkomende valkuilen zoals niet‑ondersteunde formaten of corrupte bestanden. +- Manieren om te verifiëren dat de stap **recognize text from scanned images** daadwerkelijk geslaagd is. + +Aan het einde van deze gids heb je een kant‑klaar script dat duizenden afbeeldingen in één keer kan verwerken—perfect voor elke batch‑verwerkingsscenario. + +## Vereisten + +- Python 3.8+ geïnstalleerd op je machine. +- Een map met afbeeldingsbestanden (PNG, JPEG, TIFF, enz.) die je wilt omzetten naar tekst. +- Een actief Aspose Cloud‑account of een gratis proeflicentie (de gratis tier is voldoende voor testen). + +Als je deze zaken hebt, laten we dan beginnen. + +--- + +## Stap 1 – Zet je Python‑omgeving op + +Voordat we OCR‑code gaan schrijven, zorg ervoor dat je werkt binnen een schone virtuele omgeving. Dit isoleert afhankelijkheden en voorkomt versieconflicten. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Houd je projectdirectory netjes—maak een submap genaamd `ocr_project` en plaats het script daar. Het maakt pad‑beheer later een stuk eenvoudiger. + +## Stap 2 – Installeer Aspose.OCR voor Python + +Aspose.OCR is een commerciële bibliotheek, maar wordt geleverd met een gratis NuGet‑achtige wheel die je van PyPI kunt halen. Voer het volgende commando uit binnen de geactiveerde virtuele omgeving: + +```bash +pip install aspose-ocr +``` + +Als je een permissiefout krijgt, voeg dan de `--user`‑vlag toe of voer het commando uit met `sudo` (alleen Linux/macOS). Na de installatie zou je iets moeten zien als: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Waarom Aspose?** In tegenstelling tot veel open‑source OCR‑tools ondersteunt Aspose.OCR **bulk image to text conversion** direct uit de doos en verwerkt het een breed scala aan afbeeldingsformaten zonder extra configuratie. Het biedt ook een `BatchOcrEngine`‑klasse die de taak **convert images to text python** tot een één‑regelige operatie maakt. + +## Stap 3 – Afbeeldingen naar Tekst Converteren Python met Batch OCR + +Nu het hart van de tutorial. Hieronder staat een volledig uitvoerbaar script dat: + +1. De OCR‑engineklassen importeert. +2. Een `BatchOcrEngine` instantieert. +3. De engine wijst naar een invoermap met afbeeldingen. +4. De engine instrueert om elk geëxtraheerd tekstbestand naar een uitvoermap te schrijven. +5. De `recognize()`‑methode aanroept, die **recognize text from scanned images** één voor één uitvoert. + +Sla het volgende op als `batch_ocr.py` in je projectmap: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Hoe het werkt + +- **`BatchOcrEngine`** omsluit de reguliere `OcrEngine` maar voegt orkestratie op map‑niveau toe, precies wat je nodig hebt wanneer je **afbeeldingen naar tekst python** in bulk wilt **convert images to text python**. +- De eigenschap `input_folder` vertelt de engine waar de bronafbeeldingen zich bevinden. Hij scant de directory automatisch en zet elk ondersteund bestandstype in de wachtrij. +- De eigenschap `output_folder` bepaalt waar elk `.txt`‑bestand terechtkomt. De engine spiegelt de oorspronkelijke bestandsnaam, dus `receipt1.png` wordt `receipt1.txt`. +- Het aanroepen van `recognize()` start de interne lus die elke afbeelding laadt, OCR uitvoert en het resultaat wegschrijft. De methode blokkeert tot elk bestand verwerkt is, waardoor het eenvoudig is om verdere acties te ketenen (bijv. de uitvoermap zippen). + +#### Verwachte output + +Wanneer je het script uitvoert: + +```bash +python batch_ocr.py +``` + +Zou je het volgende moeten zien: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +In `output_texts` vind je een platte‑tekstbestand voor elke afbeelding. Open er een met een teksteditor en je ziet het ruwe OCR‑resultaat—meestal een nauwkeurige benadering van de oorspronkelijke afgedrukte tekst. + +## Stap 4 – Verifieer de resultaten en handel fouten af + +Zelfs de beste OCR‑engines kunnen struikelen over lage‑resolutie scans of sterk scheve pagina's. Hier is een snelle manier om de output te controleren en eventuele fouten te loggen. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Waarom dit toevoegen?** +- Het vangt gevallen op waarin de engine stilletjes een lege string produceert (veelvoorkomend bij onleesbare afbeeldingen). +- Het geeft je een lijst met problematische bestanden zodat je ze handmatig kunt inspecteren of opnieuw kunt uitvoeren met andere instellingen (bijv. `OcrEngine.preprocess`‑opties verhogen). + +### Randgevallen & Aanpassingen + +| Situatie | Aanbevolen oplossing | +|----------|----------------------| +| Afbeeldingen zijn 90° geroteerd | Stel `batch_engine.ocr_engine.rotation_correction = True` in. | +| Gemengde talen (Engels + Frans) | Gebruik `batch_engine.ocr_engine.language = "eng+fra"` vóór `recognize()`. | +| Grote PDF‑bestanden eerst naar afbeeldingen geconverteerd | Splits PDF‑bestanden in één‑pagina‑afbeeldingen, en voer vervolgens de map in de batch engine. | +| Geheugenfouten bij zeer grote batches | Verwerk kleinere sub‑mappen opeenvolgend, of verhoog `batch_engine.max_memory_usage`. | + +## Stap 5 – Automatiseer de volledige workflow (optioneel) + +Als je deze conversie elke nacht moet laten draaien, wikkel het script dan in een eenvoudig shell‑ of Windows‑batch‑bestand, en plan het met `cron` (Linux/macOS) of Taakplanner (Windows). Hier is een minimale `run_ocr.sh` voor Unix‑achtige systemen: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Maak het uitvoerbaar (`chmod +x run_ocr.sh`) en voeg een cron‑entry toe: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Dat voert de conversie elke dag om 02:00 uur uit en logt eventuele output voor later overzicht. + +--- + +## Conclusie + +Je beschikt nu over een bewezen, productieklare methode om **afbeeldingen naar tekst python** te **convert images to text python** met behulp van Aspose.OCR’s `BatchOcrEngine`. Het script verwerkt **bulk image to text conversion**, schrijft elk resultaat netjes naar een eigen bestand, en bevat verificatiestappen om te garanderen dat je daadwerkelijk **recognize text from scanned images** correct uitvoert. + +Vanaf hier kun je: + +- Experimenteren met verschillende OCR‑instellingen (taalpakketten, deskew, ruisreductie). +- De gegenereerde tekst doorsturen naar een zoekindex zoals Elasticsearch voor directe full‑text zoekopdrachten. +- Deze pipeline combineren met PDF‑conversietools om gescande PDF‑bestanden in één keer te verwerken. + +Heb je vragen, of ben je een probleem tegengekomen met een specifiek bestandstype? Laat een reactie achter, en laten we samen troubleshootten. Veel programmeerplezier, en moge je OCR‑runs snel en foutloos verlopen! + +## Wat moet je hierna leren? + +- [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 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/dutch/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..86383ab7f --- /dev/null +++ b/ocr/dutch/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Maak een licentie‑instantie in Python en configureer eenvoudig het licentiepad. + Leer hoe je Aspose OCR-licenties instelt met duidelijke codevoorbeelden. +draft: false +keywords: +- create license instance +- configure license path +language: nl +og_description: Maak een licentie‑instantie in Python en configureer het licentiepad + direct. Volg deze tutorial om Aspose OCR met vertrouwen te activeren. +og_title: Licentie‑instantie maken in Python – Complete installatiehandleiding +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Licentie‑instantie maken in Python – Stapsgewijze handleiding +url: /nl/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Licentie‑instantie maken in Python – Complete Installatie‑gids + +Moet je **licentie‑instantie maken** voor Aspose OCR in Python? Dan ben je hier op de juiste plek. In deze tutorial laten we je ook zien hoe je **licentie‑pad configureert** zodat de SDK weet waar je `.lic`‑bestand zich bevindt. + +Als je ooit naar een leeg script hebt gekeken en je afvroeg waarom de OCR‑engine klaagt over een niet‑gelicentieerd product, ben je niet de enige. De oplossing bestaat meestal uit een paar regels code—zodra je weet waar je ze moet plaatsen. Aan het einde van deze gids heb je een volledig gelicentieerde Aspose OCR‑omgeving klaar om tekst, afbeeldingen en PDF‑bestanden zonder problemen te herkennen. + +## Wat je leert + +- Hoe je **licentie‑instantie maakt** met het `asposeocr`‑pakket. +- De juiste manier om **licentie‑pad te configureren** voor zowel ontwikkeling als productie. +- Veelvoorkomende valkuilen (ontbrekend bestand, verkeerde rechten) en hoe je ze vermijdt. +- Een compleet, uitvoerbaar script dat je in elk project kunt gebruiken. + +Er is geen voorafgaande ervaring met Aspose OCR vereist, alleen een werkende Python 3‑installatie en een geldig licentiebestand. + +--- + +## Stap 1: Installeer het Aspose OCR Python‑pakket + +Voordat we **licentie‑instantie kunnen maken**, moet de bibliotheek aanwezig zijn. Open een terminal en voer uit: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Als je een virtuele omgeving gebruikt (sterk aanbevolen), activeer deze dan eerst. Zo houd je je afhankelijkheden netjes en voorkom je versieconflicten. + +## Stap 2: Importeer de License‑klasse + +Nu de SDK beschikbaar is, moet de allereerste regel van je script de `License`‑klasse importeren. Dit is het object dat we gebruiken om **licentie‑instantie te maken**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Waarom meteen importeren? Omdat het `License`‑object **voordat** je OCR‑aanroepen doet moet worden geïnstantieerd; anders gooit de SDK een licentiefout op het moment dat je een afbeelding probeert te verwerken. + +## Stap 3: Licentie‑instantie maken + +Hier is het moment waar je op hebt gewacht—echt **licentie‑instantie maken**. Het is één regel, maar de context eromheen is belangrijk. + +```python +# Step 3: Create a License instance +license = License() +``` + +De variabele `license` bevat nu een object dat al het licentiegedrag voor het huidige Python‑proces regelt. Beschouw het als de poortwachter die Aspose OCR vertelt: “Hé, ik heb het recht om te draaien.” + +## Stap 4: Licentie‑pad configureren + +Met de instantie klaar, moeten we deze wijzen naar ons `.lic`‑bestand. Daar komt **licentie‑pad configureren** om de hoek kijken. Vervang de placeholder door het absolute pad naar je licentiebestand. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Een paar aandachtspunten: + +1. **Raw strings (`r"…"`)** voorkomen dat backslashes op Windows als escape‑tekens worden geïnterpreteerd. +2. Gebruik een **absoluut pad** om verwarring te vermijden wanneer het script vanuit een andere werkmap wordt gestart. +3. Als je een relatief pad verkiest (bijvoorbeeld wanneer je de licentie meelevert met je project), zorg er dan voor dat de relatieve basis de locatie van het script is, niet de huidige shell‑directory. + +### Ontbrekende bestanden afhandelen + +Als het pad onjuist is of het bestand niet leesbaar, zal `set_license` een uitzondering werpen. Plaats de aanroep in een `try/except`‑blok om een vriendelijke foutmelding te geven: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Dit fragment **configureert licentie‑pad** veilig en vertelt je precies wat er mis ging—geen mysterieuze stack‑traces. + +## Stap 5: Verifiëren dat de licentie actief is + +Een snelle sanity‑check bespaart later uren debuggen. Nadat je `set_license` hebt aangeroepen, probeer je een eenvoudige OCR‑bewerking. Als de licentie geldig is, verwerkt de SDK de afbeelding zonder een licentiefout te gooien. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Als je de herkende tekst ziet afgedrukt, gefeliciteerd—je hebt succesvol **licentie‑instantie gemaakt** en **licentie‑pad geconfigureerd**. Als je een licentie‑uitzondering krijgt, controleer dan het pad en de bestandsrechten opnieuw. + +## Randgevallen & Best Practices + +| Situatie | Wat te doen | +|-----------|------------| +| **Licentiebestand staat op een netwerkschijf** | Koppel de share aan een stationsletter of gebruik een UNC‑pad (`\\server\share\license.lic`). Zorg dat het Python‑proces leesrechten heeft. | +| **Draaien binnen een Docker‑container** | Kopieer het `.lic`‑bestand naar de image en verwijs ernaar met een absoluut pad zoals `/app/license/Aspose.OCR.Java.lic`. | +| **Meerdere Python‑interpreters** (bijv. conda‑omgevingen) | Installeer het licentiebestand één keer per omgeving of bewaar het op een centrale locatie en laat elke interpreter ernaar wijzen. | +| **Licentiebestand ontbreekt tijdens uitvoering** | Val gracieus terug naar een trial‑modus (indien ondersteund) of stop met een duidelijke logmelding. | + +### Veelvoorkomende valkuilen + +- **Voorwaartse schuine strepen gebruiken op Windows** – Python accepteert ze, maar sommige oudere SDK‑versies kunnen ze verkeerd interpreteren. Gebruik raw strings of dubbele backslashes. +- **Vergeten `License` te importeren** – Het script crasht met `NameError`. Altijd importeren vóór je instantie maakt. +- **`set_license` pas na OCR‑methoden aanroepen** – De SDK controleert de licentie bij de eerste gebruik, dus stel het pad **eerst** in. + +## Volledig werkend voorbeeld + +Hieronder vind je een compleet script dat alles samenbrengt. Sla het op als `ocr_setup.py` en voer het uit vanaf de commandoregel. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Verwachte output** (ervan uitgaande dat je een geldige afbeelding hebt): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Als het licentiebestand niet gevonden kan worden, zie je een duidelijke foutmelding in plaats van een cryptische “License not found”‑uitzondering. + +--- + +## Conclusie + +Je weet nu precies hoe je **licentie‑instantie maakt** in Python en **licentie‑pad configureert** voor de Aspose OCR SDK. De stappen zijn eenvoudig: het pakket installeren, `License` importeren, een instantie maken, wijzen naar je `.lic`‑bestand, en verifiëren met een kleine OCR‑test. + +Met deze kennis kun je OCR‑functionaliteit in webservices, desktop‑apps of geautomatiseerde pipelines integreren zonder tegen licentie‑fouten aan te lopen. Als volgende stap kun je geavanceerde OCR‑instellingen verkennen—taalpakketten, beeld‑preprocessing of batch‑verwerking—die allemaal voortbouwen op de solide basis die je nu hebt gelegd. + +Heb je vragen over deployment, Docker, of het omgaan met meerdere licenties? Laat een reactie achter, en happy coding! + +## Wat moet je hierna leren? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..5daa3d75e --- /dev/null +++ b/ocr/dutch/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Maak doorzoekbare PDF's van gescande afbeeldingen met Python OCR. Leer + hoe je een gescande afbeelding‑PDF kunt converteren, TIFF naar PDF kunt omzetten + en binnen enkele minuten een OCR‑tekstlaag kunt toevoegen. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: nl +og_description: Maak direct een doorzoekbare PDF. Deze gids laat zien hoe je OCR uitvoert, + een gescande afbeelding‑PDF converteert en een OCR‑tekstlaag toevoegt met één enkel + Python‑script. +og_title: Maak een doorzoekbare PDF met Python – Complete tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Maak doorzoekbare PDF met Python – Stapsgewijze handleiding +url: /nl/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak doorzoekbare PDF met Python – Stapsgewijze gids + +Heb je je ooit afgevraagd hoe je **doorzoekbare PDF** kunt maken van een gescande pagina zonder tientallen tools te gebruiken? Je bent niet de enige. In veel kantoorprocessen belandt een gescande TIFF of JPEG op een gedeelde schijf, en de volgende persoon moet de tekst handmatig kopiëren‑plakken – pijnlijk, foutgevoelig en tijdrovend. + +In deze tutorial lopen we een nette, programmeerbare oplossing door die je **gescande afbeelding‑PDF converteert**, **TIFF naar PDF converteert**, en **een OCR‑tekstlaag toevoegt** in één stap. Aan het einde heb je een kant‑klaar script dat OCR uitvoert, de verborgen tekst inbedt, en een doorzoekbare PDF oplevert die je kunt indexeren, doorzoeken of met vertrouwen kunt delen. + +## Wat je nodig hebt + +- Python 3.9+ (elke recente versie werkt) +- `aspose-ocr` en `aspose-pdf` pakketten (geïnstalleerd via `pip install aspose-ocr aspose-pdf`) +- Een gescande afbeeldingsbestand (`.tif`, `.png`, `.jpg`, of zelfs een PDF‑pagina die alleen een afbeelding bevat) +- Een bescheiden hoeveelheid RAM (de OCR‑engine is lichtgewicht; zelfs een laptop kan het aan) + +> **Pro tip:** Als je Windows gebruikt, is de makkelijkste manier om de pakketten te krijgen het uitvoeren van het commando in een verhoogde PowerShell‑venster. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Nu de vereisten geregeld zijn, duiken we in de code. + +## Stap 1: Maak een OCR‑engine‑instantie – *create searchable pdf* + +Het eerste wat we doen is de OCR‑engine opstarten. Beschouw het als het brein dat elke pixel leest en omzet in tekens. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Waarom dit belangrijk is:** De engine slechts één keer initialiseren houdt het geheugenverbruik laag. Als je `OcrEngine()` binnen een lus voor elke pagina zou aanroepen, zou je snel zonder resources komen te zitten. + +## Stap 2: Laad de gescande afbeelding – *convert tiff to pdf* & *convert scanned image pdf* + +Geef vervolgens de engine het bestand dat je wilt verwerken. De API accepteert elke rasterafbeelding, dus een TIFF werkt net zo goed als een JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Als je een PDF hebt die alleen een gescande afbeelding bevat, kun je nog steeds `load_image` gebruiken omdat Aspose automatisch de eerste pagina extraheert. + +## Stap 3: Bereid PDF‑opslaoptopties voor – *add OCR text layer* + +Hier configureren we hoe de uiteindelijke PDF eruit moet zien. De cruciale vlag is `create_searchable_pdf`; deze op `True` zetten vertelt de bibliotheek een onzichtbare tekstlaag toe te voegen die de visuele inhoud weerspiegelt. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Wat de tekstlaag doet:** Wanneer je het resulterende bestand opent in Adobe Reader en probeert tekst te selecteren, zie je de verborgen tekens. Zoekmachines kunnen ze ook indexeren – perfect voor compliance of archivering. + +## Stap 4: Voer OCR uit en sla op – *how to run OCR* in één enkele aanroep + +Nu gebeurt de magie. Eén methode‑aanroep draait de herkenningsengine en schrijft de doorzoekbare PDF naar schijf. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +De `recognize`‑methode retourneert een statusobject dat je kunt inspecteren op fouten, maar voor de meeste eenvoudige scenario's is de bovenstaande eenvoudige aanroep voldoende. + +### Verwachte output + +Het uitvoeren van het script geeft: + +``` +PDF saved as searchable PDF. +``` + +Als je `scanned_page_searchable.pdf` opent, zul je merken dat je tekst kunt selecteren, kopiëren‑plakken en zelfs een `Ctrl+F`‑zoekopdracht kunt uitvoeren. Dat is het kenmerk van een **create searchable pdf** workflow. + +## Volledig werkend script + +Hieronder staat het complete, kant‑klaar script. Vervang alleen de voorbeeldpaden door je eigen bestandslocaties. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Sla dit op als `create_searchable_pdf.py` en voer uit: + +```bash +python create_searchable_pdf.py +``` + +## Veelgestelde vragen & randgevallen + +### 1️⃣ Kan ik multi‑page PDF's verwerken? + +Ja. Gebruik `ocr_engine.load_image("file.pdf")` en loop vervolgens over elke pagina met `ocr_engine.recognize(pdf_save_options, page_number)`. De bibliotheek genereert automatisch een multi‑page doorzoekbare PDF. + +### 2️⃣ Wat als mijn bronbestand een high‑resolution TIFF is (300 dpi+)? + +Een hogere DPI levert betere OCR‑nauwkeurigheid op, maar ook meer geheugenverbruik. Als je een `MemoryError` krijgt, verklein dan eerst de afbeelding: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Hoe wijzig ik de taal van de OCR? + +Stel de `language`‑eigenschap in op de engine vóór het laden van de afbeelding: + +```python +ocr_engine.language = "fra" # French +``` + +Een volledige lijst met ondersteunde taalcodes vind je in de Aspose‑documentatie. + +### 4️⃣ Wat als ik de oorspronkelijke beeldkwaliteit wil behouden? + +De `PdfSaveOptions`‑klasse heeft een `compression`‑eigenschap. Zet deze op `PdfCompression.None` om de rasterdata exact zoals ze was te behouden. + +```python +pdf_save_options.compression = "None" +``` + +## Tips voor productie‑klare implementaties + +- **Batchverwerking:** Plaats de kernlogica in een functie die een lijst met bestands‑paden accepteert. Log elke succes‑/foutmelding naar een CSV voor audit‑trails. +- **Parallelisme:** Gebruik `concurrent.futures.ThreadPoolExecutor` om OCR op meerdere cores uit te voeren. Vergeet niet dat elke thread zijn eigen `OcrEngine`‑instantie nodig heeft. +- **Beveiliging:** Als je gevoelige documenten verwerkt, voer het script dan uit in een sandbox‑omgeving en verwijder de tijdelijke bestanden direct na verwerking. + +## Conclusie + +Je weet nu hoe je **doorzoekbare PDF**‑bestanden maakt van gescande afbeeldingen met een beknopt Python‑script. Door een OCR‑engine te initialiseren, een TIFF (of willekeurige raster) te laden, `PdfSaveOptions` te configureren om **OCR‑tekstlaag toe te voegen**, en tenslotte `recognize` aan te roepen, wordt de volledige **convert scanned image pdf** en **convert TIFF to PDF** pijplijn één herhaalbare opdracht. + +Volgende stappen? Probeer dit script te koppelen aan een bestands‑watcher zodat elke nieuwe scan die in een map wordt gedropt automatisch doorzoekbaar wordt. Of experimenteer met verschillende OCR‑talen om meertalige archieven te ondersteunen. De mogelijkheden zijn eindeloos wanneer je OCR combineert met PDF‑generatie. + +Heb je meer vragen over **how to run OCR** in andere talen of frameworks? Laat een reactie achter, en happy coding! + +![Diagram dat de stroom van gescande afbeelding → OCR‑engine → doorzoekbare PDF (create searchable pdf) toont](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## Wat moet je hierna leren? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/dutch/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..706ebbd0b --- /dev/null +++ b/ocr/dutch/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-31 +description: Verbeter de OCR-nauwkeurigheid met Python door afbeeldingen vooraf te + verwerken voor OCR. Leer hoe je tekst uit afbeeldingsbestanden kunt extraheren, + tekst uit PNG kunt herkennen en de resultaten kunt verbeteren. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: nl +og_description: Verbeter de OCR‑nauwkeurigheid in Python door beeldvoorbewerking toe + te passen voor tekst. Volg deze gids om tekst uit afbeeldingsbestanden te extraheren + en tekst uit PNG‑bestanden moeiteloos te herkennen. +og_title: Verbeter de OCR-nauwkeurigheid in Python – Volledige tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Verbeter OCR‑nauwkeurigheid in Python – Complete stapsgewijze gids +url: /nl/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Verbeter OCR-nauwkeurigheid in Python – Complete Stapsgewijze Gids + +Heb je ooit geprobeerd **OCR-nauwkeurigheid te verbeteren** en kreeg je alleen maar onsamenhangende output? Je bent niet de enige. De meeste ontwikkelaars lopen tegen een muur aan wanneer de ruwe afbeelding ruisig, scheef of gewoonweg weinig contrast heeft. Het goede nieuws? Een handvol preprocessing‑trucs kan een wazige screenshot omzetten in schone, machinaal leesbare tekst. + +In deze tutorial lopen we een praktisch voorbeeld door dat **een afbeelding preprocesses voor OCR**, de herkenningsengine uitvoert, en uiteindelijk **tekst uit afbeelding**‑bestanden extraheert – specifiek een PNG. Aan het einde weet je precies hoe je **tekst uit PNG** kunt herkennen met een hogere succesratio, en heb je een herbruikbare code‑snippet die je in elk project kunt gebruiken. + +## Wat je zult leren + +- Waarom beeld‑preprocessing belangrijk is voor OCR‑engines +- Welke preprocessing‑modi (denoise, deskew) de grootste boost geven +- Hoe je een `OcrEngine`‑instantie configureert in Python +- Het volledige, uitvoerbare script dat **tekst uit afbeelding**‑bestanden **extraheert** +- Tips voor het omgaan met randgevallen zoals gedraaide scans of afbeeldingen met lage resolutie + +Geen externe bibliotheken buiten de OCR SDK zijn vereist, maar je hebt Python 3.8+ en een PNG‑afbeelding die je wilt lezen nodig. + +--- + +![Diagram dat stappen toont om OCR-nauwkeurigheid in Python te verbeteren](image.png "Workflow voor het verbeteren van OCR-nauwkeurigheid") + +*Alt‑tekst: workflow‑diagram voor het verbeteren van OCR-nauwkeurigheid dat preprocessing‑ en herkenningsstappen illustreert.* + +## Vereisten + +- Python 3.8 of nieuwer geïnstalleerd +- Toegang tot de OCR SDK die `OcrEngine`, `OcrEngineSettings` en `ImagePreprocessMode` levert (de code hieronder gebruikt een generieke API; vervang door de klassen van jouw leverancier indien nodig) +- Een PNG‑afbeelding (`input.png`) geplaatst in een map die je kunt refereren + +Als je een virtuele omgeving gebruikt, activeer deze nu – niets ingewikkeld, gewoon `python -m venv venv && source venv/bin/activate`. + +--- + +## Stap 1: Maak de OCR‑Engine‑instantie – Begin met het Verbeteren van OCR‑Nauwkeurigheid + +Het eerste wat je nodig hebt is een OCR‑engine‑object. Beschouw het als het brein dat later de pixels leest en tekens uitspuwt. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Waarom dit belangrijk is: zonder een engine kun je geen preprocessing toepassen, en wordt de ruwe afbeelding direct aan de recognizer gevoed – meestal het slechtste scenario voor nauwkeurigheid. + +--- + +## Stap 2: Laad de Doel‑PNG – Bereid de Basis voor Tekstherkenning uit PNG + +Nu vertellen we de engine welk bestand hij moet verwerken. PNG is lossless, wat ons al een klein voordeel geeft ten opzichte van JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Als de afbeelding zich ergens anders bevindt, pas dan gewoon het pad aan. De engine accepteert elk ondersteund formaat, maar PNG behoudt vaak de fijne details die nodig zijn voor scherpe tekenranden. + +--- + +## Stap 3: Configureer Preprocessing – Preprocess Image for OCR + +Hier gebeurt de magie. We maken een instellingenobject, schakelen denoising in om vlekjes te verwijderen, en activeren deskew zodat scheefstaande tekst automatisch wordt rechtgezet. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Waarom Denoise + Deskew? + +- **Denoise**: Willekeurige pixelruis verwart patroon‑matching‑algoritmen. Het verwijderen ervan scherpt letters. +- **Deskew**: Zelfs een kanteling van 2 graden kan de confidence‑scores drastisch doen dalen. Deskew aligneert de basislijn, waardoor de recognizer lettertypen betrouwbaarder kan matchen. + +Je kunt experimenteren met extra vlaggen (bijv. `ImagePreprocessMode.CONTRAST_ENHANCE`) als je afbeeldingen bijzonder donker zijn. De SDK‑documentatie somt meestal alle beschikbare modi op. + +--- + +## Stap 4: Pas de Instellingen toe op de Engine – Koppel Preprocessing aan OCR + +Wijs het instellingenobject toe aan de engine zodat de volgende herkenningsrun de transformaties gebruikt die we zojuist hebben gedefinieerd. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Als je deze stap overslaat, valt de engine terug op de standaardinstellingen (vaak “geen preprocessing”), en zie je **lagere OCR‑nauwkeurigheid**. + +--- + +## Stap 5: Voer het Herkenningsproces uit – Extract Text from Image + +Met alles aangesloten vragen we de engine eindelijk om zijn werk te doen. De aanroep is synchroon en retourneert een result‑object dat de herkende string bevat. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Achter de schermen doet de engine nu: + +1. Laadt de PNG in het geheugen +2. Past denoise en deskew toe op basis van onze instellingen +3. Voert het neurale netwerk of klassieke patroon‑matcher uit +4. Verpakt de output in `recognition_result` + +--- + +## Stap 6: Output de Herkende Tekst – Verifieer de Verbetering + +Laten we de geëxtraheerde string afdrukken. In een echte applicatie schrijf je deze misschien naar een bestand, een database, of geef je hem door aan een andere service. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Verwachte Output + +Bevat de afbeelding de zin “Hello, OCR World!” dan zou je moeten zien: + +``` +Hello, OCR World! +``` + +Merk op hoe de tekst schoon is – geen vreemde symbolen of gebroken tekens. Dat is het resultaat van juiste **image preprocessing for text**. + +--- + +## Pro Tips & Edge Cases + +| Situatie | Wat aan te passen | Waarom | +|-----------|-------------------|--------| +| Zeer lage‑resolutie PNG (≤ 72 dpi) | Voeg `ImagePreprocessMode.SUPER_RESOLUTION` toe indien beschikbaar | Upsampling kan de recognizer meer pixels geven om mee te werken | +| Tekst is > 5° gedraaid | Verhoog deskew‑tolerantie of roteer handmatig met `Pillow` voordat je de engine voedt | Extreme hoeken omzeilen soms automatische deskew | +| Zware achtergrondpatronen | Schakel `ImagePreprocessMode.BACKGROUND_REMOVAL` in | Verwijdert niet‑tekstuele rommel die anders verkeerd gelezen zou worden | +| Meertalige document | Stel `ocr_engine.language = "eng+spa"` (of vergelijkbaar) in | De engine kiest de juiste tekenset, wat de algehele nauwkeurigheid verbetert | + +Onthoud, **improve OCR accuracy** is geen one‑size‑fits‑all; je moet mogelijk itereren over de preprocessing‑vlaggen voor jouw specifieke dataset. + +--- + +## Volledig Script – Klaar om te Kopiëren & Plakken + +Hieronder vind je het complete, uitvoerbare voorbeeld dat elke stap die we besproken hebben bevat. Sla het op als `improve_ocr_accuracy.py` en voer uit met `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Voer het uit, bekijk de console, en je ziet direct het **extract text from image**‑resultaat. Als de output niet klopt, pas dan de `preprocess_mode`‑vlaggen aan zoals beschreven in de “Pro Tips”‑tabel. + +--- + +## Conclusie + +We hebben zojuist een praktische recept doorlopen om **OCR‑nauwkeurigheid te verbeteren** met Python. Door een `OcrEngine` te maken, een PNG te laden, **de afbeelding voor OCR te preprocessen**, en uiteindelijk **tekst uit PNG te herkennen**, kun je betrouwbaar **tekst uit afbeelding**‑bestanden extraheren, zelfs wanneer de bron niet perfect is. + +Volgende stappen? Probeer een batch afbeeldingen via een lus te verwerken, sla elk resultaat op in een CSV, of experimenteer met extra preprocessing‑modi zoals contrastverbetering. Hetzelfde patroon werkt voor PDF’s, gescande bonnetjes of handgeschreven notities – vervang gewoon de invoer en pas de instellingen aan. + +Heb je vragen over een specifiek type afbeelding of wil je weten hoe je dit in een webservice kunt integreren? Laat een reactie achter, en we verkennen die scenario’s samen. Veel programmeerplezier, en moge je OCR‑resultaten altijd kristalhelder zijn! + + +## Wat moet je hierna leren? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/dutch/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..8b55a34b7 --- /dev/null +++ b/ocr/dutch/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Leer hoe je OCR-gebied van interesse gebruikt om een afbeelding te laden + voor OCR en tekst uit een rechthoek te extraheren, perfect voor het herkennen van + het bedrag op een factuur. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: nl +og_description: Beheers het OCR-gebied van interesse om een afbeelding voor OCR te + laden, tekst uit een rechthoek te extraheren en tekst van een factuur te herkennen + in één tutorial. +og_title: OCR-regio van belang – Stapsgewijze Python-gids +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR‑regio van belang – Tekst extraheren uit een rechthoek in Python +url: /nl/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Tekst extraheren uit rechthoek in Python + +Heb je je ooit afgevraagd hoe je **ocr region of interest** een specifiek deel van een gescande factuur kunt verwerken zonder de hele pagina aan de engine te voeren? Je bent niet de eerste die naar een wazige bon staart en zich afvraagt: “Hoe haal ik het bedrag eruit dat ergens rechtsonder staat?” Het goede nieuws is dat je de OCR‑bibliotheek precies kunt vertellen waar hij moet kijken, waardoor zowel snelheid als nauwkeurigheid enorm toenemen. + +In deze gids lopen we een compleet, uitvoerbaar voorbeeld door dat laat zien hoe je **load image for OCR**, een **region of interest** definieert, en vervolgens **extract text from rectangle** toepast om uiteindelijk **recognize text from invoice** te doen en de klassieke vraag “hoe haal je het bedrag eruit” te beantwoorden. Geen vage verwijzingen—alleen concrete code, duidelijke uitleg, en een paar pro‑tips die je eerder had willen weten. + +--- + +## Wat je gaat bouwen + +1. Laadt een factuurafbeelding van de schijf. +2. Markeert een rechthoekige ROI waar het totale bedrag zich bevindt. +3. Voert OCR alleen binnen die ROI uit. +4. Print de opgeschoonde bedrag‑string. + +Dit werkt met elke OCR‑bibliotheek die ROI ondersteunt—hier gebruiken we een fictief maar representatief `SimpleOCR`‑pakket dat populaire tools zoals Tesseract of EasyOCR nabootst. Voel je vrij om het te vervangen; de concepten blijven hetzelfde. + +--- + +## Vereisten + +- Python 3.8+ geïnstalleerd (`python --version` moet ≥3.8 tonen). +- Een via pip te installeren OCR‑pakket (bijv. `pip install simpleocr`). +- Een factuurafbeelding (PNG of JPEG) geplaatst in een map die je kunt refereren. +- Basiskennis van Python‑functies en -klassen (niets geavanceerd). + +Als je die al hebt, prima—laten we erin duiken. Zo niet, haal dan eerst de afbeelding; de rest van de stappen is onafhankelijk van de feitelijke bestandsinhoud. + +--- + +## Stap 1: Afbeelding laden voor OCR + +Het eerste wat elke OCR‑workflow nodig heeft, is een bitmap om van te lezen. De meeste bibliotheken bieden een eenvoudige `load_image`‑methode die een bestandspad accepteert. Zo doe je het met onze `SimpleOCR`‑engine: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Gebruik absolute paden of `os.path.join` om “bestand niet gevonden” verrassingen te vermijden wanneer je het script vanuit een andere werkmap uitvoert. + +--- + +## Stap 2: OCR Region of Interest definiëren + +In plaats van de engine de hele pagina te laten scannen, vertellen we hem *exact* waar het bedrag staat. Dit is de **ocr region of interest** stap, en het is de sleutel tot betrouwbare extractie, vooral wanneer het document rommelige kopteksten of voetteksten bevat. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Waarom die getallen? `x` en `y` zijn pixel‑offsets vanaf de linkerbovenhoek, terwijl `width` en `height` de afmetingen van de doos beschrijven. Als je het niet zeker weet, open de afbeelding in een editor, zet een liniaal aan en noteer de coördinaten. Veel IDE’s laten zelfs de cursorpositie zien tijdens het zweven. + +--- + +## Stap 3: Tekst extraheren uit rechthoek + +Nu de ROI is ingesteld, vragen we de engine om **recognize text from invoice** maar beperkt tot de rechthoek die we zojuist hebben toegevoegd. De aanroep retourneert een result‑object dat doorgaans de ruwe string, vertrouwensscores en soms begrenzingskaders bevat. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Achter de schermen iterereert `recognize()` over elke ROI, snijdt dat deel uit, voert het OCR‑model uit en voegt de resultaten samen. Daarom kan het definiëren van een strakke **extract text from rectangle**‑regio seconden schelen in de verwerkingstijd voor batch‑taken. + +--- + +## Stap 4: Hoe het bedrag te extraheren – Output opschonen + +OCR is niet perfect; je krijgt vaak vreemde spaties, regeleinden of zelfs verkeerd gelezen tekens (denk aan “S” vs “5”). Een snelle `strip()` en een kleine regex lossen meestal het probleem op voor monetaire waarden. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Waarom dit belangrijk is:** Als je het bedrag in een database of een betalingsgateway wilt invoeren, heb je een voorspelbaar formaat nodig. Het verwijderen van witruimte en het filteren van niet‑numerieke tekens voorkomt fouten later in de keten. + +--- + +## Stap 5: Recognize Text from Invoice – Volledig script + +Alles bij elkaar, hier is het volledige, kant‑klaar script. Sla het op als `extract_amount.py` en voer `python extract_amount.py` uit. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Verwachte output + +``` +Amount: 1,245.67 +``` + +Als de ROI niet goed uitgelijnd is, zie je misschien iets als `Amount: 1245.6S`—let op de vreemde “S”. Pas de rechthoekcoördinaten aan en voer opnieuw uit totdat de output er schoon uitziet. + +--- + +## Veelvoorkomende valkuilen & randgevallen + +| Probleem | Waarom het gebeurt | Oplossing | +|----------|--------------------|-----------| +| **ROI te klein** | De bedragtekst wordt afgesneden, wat leidt tot gedeeltelijke herkenning. | Vergroot `width`/`height` met ~10‑20 % en test opnieuw. | +| **Onjuiste DPI** | Scans met lage resolutie (≤150 dpi) verminderen de OCR‑nauwkeurigheid. | Resample de afbeelding naar 300 dpi vóór het laden, of vraag de scanner om een hogere DPI. | +| **Meerdere valuta's** | Regex pakt de eerste numerieke groep, die een factuurnummer kan zijn. | Verfijn de regex om naar valutasymbolen (`$`, `€`, `£`) vóór de cijfers te zoeken. | +| **Gedraaide facturen** | OCR‑engines gaan uit van rechtopstaande tekst; gedraaide pagina's breken de herkenning. | Pas een rotatiecorrectie toe (`ocr_engine.rotate(90)`) vóór het toevoegen van ROI. | +| **Ruis op achtergrond** | Schaduwen of stempels verwarren het model. | Pre‑process met een eenvoudige drempel (`cv2.threshold`) of gebruik een denoise‑filter. | + +Het vroeg aanpakken van deze randgevallen bespaart je later uren aan debuggen. + +--- + +## Pro‑tips voor real‑world projecten + +- **Batchverwerking:** Loop over een map met facturen, bereken ROI dynamisch (bijv. op basis van sjabloondetectie), en sla resultaten op in CSV. +- **Sjabloonmatching:** Als je verschillende factuurlay-outs verwerkt, onderhoud dan een JSON‑map van `template_id → ROI‑coördinaten`. Wissel ROI op basis van een snelle lay‑out‑classifier. +- **Parallelle uitvoering:** Gebruik `concurrent.futures.ThreadPoolExecutor` om meerdere OCR‑instanties gelijktijdig uit te voeren—ideaal voor high‑volume back‑office pipelines. +- **Vertrouwensfiltering:** De meeste OCR‑resultaten bevatten een vertrouwensscore. Verwijder resultaten onder een drempel (bijv. 85 %) en markeer ze voor handmatige controle. + +--- + +## Conclusie + +We hebben alles behandeld wat je nodig hebt om **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, en uiteindelijk **recognize text from invoice** uit te voeren om de klassieke **how to extract amount**‑vraag te beantwoorden. Het script is compact, maar toch flexibel genoeg om zich aan te passen aan verschillende documentformaten, talen en OCR‑back‑ends. + +Nu je de basis onder de knie hebt, overweeg het uitbreiden van de workflow: voeg barcode‑scanning toe, integreer met een PDF‑parser, of stuur het geëxtraheerde bedrag naar een boekhoud‑API. De mogelijkheden zijn eindeloos, en met een goed gedefinieerde ROI krijg je altijd snellere, schonere resultaten. + +Als je tegen een probleem aanloopt, laat dan een reactie achter—veel succes met OCRen! + +![ocr region of interest voorbeeld](https://example.com/ocr_roi_example.png "ocr region of interest voorbeeld") + + +## Wat kun je hierna leren? + +- [Hoe tekst uit afbeelding te extraheren door rechthoeken voor OCR voor te bereiden](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Tekst uit afbeelding extraheren Java met Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Tekst uit afbeelding extraheren – OCR-optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/english/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..4710a9e85 --- /dev/null +++ b/ocr/english/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: en +og_description: Async OCR tutorial walks you through using Aspose OCR in Python with + asyncio for efficient image text extraction. +og_title: Async OCR Tutorial – Python asyncio with Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Async OCR Tutorial – Python asyncio with Aspose OCR +url: /python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR Tutorial – Python asyncio with Aspose OCR + +Ever wondered how to run optical character recognition without blocking your app? In an **async OCR tutorial** you’ll see exactly that—non‑blocking text extraction using Python’s `asyncio` and the Aspose OCR library. + +If you’ve been stuck waiting for a heavy image to be processed, this guide gives you a clean, asynchronous solution that keeps your event loop humming. + +In the sections that follow we’ll cover everything you need: installing the library, wiring up an asynchronous helper, handling the result, and even a quick tip for scaling to multiple images. By the end you’ll be able to drop an **async OCR tutorial** into any Python project that already uses `asyncio`. + +## What You’ll Need + +Before we dive in, make sure you have: + +* Python 3.9+ (the `asyncio` API we use is stable from 3.7 onward) +* An active Aspose OCR license or a free trial (the library is pure‑Python, no native binaries) +* A small image file (`.jpg`, `.png`, etc.) you want to read – keep it in a known folder + +No other external tools are required; everything runs in pure Python. + +## Step 1: Install the Aspose OCR Package + +First things first, get the Aspose OCR package from PyPI. Open a terminal and run: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** If you’re working inside a virtual environment (highly recommended), activate it first. This keeps dependencies isolated and avoids version clashes. + +## Step 2: Initialise the OCR Engine Asynchronously + +The heart of our **async OCR tutorial** is an asynchronous helper function. It creates an `OcrEngine` instance, loads an image, and then calls `recognize_async()`. The engine itself is synchronous, but the wrapper method returns an awaitable, letting the event loop stay responsive. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Why we do it this way:** +*Creating the engine inside the helper ensures thread‑safety if you later run many OCR jobs in parallel. The `await` keyword hands control back to the event loop while the heavy lifting happens in the library’s internal thread pool.* + +## Step 3: Drive the Helper from an Async Main Function + +Now we need a tiny `main()` coroutine that calls `async_ocr()` and prints the outcome. This mirrors the typical entry point for an `asyncio` script. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**What’s happening under the hood?** +`asyncio.run()` creates a fresh event loop, schedules `main()`, and shuts the loop down cleanly when `main()` finishes. This pattern is the recommended way to start asynchronous programs in Python 3.7+. + +## Step 4: Test the Full Script + +Save the two code blocks above into a single file, e.g., `async_ocr_demo.py`. Run it from the command line: + +```bash +python async_ocr_demo.py +``` + +If everything is set up correctly you should see something like: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +The exact output will depend on the content of `photo.jpg`. The key point is that the script finishes quickly, even if the image is large, because the OCR work happens in the background. + +## Step 5: Scaling Up – Process Multiple Images Concurrently + +A common follow‑up question is, *“Can I OCR a batch of files without launching a new process for each?”* Absolutely. Because our helper is fully asynchronous, we can gather many coroutines with `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Why this works:** `asyncio.gather()` schedules all the OCR tasks at once. The underlying Aspose OCR library still uses its own thread pool, but from Python’s perspective everything stays non‑blocking, letting you handle dozens of images in the time a single synchronous call would take. + +## Step 6: Handling Errors Gracefully + +When you work with external files, you’ll inevitably hit missing files, corrupted images, or license issues. Wrap the OCR call in a `try/except` block to keep the event loop alive: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Now `batch_ocr()` can call `safe_async_ocr` instead, ensuring one bad file won’t abort the whole batch. + +## Visual Overview + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial flowchart showing async_ocr helper, event loop, and Aspose OCR engine"} + +The diagram above visualises the flow: the event loop → `async_ocr` → `OcrEngine` → background thread → result back to the loop. + +## Common Pitfalls & How to Avoid Them + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Blocking I/O inside the helper** | Accidentally using `open()` without `await` can block the loop. | Use `aiofiles` for file reads, or let `engine.load_image` handle it (it’s already non‑blocking). | +| **Re‑using a single `OcrEngine` across coroutines** | The engine isn’t thread‑safe; concurrent calls may corrupt state. | Instantiate a fresh engine inside each `async_ocr` call (as shown). | +| **Missing license** | Aspose OCR throws a license‑related exception at runtime. | Register your license early (`OcrEngine.set_license("license.json")`). | +| **Large images causing memory spikes** | The library loads the whole image into RAM. | Downscale images before OCR if memory is a concern. | + +## Recap: What We Achieved + +In this **async OCR tutorial** we: + +1. Installed the Aspose OCR library. +2. Built an `async_ocr` helper that runs recognition without blocking. +3. Ran the helper from a clean `asyncio` entry point. +4. Demonstrated batch processing with `asyncio.gather`. +5. Added error handling and best‑practice tips. + +All of this is pure Python, so you can drop it into a web server, a CLI tool, or a data‑pipeline without rewriting existing async code. + +## Next Steps & Related Topics + +* **Asynchronous image preprocessing** – use `aiohttp` to download images concurrently before OCR. +* **Storing OCR results** – combine this tutorial with an async database driver like `asyncpg` for PostgreSQL. +* **Performance tuning** – experiment with `engine.recognize_async(max_threads=4)` if the library exposes such an option. +* **Alternative OCR engines** – compare Aspose OCR with Tesseract’s async wrappers for a cost‑benefit analysis. + +Feel free to experiment: try feeding PDFs, adjust language settings, or hook the results into a chatbot. The sky’s the limit once you have a solid **async OCR tutorial** foundation. + +Happy coding, and may your text extraction be ever swift! + + +## What Should You Learn Next? + +- [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/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/english/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..01e13e197 --- /dev/null +++ b/ocr/english/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-05-31 +description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: en +og_description: Automatic language detection in OCR made easy. Follow this step‑by‑step + tutorial to enable auto language detection, load image OCR, and recognize text image. +og_title: Automatic Language Detection with OCR – Complete Python Guide +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatic Language Detection with OCR – Complete Python Guide +url: /python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatic Language Detection with OCR – Complete Python Guide + +Ever wondered how to make an OCR engine *guess* the language of a scanned document without you telling it what to look for? That's exactly what **automatic language detection** does, and it's a total game‑changer when you deal with multilingual PDFs, photos of street signs, or any image that mixes scripts. + +In this tutorial we'll walk through a hands‑on example that shows you how to **enable auto language detection**, **load image OCR**, and **recognize text image** using a Python‑style API. By the end you’ll have a self‑contained script that prints both the detected language code and the extracted text—no manual language settings required. + +## What You'll Learn + +- How to create an OCR engine instance and turn on **automatic language detection**. +- The exact steps to **load image OCR** from disk. +- How to call the engine’s `recognize()` method and get back a result that includes the language code. +- Tips for handling edge cases like low‑resolution images or unsupported scripts. + +No prior experience with multilingual OCR is needed; just a basic Python setup and an image file. + +--- + +## Prerequisites + +Before we dive in, make sure you have: + +1. Python 3.8+ installed (any recent version works). +2. The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. – for this guide we’ll assume a hypothetical package called `myocr`. Install it with: + + ```bash + pip install myocr + ``` + +3. An image file (`multilingual_sample.png`) that contains text in at least two different languages. +4. A little curiosity—if you’ve never touched OCR before, don’t worry; the code is deliberately straightforward. + +--- + +## Step 1: Enable Automatic Language Detection + +The first thing you need to do is tell the engine that it should *figure out* the language on its own. This is where the **automatic language detection** flag comes into play. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Why this matters:** +> When `AUTO_DETECT` is set, the engine runs a lightweight language classifier on the image before the heavy‑weight character recognition kicks in. That means you don’t have to guess whether the text is English, Russian, French, or any combination thereof. The engine will automatically pick the best language model for each region of the image. + +--- + +## Step 2: Load Image OCR + +Now that the engine knows it should auto‑detect languages, we need to give it something to work on. The **load image OCR** step reads the bitmap and prepares internal buffers. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro tip:** +> If your image is larger than 300 dpi, consider downscaling it to around 150‑200 dpi. Too much detail can actually *slow* down the language detection stage without improving accuracy. + +--- + +## Step 3: Recognize Text from Image + +With the image in memory and language detection enabled, the final piece is to ask the engine to **recognize text image**. This single call does all the heavy lifting. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` is an object that typically contains at least two attributes: + +| Attribute | Description | +|-----------|-------------| +| `language` | ISO‑639‑1 code of the detected language (e.g., `"en"` for English). | +| `text` | The plain‑text transcription of the image. | + +--- + +## Step 4: Retrieve Detected Language and Extracted Text + +Now we simply print out what the engine discovered. This demonstrates the **detect language OCR** capability in action. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Sample output** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **What if the engine returns `None`?** +> That usually means the image is too blurry or the text is too small (< 8 pt). Try increasing contrast or using a higher‑resolution source. + +--- + +## Full Working Example (Enable Auto Language Detection End‑to‑End) + +Putting everything together, here’s a ready‑to‑run script that covers **enable auto language detection**, **load image OCR**, **recognize text image**, and **detect language OCR** in one go. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Save this as `automatic_language_detection_ocr.py`, replace `YOUR_DIRECTORY` with the folder that holds your PNG, and run: + +```bash +python automatic_language_detection_ocr.py +``` + +You should see the language code followed by the extracted text, just like the sample output above. + +--- + +## Handling Common Edge Cases + +| Situation | Suggested Fix | +|-----------|----------------| +| **Very low‑resolution image** (under 100 dpi) | Upscale with a bicubic filter before loading, or request a higher‑resolution source. | +| **Mixed scripts in one image** (e.g., English + Cyrillic) | The engine will usually split the page into regions; if you notice mis‑detections, set `engine.enable_region_split = True`. | +| **Unsupported language** | Verify that the OCR library ships with a language pack for the script you need; you may have to download additional models. | +| **Large batch processing** | Initialize the engine once, then reuse it across multiple `load_image` / `recognize` cycles to avoid repeated model loading. | + +--- + +## Visual Overview + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt text:* automatic language detection example output showing detected language code and extracted multilingual text. + +--- + +## Conclusion + +We’ve just covered **automatic language detection** from start to finish—creating the engine, enabling auto language detection, loading an image for OCR, recognizing the text, and finally retrieving the detected language. This end‑to‑end flow lets you process multilingual documents without manually configuring language models each time. + +If you’re ready to push this further, consider: + +- **Batching** hundreds of images with a loop that reuses the same `OcrEngine` instance. +- **Post‑processing** the extracted text with a spell‑checker or language‑specific tokenizer. +- **Integrating** the script into a web service that accepts user uploads and returns JSON with `language` and `text` fields. + +Feel free to experiment with different image formats (`.jpg`, `.tif`) and see how the detection accuracy changes. Got questions or a tricky image that refuses to be read? Drop a comment below—happy coding! + + +## What Should You Learn Next? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/english/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..13c998c05 --- /dev/null +++ b/ocr/english/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-31 +description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: en +og_description: Convert images to text python instantly. This guide shows bulk image + to text conversion and how to recognize text from scanned images with Aspose.OCR. +og_title: Convert Images to Text Python – Full Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Convert Images to Text Python – Complete Step‑by‑Step Guide +url: /python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert Images to Text Python – Complete Step‑by‑Step Guide + +Ever wondered how to **convert images to text python** without hunting down dozens of libraries? You're not the only one. Whether you're digitizing old receipts, pulling data from scanned invoices, or building a searchable archive of PDFs, turning pictures into plain‑text files is a daily grind for many developers. + +In this tutorial we’ll walk through a **bulk image to text conversion** pipeline that recognizes text from scanned images, saves each result as an individual `.txt` file, and does it all with just a few lines of Python. No mystery‑shopping for obscure APIs—Aspose.OCR does the heavy lifting, and we’ll show you exactly how to wire it up. + +## What You’ll Learn + +- How to install and configure the Aspose.OCR for Python package. +- The exact code needed to **convert images to text python** using the `BatchOcrEngine`. +- Tips for handling common pitfalls like unsupported formats or corrupted files. +- Ways to verify that the **recognize text from scanned images** step actually succeeded. + +By the end of this guide you’ll have a ready‑to‑run script that can process thousands of images in one go—perfect for any batch‑processing scenario. + +## Prerequisites + +- Python 3.8+ installed on your machine. +- A folder of image files (PNG, JPEG, TIFF, etc.) you want to turn into text. +- An active Aspose Cloud account or a free trial license (the free tier is enough for testing). + +If you’ve got those, let’s dive in. + +--- + +## Step 1 – Set Up Your Python Environment + +Before we start writing any OCR code, make sure you’re working inside a clean virtual environment. This isolates dependencies and prevents version clashes. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Keep your project directory tidy—create a subfolder called `ocr_project` and place the script there. It makes path handling a breeze later on. + +## Step 2 – Install Aspose.OCR for Python + +Aspose.OCR is a commercial library, but it ships with a free NuGet‑style wheel that you can pull from PyPI. Run the following command inside the activated virtual environment: + +```bash +pip install aspose-ocr +``` + +If you hit a permission error, add the `--user` flag or run the command with `sudo` (Linux/macOS only). After installation you should see something like: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** Unlike many open‑source OCR tools, Aspose.OCR supports **bulk image to text conversion** out of the box and handles a wide range of image formats without extra configuration. It also offers a `BatchOcrEngine` class that makes the “convert images to text python” task a single‑line operation. + +## Step 3 – Convert Images to Text Python with Batch OCR + +Now for the heart of the tutorial. Below is a fully‑runnable script that: + +1. Imports the OCR engine classes. +2. Instantiates a `BatchOcrEngine`. +3. Points the engine at an input folder of images. +4. Directs the engine to write each extracted text file into an output folder. +5. Fires the `recognize()` method, which **recognize text from scanned images** one by one. + +Save the following as `batch_ocr.py` inside your project folder: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### How It Works + +- **`BatchOcrEngine`** wraps the regular `OcrEngine` but adds folder‑level orchestration, which is exactly what you need when you want to **convert images to text python** in bulk. +- The `input_folder` property tells the engine where to look for source images. It automatically scans the directory and queues every supported file type. +- The `output_folder` property determines where each `.txt` file lands. The engine mirrors the original file name, so `receipt1.png` becomes `receipt1.txt`. +- Calling `recognize()` triggers the internal loop that loads each image, runs OCR, and writes the result. The method blocks until every file is processed, making it easy to chain further actions (e.g., zip the output folder). + +#### Expected Output + +When you run the script: + +```bash +python batch_ocr.py +``` + +You should see: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Inside `output_texts` you’ll find a plain‑text file for every image. Open any of them with a text editor and you’ll see the raw OCR result—usually a close approximation of the original printed text. + +## Step 4 – Verify the Results and Handle Errors + +Even the best OCR engines can stumble on low‑resolution scans or heavily skewed pages. Here’s a quick way to sanity‑check the output and log any failures. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Why add this?** +- It catches cases where the engine silently produced an empty string (common with unreadable images). +- It gives you a list of problematic files so you can manually inspect or re‑run with different settings (e.g., increase `OcrEngine.preprocess` options). + +### Edge Cases & Tweaks + +| Situation | Suggested Fix | +|-----------|----------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Step 5 – Automate the Whole Workflow (Optional) + +If you need to run this conversion nightly, wrap the script in a simple shell or Windows batch file, and schedule it with `cron` (Linux/macOS) or Task Scheduler (Windows). Here’s a minimal `run_ocr.sh` for Unix‑like systems: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Make it executable (`chmod +x run_ocr.sh`) and add a cron entry: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +That runs the conversion every day at 2 AM and logs any output for later review. + +--- + +## Conclusion + +You now have a proven, production‑ready method to **convert images to text python** using Aspose.OCR’s `BatchOcrEngine`. The script handles **bulk image to text conversion**, gracefully writes each result to a dedicated file, and includes verification steps to ensure you actually **recognize text from scanned images** correctly. + +From here you might: + +- Experiment with different OCR settings (language packs, deskew, noise reduction). +- Pipe the generated text into a search index like Elasticsearch for instant full‑text search. +- Combine this pipeline with PDF conversion tools to process scanned PDFs in one go. + +Got questions, or spotted a hiccup with a particular file type? Drop a comment below, and let’s troubleshoot together. Happy coding, and may your OCR runs be fast and error‑free! + + +## What Should You Learn Next? + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/english/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..f21dc08c0 --- /dev/null +++ b/ocr/english/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. +draft: false +keywords: +- create license instance +- configure license path +language: en +og_description: Create license instance in Python and configure license path instantly. + Follow this tutorial to activate Aspose OCR with confidence. +og_title: Create license instance in Python – Complete Setup Guide +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Create license instance in Python – Step‑by‑Step Guide +url: /python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create license instance in Python – Complete Setup Guide + +Need to **create license instance** for Aspose OCR in Python? You’re in the right spot. In this tutorial we’ll also show you how to **configure license path** so the SDK knows where to find your `.lic` file. + +If you’ve ever stared at a blank script wondering why the OCR engine keeps complaining about an unlicensed product, you’re not alone. The fix is usually just a couple of lines of code—once you know exactly where to place them. By the end of this guide you’ll have a fully licensed Aspose OCR environment ready to recognize text, images, and PDFs without a hitch. + +## What You’ll Learn + +- How to **create license instance** using the `asposeocr` package. +- The correct way to **configure license path** for both development and production. +- Common pitfalls (missing file, wrong permissions) and how to avoid them. +- A complete, runnable script you can drop into any project. + +No prior experience with Aspose OCR is required, just a working Python 3 installation and a valid license file. + +--- + +## Step 1: Install the Aspose OCR Python Package + +Before we can **create license instance**, the library itself must be present. Open a terminal and run: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** If you’re using a virtual environment (highly recommended), activate it first. This keeps your dependencies tidy and prevents version clashes. + +## Step 2: Import the License Class + +Now that the SDK is available, the very first line of your script should import the `License` class. This is the object we’ll use to **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Why import it right away? Because the `License` object must be instantiated **before** any OCR calls; otherwise the SDK will throw a licensing error the moment you try to process an image. + +## Step 3: Create License Instance + +Here’s the moment you’ve been waiting for—actually **create license instance**. It’s a single line, but the surrounding context matters. + +```python +# Step 3: Create a License instance +license = License() +``` + +The variable `license` now holds an object that controls all licensing behavior for the current Python process. Think of it as the gatekeeper that tells Aspose OCR, “Hey, I’ve got the right to run.” + +## Step 4: Configure License Path + +With the instance ready, we need to point it at our `.lic` file. That’s where **configure license path** comes into play. Replace the placeholder with the absolute path to your license file. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +A few things to note: + +1. **Raw strings (`r"…"`)** prevent backslashes from being interpreted as escape characters on Windows. +2. Use an **absolute path** to avoid confusion when the script is launched from a different working directory. +3. If you prefer a relative path (e.g., when bundling the license with your project), make sure the relative base is the script’s location, not the current shell directory. + +### Handling Missing Files + +If the path is wrong or the file is unreadable, `set_license` will raise an exception. Wrap the call in a `try/except` block to give a friendly error message: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +This snippet **configures license path** safely and tells you exactly what went wrong—no mysterious stack traces. + +## Step 5: Verify the License Is Active + +A quick sanity check saves hours of debugging later. After you’ve called `set_license`, try a simple OCR operation. If the license is valid, the SDK will process the image without throwing a licensing error. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +If you see the recognized text printed, congratulations—you’ve successfully **create license instance** and **configure license path**. If you get a licensing exception, double‑check the path and file permissions. + +## Edge Cases & Best Practices + +| Situation | What to Do | +|-----------|------------| +| **License file lives in a network share** | Map the share to a drive letter or use a UNC path (`\\server\share\license.lic`). Ensure the Python process has read access. | +| **Running inside a Docker container** | Copy the `.lic` file into the image and reference it with an absolute path like `/app/license/Aspose.OCR.Java.lic`. | +| **Multiple Python interpreters** (e.g., conda envs) | Install the license file once per environment or keep a central location and point each interpreter to it. | +| **License file missing at runtime** | Gracefully fallback to a trial mode (if supported) or abort with a clear log message. | + +### Common Pitfalls + +- **Using forward slashes on Windows** – Python accepts them, but some older versions of the SDK might misinterpret them. Stick with raw strings or double backslashes. +- **Forgot to import `License`** – The script will crash with `NameError`. Always import before you instantiate. +- **Calling `set_license` after OCR methods** – The SDK checks licensing on first use, so set the path **first**. + +## Full Working Example + +Below is a complete script that ties everything together. Save it as `ocr_setup.py` and run it from the command line. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Expected output** (assuming a valid image): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +If the license file can’t be found, you’ll see a clear error message instead of a cryptic “License not found” exception. + +--- + +## Conclusion + +You now know exactly how to **create license instance** in Python and **configure license path** for the Aspose OCR SDK. The steps are straightforward: install the package, import `License`, instantiate it, point it at your `.lic` file, and verify with a tiny OCR test. + +Armed with this knowledge you can embed OCR capabilities into web services, desktop apps, or automated pipelines without stumbling over licensing errors. Next, consider exploring advanced OCR settings—language packs, image preprocessing, or batch processing—each of which builds on the solid foundation you’ve just set up. + +Got questions about deployment, Docker, or handling multiple licenses? Drop a comment, and happy coding! + + +## What Should You Learn Next? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/english/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..6d1beefb6 --- /dev/null +++ b/ocr/english/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: en +og_description: Create searchable PDF instantly. This guide shows how to run OCR, + convert scanned image PDF, and add OCR text layer using a single Python script. +og_title: Create Searchable PDF with Python – Complete Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Create Searchable PDF with Python – Step‑by‑Step Guide +url: /python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create Searchable PDF with Python – Step‑by‑Step Guide + +Ever wondered how to **create searchable PDF** from a scanned page without juggling dozens of tools? You’re not alone. In many office workflows a scanned TIFF or JPEG lands on a shared drive, and the next person has to copy‑paste text manually—painful, error‑prone, and time‑wasting. + +In this tutorial we’ll walk through a clean, programmatic solution that lets you **convert scanned image PDF**, **convert TIFF to PDF**, and **add OCR text layer** in one go. By the end you’ll have a ready‑to‑use script that runs OCR, embeds the hidden text, and spits out a searchable PDF you can index, search, or share with confidence. + +## What You’ll Need + +- Python 3.9+ (any recent version works) +- `aspose-ocr` and `aspose-pdf` packages (installed via `pip install aspose-ocr aspose-pdf`) +- A scanned image file (`.tif`, `.png`, `.jpg`, or even a PDF page that’s just an image) +- A modest amount of RAM (the OCR engine is lightweight; even a laptop handles it) + +> **Pro tip:** If you’re on Windows, the easiest way to get the packages is to run the command in an elevated PowerShell window. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Now that the prerequisites are out of the way, let’s dive into the code. + +## Step 1: Create an OCR Engine Instance – *create searchable pdf* + +The first thing we do is spin up the OCR engine. Think of it as the brain that will read every pixel and turn it into characters. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Why this matters:** Initializing the engine only once keeps memory usage low. If you were to call `OcrEngine()` inside a loop for each page, you’d quickly run out of resources. + +## Step 2: Load the Scanned Image – *convert tiff to pdf* & *convert scanned image pdf* + +Next, point the engine at the file you want to process. The API accepts any raster image, so a TIFF works just as well as a JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +If you happen to have a PDF that contains only a scanned image, you can still use `load_image` because Aspose will extract the first page automatically. + +## Step 3: Prepare PDF Save Options – *add OCR text layer* + +Here we configure how the final PDF should look. The crucial flag is `create_searchable_pdf`; setting it to `True` tells the library to embed an invisible text layer that mirrors the visual content. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **What the text layer does:** When you open the resulting file in Adobe Reader and try to select text, you’ll see the hidden characters. Search engines can index them, too—perfect for compliance or archiving. + +## Step 4: Run OCR and Save – *how to run OCR* in a single call + +Now the magic happens. One method call runs the recognition engine and writes the searchable PDF to disk. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +The `recognize` method returns a status object you can inspect for errors, but for most straightforward scenarios the simple call above is sufficient. + +### Expected Output + +Running the script prints: + +``` +PDF saved as searchable PDF. +``` + +If you open `scanned_page_searchable.pdf` you’ll notice you can select text, copy‑paste it, and even run a `Ctrl+F` search. That’s the hallmark of a **create searchable pdf** workflow. + +## Full Working Script + +Below is the complete, ready‑to‑run script. Just replace the placeholder paths with your actual file locations. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Save this as `create_searchable_pdf.py` and execute: + +```bash +python create_searchable_pdf.py +``` + +## Common Questions & Edge Cases + +### 1️⃣ Can I process multi‑page PDFs? + +Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will automatically generate a multi‑page searchable PDF. + +### 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + +Higher DPI yields better OCR accuracy but also larger memory usage. If you hit a `MemoryError`, downscale the image first: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ How do I change the language of the OCR? + +Set the `language` property on the engine before loading the image: + +```python +ocr_engine.language = "fra" # French +``` + +A full list of supported language codes lives in the Aspose documentation. + +### 4️⃣ What if I need to keep the original image quality? + +The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` to preserve the raster data exactly as it was. + +```python +pdf_save_options.compression = "None" +``` + +## Tips for Production‑Ready Deployments + +- **Batch processing:** Wrap the core logic in a function that accepts a list of file paths. Log each success/failure to a CSV for audit trails. +- **Parallelism:** Use `concurrent.futures.ThreadPoolExecutor` to run OCR on multiple cores. Just remember each thread needs its own `OcrEngine` instance. +- **Security:** If you’re handling sensitive documents, run the script in a sandboxed environment and delete the temporary files immediately after processing. + +## Conclusion + +You now know how to **create searchable PDF** files from scanned images using a concise Python script. By initializing an OCR engine, loading a TIFF (or any raster), configuring `PdfSaveOptions` to **add OCR text layer**, and finally calling `recognize`, the whole **convert scanned image pdf** and **convert TIFF to PDF** pipeline becomes a single, repeatable command. + +Next steps? Try chaining this script with a file‑watcher so any new scan dropped into a folder automatically becomes searchable. Or experiment with different OCR languages to support multilingual archives. The sky’s the limit when you combine OCR with PDF generation. + +Got more questions about **how to run OCR** in other languages or frameworks? Drop a comment below, and happy coding! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## What Should You Learn Next? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/english/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..567645ab5 --- /dev/null +++ b/ocr/english/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: en +og_description: Improve OCR accuracy in Python by applying image preprocessing for + text. Follow this guide to extract text from image files and recognize text from + PNG effortlessly. +og_title: Improve OCR Accuracy in Python – Full Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide +url: /python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + +Ever tried to **improve OCR accuracy** only to get garbled output? You're not the only one. Most developers hit the wall when the raw image is noisy, skewed, or just plain low‑contrast. The good news? A handful of preprocessing tricks can turn a blurry screenshot into clean, machine‑readable text. + +In this tutorial we’ll walk through a real‑world example that **preprocesses an image for OCR**, runs the recognition engine, and finally **extracts text from image** files—specifically a PNG. By the end you’ll know exactly how to **recognize text from PNG** with a higher success rate, and you’ll have a reusable code snippet you can drop into any project. + +## What You’ll Learn + +- Why image preprocessing matters for OCR engines +- Which preprocessing modes (denoise, deskew) give the biggest boost +- How to configure an `OcrEngine` instance in Python +- The complete, runnable script that **extracts text from image** files +- Tips for handling edge cases like rotated scans or low‑resolution pictures + +No external libraries beyond the OCR SDK are required, but you’ll need Python 3.8+ and a PNG image you want to read. + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Improve OCR accuracy workflow") + +*Alt text: improve OCR accuracy workflow diagram illustrating preprocessing and recognition steps.* + +## Prerequisites + +- Python 3.8 or newer installed +- Access to the OCR SDK that provides `OcrEngine`, `OcrEngineSettings`, and `ImagePreprocessMode` (the code below uses a generic API; replace with your vendor’s classes if needed) +- A PNG image (`input.png`) placed in a folder you can reference + +If you’re using a virtual environment, activate it now—nothing fancy, just `python -m venv venv && source venv/bin/activate`. + +--- + +## Step 1: Create the OCR Engine Instance – Start Improving OCR Accuracy + +The first thing you need is an OCR engine object. Think of it as the brain that will later read the pixels and spit out characters. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Why this matters: without an engine you can’t apply any preprocessing, and the raw image will be fed directly to the recogniser—usually the worst‑case scenario for accuracy. + +--- + +## Step 2: Load the Target PNG – Set the Stage for Recognize Text from PNG + +Now we tell the engine which file to work on. PNG is lossless, which already gives us a small edge over JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +If the image lives somewhere else, just adjust the path. The engine accepts any supported format, but PNG often preserves the fine details needed for crisp character edges. + +--- + +## Step 3: Configure Preprocessing – Preprocess Image for OCR + +Here’s where the magic happens. We create a settings object, enable denoising to wipe out speckles, and turn on deskew so tilted text is straightened automatically. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Why Denoise + Deskew? + +- **Denoise**: Random pixel noise confuses pattern‑matching algorithms. Removing it sharpens letters. +- **Deskew**: Even a 2‑degree tilt can drop confidence scores dramatically. Deskew aligns the baseline, letting the recogniser match fonts more reliably. + +You can experiment with additional flags (e.g., `ImagePreprocessMode.CONTRAST_ENHANCE`) if your images are especially dark. The SDK documentation usually lists all available modes. + +--- + +## Step 4: Apply the Settings to the Engine – Tie Preprocessing to OCR + +Assign the settings object to the engine so that the next recognition run uses the transformations we just defined. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +If you skip this step, the engine will fall back to its default (often “no preprocessing”), and you’ll see **lower OCR accuracy**. + +--- + +## Step 5: Run the Recognition Process – Extract Text from Image + +With everything wired up, we finally ask the engine to do its job. The call is synchronous, returning a result object that contains the recognized string. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Behind the scenes the engine now: + +1. Loads the PNG into memory +2. Applies denoise and deskew based on our settings +3. Runs the neural‑network or classic pattern matcher +4. Packages the output into `recognition_result` + +--- + +## Step 6: Output the Recognized Text – Verify the Improvement + +Let’s print the extracted string. In a real application you might write it to a file, a database, or pass it to another service. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Expected Output + +If the image contains the sentence “Hello, OCR World!” you should see: + +``` +Hello, OCR World! +``` + +Notice how the text is clean—no stray symbols or broken characters. That’s the result of proper **image preprocessing for text**. + +--- + +## Pro Tips & Edge Cases + +| Situation | What to Adjust | Why | +|-----------|----------------|-----| +| Very low‑resolution PNG (≤ 72 dpi) | Add `ImagePreprocessMode.SUPER_RESOLUTION` if available | Upsampling can give the recogniser more pixels to work with | +| Text is rotated > 5° | Increase deskew tolerance or manually rotate with `Pillow` before feeding the engine | Extreme angles sometimes bypass automatic deskew | +| Heavy background patterns | Enable `ImagePreprocessMode.BACKGROUND_REMOVAL` | Strips non‑text clutter that would otherwise be mis‑read | +| Multi‑language document | Set `ocr_engine.language = "eng+spa"` (or similar) | The engine picks the correct character set, improving overall accuracy | + +Remember, **improve OCR accuracy** isn’t a one‑size‑fits‑all; you may need to iterate on the preprocessing flags for your specific dataset. + +--- + +## Full Script – Ready to Copy & Paste + +Below is the complete, runnable example that incorporates every step we discussed. Save it as `improve_ocr_accuracy.py` and execute with `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Run it, watch the console, and you’ll see the **extract text from image** result right away. If the output looks off, tweak the `preprocess_mode` flags as described in the “Pro Tips” table. + +--- + +## Conclusion + +We’ve just walked through a practical recipe to **improve OCR accuracy** using Python. By creating an `OcrEngine`, loading a PNG, **preprocessing the image for OCR**, and finally **recognize text from PNG**, you can reliably **extract text from image** files even when the source isn’t perfect. + +Next steps? Try feeding a batch of images through a loop, store each result in a CSV, or experiment with additional preprocessing modes like contrast enhancement. The same pattern works for PDFs, scanned receipts, or handwritten notes—just swap the input and adjust the settings. + +Got questions about a specific image type or want to know how to integrate this into a web service? Drop a comment, and we’ll explore those scenarios together. Happy coding, and may your OCR results be ever crystal‑clear! + + +## What Should You Learn Next? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/english/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..7b9361d19 --- /dev/null +++ b/ocr/english/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: en +og_description: Master OCR region of interest to load image for OCR, extract text + from rectangle and recognize text from invoice in a single tutorial. +og_title: OCR Region of Interest – Step‑by‑Step Python Guide +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Region of Interest – Extract Text from Rectangle in Python +url: /python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Extract Text from Rectangle in Python + +Ever wondered how to **ocr region of interest** a specific part of a scanned invoice without feeding the whole page into the engine? You're not the first one staring at a blurry receipt and thinking, “How do I extract the amount that lives somewhere in the lower right?” The good news is that you can tell the OCR library exactly where to look, dramatically boosting both speed and accuracy. + +In this guide we’ll walk through a complete, runnable example that shows you how to **load image for OCR**, define a **region of interest**, and then **extract text from rectangle** to finally **recognize text from invoice** and answer the classic “how to extract amount” question. No vague references—just concrete code, clear explanations, and a few pro tips you’ll wish you’d known earlier. + +--- + +## What You’ll Build + +By the end of this tutorial you’ll have a tiny Python script that: + +1. Loads an invoice image from disk. +2. Marks a rectangular ROI where the total amount lives. +3. Runs OCR only inside that ROI. +4. Prints the cleaned‑up amount string. + +All of this works with any OCR library that supports ROI—here we’ll use a fictitious but representative `SimpleOCR` package that mimics popular tools like Tesseract or EasyOCR. Feel free to swap it out; the concepts stay the same. + +--- + +## Prerequisites + +- Python 3.8+ installed (`python --version` should show ≥3.8). +- A pip‑installable OCR package (e.g., `pip install simpleocr`). +- An invoice image (PNG or JPEG) placed in a folder you can reference. +- Basic familiarity with Python functions and classes (nothing fancy). + +If you already have those, great—let’s dive in. If not, grab the image first; the rest of the steps are independent of the actual file content. + +--- + +## Step 1: Load Image for OCR + +The first thing any OCR workflow needs is a bitmap to read from. Most libraries expose a simple `load_image` method that accepts a file path. Here’s how you do it with our `SimpleOCR` engine: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Use absolute paths or `os.path.join` to avoid “file not found” surprises when running the script from a different working directory. + +--- + +## Step 2: Define OCR Region of Interest + +Instead of letting the engine scan the whole page, we tell it *exactly* where the amount sits. This is the **ocr region of interest** step, and it’s the key to reliable extraction, especially when the document contains noisy headers or footers. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Why those numbers? `x` and `y` are pixel offsets from the top‑left corner, while `width` and `height` describe the box size. If you’re unsure, open the image in any editor, enable a ruler, and note the coordinates. Many IDEs even let you print the cursor position while hovering. + +--- + +## Step 3: Extract Text from Rectangle + +Now that the ROI is set, we ask the engine to **recognize text from invoice** but limited to the rectangle we just added. The call returns a result object that typically contains the raw string, confidence scores, and sometimes bounding boxes. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Behind the scenes, `recognize()` iterates over each ROI, crops that slice, runs the OCR model, and stitches the results together. This is why defining a tight **extract text from rectangle** region can shave seconds off processing time for batch jobs. + +--- + +## Step 4: How to Extract Amount – Clean the Output + +OCR isn’t perfect; you’ll often get stray spaces, line feeds, or even mis‑read characters (think “S” vs “5”). A quick `strip()` and a tiny regex usually do the trick for monetary values. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** If you plan to feed the amount into a database or a payment gateway, you need a predictable format. Stripping whitespace and filtering non‑numeric characters prevents downstream errors. + +--- + +## Step 5: Recognize Text from Invoice – Full Script + +Putting it all together, here’s the complete, ready‑to‑run script. Save it as `extract_amount.py` and execute `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Expected Output + +``` +Amount: 1,245.67 +``` + +If the ROI is mis‑aligned, you might see something like `Amount: 1245.6S`—notice the stray “S”. Adjust the rectangle coordinates and rerun until the output looks clean. + +--- + +## Common Pitfalls & Edge Cases + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI too small** | The amount text gets clipped, leading to partial recognition. | Expand `width`/`height` by ~10‑20 % and re‑test. | +| **Incorrect DPI** | Low‑resolution scans (≤150 dpi) reduce OCR accuracy. | Resample the image to 300 dpi before loading, or ask the scanner for higher DPI. | +| **Multiple currencies** | Regex picks the first numeric group, which might be an invoice number. | Refine the regex to look for currency symbols (`$`, `€`, `£`) before the digits. | +| **Rotated invoices** | OCR engines assume upright text; rotated pages break recognition. | Apply a rotation correction (`ocr_engine.rotate(90)`) before adding ROI. | +| **Noise in background** | Shadows or stamps confuse the model. | Pre‑process with a simple threshold (`cv2.threshold`) or use a denoising filter. | + +Addressing these edge cases early saves you hours of debugging later. + +--- + +## Pro Tips for Real‑World Projects + +- **Batch Processing:** Loop over a folder of invoices, compute ROI dynamically (e.g., based on template detection), and store results in CSV. +- **Template Matching:** If you handle several invoice layouts, maintain a JSON map of `template_id → ROI coordinates`. Switch ROI based on a quick layout classifier. +- **Parallel Execution:** Use `concurrent.futures.ThreadPoolExecutor` to run multiple OCR instances concurrently—great for high‑volume back‑office pipelines. +- **Confidence Filtering:** Most OCR results include a confidence score. Discard results below a threshold (e.g., 85 %) and flag them for manual review. + +--- + +## Conclusion + +We’ve covered everything you need to **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, and finally **recognize text from invoice** to answer the classic **how to extract amount** question. The script is compact, yet flexible enough to adapt to different document formats, languages, and OCR back‑ends. + +Now that you’ve mastered the basics, consider extending the workflow: add barcode scanning, integrate with a PDF parser, or push the extracted amount to an accounting API. The sky’s the limit, and with a well‑defined ROI you’ll always get faster, cleaner results. + +If you hit a snag, drop a comment below—happy OCRing! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## What Should You Learn Next? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/french/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..7dbb6fd30 --- /dev/null +++ b/ocr/french/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Tutoriel OCR asynchrone montrant comment utiliser Aspose OCR en Python + avec asyncio pour une extraction rapide du texte d'image. Apprenez la mise en œuvre + OCR asynchrone pas à pas. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: fr +og_description: Le tutoriel OCR asynchrone vous guide dans l’utilisation d’Aspose + OCR en Python avec asyncio pour une extraction efficace du texte des images. +og_title: Tutoriel OCR asynchrone – Python asyncio avec Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Tutoriel OCR asynchrone – Python asyncio avec Aspose OCR +url: /fr/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutoriel OCR Asynchrone – Python asyncio avec Aspose OCR + +Vous vous êtes déjà demandé comment exécuter la reconnaissance optique de caractères sans bloquer votre application ? Dans ce **tutoriel OCR asynchrone**, vous verrez exactement cela — extraction de texte non bloquante grâce à `asyncio` de Python et à la bibliothèque Aspose OCR. + +Si vous avez été coincé à attendre le traitement d’une image lourde, ce guide vous propose une solution propre et asynchrone qui garde votre boucle d’événements en activité. + +Dans les sections suivantes, nous couvrirons tout ce dont vous avez besoin : installation de la bibliothèque, mise en place d’un helper asynchrone, gestion du résultat, et même une astuce rapide pour passer à l’échelle avec plusieurs images. À la fin, vous pourrez intégrer un **tutoriel OCR asynchrone** dans n’importe quel projet Python qui utilise déjà `asyncio`. + +## Ce qu’il vous faut + +Avant de commencer, assurez‑vous d’avoir : + +* Python 3.9+ (l’API `asyncio` que nous utilisons est stable depuis la version 3.7) +* Une licence Aspose OCR active ou un essai gratuit (la bibliothèque est pure‑Python, sans binaires natifs) +* Un petit fichier image (`.jpg`, `.png`, etc.) que vous souhaitez lire – placez‑le dans un dossier connu + +Aucun autre outil externe n’est requis ; tout fonctionne en Python pur. + +## Étape 1 : Installer le package Aspose OCR + +Première chose, récupérez le package Aspose OCR depuis PyPI. Ouvrez un terminal et lancez : + +```bash +pip install aspose-ocr +``` + +> **Astuce :** Si vous travaillez dans un environnement virtuel (fortement recommandé), activez‑le d’abord. Cela maintient les dépendances isolées et évite les conflits de versions. + +## Étape 2 : Initialiser le moteur OCR de façon asynchrone + +Le cœur de notre **tutoriel OCR asynchrone** est une fonction helper asynchrone. Elle crée une instance `OcrEngine`, charge une image, puis appelle `recognize_async()`. Le moteur lui‑même est synchrone, mais la méthode wrapper renvoie un objet awaitable, permettant à la boucle d’événements de rester réactive. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Pourquoi procéder ainsi :** +*Créer le moteur à l’intérieur du helper garantit la sécurité des threads si vous lancez plus tard de nombreux travaux OCR en parallèle. Le mot‑clé `await` rend le contrôle à la boucle d’événements pendant que le travail lourd s’exécute dans le pool de threads interne de la bibliothèque.* + +## Étape 3 : Piloter le helper depuis une fonction principale asynchrone + +Nous avons maintenant besoin d’une petite coroutine `main()` qui appelle `async_ocr()` et affiche le résultat. Cela reflète le point d’entrée typique d’un script `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Que se passe‑t‑il en coulisses ?** +`asyncio.run()` crée une nouvelle boucle d’événements, planifie `main()`, puis ferme proprement la boucle lorsque `main()` se termine. Ce modèle est la façon recommandée de démarrer des programmes asynchrones sous Python 3.7+. + +## Étape 4 : Tester le script complet + +Enregistrez les deux blocs de code ci‑dessus dans un seul fichier, par ex. `async_ocr_demo.py`. Exécutez‑le depuis la ligne de commande : + +```bash +python async_ocr_demo.py +``` + +Si tout est correctement configuré, vous devriez voir quelque chose comme : + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +La sortie exacte dépendra du contenu de `photo.jpg`. L’essentiel est que le script se termine rapidement, même si l’image est volumineuse, car le travail OCR s’effectue en arrière‑plan. + +## Étape 5 : Mise à l’échelle – Traiter plusieurs images simultanément + +Une question fréquente est : *« Puis‑je OCR‑er un lot de fichiers sans lancer un nouveau processus pour chacun ? »* Absolument. Comme notre helper est entièrement asynchrone, nous pouvons regrouper de nombreuses coroutines avec `asyncio.gather()` : + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Pourquoi cela fonctionne :** `asyncio.gather()` planifie toutes les tâches OCR d’un coup. La bibliothèque Aspose OCR sous‑jacente utilise toujours son propre pool de threads, mais du point de vue de Python tout reste non bloquant, vous permettant de gérer des dizaines d’images dans le temps qu’une seule appel synchrone prendrait. + +## Étape 6 : Gérer les erreurs avec élégance + +Lorsque vous travaillez avec des fichiers externes, vous rencontrerez inévitablement des fichiers manquants, des images corrompues ou des problèmes de licence. Enveloppez l’appel OCR dans un bloc `try/except` pour garder la boucle d’événements active : + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Désormais, `batch_ocr()` peut appeler `safe_async_ocr` à la place, garantissant qu’un fichier défectueux n’interrompt pas tout le lot. + +## Vue d’ensemble visuelle + +![Diagramme du tutoriel OCR asynchrone](async-ocr-diagram.png){alt="Diagramme du flux du tutoriel OCR asynchrone montrant le helper async_ocr, la boucle d'événements et le moteur Aspose OCR"} + +Le diagramme ci‑dessus visualise le flux : boucle d’événements → `async_ocr` → `OcrEngine` → thread en arrière‑plan → résultat renvoyé à la boucle. + +## Pièges courants & Comment les éviter + +| Piège | Pourquoi cela arrive | Solution | +|-------|----------------------|----------| +| **Entrées‑sorties bloquantes dans le helper** | Utiliser accidentellement `open()` sans `await` bloque la boucle. | Utilisez `aiofiles` pour la lecture de fichiers, ou laissez `engine.load_image` s’en charger (c’est déjà non bloquant). | +| **Réutilisation d’un même `OcrEngine` entre coroutines** | Le moteur n’est pas thread‑safe ; les appels concurrents peuvent corrompre l’état. | Instanciez un nouveau moteur à chaque appel `async_ocr` (comme montré). | +| **Licence manquante** | Aspose OCR lève une exception liée à la licence à l’exécution. | Enregistrez votre licence tôt (`OcrEngine.set_license("license.json")`). | +| **Images volumineuses provoquant des pics de mémoire** | La bibliothèque charge l’image entière en RAM. | Redimensionnez les images avant l’OCR si la mémoire est un problème. | + +## Récapitulatif : Ce que nous avons accompli + +Dans ce **tutoriel OCR asynchrone**, nous : + +1. Installé la bibliothèque Aspose OCR. +2. Construit un helper `async_ocr` qui exécute la reconnaissance sans bloquer. +3. Lancé le helper depuis un point d’entrée `asyncio` propre. +4. Démontré le traitement par lot avec `asyncio.gather`. +5. Ajouté la gestion des erreurs et des bonnes pratiques. + +Tout cela est du pur Python, vous pouvez donc l’intégrer à un serveur web, un outil CLI ou un pipeline de données sans réécrire le code asynchrone existant. + +## Prochaines étapes & Sujets associés + +* **Pré‑traitement d’image asynchrone** – utilisez `aiohttp` pour télécharger les images en parallèle avant l’OCR. +* **Stockage des résultats OCR** – combinez ce tutoriel avec un driver de base de données asynchrone comme `asyncpg` pour PostgreSQL. +* **Optimisation des performances** – expérimentez avec `engine.recognize_async(max_threads=4)` si la bibliothèque expose une telle option. +* **Moteurs OCR alternatifs** – comparez Aspose OCR avec les wrappers asynchrones de Tesseract pour une analyse coût‑bénéfice. + +N’hésitez pas à expérimenter : essayez avec des PDF, ajustez les paramètres de langue, ou branchez les résultats à un chatbot. Le ciel est la limite une fois que vous avez une base solide de **tutoriel OCR asynchrone**. + +Bon codage, et que votre extraction de texte soit toujours rapide ! + +## Que devez‑vous apprendre ensuite ? + +- [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/) +- [Tutoriel Aspose OCR – Reconnaissance optique de caractères](/ocr/english/) +- [Comment OCR‑er du texte d’image avec langue en utilisant Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/french/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..f9a36a1bc --- /dev/null +++ b/ocr/french/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Détection automatique de la langue dans l’OCR simplifiée. Apprenez comment + charger une image OCR, activer la détection automatique de la langue et reconnaître + le texte de l’image en quelques étapes seulement. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: fr +og_description: Détection automatique de la langue dans l’OCR simplifiée. Suivez ce + tutoriel étape par étape pour activer la détection automatique de la langue, charger + l’OCR d’image et reconnaître le texte d’une image. +og_title: Détection automatique de la langue avec OCR – Guide complet Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Détection automatique de la langue avec OCR – Guide complet Python +url: /fr/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Détection automatique de la langue avec OCR – Guide complet Python + +Vous êtes‑vous déjà demandé comment faire en sorte qu'un moteur OCR *devine* la langue d'un document numérisé sans que vous ayez à lui indiquer ce qu'il doit rechercher ? C'est exactement ce que fait la **détection automatique de la langue**, et c'est une véritable révolution lorsque vous traitez des PDF multilingues, des photos de panneaux de rue ou toute image mélangeant plusieurs scripts. + +Dans ce tutoriel, nous parcourrons un exemple pratique qui vous montre comment **activer la détection automatique de la langue**, **charger l'image OCR**, et **reconnaître le texte d'une image** en utilisant une API de style Python. À la fin, vous disposerez d'un script autonome qui affiche à la fois le code de langue détecté et le texte extrait — aucune configuration manuelle de langue requise. + +## Ce que vous allez apprendre + +- Comment créer une instance du moteur OCR et activer la **détection automatique de la langue**. +- Les étapes exactes pour **charger l'image OCR** depuis le disque. +- Comment appeler la méthode `recognize()` du moteur et récupérer un résultat incluant le code de langue. +- Conseils pour gérer les cas limites comme les images à basse résolution ou les scripts non pris en charge. + +Aucune expérience préalable avec l'OCR multilingue n'est nécessaire ; il suffit d'une configuration Python de base et d'un fichier image. + +--- + +## Prérequis + +Avant de commencer, assurez‑vous d'avoir : + +1. Python 3.8+ installé (toute version récente fonctionne). +2. La bibliothèque OCR qui fournit `OcrEngine`, `LanguageAutoDetectMode`, etc. – pour ce guide, nous supposerons un package hypothétique appelé `myocr`. Installez‑le avec : + + ```bash + pip install myocr + ``` + +3. Un fichier image (`multilingual_sample.png`) contenant du texte dans au moins deux langues différentes. +4. Un peu de curiosité—si vous n’avez jamais touché à l’OCR auparavant, ne vous inquiétez pas ; le code est délibérément simple. + +--- + +## Étape 1 : Activer la détection automatique de la langue + +La première chose à faire est d'indiquer au moteur qu'il doit *déterminer* la langue tout seul. C’est ici que le drapeau de **détection automatique de la langue** entre en jeu. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Pourquoi c’est important :** +> Lorsque `AUTO_DETECT` est activé, le moteur exécute un classificateur de langue léger sur l'image avant que la reconnaissance de caractères lourde ne démarre. Cela signifie que vous n’avez pas à deviner si le texte est en anglais, russe, français ou toute autre combinaison. Le moteur sélectionnera automatiquement le meilleur modèle linguistique pour chaque région de l'image. + +--- + +## Étape 2 : Charger l'image OCR + +Maintenant que le moteur sait qu'il doit détecter automatiquement les langues, nous devons lui fournir quelque chose à traiter. L’étape **charger l'image OCR** lit le bitmap et prépare les tampons internes. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Astuce :** +> Si votre image dépasse 300 dpi, envisagez de la réduire à environ 150‑200 dpi. Trop de détails peuvent en fait *ralentir* l’étape de détection de la langue sans améliorer la précision. + +--- + +## Étape 3 : Reconnaître le texte à partir de l'image + +Avec l'image en mémoire et la détection de langue activée, la dernière étape consiste à demander au moteur de **reconnaître le texte de l'image**. Cet appel unique effectue tout le travail lourd. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` est un objet qui contient généralement au moins deux attributs : + +| Attribut | Description | +|-----------|-------------| +| `language` | Code ISO‑639‑1 de la langue détectée (par ex., `"en"` pour l'anglais). | +| `text` | La transcription en texte brut de l'image. | + +--- + +## Étape 4 : Récupérer la langue détectée et le texte extrait + +Nous affichons maintenant simplement ce que le moteur a découvert. Cela montre la capacité **detect language OCR** en action. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Exemple de sortie** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Et si le moteur renvoie `None` ?** +> Cela signifie généralement que l'image est trop floue ou que le texte est trop petit (< 8 pt). Essayez d'augmenter le contraste ou d'utiliser une source à plus haute résolution. + +--- + +## Exemple complet fonctionnel (Activer la détection automatique de la langue de bout en bout) + +En réunissant tous les éléments, voici un script prêt à l'exécution qui couvre **activer la détection automatique de la langue**, **charger l'image OCR**, **reconnaître le texte de l'image**, et **detect language OCR** en une seule fois. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Enregistrez‑le sous le nom `automatic_language_detection_ocr.py`, remplacez `YOUR_DIRECTORY` par le dossier contenant votre PNG, puis exécutez : + +```bash +python automatic_language_detection_ocr.py +``` + +Vous devriez voir le code de langue suivi du texte extrait, exactement comme l'exemple de sortie ci‑dessus. + +--- + +## Gestion des cas limites courants + +| Situation | Solution suggérée | +|-----------|-------------------| +| **Image très basse résolution** (moins de 100 dpi) | Agrandir avec un filtre bicubique avant le chargement, ou demander une source à plus haute résolution. | +| **Scripts mixtes dans une même image** (p. ex., anglais + cyrillique) | Le moteur divise généralement la page en régions ; si vous remarquez des détections erronées, définissez `engine.enable_region_split = True`. | +| **Langue non prise en charge** | Vérifiez que la bibliothèque OCR inclut un pack de langue pour le script requis ; il peut être nécessaire de télécharger des modèles supplémentaires. | +| **Traitement de gros lots** | Initialisez le moteur une fois, puis réutilisez‑le pour plusieurs cycles `load_image` / `recognize` afin d'éviter de recharger les modèles à chaque fois. | + +--- + +## Aperçu visuel + +![exemple de sortie de détection automatique de la langue montrant le code de langue détecté et le texte multilingue extrait](https://example.com/auto-lang-detect.png "détection automatique de la langue") + +*Texte alternatif :* exemple de sortie de détection automatique de la langue montrant le code de langue détecté et le texte multilingue extrait. + +--- + +## Conclusion + +Nous venons de couvrir la **détection automatique de la langue** de bout en bout — création du moteur, activation de la détection automatique de la langue, chargement d’une image pour l’OCR, reconnaissance du texte, et enfin récupération de la langue détectée. Ce flux complet vous permet de traiter des documents multilingues sans configurer manuellement les modèles de langue à chaque fois. + +Si vous êtes prêt à aller plus loin, envisagez : + +- **Batching** des centaines d'images avec une boucle qui réutilise la même instance `OcrEngine`. +- **Post‑processing** du texte extrait avec un correcteur orthographique ou un tokenizer spécifique à la langue. +- **Integrating** le script dans un service web qui accepte les téléchargements d'utilisateurs et renvoie du JSON avec les champs `language` et `text`. + +N'hésitez pas à expérimenter différents formats d'image (`.jpg`, `.tif`) et à observer comment la précision de la détection varie. Vous avez des questions ou une image difficile à lire ? Laissez un commentaire ci‑dessous—bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +- [Comment OCR le texte d'une image avec la langue en utilisant Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extraire le texte d'une image C# avec sélection de langue en utilisant Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [reconnaître le texte d'une image avec Aspose OCR pour plusieurs langues](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/french/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f4c7c6f18 --- /dev/null +++ b/ocr/french/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Apprenez à convertir des images en texte avec Python grâce à un script + de conversion d’images en texte en masse. Reconnaissez le texte des images numérisées + avec Aspose.OCR en quelques minutes. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: fr +og_description: Convertir des images en texte avec Python instantanément. Ce guide + montre la conversion d’images en texte en masse et comment reconnaître le texte + à partir d’images numérisées avec Aspose.OCR. +og_title: Convertir des images en texte Python – Tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Convertir des images en texte Python – Guide complet étape par étape +url: /fr/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir des images en texte Python – Guide complet étape par étape + +Vous vous êtes déjà demandé comment **convertir des images en texte python** sans devoir fouiller des dizaines de bibliothèques ? Vous n'êtes pas seul. Que vous numérisiez d'anciens reçus, extrayiez des données de factures scannées, ou construisiez une archive PDF consultable, transformer des images en fichiers texte brut est une tâche quotidienne pour de nombreux développeurs. + +Dans ce tutoriel, nous allons parcourir un pipeline de **conversion d’images en texte en masse** qui reconnaît le texte à partir d’images scannées, enregistre chaque résultat dans un fichier `.txt` individuel, et le fait le tout en quelques lignes de Python. Pas de recherche d’API obscures — Aspose.OCR fait le gros du travail, et nous vous montrons exactement comment le configurer. + +## Ce que vous allez apprendre + +- Comment installer et configurer le package Aspose.OCR pour Python. +- Le code exact nécessaire pour **convertir des images en texte python** à l’aide du `BatchOcrEngine`. +- Des astuces pour gérer les pièges courants comme les formats non pris en charge ou les fichiers corrompus. +- Des méthodes pour vérifier que l’étape **reconnaître le texte à partir d’images scannées** a réellement réussi. + +À la fin de ce guide, vous disposerez d’un script prêt à l’emploi capable de traiter des milliers d’images en une seule fois—parfait pour tout scénario de traitement par lots. + +## Prérequis + +- Python 3.8+ installé sur votre machine. +- Un dossier contenant les fichiers image (PNG, JPEG, TIFF, etc.) que vous souhaitez transformer en texte. +- Un compte Aspose Cloud actif ou une licence d’essai gratuite (le niveau gratuit suffit pour les tests). + +Si vous avez tout cela, plongeons‑y. + +--- + +## Étape 1 – Configurer votre environnement Python + +Avant d’écrire du code OCR, assurez‑vous de travailler dans un environnement virtuel propre. Cela isole les dépendances et évite les conflits de versions. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Astuce :** Gardez votre répertoire de projet bien organisé—créez un sous‑dossier nommé `ocr_project` et placez le script à l’intérieur. Cela simplifie la gestion des chemins plus tard. + +## Étape 2 – Installer Aspose.OCR pour Python + +Aspose.OCR est une bibliothèque commerciale, mais elle est distribuée avec une roue de type NuGet gratuite que vous pouvez récupérer depuis PyPI. Exécutez la commande suivante dans l’environnement virtuel activé : + +```bash +pip install aspose-ocr +``` + +Si vous obtenez une erreur de permission, ajoutez le drapeau `--user` ou lancez la commande avec `sudo` (Linux/macOS uniquement). Après l’installation, vous devriez voir quelque chose comme : + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Pourquoi Aspose ?** Contrairement à de nombreux outils OCR open‑source, Aspose.OCR prend en charge la **conversion d’images en texte en masse** dès le départ et gère une large gamme de formats d’image sans configuration supplémentaire. Il propose également la classe `BatchOcrEngine` qui transforme la tâche **convertir des images en texte python** en une opération d’une seule ligne. + +## Étape 3 – Convertir des images en texte Python avec le Batch OCR + +Passons maintenant au cœur du tutoriel. Le script ci‑dessous est entièrement exécutable et : + +1. Importe les classes du moteur OCR. +2. Instancie un `BatchOcrEngine`. +3. Pointe le moteur vers un dossier d’entrée contenant les images. +4. Indique au moteur d’écrire chaque fichier texte extrait dans un dossier de sortie. +5. Lance la méthode `recognize()`, qui **reconnaît le texte à partir d’images scannées** une par une. + +Enregistrez le fichier suivant sous le nom `batch_ocr.py` dans votre dossier de projet : + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Comment ça fonctionne + +- **`BatchOcrEngine`** enveloppe le `OcrEngine` classique mais ajoute une orchestration au niveau du dossier, exactement ce qu’il faut lorsque vous voulez **convertir des images en texte python** en lot. +- La propriété `input_folder` indique au moteur où chercher les images sources. Il parcourt automatiquement le répertoire et met en file d’attente chaque type de fichier pris en charge. +- La propriété `output_folder` détermine où chaque fichier `.txt` sera placé. Le moteur reproduit le nom de fichier d’origine, ainsi `receipt1.png` devient `receipt1.txt`. +- L’appel à `recognize()` déclenche la boucle interne qui charge chaque image, exécute l’OCR et écrit le résultat. La méthode bloque jusqu’à ce que tous les fichiers soient traités, ce qui facilite le chaînage d’actions supplémentaires (par ex., compresser le dossier de sortie). + +#### Résultat attendu + +Lorsque vous exécutez le script : + +```bash +python batch_ocr.py +``` + +Vous devriez voir : + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Dans le dossier `output_texts`, vous trouverez un fichier texte pour chaque image. Ouvrez‑en un avec un éditeur de texte et vous verrez le résultat brut de l’OCR — généralement une approximation proche du texte imprimé d’origine. + +## Étape 4 – Vérifier les résultats et gérer les erreurs + +Même les meilleurs moteurs OCR peuvent rencontrer des difficultés avec des scans basse résolution ou des pages fortement inclinées. Voici une méthode rapide pour vérifier la cohérence de la sortie et consigner les échecs. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Pourquoi ajouter cela ?** +- Cela capture les cas où le moteur produit silencieusement une chaîne vide (courant avec les images illisibles). +- Cela vous fournit une liste de fichiers problématiques afin que vous puissiez les inspecter manuellement ou relancer le processus avec d’autres paramètres (par ex., augmenter les options `OcrEngine.preprocess`). + +### Cas particuliers & ajustements + +| Situation | Solution suggérée | +|-----------|-------------------| +| Les images sont pivotées de 90° | Définissez `batch_engine.ocr_engine.rotation_correction = True`. | +| Langues mixtes (anglais + français) | Utilisez `batch_engine.ocr_engine.language = "eng+fra"` avant `recognize()`. | +| Gros PDFs convertis d’abord en images | Découpez les PDFs en images page par page, puis alimentez le dossier du batch engine. | +| Erreurs de mémoire sur des lots très volumineux | Traitez des sous‑dossiers plus petits séquentiellement, ou augmentez `batch_engine.max_memory_usage`. | + +## Étape 5 – Automatiser le workflow complet (optionnel) + +Si vous devez exécuter cette conversion chaque nuit, encapsulez le script dans un simple script shell ou un fichier batch Windows, puis planifiez‑le avec `cron` (Linux/macOS) ou le Planificateur de tâches (Windows). Voici un `run_ocr.sh` minimal pour les systèmes de type Unix : + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Rendez‑le exécutable (`chmod +x run_ocr.sh`) et ajoutez une entrée cron : + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Cela exécutera la conversion chaque jour à 2 h du matin et consignera toute sortie pour une révision ultérieure. + +--- + +## Conclusion + +Vous disposez maintenant d’une méthode éprouvée, prête pour la production, afin de **convertir des images en texte python** en utilisant le `BatchOcrEngine` d’Aspose.OCR. Le script gère la **conversion d’images en texte en masse**, écrit chaque résultat dans un fichier dédié, et inclut des étapes de vérification pour s’assurer que vous **reconnaissez le texte à partir d’images scannées** correctement. + +À partir d’ici, vous pouvez : + +- Expérimenter avec différents paramètres OCR (packs de langues, correction d’inclinaison, réduction du bruit). +- Alimenter le texte généré dans un index de recherche comme Elasticsearch pour une recherche plein texte instantanée. +- Combiner ce pipeline avec des outils de conversion PDF afin de traiter des PDFs scannés en une seule passe. + +Des questions ou un problème avec un type de fichier particulier ? Laissez un commentaire ci‑dessous, et résolvons‑le ensemble. Bon codage, et que vos exécutions OCR soient rapides et sans erreur ! + +## Ce que vous devriez apprendre ensuite + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/french/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..20631e03e --- /dev/null +++ b/ocr/french/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Créez une instance de licence en Python et configurez facilement le chemin + de la licence. Apprenez à configurer la licence Aspose OCR avec des exemples de + code clairs. +draft: false +keywords: +- create license instance +- configure license path +language: fr +og_description: Créez une instance de licence en Python et configurez le chemin de + licence instantanément. Suivez ce tutoriel pour activer Aspose OCR en toute confiance. +og_title: Créer une instance de licence en Python – Guide complet d'installation +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Créer une instance de licence en Python – Guide étape par étape +url: /fr/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer une instance de licence en Python – Guide complet d'installation + +Besoin de **create license instance** pour Aspose OCR en Python ? Vous êtes au bon endroit. Dans ce tutoriel, nous vous montrerons également comment **configure license path** afin que le SDK sache où trouver votre fichier `.lic`. + +Si vous avez déjà fixé les yeux sur un script vierge en vous demandant pourquoi le moteur OCR se plaint d’un produit non licencié, vous n’êtes pas seul. La solution se résume généralement à quelques lignes de code—une fois que vous savez exactement où les placer. À la fin de ce guide, vous disposerez d’un environnement Aspose OCR entièrement licencié, prêt à reconnaître du texte, des images et des PDF sans accroc. + +## Ce que vous allez apprendre + +- Comment **create license instance** en utilisant le package `asposeocr`. +- La bonne façon de **configure license path** pour le développement et la production. +- Les pièges courants (fichier manquant, permissions incorrectes) et comment les éviter. +- Un script complet, exécutable, que vous pouvez intégrer dans n’importe quel projet. + +Aucune expérience préalable avec Aspose OCR n’est requise, juste une installation fonctionnelle de Python 3 et un fichier de licence valide. + +--- + +## Étape 1 : Installer le package Python Aspose OCR + +Avant de pouvoir **create license instance**, la bibliothèque doit être présente. Ouvrez un terminal et exécutez : + +```bash +pip install aspose-ocr +``` + +> **Astuce :** Si vous utilisez un environnement virtuel (fortement recommandé), activez‑le d’abord. Cela garde vos dépendances propres et évite les conflits de version. + +## Étape 2 : Importer la classe License + +Maintenant que le SDK est disponible, la toute première ligne de votre script doit importer la classe `License`. C’est l’objet que nous utiliserons pour **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Pourquoi l’importer immédiatement ? Parce que l’objet `License` doit être instancié **avant** tout appel OCR ; sinon le SDK lèvera une erreur de licence dès que vous tenterez de traiter une image. + +## Étape 3 : Créer l'instance de licence + +Voici le moment que vous attendiez—**create license instance** réellement. C’est une seule ligne, mais le contexte qui l’entoure est important. + +```python +# Step 3: Create a License instance +license = License() +``` + +La variable `license` contient maintenant un objet qui contrôle tout le comportement de licence pour le processus Python en cours. Pensez‑y comme le gardien qui dit à Aspose OCR : « Hey, j’ai le droit de fonctionner. » + +## Étape 4 : Configurer le chemin de la licence + +Avec l’instance prête, nous devons la pointer vers notre fichier `.lic`. C’est là que **configure license path** entre en jeu. Remplacez le texte de substitution par le chemin absolu de votre fichier de licence. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Quelques points à retenir : + +1. **Les chaînes brutes (`r"…"`)** empêchent les barres obliques inverses d’être interprétées comme des caractères d’échappement sous Windows. +2. Utilisez un **chemin absolu** pour éviter toute confusion lorsque le script est lancé depuis un répertoire de travail différent. +3. Si vous préférez un chemin relatif (par ex., lors de l’inclusion de la licence dans votre projet), assurez‑vous que la base relative soit l’emplacement du script, et non le répertoire du shell actuel. + +### Gestion des fichiers manquants + +Si le chemin est incorrect ou que le fichier est illisible, `set_license` lèvera une exception. Enveloppez l’appel dans un bloc `try/except` pour afficher un message d’erreur convivial : + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Ce fragment **configure license path** en toute sécurité et vous indique exactement ce qui a échoué—pas de traces de pile mystérieuses. + +## Étape 5 : Vérifier que la licence est active + +Une vérification rapide évite des heures de débogage plus tard. Après avoir appelé `set_license`, essayez une opération OCR simple. Si la licence est valide, le SDK traitera l’image sans lever d’erreur de licence. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Si le texte reconnu s’affiche, félicitations — vous avez bien **create license instance** et **configure license path**. Si vous obtenez une exception de licence, revérifiez le chemin et les permissions du fichier. + +## Cas particuliers & bonnes pratiques + +| Situation | Que faire | +|-----------|-----------| +| **Le fichier de licence se trouve sur un partage réseau** | Mapper le partage à une lettre de lecteur ou utiliser un chemin UNC (`\\server\share\license.lic`). Assurez‑vous que le processus Python a les droits de lecture. | +| **Exécution dans un conteneur Docker** | Copier le fichier `.lic` dans l’image et le référencer avec un chemin absolu comme `/app/license/Aspose.OCR.Java.lic`. | +| **Plusieurs interprètes Python** (ex. environnements conda) | Installer le fichier de licence une fois par environnement ou le placer dans un emplacement central et pointer chaque interprète vers celui‑ci. | +| **Fichier de licence absent au moment de l’exécution** | Revenir à un mode d’essai (si supporté) ou interrompre avec un message de log clair. | + +### Pièges courants + +- **Utiliser des barres obliques (`/`) sous Windows** – Python les accepte, mais certaines versions plus anciennes du SDK peuvent les mal interpréter. Préférez les chaînes brutes ou les doubles barres obliques inverses (`\\`). +- **Oublier d’importer `License`** – Le script plantera avec `NameError`. Importez toujours avant d’instancier. +- **Appeler `set_license` après les méthodes OCR** – Le SDK vérifie la licence dès la première utilisation, donc définissez le chemin **en premier**. + +## Exemple complet fonctionnel + +Voici un script complet qui réunit tous les éléments. Enregistrez‑le sous le nom `ocr_setup.py` et exécutez‑le depuis la ligne de commande. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Sortie attendue** (avec une image valide) : + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Si le fichier de licence est introuvable, vous verrez un message d’erreur clair au lieu d’une exception « License not found » cryptique. + +--- + +## Conclusion + +Vous savez maintenant comment **create license instance** en Python et **configure license path** pour le SDK Aspose OCR. Les étapes sont simples : installer le package, importer `License`, l’instancier, le pointer vers votre fichier `.lic`, puis vérifier avec un petit test OCR. + +Fort de ces connaissances, vous pouvez intégrer des capacités OCR dans des services web, des applications de bureau ou des pipelines automatisés sans rencontrer d’erreurs de licence. Ensuite, explorez les réglages OCR avancés — packs de langues, prétraitement d’image, traitement par lots—tous basés sur la solide fondation que vous venez de mettre en place. + +Des questions sur le déploiement, Docker ou la gestion de licences multiples ? Laissez un commentaire, et bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/french/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..60116b12e --- /dev/null +++ b/ocr/french/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: Créez un PDF consultable à partir d'images numérisées avec Python OCR. + Apprenez à convertir un PDF d'images numérisées, à transformer un TIFF en PDF et + à ajouter une couche de texte OCR en quelques minutes. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: fr +og_description: Créez un PDF consultable instantanément. Ce guide montre comment exécuter + l’OCR, convertir un PDF d’image numérisée et ajouter une couche de texte OCR à l’aide + d’un seul script Python. +og_title: Créer un PDF consultable avec Python – Tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Créer un PDF consultable avec Python – Guide étape par étape +url: /fr/python-java/general/create-searchable-pdf-with-python-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 avec Python – Guide pas à pas + +Vous êtes‑vous déjà demandé comment **créer un PDF interrogeable** à partir d’une page numérisée sans jongler avec des dizaines d’outils ? Vous n’êtes pas seul. Dans de nombreux flux de travail de bureau, un TIFF ou JPEG numérisé atterrit sur un lecteur partagé, et la personne suivante doit copier‑coller le texte manuellement — fastidieux, source d’erreurs et perte de temps. + +Dans ce tutoriel, nous parcourrons une solution propre et programmatique qui vous permet de **convertir un PDF d’image numérisée**, **convertir TIFF en PDF**, et **ajouter une couche de texte OCR** en une seule étape. À la fin, vous disposerez d’un script prêt à l’emploi qui exécute l’OCR, intègre le texte caché et génère un PDF interrogeable que vous pouvez indexer, rechercher ou partager en toute confiance. + +## Ce dont vous avez besoin + +- Python 3.9+ (toute version récente fonctionne) +- `aspose-ocr` et `aspose-pdf` packages (installés via `pip install aspose-ocr aspose-pdf`) +- Un fichier image numérisé (`.tif`, `.png`, `.jpg`, ou même une page PDF qui n’est qu’une image) +- Une quantité modeste de RAM (le moteur OCR est léger ; même un ordinateur portable le gère) + +> **Astuce :** Si vous êtes sous Windows, le moyen le plus simple d’obtenir les paquets est d’exécuter la commande dans une fenêtre PowerShell élevée. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Maintenant que les prérequis sont réglés, plongeons dans le code. + +## Étape 1 : Créer une instance du moteur OCR – *create searchable pdf* + +La première chose que nous faisons est de lancer le moteur OCR. Considérez-le comme le cerveau qui lira chaque pixel et le transformera en caractères. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Pourquoi c’est important :** Initialiser le moteur une seule fois maintient une faible utilisation de la mémoire. Si vous appeliez `OcrEngine()` dans une boucle pour chaque page, vous manqueriez rapidement de ressources. + +## Étape 2 : Charger l’image numérisée – *convert tiff to pdf* & *convert scanned image pdf* + +Ensuite, pointez le moteur vers le fichier que vous souhaitez traiter. L’API accepte n’importe quelle image raster, donc un TIFF fonctionne tout aussi bien qu’un JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Si vous avez un PDF qui ne contient qu’une image numérisée, vous pouvez toujours utiliser `load_image` car Aspose extraira automatiquement la première page. + +## Étape 3 : Préparer les options d’enregistrement PDF – *add OCR text layer* + +Ici, nous configurons l’apparence du PDF final. Le drapeau crucial est `create_searchable_pdf` ; le définir à `True` indique à la bibliothèque d’intégrer une couche de texte invisible qui reflète le contenu visuel. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Ce que fait la couche de texte :** Lorsque vous ouvrez le fichier résultant dans Adobe Reader et essayez de sélectionner du texte, vous verrez les caractères cachés. Les moteurs de recherche peuvent également les indexer — idéal pour la conformité ou l’archivage. + +## Étape 4 : Exécuter l’OCR et enregistrer – *how to run OCR* in a single call + +Maintenant, la magie opère. Un seul appel de méthode exécute le moteur de reconnaissance et écrit le PDF interrogeable sur le disque. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +La méthode `recognize` renvoie un objet d’état que vous pouvez inspecter pour détecter des erreurs, mais pour la plupart des scénarios simples, l’appel simple ci‑dessus suffit. + +### Sortie attendue + +L’exécution du script affiche : + +``` +PDF saved as searchable PDF. +``` + +Si vous ouvrez `scanned_page_searchable.pdf`, vous remarquerez que vous pouvez sélectionner du texte, le copier‑coller, et même lancer une recherche `Ctrl+F`. C’est la marque d’un flux de travail **create searchable pdf**. + +## Script complet fonctionnel + +Ci‑dessous se trouve le script complet, prêt à être exécuté. Remplacez simplement les chemins factices par vos emplacements de fichiers réels. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Enregistrez-le sous le nom `create_searchable_pdf.py` et exécutez : + +```bash +python create_searchable_pdf.py +``` + +## Questions fréquentes & cas particuliers + +### 1️⃣ Puis‑je traiter des PDF multi‑pages ? + +Oui. Utilisez `ocr_engine.load_image("file.pdf")` puis bouclez sur chaque page avec `ocr_engine.recognize(pdf_save_options, page_number)`. La bibliothèque générera automatiquement un PDF interrogeable multi‑pages. + +### 2️⃣ Que faire si mon fichier source est un TIFF haute résolution (300 dpi+) ? + +Une résolution DPI plus élevée donne une meilleure précision OCR mais aussi une utilisation mémoire plus importante. Si vous rencontrez un `MemoryError`, réduisez d’abord la taille de l’image : + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Comment changer la langue de l’OCR ? + +Définissez la propriété `language` sur le moteur avant de charger l’image : + +```python +ocr_engine.language = "fra" # French +``` + +Une liste complète des codes de langue pris en charge se trouve dans la documentation Aspose. + +### 4️⃣ Que faire si je dois conserver la qualité d’image d’origine ? + +La classe `PdfSaveOptions` possède une propriété `compression`. Réglez‑la sur `PdfCompression.None` pour préserver les données raster exactement telles qu’elles étaient. + +```python +pdf_save_options.compression = "None" +``` + +## Conseils pour des déploiements prêts pour la production + +- **Traitement par lots :** Encapsulez la logique principale dans une fonction qui accepte une liste de chemins de fichiers. Enregistrez chaque succès/échec dans un CSV pour les traces d’audit. +- **Parallélisme :** Utilisez `concurrent.futures.ThreadPoolExecutor` pour exécuter l’OCR sur plusieurs cœurs. N’oubliez pas que chaque thread a besoin de sa propre instance `OcrEngine`. +- **Sécurité :** Si vous traitez des documents sensibles, exécutez le script dans un environnement sandbox et supprimez les fichiers temporaires immédiatement après le traitement. + +## Conclusion + +Vous savez maintenant comment **créer des PDF interrogeables** à partir d’images numérisées en utilisant un script Python concis. En initialisant un moteur OCR, en chargeant un TIFF (ou tout raster), en configurant `PdfSaveOptions` pour **add OCR text layer**, et enfin en appelant `recognize`, l’ensemble du pipeline **convert scanned image pdf** et **convert TIFF to PDF** devient une commande unique et réutilisable. + +Prochaines étapes ? Essayez d’enchaîner ce script avec un observateur de fichiers afin que chaque nouvelle numérisation déposée dans un dossier devienne automatiquement interrogeable. Ou expérimentez différentes langues OCR pour prendre en charge des archives multilingues. Le ciel est la limite lorsque vous combinez OCR et génération de PDF. + +Vous avez d’autres questions sur **how to run OCR** dans d’autres langages ou frameworks ? Laissez un commentaire ci‑dessous, et bon codage ! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + +## Que devriez‑vous apprendre ensuite ? + +- [Comment faire de l’OCR d’un PDF en .NET avec Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convertir des images en PDF C# – Enregistrer le résultat OCR multi‑pages](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Comment faire de l’OCR de texte d’image avec la langue en utilisant Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/french/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..198f7803f --- /dev/null +++ b/ocr/french/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Améliorez la précision de l'OCR avec Python en prétraitant les images + pour l'OCR. Apprenez à extraire le texte des fichiers image, à reconnaître le texte + à partir de PNG et à optimiser les résultats. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: fr +og_description: Améliorez la précision de l'OCR en Python en appliquant un prétraitement + d'image pour le texte. Suivez ce guide pour extraire le texte des fichiers image + et reconnaître le texte des PNG sans effort. +og_title: Améliorer la précision de l'OCR en Python – Tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Améliorer la précision de l’OCR en Python – Guide complet étape par étape +url: /fr/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-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 étape par étape + +Vous avez déjà essayé d'**améliorer la précision OCR** pour n'obtenir qu'un texte illisible ? Vous n'êtes pas seul. La plupart des développeurs se heurtent à un mur lorsque l'image brute est bruitée, inclinée ou simplement à faible contraste. Bonne nouvelle ? Quelques astuces de prétraitement peuvent transformer une capture d'écran floue en texte propre, lisible par machine. + +Dans ce tutoriel, nous allons parcourir un exemple réel qui **prétraite une image pour l'OCR**, exécute le moteur de reconnaissance, puis **extrait le texte d'un fichier image** — spécifiquement un PNG. À la fin, vous saurez exactement comment **reconnaître du texte à partir d'un PNG** avec un taux de succès plus élevé, et vous disposerez d'un extrait de code réutilisable à intégrer dans n'importe quel projet. + +## Ce que vous allez apprendre + +- Pourquoi le prétraitement d'image est essentiel pour les moteurs OCR +- Quels modes de prétraitement (denoise, deskew) offrent le plus grand gain +- Comment configurer une instance `OcrEngine` en Python +- Le script complet, exécutable, qui **extrait le texte d'un fichier image** +- Astuces pour gérer les cas particuliers comme les scans tournés ou les images basse résolution + +Aucune bibliothèque externe au-delà du SDK OCR n'est requise, mais vous aurez besoin de Python 3.8+ et d'une image PNG que vous souhaitez lire. + +--- + +![Diagramme montrant les étapes pour améliorer la précision OCR en Python](image.png "Flux de travail d'amélioration de la précision OCR") + +*Texte alternatif : diagramme du flux de travail d'amélioration de la précision OCR illustrant les étapes de prétraitement et de reconnaissance.* + +## Prérequis + +- Python 3.8 ou version supérieure installé +- Accès au SDK OCR qui fournit `OcrEngine`, `OcrEngineSettings` et `ImagePreprocessMode` (le code ci‑dessous utilise une API générique ; remplacez‑la par les classes de votre fournisseur si nécessaire) +- Une image PNG (`input.png`) placée dans un dossier que vous pouvez référencer + +Si vous utilisez un environnement virtuel, activez‑le maintenant — rien de compliqué, juste `python -m venv venv && source venv/bin/activate`. + +--- + +## Étape 1 : Créer l'instance du moteur OCR – Commencer à améliorer la précision OCR + +La première chose dont vous avez besoin est un objet moteur OCR. Pensez‑y comme le cerveau qui lira plus tard les pixels et générera des caractères. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Pourquoi c’est important : sans moteur, vous ne pouvez appliquer aucun prétraitement, et l'image brute sera directement transmise au reconnaisseur—généralement le pire scénario pour la précision. + +--- + +## Étape 2 : Charger le PNG cible – Préparer la reconnaissance de texte à partir du PNG + +Nous indiquons maintenant au moteur quel fichier traiter. Le PNG est sans perte, ce qui nous donne déjà un léger avantage sur le JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Si l'image se trouve ailleurs, ajustez simplement le chemin. Le moteur accepte tout format supporté, mais le PNG conserve souvent les détails fins nécessaires aux contours nets des caractères. + +--- + +## Étape 3 : Configurer le prétraitement – Prétraiter l'image pour l'OCR + +C’est ici que la magie opère. Nous créons un objet de paramètres, activons le débruitage pour éliminer les taches, et activons le redressement afin que le texte incliné soit automatiquement remis à plat. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Pourquoi Denoise + Deskew ? + +- **Denoise** : Le bruit aléatoire des pixels perturbe les algorithmes de correspondance de motifs. Le supprimer affine les lettres. +- **Deskew** : Même une inclinaison de 2 degrés peut faire chuter les scores de confiance de façon spectaculaire. Le redressement aligne la ligne de base, permettant au reconnaisseur de faire correspondre les polices de façon plus fiable. + +Vous pouvez expérimenter avec des drapeaux supplémentaires (par ex., `ImagePreprocessMode.CONTRAST_ENHANCE`) si vos images sont particulièrement sombres. La documentation du SDK répertorie généralement tous les modes disponibles. + +--- + +## Étape 4 : Appliquer les paramètres au moteur – Lier le prétraitement à l'OCR + +Attribuez l'objet de paramètres au moteur afin que la prochaine exécution de reconnaissance utilise les transformations que nous venons de définir. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Si vous sautez cette étape, le moteur reviendra à ses paramètres par défaut (souvent « pas de prétraitement »), et vous constaterez **une moindre précision OCR**. + +--- + +## Étape 5 : Exécuter le processus de reconnaissance – Extraire le texte de l'image + +Une fois tout câblé, nous demandons enfin au moteur d’accomplir sa tâche. L’appel est synchrone et renvoie un objet résultat contenant la chaîne reconnue. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +En coulisses, le moteur effectue maintenant : + +1. Charge le PNG en mémoire +2. Applique le débruitage et le redressement selon nos paramètres +3. Exécute le réseau neuronal ou le moteur de correspondance classique +4. Emballe la sortie dans `recognition_result` + +--- + +## Étape 6 : Afficher le texte reconnu – Vérifier l'amélioration + +Imprimons la chaîne extraite. Dans une vraie application, vous pourriez l’écrire dans un fichier, une base de données, ou la transmettre à un autre service. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Résultat attendu + +Si l'image contient la phrase « Hello, OCR World! », vous devriez voir : + +``` +Hello, OCR World! +``` + +Remarquez que le texte est propre—pas de symboles errants ni de caractères cassés. C’est le résultat d’un **prétraitement d'image adéquat pour le texte**. + +--- + +## Astuces pro & cas particuliers + +| Situation | Ajustement à effectuer | Pourquoi | +|-----------|------------------------|----------| +| PNG très basse résolution (≤ 72 dpi) | Ajouter `ImagePreprocessMode.SUPER_RESOLUTION` si disponible | L'up‑sampling fournit plus de pixels au reconnaisseur | +| Texte tourné de plus de 5° | Augmenter la tolérance du deskew ou faire une rotation manuelle avec `Pillow` avant d’alimenter le moteur | Les angles extrêmes contournent parfois le deskew automatique | +| Motifs de fond lourds | Activer `ImagePreprocessMode.BACKGROUND_REMOVAL` | Supprime le bruit non textuel qui serait autrement mal interprété | +| Document multilingue | Définir `ocr_engine.language = "eng+spa"` (ou similaire) | Le moteur sélectionne le jeu de caractères adéquat, améliorant la précision globale | + +Rappelez‑vous, **améliorer la précision OCR** n’est pas une solution universelle ; il vous faudra peut‑être itérer sur les drapeaux de prétraitement selon votre jeu de données. + +--- + +## Script complet – Prêt à copier‑coller + +Voici l’exemple complet, exécutable, qui intègre chaque étape décrite. Enregistrez‑le sous `improve_ocr_accuracy.py` et lancez‑le avec `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Exécutez‑le, observez la console, et vous verrez immédiatement le résultat **extract text from image**. Si la sortie semble incorrecte, ajustez les drapeaux `preprocess_mode` comme indiqué dans le tableau « Astuces pro ». + +--- + +## Conclusion + +Nous venons de parcourir une recette pratique pour **améliorer la précision OCR** avec Python. En créant un `OcrEngine`, en chargeant un PNG, en **prétraitant l'image pour l'OCR**, puis en **reconnaissant du texte à partir du PNG**, vous pouvez extraire de façon fiable du texte d'images même lorsque la source n’est pas parfaite. + +Prochaines étapes ? Essayez de traiter un lot d’images dans une boucle, stockez chaque résultat dans un CSV, ou expérimentez d’autres modes de prétraitement comme l’amélioration du contraste. Le même schéma fonctionne pour les PDF, les reçus scannés ou les notes manuscrites—il suffit de changer l’entrée et d’ajuster les paramètres. + +Des questions sur un type d’image spécifique ou sur l’intégration dans un service web ? Laissez un commentaire, et nous explorerons ces scénarios ensemble. Bon codage, et que vos résultats OCR soient toujours d’une clarté cristalline ! + +## Que devez‑vous apprendre ensuite ? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/french/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..4273e4aa2 --- /dev/null +++ b/ocr/french/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Apprenez à utiliser la région d'intérêt OCR pour charger une image, effectuer + l'OCR et extraire le texte d'un rectangle, idéal pour reconnaître le montant sur + une facture. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: fr +og_description: Maîtrisez la région d'intérêt OCR pour charger l'image pour l'OCR, + extraire le texte du rectangle et reconnaître le texte d'une facture dans un seul + tutoriel. +og_title: OCR Région d'intérêt – Guide Python étape par étape +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Région d'intérêt – Extraire le texte d'un rectangle en Python +url: /fr/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Région d'intérêt OCR – Extraire du texte d'un rectangle en Python + +Vous vous êtes déjà demandé comment **ocr region of interest** une partie spécifique d'une facture numérisée sans alimenter toute la page dans le moteur ? Vous n'êtes pas le premier à fixer un reçu flou en pensant « Comment extraire le montant qui se trouve quelque part en bas à droite ? » La bonne nouvelle, c'est que vous pouvez indiquer à la bibliothèque OCR exactement où regarder, ce qui augmente considérablement la vitesse et la précision. + +Dans ce guide, nous parcourrons un exemple complet et exécutable qui montre comment **load image for OCR**, définir une **region of interest**, puis **extract text from rectangle** pour finalement **recognize text from invoice** et répondre à la question classique « how to extract amount ». Pas de références vagues – seulement du code concret, des explications claires et quelques astuces professionnelles que vous auriez aimé connaître plus tôt. + +--- + +## Ce que vous allez construire + +À la fin de ce tutoriel, vous disposerez d’un petit script Python qui : + +1. Charge une image de facture depuis le disque. +2. Marque une ROI rectangulaire où se trouve le montant total. +3. Exécute l'OCR uniquement à l'intérieur de cette ROI. +4. Affiche la chaîne du montant nettoyée. + +Tout cela fonctionne avec n'importe quelle bibliothèque OCR qui prend en charge les ROI – ici nous utiliserons un package fictif mais représentatif `SimpleOCR` qui imite des outils populaires comme Tesseract ou EasyOCR. N'hésitez pas à le remplacer ; les concepts restent les mêmes. + +--- + +## Prérequis + +- Python 3.8+ installé (`python --version` doit afficher ≥3.8). +- Un package OCR installable via pip (par ex., `pip install simpleocr`). +- Une image de facture (PNG ou JPEG) placée dans un dossier que vous pouvez référencer. +- Une connaissance de base des fonctions et classes Python (rien de compliqué). + +Si vous avez déjà tout cela, super—plongeons‑nous dedans. Sinon, récupérez d'abord l'image ; le reste des étapes est indépendant du contenu réel du fichier. + +--- + +## Étape 1 : Charger l'image pour l'OCR + +La première chose dont tout flux de travail OCR a besoin est un bitmap à lire. La plupart des bibliothèques exposent une méthode simple `load_image` qui accepte un chemin de fichier. Voici comment le faire avec notre moteur `SimpleOCR` : + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Astuce :** Utilisez des chemins absolus ou `os.path.join` pour éviter les surprises « file not found » lors de l'exécution du script depuis un répertoire de travail différent. + +--- + +## Étape 2 : Définir la région d'intérêt OCR + +Au lieu de laisser le moteur scanner toute la page, nous lui indiquons *exactement* où se trouve le montant. C’est l’étape **ocr region of interest**, et c’est la clé d’une extraction fiable, surtout lorsque le document contient des en‑têtes ou pieds‑de‑page bruyants. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Pourquoi ces nombres ? `x` et `y` sont des décalages en pixels depuis le coin supérieur gauche, tandis que `width` et `height` décrivent la taille du rectangle. Si vous n'êtes pas sûr, ouvrez l'image dans n'importe quel éditeur, activez une règle et notez les coordonnées. De nombreux IDE permettent même d'afficher la position du curseur au survol. + +--- + +## Étape 3 : Extraire du texte du rectangle + +Maintenant que la ROI est définie, nous demandons au moteur de **recognize text from invoice** mais limité au rectangle que nous venons d'ajouter. L'appel renvoie un objet résultat qui contient généralement la chaîne brute, les scores de confiance et parfois les boîtes englobantes. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +En coulisses, `recognize()` parcourt chaque ROI, découpe cette portion, exécute le modèle OCR et assemble les résultats. C’est pourquoi définir une région **extract text from rectangle** précise peut économiser des secondes de temps de traitement pour les travaux par lots. + +--- + +## Étape 4 : Comment extraire le montant – Nettoyer la sortie + +L'OCR n'est pas parfait ; vous obtiendrez souvent des espaces superflus, des sauts de ligne ou même des caractères mal lus (pensez « S » vs « 5 »). Un rapide `strip()` et une petite expression régulière suffisent généralement pour les valeurs monétaires. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Pourquoi c’est important :** Si vous prévoyez d’alimenter le montant dans une base de données ou une passerelle de paiement, vous avez besoin d’un format prévisible. Supprimer les espaces et filtrer les caractères non numériques évite les erreurs en aval. + +--- + +## Étape 5 : Reconnaître le texte de la facture – Script complet + +En combinant le tout, voici le script complet, prêt à être exécuté. Enregistrez‑le sous `extract_amount.py` et lancez `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Sortie attendue + +``` +Amount: 1,245.67 +``` + +Si la ROI est mal alignée, vous pourriez voir quelque chose comme `Amount: 1245.6S`—remarquez le « S » errant. Ajustez les coordonnées du rectangle et relancez jusqu'à ce que la sortie soit propre. + +--- + +## Pièges courants & cas limites + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI trop petite** | Le texte du montant est tronqué, entraînant une reconnaissance partielle. | Agrandissez `width`/`height` d’environ 10‑20 % et retestez. | +| **DPI incorrect** | Les scans à basse résolution (≤150 dpi) réduisent la précision de l'OCR. | Rééchantillonnez l'image à 300 dpi avant le chargement, ou demandez au scanner une résolution plus élevée. | +| **Multiples devises** | L'expression régulière prend le premier groupe numérique, qui peut être le numéro de facture. | Affinez l'expression régulière pour rechercher les symboles monétaires (`$`, `€`, `£`) avant les chiffres. | +| **Factures tournées** | Les moteurs OCR supposent du texte droit ; les pages tournées perturbent la reconnaissance. | Appliquez une correction de rotation (`ocr_engine.rotate(90)`) avant d'ajouter la ROI. | +| **Bruit en arrière‑plan** | Les ombres ou tampons confondent le modèle. | Pré‑traitez avec un simple seuil (`cv2.threshold`) ou utilisez un filtre de débruitage. | + +--- + +## Astuces pro pour les projets réels + +- **Traitement par lots :** Parcourez un dossier de factures, calculez la ROI dynamiquement (par ex., basé sur la détection de modèle), et stockez les résultats dans un CSV. +- **Correspondance de modèles :** Si vous gérez plusieurs mises en page de factures, conservez une carte JSON de `template_id → ROI coordinates`. Changez la ROI en fonction d'un classificateur de mise en page rapide. +- **Exécution parallèle :** Utilisez `concurrent.futures.ThreadPoolExecutor` pour exécuter plusieurs instances OCR en parallèle—idéal pour les pipelines back‑office à haut volume. +- **Filtrage par confiance :** La plupart des résultats OCR incluent un score de confiance. Écartez les résultats en dessous d’un seuil (par ex., 85 %) et signalez‑les pour une révision manuelle. + +--- + +## Conclusion + +Nous avons couvert tout ce dont vous avez besoin pour **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, et enfin **recognize text from invoice** afin de répondre à la question classique **how to extract amount**. Le script est compact, tout en étant suffisamment flexible pour s'adapter à différents formats de documents, langues et back‑ends OCR. + +Maintenant que vous avez maîtrisé les bases, envisagez d'étendre le flux de travail : ajouter la lecture de codes‑barres, intégrer un analyseur PDF, ou envoyer le montant extrait à une API comptable. Le ciel est la limite, et avec une ROI bien définie vous obtiendrez toujours des résultats plus rapides et plus propres. + +Si vous rencontrez un problème, laissez un commentaire ci‑dessous—bon OCR ! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## Que devriez‑vous apprendre ensuite ? + +- [Comment extraire du texte d'une image en préparant des rectangles dans l'OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extraire du texte d'une image Java avec Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Extraire du texte d'une image – Optimisation OCR avec Aspose.OCR pour .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/german/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..381748407 --- /dev/null +++ b/ocr/german/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Asynchrones OCR‑Tutorial, das zeigt, wie man Aspose OCR in Python mit + asyncio für schnelle Texterkennung aus Bildern verwendet. Lernen Sie die schrittweise + asynchrone OCR‑Implementierung. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: de +og_description: Das Async-OCR‑Tutorial führt Sie durch die Verwendung von Aspose OCR + in Python mit asyncio für eine effiziente Texterkennung aus Bildern. +og_title: Async-OCR-Tutorial – Python asyncio mit Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Asynchrones OCR‑Tutorial – Python asyncio mit Aspose OCR +url: /de/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR Tutorial – Python asyncio mit Aspose OCR + +Haben Sie sich jemals gefragt, wie man optische Zeichenerkennung ausführt, ohne Ihre Anwendung zu blockieren? In einem **async OCR tutorial** sehen Sie genau das — nicht blockierende Textextraktion mit Python’s `asyncio` und der Aspose OCR Bibliothek. + +Wenn Sie bisher darauf warten mussten, bis ein großes Bild verarbeitet war, bietet Ihnen dieser Leitfaden eine saubere, asynchrone Lösung, die Ihre Ereignisschleife am Laufen hält. + +In den folgenden Abschnitten behandeln wir alles, was Sie benötigen: die Bibliothek installieren, einen asynchronen Helfer einrichten, das Ergebnis verarbeiten und sogar einen schnellen Tipp zur Skalierung auf mehrere Bilder. Am Ende können Sie ein **async OCR tutorial** in jedes Python‑Projekt einbinden, das bereits `asyncio` verwendet. + +## Was Sie benötigen + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes haben: + +* Python 3.9+ (die `asyncio`‑API, die wir verwenden, ist ab 3.7 stabil) +* Eine aktive Aspose OCR Lizenz oder eine kostenlose Testversion (die Bibliothek ist reines Python, keine nativen Binärdateien) +* Eine kleine Bilddatei (`.jpg`, `.png`, usw.), die Sie auslesen möchten — legen Sie sie in einem bekannten Ordner ab + +Keine weiteren externen Werkzeuge sind erforderlich; alles läuft in reinem Python. + +## Schritt 1: Installieren Sie das Aspose OCR Paket + +Zuerst holen Sie das Aspose OCR Paket von PyPI. Öffnen Sie ein Terminal und führen Sie aus: + +```bash +pip install aspose-ocr +``` + +> **Pro‑Tipp:** Wenn Sie in einer virtuellen Umgebung arbeiten (dringend empfohlen), aktivieren Sie diese zuerst. So bleiben Abhängigkeiten isoliert und Versionskonflikte werden vermieden. + +## Schritt 2: Initialisieren Sie die OCR‑Engine asynchron + +Das Herz unseres **async OCR tutorial** ist eine asynchrone Helferfunktion. Sie erstellt eine `OcrEngine`‑Instanz, lädt ein Bild und ruft dann `recognize_async()` auf. Die Engine selbst ist synchron, aber die Wrapper‑Methode gibt ein Awaitable zurück, sodass die Ereignisschleife responsiv bleibt. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Warum wir es so machen:** +*Das Erzeugen der Engine innerhalb des Helfers gewährleistet Thread‑Sicherheit, falls Sie später viele OCR‑Jobs parallel ausführen. Das Schlüsselwort `await` gibt die Kontrolle zurück an die Ereignisschleife, während die schwere Arbeit im internen Thread‑Pool der Bibliothek erledigt wird.* + +## Schritt 3: Steuern Sie den Helfer aus einer async Main‑Funktion + +Jetzt benötigen wir eine kleine `main()`‑Koroutine, die `async_ocr()` aufruft und das Ergebnis ausgibt. Das entspricht dem typischen Einstiegspunkt für ein `asyncio`‑Skript. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Was im Hintergrund passiert:** +`asyncio.run()` erstellt eine frische Ereignisschleife, plant `main()` und schließt die Schleife sauber, sobald `main()` beendet ist. Dieses Muster ist der empfohlene Weg, um asynchrone Programme in Python 3.7+ zu starten. + +## Schritt 4: Testen Sie das vollständige Skript + +Speichern Sie die beiden Code‑Blöcke oben in einer einzigen Datei, z. B. `async_ocr_demo.py`. Führen Sie sie von der Befehlszeile aus: + +```bash +python async_ocr_demo.py +``` + +Wenn alles korrekt eingerichtet ist, sollten Sie etwas Ähnliches sehen: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Die genaue Ausgabe hängt vom Inhalt von `photo.jpg` ab. Der entscheidende Punkt ist, dass das Skript schnell beendet wird, selbst wenn das Bild groß ist, weil die OCR‑Arbeit im Hintergrund läuft. + +## Schritt 5: Skalierung – Mehrere Bilder gleichzeitig verarbeiten + +Eine häufige Anschlussfrage lautet: *„Kann ich einen Stapel Dateien OCR‑en, ohne für jede einen neuen Prozess zu starten?“* Absolut. Da unser Helfer vollständig asynchron ist, können wir viele Koroutinen mit `asyncio.gather()` sammeln: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Warum das funktioniert:** `asyncio.gather()` plant alle OCR‑Aufgaben gleichzeitig. Die zugrundeliegende Aspose OCR Bibliothek nutzt weiterhin ihren eigenen Thread‑Pool, aber aus Sicht von Python bleibt alles nicht‑blockierend, sodass Sie Dutzende Bilder in der Zeit verarbeiten können, die ein einzelner synchroner Aufruf benötigen würde. + +## Schritt 6: Fehler elegant behandeln + +Wenn Sie mit externen Dateien arbeiten, stoßen Sie unvermeidlich auf fehlende Dateien, beschädigte Bilder oder Lizenzprobleme. Wickeln Sie den OCR‑Aufruf in einen `try/except`‑Block, um die Ereignisschleife am Leben zu erhalten: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Jetzt kann `batch_ocr()` stattdessen `safe_async_ocr` aufrufen, sodass eine fehlerhafte Datei nicht den gesamten Batch abbricht. + +## Visuelle Übersicht + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial flowchart showing async_ocr helper, event loop, and Aspose OCR engine"} + +Das obige Diagramm visualisiert den Ablauf: Ereignisschleife → `async_ocr` → `OcrEngine` → Hintergrund‑Thread → Ergebnis zurück zur Schleife. + +## Häufige Fallstricke & wie man sie vermeidet + +| Fallstrick | Warum es passiert | Lösung | +|------------|-------------------|--------| +| **Blocking I/O inside the helper** | Durch versehentliches Verwenden von `open()` ohne `await` wird die Schleife blockiert. | Verwenden Sie `aiofiles` für Datei‑Lesevorgänge oder lassen Sie `engine.load_image` das erledigen (es ist bereits nicht‑blockierend). | +| **Re‑using a single `OcrEngine` across coroutines** | Die Engine ist nicht thread‑sicher; gleichzeitige Aufrufe können den Zustand beschädigen. | Instanziieren Sie innerhalb jedes `async_ocr`‑Aufrufs eine frische Engine (wie gezeigt). | +| **Missing license** | Aspose OCR wirft zur Laufzeit eine lizenzbezogene Ausnahme. | Registrieren Sie Ihre Lizenz frühzeitig (`OcrEngine.set_license("license.json")`). | +| **Large images causing memory spikes** | Die Bibliothek lädt das gesamte Bild in den RAM. | Skalieren Sie Bilder vor dem OCR‑Vorgang herunter, falls der Speicher knapp ist. | + +## Zusammenfassung: Was wir erreicht haben + +In diesem **async OCR tutorial** haben wir: + +1. Die Aspose OCR Bibliothek installiert. +2. Einen `async_ocr`‑Helfer gebaut, der die Erkennung ohne Blockierung ausführt. +3. Den Helfer von einem sauberen `asyncio`‑Einstiegspunkt aus gestartet. +4. Die Batch‑Verarbeitung mit `asyncio.gather` demonstriert. +5. Fehlerbehandlung und Best‑Practice‑Tipps hinzugefügt. + +All das ist reines Python, sodass Sie es in einen Web‑Server, ein CLI‑Tool oder eine Daten‑Pipeline einbinden können, ohne bestehenden Async‑Code neu zu schreiben. + +## Nächste Schritte & verwandte Themen + +* **Asynchrone Bild‑Vorverarbeitung** – verwenden Sie `aiohttp`, um Bilder gleichzeitig herunterzuladen, bevor Sie OCR ausführen. +* **Speichern von OCR‑Ergebnissen** – kombinieren Sie dieses Tutorial mit einem asynchronen Datenbank‑Treiber wie `asyncpg` für PostgreSQL. +* **Performance‑Optimierung** – experimentieren Sie mit `engine.recognize_async(max_threads=4)`, falls die Bibliothek eine solche Option bereitstellt. +* **Alternative OCR‑Engines** – vergleichen Sie Aspose OCR mit den async‑Wrappers von Tesseract für eine Kosten‑Nutzen‑Analyse. + +Probieren Sie es aus: Verarbeiten Sie PDFs, passen Sie Spracheinstellungen an oder verknüpfen Sie die Ergebnisse mit einem Chatbot. Der Himmel ist die Grenze, sobald Sie eine solide **async OCR tutorial**‑Basis haben. + +Viel Spaß beim Coden, und möge Ihre Textextraktion stets schnell sein! + +## Was sollten Sie als Nächstes lernen? + +- [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/) +- [Aspose OCR Tutorial – Optische Zeichenerkennung](/ocr/english/) +- [Wie man Bildtext mit Sprache mittels Aspose.OCR OCR durchführt](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/german/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..30e5eea48 --- /dev/null +++ b/ocr/german/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Automatische Spracherkennung in der OCR leicht gemacht. Erfahren Sie, + wie Sie die Bild‑OCR laden, die automatische Spracherkennung aktivieren und Textbilder + in nur wenigen Schritten erkennen. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: de +og_description: Automatische Spracherkennung in OCR leicht gemacht. Folgen Sie dieser + Schritt‑für‑Schritt‑Anleitung, um die automatische Spracherkennung zu aktivieren, + Bild‑OCR zu laden und Textbilder zu erkennen. +og_title: Automatische Spracherkennung mit OCR – Vollständiger Python-Leitfaden +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatische Spracherkennung mit OCR – Vollständiger Python-Leitfaden +url: /de/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatische Spracherkennung mit OCR – Vollständiger Python‑Leitfaden + +Haben Sie sich schon einmal gefragt, wie ein OCR‑Engine *erraten* kann, welche Sprache ein gescanntes Dokument hat, ohne dass Sie ihr sagen, wonach sie suchen soll? Genau das macht die **automatische Spracherkennung**, und sie ist ein echter Game‑Changer, wenn Sie mit mehrsprachigen PDFs, Fotos von Straßenschildern oder Bildern arbeiten, die verschiedene Schriftsysteme mischen. + +In diesem Tutorial gehen wir Schritt für Schritt durch ein praktisches Beispiel, das zeigt, wie Sie **automatische Spracherkennung aktivieren**, **Bild‑OCR laden** und **Text aus einem Bild erkennen** können – alles über eine Python‑ähnliche API. Am Ende haben Sie ein eigenständiges Skript, das sowohl den erkannten Sprachcode als auch den extrahierten Text ausgibt – ohne manuelle Spracheinstellungen. + +## Was Sie lernen werden + +- Wie Sie eine OCR‑Engine‑Instanz erstellen und **automatische Spracherkennung** einschalten. +- Die genauen Schritte, um **Bild‑OCR** von der Festplatte zu **laden**. +- Wie Sie die Methode `recognize()` der Engine aufrufen und ein Ergebnis erhalten, das den Sprachcode enthält. +- Tipps zum Umgang mit Sonderfällen wie niedrig aufgelösten Bildern oder nicht unterstützten Schriftsystemen. + +Vorkenntnisse in mehrsprachiger OCR sind nicht nötig; ein einfaches Python‑Setup und eine Bilddatei reichen aus. + +--- + +## Voraussetzungen + +Bevor wir starten, stellen Sie sicher, dass Sie folgendes haben: + +1. Python 3.8+ installiert (jede aktuelle Version funktioniert). +2. Die OCR‑Bibliothek, die `OcrEngine`, `LanguageAutoDetectMode` usw. bereitstellt – für dieses Beispiel gehen wir von einem hypothetischen Paket namens `myocr` aus. Installieren Sie es mit: + + ```bash + pip install myocr + ``` + +3. Eine Bilddatei (`multilingual_sample.png`), die Text in mindestens zwei verschiedenen Sprachen enthält. +4. Ein wenig Neugierde – falls Sie noch nie mit OCR gearbeitet haben, keine Sorge; der Code ist bewusst einfach gehalten. + +--- + +## Schritt 1: Automatische Spracherkennung aktivieren + +Das Erste, was Sie tun müssen, ist der Engine mitzuteilen, dass sie die Sprache selbst **herausfinden** soll. Hier kommt das Flag für die **automatische Spracherkennung** ins Spiel. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Warum das wichtig ist:** +> Wenn `AUTO_DETECT` gesetzt ist, führt die Engine vor der eigentlichen Zeichen­erkennung einen leichten Sprachklassifikator auf dem Bild aus. Das bedeutet, Sie müssen nicht raten, ob der Text Englisch, Russisch, Französisch oder eine beliebige Kombination davon ist. Die Engine wählt automatisch das passende Sprachmodell für jede Region des Bildes aus. + +--- + +## Schritt 2: Bild‑OCR laden + +Jetzt, wo die Engine weiß, dass sie Sprachen automatisch erkennen soll, müssen wir ihr etwas zum Arbeiten geben. Der **load image OCR**‑Schritt liest das Bitmap ein und bereitet interne Puffer vor. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro‑Tipp:** +> Wenn Ihr Bild größer als 300 dpi ist, sollten Sie es auf etwa 150‑200 dpi herunter­skalieren. Zu viele Details können die Phase der Spracherkennung tatsächlich **verlangsamen**, ohne die Genauigkeit zu verbessern. + +--- + +## Schritt 3: Text aus Bild erkennen + +Mit dem Bild im Speicher und aktivierter Spracherkennung ist der letzte Schritt, die Engine zu bitten, **text image** zu **recognize**. Dieser einzelne Aufruf erledigt die gesamte schwere Arbeit. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` ist ein Objekt, das typischerweise mindestens zwei Attribute enthält: + +| Attribut | Beschreibung | +|------------|--------------| +| `language` | ISO‑639‑1‑Code der erkannten Sprache (z. B. `"en"` für Englisch). | +| `text` | Die reine Text‑Transkription des Bildes. | + +--- + +## Schritt 4: Erkannten Sprachcode und extrahierten Text ausgeben + +Jetzt geben wir einfach aus, was die Engine herausgefunden hat. Das demonstriert die **detect language OCR**‑Funktionalität in Aktion. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Beispielausgabe** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Was, wenn die Engine `None` zurückgibt?** +> Das bedeutet meist, dass das Bild zu unscharf ist oder der Text zu klein (< 8 pt). Versuchen Sie, den Kontrast zu erhöhen oder eine höher aufgelöste Quelle zu verwenden. + +--- + +## Vollständiges Beispiel (End‑to‑End‑Aktivierung der automatischen Spracherkennung) + +Alles zusammengefügt, hier ein sofort ausführbares Skript, das **enable auto language detection**, **load image OCR**, **recognize text image** und **detect language OCR** in einem Durchgang abdeckt. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Speichern Sie das unter `automatic_language_detection_ocr.py`, ersetzen Sie `YOUR_DIRECTORY` durch den Ordner, der Ihr PNG enthält, und führen Sie es aus: + +```bash +python automatic_language_detection_ocr.py +``` + +Sie sollten den Sprachcode gefolgt vom extrahierten Text sehen – genau wie in der Beispielausgabe oben. + +--- + +## Umgang mit häufigen Sonderfällen + +| Situation | Empfohlene Lösung | +|-----------|-------------------| +| **Sehr niedrige Auflösung** (unter 100 dpi) | Vor dem Laden mit einem bikubischen Filter hochskalieren oder eine höher aufgelöste Quelle anfordern. | +| **Gemischte Schriftsysteme in einem Bild** (z. B. Englisch + Kyrillisch) | Die Engine teilt die Seite normalerweise in Regionen; falls Fehl­erkennungen auftreten, setzen Sie `engine.enable_region_split = True`. | +| **Nicht unterstützte Sprache** | Prüfen Sie, ob das OCR‑Library ein Sprachpaket für das gewünschte Schriftsystem enthält; ggf. zusätzliche Modelle herunterladen. | +| **Großes Batch‑Processing** | Engine einmal initialisieren und dann für mehrere `load_image` / `recognize`‑Durchläufe wiederverwenden, um wiederholtes Laden von Modellen zu vermeiden. | + +--- + +## Visueller Überblick + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt‑Text:* Beispielausgabe der automatischen Spracherkennung, die den erkannten Sprachcode und den extrahierten mehrsprachigen Text zeigt. + +--- + +## Fazit + +Wir haben die **automatische Spracherkennung** von Anfang bis Ende behandelt – Engine erstellen, automatische Spracherkennung aktivieren, ein Bild für OCR laden, den Text erkennen und schließlich die erkannte Sprache auslesen. Dieser End‑to‑End‑Workflow ermöglicht die Verarbeitung mehrsprachiger Dokumente, ohne jedes Mal manuell Sprachmodelle konfigurieren zu müssen. + +Wenn Sie weitergehen wollen, überlegen Sie: + +- **Batch‑Verarbeitung** von Hunderten Bildern mit einer Schleife, die dieselbe `OcrEngine`‑Instanz wiederverwendet. +- **Nachbearbeitung** des extrahierten Textes mit einem Rechtschreib‑Checker oder sprachspezifischen Tokenizer. +- **Integration** des Skripts in einen Web‑Service, der Benutzer‑Uploads akzeptiert und JSON mit den Feldern `language` und `text` zurückgibt. + +Probieren Sie verschiedene Bildformate (`.jpg`, `.tif`) aus und beobachten Sie, wie sich die Erkennungsgenauigkeit ändert. Fragen oder ein kniffliges Bild, das sich nicht lesen lässt? Hinterlassen Sie einen Kommentar unten – happy coding! + +## Was sollten Sie als Nächstes lernen? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/german/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c254840c0 --- /dev/null +++ b/ocr/german/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-31 +description: Erfahren Sie, wie Sie Bilder mit Python in Text umwandeln, mithilfe eines + Skripts zur massenhaften Bild‑zu‑Text‑Konvertierung. Erkennen Sie Text aus gescannten + Bildern mit Aspose.OCR in wenigen Minuten. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: de +og_description: Bilder sofort mit Python in Text umwandeln. Dieser Leitfaden zeigt + die Massenumwandlung von Bildern in Text und wie man Text aus gescannten Bildern + mit Aspose.OCR erkennt. +og_title: Bilder zu Text konvertieren mit Python – Vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Bilder in Text umwandeln mit Python – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bilder zu Text konvertieren mit Python – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie sich jemals gefragt, wie man **convert images to text python** ohne Dutzende von Bibliotheken zu durchsuchen, konvertiert? Sie sind nicht allein. Ob Sie alte Quittungen digitalisieren, Daten aus gescannten Rechnungen extrahieren oder ein durchsuchbares PDF‑Archiv erstellen, das Umwandeln von Bildern in reine Textdateien ist für viele Entwickler ein täglicher Aufwand. + +In diesem Tutorial führen wir Sie durch eine **bulk image to text conversion**‑Pipeline, die Text aus gescannten Bildern erkennt, jedes Ergebnis als einzelne `.txt`‑Datei speichert und das alles mit nur wenigen Zeilen Python erledigt. Kein Rätselraten bei obskuren APIs – Aspose.OCR übernimmt die schwere Arbeit, und wir zeigen Ihnen genau, wie Sie es einbinden. + +## Was Sie lernen werden + +- Wie man das Aspose.OCR‑Paket für Python installiert und konfiguriert. +- Der genaue Code, der benötigt wird, um **convert images to text python** mit dem `BatchOcrEngine` zu verwenden. +- Tipps zum Umgang mit häufigen Fallstricken wie nicht unterstützten Formaten oder beschädigten Dateien. +- Möglichkeiten zu überprüfen, dass der Schritt **recognize text from scanned images** tatsächlich erfolgreich war. + +Am Ende dieses Leitfadens haben Sie ein sofort einsatzbereites Skript, das Tausende von Bildern in einem Durchgang verarbeiten kann – perfekt für jedes Batch‑Verarbeitungsszenario. + +## Voraussetzungen + +- Python 3.8+ auf Ihrem Rechner installiert. +- Ein Ordner mit Bilddateien (PNG, JPEG, TIFF usw.), die Sie in Text umwandeln möchten. +- Ein aktives Aspose‑Cloud‑Konto oder eine kostenlose Testlizenz (die kostenlose Stufe reicht für Tests). + +Wenn Sie das haben, lassen Sie uns loslegen. + +--- + +## Schritt 1 – Richten Sie Ihre Python‑Umgebung ein + +Bevor wir mit dem Schreiben von OCR‑Code beginnen, stellen Sie sicher, dass Sie in einer sauberen virtuellen Umgebung arbeiten. Diese isoliert Abhängigkeiten und verhindert Versionskonflikte. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro Tipp:** Halten Sie Ihr Projektverzeichnis ordentlich – erstellen Sie einen Unterordner namens `ocr_project` und legen Sie das Skript dort ab. Das erleichtert die Pfadverwaltung später. + +## Schritt 2 – Installieren Sie Aspose.OCR für Python + +Aspose.OCR ist eine kommerzielle Bibliothek, wird jedoch mit einem kostenlosen NuGet‑ähnlichen Wheel geliefert, das Sie von PyPI beziehen können. Führen Sie den folgenden Befehl innerhalb der aktivierten virtuellen Umgebung aus: + +```bash +pip install aspose-ocr +``` + +Falls Sie einen Berechtigungsfehler erhalten, fügen Sie das Flag `--user` hinzu oder führen Sie den Befehl mit `sudo` aus (nur Linux/macOS). Nach der Installation sollten Sie etwas Ähnliches sehen: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Warum Aspose?** Im Gegensatz zu vielen Open‑Source‑OCR‑Tools unterstützt Aspose.OCR **bulk image to text conversion** sofort und verarbeitet eine breite Palette von Bildformaten ohne zusätzliche Konfiguration. Es bietet außerdem die Klasse `BatchOcrEngine`, die die Aufgabe “convert images to text python” zu einer Einzeilen‑Operation macht. + +## Schritt 3 – Bilder zu Text konvertieren mit Python und Batch OCR + +Jetzt zum Kern des Tutorials. Unten finden Sie ein vollständig ausführbares Skript, das: + +1. Die OCR‑Engine‑Klassen importiert. +2. Eine `BatchOcrEngine` instanziiert. +3. Die Engine auf einen Eingabeordner mit Bildern richtet. +4. Die Engine anweist, jede extrahierte Textdatei in einen Ausgabordner zu schreiben. +5. Die Methode `recognize()` auslöst, die **recognize text from scanned images** einzeln verarbeitet. + +Speichern Sie das Folgende als `batch_ocr.py` in Ihrem Projektordner: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Wie es funktioniert + +- **`BatchOcrEngine`** umschließt die reguläre `OcrEngine`, fügt jedoch eine Orchestrierung auf Ordner‑Ebene hinzu, genau das, was Sie benötigen, wenn Sie **convert images to text python** in großen Mengen durchführen möchten. +- Die Eigenschaft `input_folder` gibt der Engine an, wo sie nach Quellbildern suchen soll. Sie scannt das Verzeichnis automatisch und stellt jede unterstützte Dateityp in die Warteschlange. +- Die Eigenschaft `output_folder` bestimmt, wo jede `.txt`‑Datei abgelegt wird. Die Engine spiegelt den ursprünglichen Dateinamen, sodass `receipt1.png` zu `receipt1.txt` wird. +- Der Aufruf von `recognize()` startet die interne Schleife, die jedes Bild lädt, OCR ausführt und das Ergebnis schreibt. Die Methode blockiert, bis jede Datei verarbeitet ist, was das Ketten weiterer Aktionen erleichtert (z. B. das Zippen des Ausgabeverzeichnisses). + +#### Erwartete Ausgabe + +When you run the script: + +```bash +python batch_ocr.py +``` + +You should see: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Im Ordner `output_texts` finden Sie für jedes Bild eine reine Textdatei. Öffnen Sie eine beliebige mit einem Texteditor und Sie sehen das rohe OCR‑Ergebnis – in der Regel eine nahe Annäherung an den ursprünglichen gedruckten Text. + +## Schritt 4 – Überprüfen Sie die Ergebnisse und behandeln Sie Fehler + +Selbst die besten OCR‑Engines können bei niedrig aufgelösten Scans oder stark verzerrten Seiten stolpern. Hier ist ein schneller Weg, die Ausgabe zu prüfen und etwaige Fehler zu protokollieren. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Warum das hinzufügen?** +- Es fängt Fälle ab, in denen die Engine stillschweigend einen leeren String erzeugt hat (häufig bei nicht lesbaren Bildern). +- Es liefert Ihnen eine Liste problematischer Dateien, damit Sie diese manuell prüfen oder mit anderen Einstellungen erneut ausführen können (z. B. die Optionen `OcrEngine.preprocess` erhöhen). + +### Randfälle & Anpassungen + +| Situation | Vorgeschlagene Lösung | +|-----------|-----------------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Schritt 5 – Automatisieren Sie den gesamten Workflow (optional) + +Wenn Sie diese Konvertierung nachts ausführen müssen, verpacken Sie das Skript in eine einfache Shell‑ oder Windows‑Batch‑Datei und planen Sie es mit `cron` (Linux/macOS) oder dem Task Scheduler (Windows). Hier ist ein minimaler `run_ocr.sh` für Unix‑ähnliche Systeme: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Machen Sie es ausführbar (`chmod +x run_ocr.sh`) und fügen Sie einen Cron‑Eintrag hinzu: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Damit wird die Konvertierung jeden Tag um 2 Uhr morgens ausgeführt und protokolliert die Ausgabe für eine spätere Überprüfung. + +## Fazit + +Sie haben nun eine bewährte, produktionsreife Methode, um **convert images to text python** mit Aspose.OCRs `BatchOcrEngine` zu verwenden. Das Skript erledigt **bulk image to text conversion**, schreibt jedes Ergebnis elegant in eine eigene Datei und enthält Verifizierungsschritte, um sicherzustellen, dass Sie tatsächlich **recognize text from scanned images** korrekt erkennen. + +Von hier aus könnten Sie: + +- Experimentieren Sie mit verschiedenen OCR‑Einstellungen (Sprachpakete, Deskew, Rauschunterdrückung). +- Leiten Sie den erzeugten Text in einen Suchindex wie Elasticsearch weiter für sofortige Volltextsuche. +- Kombinieren Sie diese Pipeline mit PDF‑Konvertierungstools, um gescannte PDFs in einem Durchgang zu verarbeiten. + +Haben Sie Fragen oder haben Sie ein Problem mit einem bestimmten Dateityp bemerkt? Hinterlassen Sie unten einen Kommentar, und wir lösen das gemeinsam. Viel Spaß beim Programmieren, und möge Ihr OCR‑Durchlauf schnell und fehlerfrei sein! + +## Was sollten Sie als Nächstes lernen? + +- [Text aus Bild extrahieren mit Aspose OCR – Schritt‑für‑Schritt‑Anleitung](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Text aus Bildern extrahieren mittels OCR‑Operation auf Ordnern](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Bildtext in C# extrahieren mit Sprachauswahl mittels 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/german/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..46d024f9b --- /dev/null +++ b/ocr/german/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Erstellen Sie eine Lizenzinstanz in Python und konfigurieren Sie den + Lizenzpfad einfach. Erfahren Sie, wie Sie die Aspose OCR‑Lizenzierung mit klaren + Codebeispielen einrichten. +draft: false +keywords: +- create license instance +- configure license path +language: de +og_description: Erstellen Sie eine Lizenzinstanz in Python und konfigurieren Sie den + Lizenzpfad sofort. Folgen Sie diesem Tutorial, um Aspose OCR mit Zuversicht zu aktivieren. +og_title: Lizenzinstanz in Python erstellen – Vollständige Installationsanleitung +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Lizenzinstanz in Python erstellen – Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lizenzinstanz in Python erstellen – Komplett‑Anleitung + +Möchten Sie eine **license instance** für Aspose OCR in Python **erstellen**? Sie sind hier genau richtig. In diesem Tutorial zeigen wir Ihnen außerdem, wie Sie den **license path** **konfigurieren**, damit das SDK weiß, wo Ihre `.lic`‑Datei zu finden ist. + +Wenn Sie jemals vor einem leeren Skript gesessen haben und sich gefragt haben, warum die OCR‑Engine ständig über ein nicht lizenziertes Produkt klagt, sind Sie nicht allein. Die Lösung besteht meist nur aus ein paar Code‑Zeilen – sobald Sie genau wissen, wo Sie sie platzieren müssen. Am Ende dieses Leitfadens haben Sie eine vollständig lizenzierte Aspose OCR‑Umgebung, bereit, Text, Bilder und PDFs ohne Probleme zu erkennen. + +## Was Sie lernen werden + +- Wie man mit dem `asposeocr`‑Paket eine **license instance** **erstellt**. +- Die korrekte Methode, den **license path** für Entwicklung und Produktion **zu konfigurieren**. +- Häufige Fallstricke (fehlende Datei, falsche Berechtigungen) und wie man sie vermeidet. +- Ein vollständiges, ausführbares Skript, das Sie in jedes Projekt einbinden können. + +Keine Vorkenntnisse mit Aspose OCR sind erforderlich, nur eine funktionierende Python 3‑Installation und eine gültige Lizenzdatei. + +--- + +## Schritt 1: Das Aspose OCR Python‑Paket installieren + +Bevor wir eine **license instance** **erstellen** können, muss die Bibliothek selbst vorhanden sein. Öffnen Sie ein Terminal und führen Sie aus: + +```bash +pip install aspose-ocr +``` + +> **Pro‑Tipp:** Wenn Sie eine virtuelle Umgebung verwenden (dringend empfohlen), aktivieren Sie diese zuerst. So bleiben Ihre Abhängigkeiten übersichtlich und Versionskonflikte werden vermieden. + +## Schritt 2: Die License‑Klasse importieren + +Jetzt, wo das SDK verfügbar ist, sollte die allererste Zeile Ihres Skripts die `License`‑Klasse importieren. Dieses Objekt verwenden wir, um eine **license instance** **zu erstellen**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Warum sofort importieren? Weil das `License`‑Objekt **vor** allen OCR‑Aufrufen instanziiert werden muss; andernfalls wirft das SDK sofort einen Lizenzfehler, sobald Sie versuchen, ein Bild zu verarbeiten. + +## Schritt 3: Lizenzinstanz erstellen + +Hier kommt der Moment, auf den Sie gewartet haben – tatsächlich eine **license instance** **erstellen**. Es ist nur eine Zeile, aber der umgebende Kontext ist wichtig. + +```python +# Step 3: Create a License instance +license = License() +``` + +Die Variable `license` enthält nun ein Objekt, das das gesamte Lizenzverhalten für den aktuellen Python‑Prozess steuert. Denken Sie an sie als den Türsteher, der Aspose OCR sagt: „Hey, ich habe die Erlaubnis zu laufen.“ + +## Schritt 4: Lizenzpfad konfigurieren + +Mit der Instanz bereit, müssen wir sie auf unsere `.lic`‑Datei zeigen. Hier kommt das **configure license path** ins Spiel. Ersetzen Sie den Platzhalter durch den absoluten Pfad zu Ihrer Lizenzdatei. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Ein paar Dinge sind zu beachten: + +1. **Raw‑Strings (`r"…"`)** verhindern, dass Backslashes unter Windows als Escape‑Zeichen interpretiert werden. +2. Verwenden Sie einen **absoluten Pfad**, um Verwirrungen zu vermeiden, wenn das Skript aus einem anderen Arbeitsverzeichnis gestartet wird. +3. Wenn Sie einen relativen Pfad bevorzugen (z. B. beim Bündeln der Lizenz mit Ihrem Projekt), stellen Sie sicher, dass die relative Basis der Speicherort des Skripts ist, nicht das aktuelle Shell‑Verzeichnis. + +### Umgang mit fehlenden Dateien + +Ist der Pfad falsch oder die Datei nicht lesbar, wirft `set_license` eine Ausnahme. Wickeln Sie den Aufruf in einen `try/except`‑Block, um eine freundliche Fehlermeldung auszugeben: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Dieses Snippet **configures license path** sicher und sagt Ihnen exakt, was schiefgelaufen ist – keine mysteriösen Stack‑Traces. + +## Schritt 5: Lizenz aktiv prüfen + +Ein kurzer Sanity‑Check spart später Stunden an Fehlersuche. Nachdem Sie `set_license` aufgerufen haben, probieren Sie eine einfache OCR‑Operation. Ist die Lizenz gültig, verarbeitet das SDK das Bild, ohne einen Lizenzfehler zu werfen. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Wenn der erkannte Text ausgegeben wird, herzlichen Glückwunsch – Sie haben erfolgreich **license instance** **erstellt** und **license path** **konfiguriert**. Erhalten Sie eine Lizenz‑Ausnahme, prüfen Sie Pfad und Dateiberechtigungen erneut. + +## Sonderfälle & bewährte Vorgehensweisen + +| Situation | Was zu tun ist | +|-----------|----------------| +| **Lizenzdatei befindet sich auf einem Netzwerk‑Share** | Ordnen Sie den Share einem Laufwerksbuchstaben zu oder verwenden Sie einen UNC‑Pfad (`\\server\share\license.lic`). Stellen Sie sicher, dass der Python‑Prozess Lesezugriff hat. | +| **Ausführung innerhalb eines Docker‑Containers** | Kopieren Sie die `.lic`‑Datei in das Image und referenzieren Sie sie mit einem absoluten Pfad wie `/app/license/Aspose.OCR.Java.lic`. | +| **Mehrere Python‑Interpreter** (z. B. conda‑Umgebungen) | Installieren Sie die Lizenzdatei einmal pro Umgebung oder halten Sie sie an einem zentralen Ort und verweisen Sie jeden Interpreter darauf. | +| **Lizenzdatei zur Laufzeit nicht gefunden** | Führen Sie elegant in einen Test‑Modus (falls unterstützt) zurück oder brechen Sie mit einer klaren Log‑Meldung ab. | + +### Häufige Fallstricke + +- **Vorwärts‑Schrägstriche unter Windows verwenden** – Python akzeptiert sie, aber einige ältere SDK‑Versionen könnten sie missverstehen. Bleiben Sie bei Raw‑Strings oder doppelten Backslashes. +- **Vergessen, `License` zu importieren** – Das Skript stürzt mit `NameError` ab. Immer importieren, bevor Sie instanziieren. +- **`set_license` nach OCR‑Methoden aufrufen** – Das SDK prüft die Lizenz beim ersten Gebrauch, also setzen Sie den Pfad **zuerst**. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie ein komplettes Skript, das alles zusammenführt. Speichern Sie es als `ocr_setup.py` und führen Sie es über die Kommandozeile aus. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Erwartete Ausgabe** (bei einem gültigen Bild): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Kann die Lizenzdatei nicht gefunden werden, erhalten Sie stattdessen eine klare Fehlermeldung anstelle einer kryptischen „License not found“‑Ausnahme. + +--- + +## Fazit + +Sie wissen jetzt genau, wie Sie eine **license instance** in Python **erstellen** und den **license path** für das Aspose OCR SDK **konfigurieren**. Die Schritte sind einfach: Paket installieren, `License` importieren, instanziieren, auf Ihre `.lic`‑Datei zeigen und mit einem kleinen OCR‑Test verifizieren. + +Mit diesem Wissen können Sie OCR‑Funktionen in Web‑Services, Desktop‑Apps oder automatisierte Pipelines einbetten, ohne über Lizenzfehler zu stolpern. Als Nächstes können Sie erweiterte OCR‑Einstellungen erkunden – Sprachpakete, Bild‑Pre‑Processing oder Batch‑Verarbeitung – die alle auf dem soliden Fundament aufbauen, das Sie gerade geschaffen haben. + +Haben Sie Fragen zu Deployment, Docker oder dem Umgang mit mehreren Lizenzen? Hinterlassen Sie einen Kommentar, und happy coding! + +## Was Sie als Nächstes lernen sollten + +- [Aspose OCR Tutorial – Optische Zeichenerkennung](/ocr/english/) +- [Wie man Lizenz setzt und Aspose.OCR Lizenz in Java überprüft](/ocr/english/java/ocr-basics/set-license/) +- [Wie man Bildtext mit Sprache mittels Aspose.OCR OCRt](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/german/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..ba6db315f --- /dev/null +++ b/ocr/german/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Erstelle ein durchsuchbares PDF aus gescannten Bildern mit Python‑OCR. + Erfahre, wie du ein gescanntes Bild‑PDF konvertierst, TIFF in PDF umwandelst und + in wenigen Minuten eine OCR‑Textschicht hinzufügst. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: de +og_description: Erstelle sofort durchsuchbare PDFs. Diese Anleitung zeigt, wie man + OCR ausführt, gescannte Bild‑PDFs konvertiert und eine OCR‑Textschicht mit einem + einzigen Python‑Skript hinzufügt. +og_title: Erstelle durchsuchbare PDF mit Python – Komplettes Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Durchsuchbares PDF mit Python erstellen – Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Erstellen durchsuchbare PDF mit Python – Schritt‑für‑Schritt-Anleitung + +Haben Sie sich jemals gefragt, wie man **create searchable PDF** aus einer gescannten Seite erstellt, ohne Dutzende Werkzeuge zu jonglieren? Sie sind nicht allein. In vielen Büroabläufen landet ein gescanntes TIFF oder JPEG auf einem gemeinsamen Laufwerk, und die nächste Person muss den Text manuell copy‑pasten – schmerzhaft, fehleranfällig und zeitaufwendig. + +In diesem Tutorial gehen wir eine saubere, programmatische Lösung durch, die es Ihnen ermöglicht, **convert scanned image PDF**, **convert TIFF to PDF** und **add OCR text layer** in einem Schritt. Am Ende haben Sie ein einsatzbereites Skript, das OCR ausführt, den versteckten Text einbettet und ein durchsuchbares PDF ausgibt, das Sie indexieren, durchsuchen oder mit Vertrauen teilen können. + +## Was Sie benötigen + +- Python 3.9+ (jede aktuelle Version funktioniert) +- Pakete `aspose-ocr` und `aspose-pdf` (installiert über `pip install aspose-ocr aspose-pdf`) +- Eine gescannte Bilddatei (`.tif`, `.png`, `.jpg` oder sogar eine PDF‑Seite, die nur ein Bild enthält) +- Ein bescheidener Arbeitsspeicher (die OCR‑Engine ist leichtgewichtig; selbst ein Laptop bewältigt das) + +> **Pro‑Tipp:** Wenn Sie Windows verwenden, ist der einfachste Weg, die Pakete zu erhalten, den Befehl in einem erhöhten PowerShell‑Fenster auszuführen. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Jetzt, da die Voraussetzungen erledigt sind, tauchen wir in den Code ein. + +## Schritt 1: OCR‑Engine‑Instanz erstellen – *create searchable pdf* + +Das Erste, was wir tun, ist die OCR‑Engine zu starten. Stellen Sie sich sie als das Gehirn vor, das jedes Pixel liest und in Zeichen umwandelt. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Warum das wichtig ist:** Die Engine nur einmal zu initialisieren hält den Speicherverbrauch niedrig. Wenn Sie `OcrEngine()` in einer Schleife für jede Seite aufrufen würden, würden Sie schnell an Ressourcenmangel geraten. + +## Schritt 2: Gescanntes Bild laden – *convert tiff to pdf* & *convert scanned image pdf* + +Als Nächstes zeigen Sie die Engine auf die Datei, die Sie verarbeiten möchten. Die API akzeptiert jedes Rasterbild, sodass ein TIFF genauso gut funktioniert wie ein JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Falls Sie ein PDF haben, das nur ein gescanntes Bild enthält, können Sie weiterhin `load_image` verwenden, da Aspose die erste Seite automatisch extrahiert. + +## Schritt 3: PDF‑Speicheroptionen vorbereiten – *add OCR text layer* + +Hier konfigurieren wir, wie das endgültige PDF aussehen soll. Das entscheidende Flag ist `create_searchable_pdf`; wird es auf `True` gesetzt, weist dies die Bibliothek an, eine unsichtbare Textebene einzubetten, die den visuellen Inhalt widerspiegelt. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Was die Textebene bewirkt:** Wenn Sie die resultierende Datei in Adobe Reader öffnen und versuchen, Text zu markieren, sehen Sie die versteckten Zeichen. Suchmaschinen können sie ebenfalls indexieren – ideal für Compliance oder Archivierung. + +## Schritt 4: OCR ausführen und speichern – *how to run OCR* in a single call + +Jetzt geschieht die Magie. Ein Methodenaufruf führt die Erkennungs‑Engine aus und schreibt das durchsuchbare PDF auf die Festplatte. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Die Methode `recognize` gibt ein Status‑Objekt zurück, das Sie auf Fehler prüfen können, aber für die meisten einfachen Szenarien reicht der obige einfache Aufruf aus. + +### Erwartete Ausgabe + +Das Ausführen des Skripts gibt Folgendes aus: + +``` +PDF saved as searchable PDF. +``` + +Wenn Sie `scanned_page_searchable.pdf` öffnen, werden Sie feststellen, dass Sie Text auswählen, copy‑pasten und sogar eine `Ctrl+F`‑Suche durchführen können. Das ist das Kennzeichen eines **create searchable pdf** Workflows. + +## Vollständiges funktionierendes Skript + +Unten finden Sie das vollständige, sofort ausführbare Skript. Ersetzen Sie einfach die Platzhalter‑Pfade durch Ihre tatsächlichen Dateipfade. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Speichern Sie dies als `create_searchable_pdf.py` und führen Sie es aus: + +```bash +python create_searchable_pdf.py +``` + +## Häufige Fragen & Sonderfälle + +### 1️⃣ Kann ich mehrseitige PDFs verarbeiten? + +Ja. Verwenden Sie `ocr_engine.load_image("file.pdf")` und iterieren Sie dann über jede Seite mit `ocr_engine.recognize(pdf_save_options, page_number)`. Die Bibliothek erzeugt automatisch ein mehrseitiges durchsuchbares PDF. + +### 2️⃣ Was, wenn meine Quelldatei ein hochauflösendes TIFF (300 dpi+) ist? + +Eine höhere DPI führt zu besserer OCR‑Genauigkeit, aber auch zu höherem Speicherverbrauch. Wenn Sie einen `MemoryError` erhalten, skalieren Sie das Bild zuerst herunter: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Wie ändere ich die Sprache der OCR? + +Setzen Sie die Eigenschaft `language` auf der Engine, bevor Sie das Bild laden: + +```python +ocr_engine.language = "fra" # French +``` + +Eine vollständige Liste der unterstützten Sprachcodes finden Sie in der Aspose‑Dokumentation. + +### 4️⃣ Was, wenn ich die ursprüngliche Bildqualität beibehalten muss? + +Die Klasse `PdfSaveOptions` verfügt über eine Eigenschaft `compression`. Setzen Sie sie auf `PdfCompression.None`, um die Rasterdaten exakt wie ursprünglich zu erhalten. + +```python +pdf_save_options.compression = "None" +``` + +## Tipps für produktionsreife Bereitstellungen + +- **Batch‑Verarbeitung:** Verpacken Sie die Kernlogik in einer Funktion, die eine Liste von Dateipfaden akzeptiert. Protokollieren Sie jeden Erfolg/Fehlschlag in einer CSV für Prüfpfade. +- **Parallelität:** Verwenden Sie `concurrent.futures.ThreadPoolExecutor`, um OCR auf mehreren Kernen auszuführen. Denken Sie daran, dass jeder Thread seine eigene `OcrEngine`‑Instanz benötigt. +- **Sicherheit:** Wenn Sie sensible Dokumente verarbeiten, führen Sie das Skript in einer sandbox‑Umgebung aus und löschen Sie die temporären Dateien sofort nach der Verarbeitung. + +## Fazit + +Sie wissen jetzt, wie man **create searchable PDF** Dateien aus gescannten Bildern mit einem knappen Python‑Skript erstellt. Durch das Initialisieren einer OCR‑Engine, das Laden eines TIFF (oder eines beliebigen Rasters), das Konfigurieren von `PdfSaveOptions` zum **add OCR text layer** und schließlich das Aufrufen von `recognize` wird die gesamte **convert scanned image pdf** und **convert TIFF to PDF** Pipeline zu einem einzigen, wiederholbaren Befehl. + +Nächste Schritte? Versuchen Sie, dieses Skript mit einem Datei‑Watcher zu verketten, sodass jeder neue Scan, der in einen Ordner gelegt wird, automatisch durchsuchbar wird. Oder experimentieren Sie mit verschiedenen OCR‑Sprachen, um mehrsprachige Archive zu unterstützen. Der Himmel ist die Grenze, wenn Sie OCR mit PDF‑Erstellung kombinieren. + +Haben Sie weitere Fragen zu **how to run OCR** in anderen Sprachen oder Frameworks? Hinterlassen Sie unten einen Kommentar und viel Spaß beim Programmieren! + +![Diagramm, das den Ablauf von gescanntem Bild → OCR‑Engine → durchsuchbarem PDF (create searchable pdf) zeigt](searchable-pdf-flow.png "Ablaufdiagramm für create searchable pdf") + + +## Was sollten Sie als Nächstes lernen? + +- [Wie man PDF in .NET mit Aspose.OCR OCR‑t](/ocr/english/net/text-recognition/recognize-pdf/) +- [Bilder zu PDF in C# konvertieren – Mehrseitiges OCR‑Ergebnis speichern](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Wie man Bildtext mit Sprache mittels Aspose.OCR OCR‑t](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/german/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2caf15dc7 --- /dev/null +++ b/ocr/german/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Verbessern Sie die OCR‑Genauigkeit mit Python, indem Sie Bilder für die + OCR vorverarbeiten. Lernen Sie, wie Sie Text aus Bilddateien extrahieren, Text aus + PNG erkennen und die Ergebnisse steigern. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: de +og_description: Verbessern Sie die OCR-Genauigkeit in Python, indem Sie Bildvorverarbeitung + für Text anwenden. Folgen Sie dieser Anleitung, um Text aus Bilddateien zu extrahieren + und Text aus PNGs mühelos zu erkennen. +og_title: Verbessern Sie die OCR‑Genauigkeit in Python – Vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Verbessern Sie die OCR‑Genauigkeit in Python – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Verbessern Sie die OCR‑Genauigkeit in Python – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie schon versucht, **die OCR‑Genauigkeit zu verbessern**, nur um ein wirres Ergebnis zu erhalten? Sie sind nicht allein. Die meisten Entwickler stoßen an Grenzen, wenn das Rohbild verrauscht, schief oder einfach nur kontrastarm ist. Die gute Nachricht? Ein paar Vorverarbeitungs‑Tricks können einen verschwommenen Screenshot in sauberen, maschinenlesbaren Text verwandeln. + +In diesem Tutorial gehen wir ein praxisnahes Beispiel durch, das **ein Bild für OCR vorverarbeitet**, die Erkennungs‑Engine ausführt und schließlich **Text aus Bild**‑Dateien extrahiert – speziell ein PNG. Am Ende wissen Sie genau, wie Sie **Text aus PNG** mit höherer Erfolgsrate **erkennen**, und Sie erhalten ein wiederverwendbares Code‑Snippet, das Sie in jedes Projekt einbinden können. + +## Was Sie lernen werden + +- Warum Bildvorverarbeitung für OCR‑Engines wichtig ist +- Welche Vorverarbeitungsmodi (Denoise, Deskew) den größten Nutzen bringen +- Wie man eine `OcrEngine`‑Instanz in Python konfiguriert +- Das vollständige, ausführbare Skript, das **Text aus Bild**‑Dateien extrahiert +- Tipps zum Umgang mit Randfällen wie gedrehten Scans oder Bildern mit niedriger Auflösung + +Keine externen Bibliotheken über das OCR‑SDK hinaus werden benötigt, aber Sie benötigen Python 3.8+ und ein PNG‑Bild, das Sie lesen möchten. + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Workflow zur Verbesserung der OCR‑Genauigkeit") + +*Alt‑Text: Diagramm zum Workflow zur Verbesserung der OCR‑Genauigkeit, das Vorverarbeitung und Erkennungsschritte illustriert.* + +## Voraussetzungen + +- Python 3.8 oder neuer installiert +- Zugriff auf das OCR SDK, das `OcrEngine`, `OcrEngineSettings` und `ImagePreprocessMode` bereitstellt (der untenstehende Code verwendet eine generische API; ersetzen Sie sie bei Bedarf durch die Klassen Ihres Anbieters) +- Ein PNG‑Bild (`input.png`) in einem Ordner, auf den Sie verweisen können + +Wenn Sie eine virtuelle Umgebung verwenden, aktivieren Sie sie jetzt – nichts Aufwändiges, einfach `python -m venv venv && source venv/bin/activate`. + +--- + +## Schritt 1: OCR‑Engine‑Instanz erstellen – Verbesserung der OCR‑Genauigkeit starten + +Das erste, was Sie benötigen, ist ein OCR‑Engine‑Objekt. Denken Sie daran wie an das Gehirn, das später die Pixel liest und Zeichen ausgibt. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Warum das wichtig ist: Ohne eine Engine können Sie keine Vorverarbeitung anwenden, und das Rohbild wird direkt an den Erkenner übergeben – meist das schlechteste Szenario für die Genauigkeit. + +--- + +## Schritt 2: Ziel‑PNG laden – Vorbereitung für das Erkennen von Text aus PNG + +Jetzt teilen wir der Engine mit, welche Datei verarbeitet werden soll. PNG ist verlustfrei, was uns bereits einen kleinen Vorteil gegenüber JPEG verschafft. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Falls das Bild an einem anderen Ort liegt, passen Sie einfach den Pfad an. Die Engine akzeptiert jedes unterstützte Format, aber PNG bewahrt oft die feinen Details, die für klare Zeichenkanten nötig sind. + +--- + +## Schritt 3: Vorverarbeitung konfigurieren – Bild für OCR vorverarbeiten + +Hier passiert die Magie. Wir erstellen ein Settings‑Objekt, aktivieren Denoising, um Sprenkel zu entfernen, und schalten Deskew ein, sodass schräger Text automatisch begradigt wird. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Warum Denoise + Deskew? + +- **Denoise**: Zufälliges Pixelrauschen verwirrt Muster‑Matching‑Algorithmen. Das Entfernen schärft die Buchstaben. +- **Deskew**: Bereits eine Neigung von 2 Grad kann die Vertrauenswerte stark senken. Deskew richtet die Grundlinie aus, sodass der Erkenner Schriften zuverlässiger zuordnen kann. + +Sie können mit zusätzlichen Flags experimentieren (z. B. `ImagePreprocessMode.CONTRAST_ENHANCE`), wenn Ihre Bilder besonders dunkel sind. Die SDK‑Dokumentation listet in der Regel alle verfügbaren Modi auf. + +--- + +## Schritt 4: Einstellungen auf die Engine anwenden – Vorverarbeitung mit OCR verknüpfen + +Weisen Sie das Settings‑Objekt der Engine zu, damit der nächste Erkennungsdurchlauf die von uns definierten Transformationen verwendet. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Wenn Sie diesen Schritt überspringen, fällt die Engine auf ihre Standardeinstellung zurück (oft „keine Vorverarbeitung“), und Sie werden **niedrigere OCR‑Genauigkeit** sehen. + +--- + +## Schritt 5: Erkennungsprozess ausführen – Text aus Bild extrahieren + +Nachdem alles verkabelt ist, lassen wir die Engine endlich ihre Arbeit tun. Der Aufruf ist synchron und gibt ein Result‑Objekt zurück, das den erkannten String enthält. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Im Hintergrund erledigt die Engine nun: + +1. Lädt das PNG in den Speicher +2. Wendet Denoise und Deskew basierend auf unseren Einstellungen an +3. Führt das neuronale Netzwerk oder den klassischen Muster‑Matcher aus +4. Verpackt die Ausgabe in `recognition_result` + +--- + +## Schritt 6: Erkannten Text ausgeben – Verbesserung überprüfen + +Lassen Sie uns den extrahierten String ausgeben. In einer realen Anwendung könnten Sie ihn in eine Datei, eine Datenbank schreiben oder an einen anderen Service weitergeben. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Erwartete Ausgabe + +Wenn das Bild den Satz „Hello, OCR World!“ enthält, sollten Sie Folgendes sehen: + +``` +Hello, OCR World! +``` + +Beachten Sie, wie sauber der Text ist – keine fremden Symbole oder zerbrochenen Zeichen. Das ist das Ergebnis einer ordentlichen **Bildvorverarbeitung für Text**. + +--- + +## Pro‑Tipps & Randfälle + +| Situation | Was anzupassen | Warum | +|-----------|----------------|------| +| Sehr niedrige Auflösung PNG (≤ 72 dpi) | `ImagePreprocessMode.SUPER_RESOLUTION` hinzufügen, falls verfügbar | Upsampling kann dem Erkenner mehr Pixel zum Arbeiten geben | +| Text ist um > 5° gedreht | Deskew‑Toleranz erhöhen oder das Bild vor dem Einspeisen mit `Pillow` manuell drehen | Extreme Winkel umgehen manchmal die automatische Deskew‑Funktion | +| Starke Hintergrundmuster | `ImagePreprocessMode.BACKGROUND_REMOVAL` aktivieren | Entfernt nicht‑textuelle Störungen, die sonst falsch gelesen würden | +| Mehrsprachiges Dokument | `ocr_engine.language = "eng+spa"` (oder ähnlich) setzen | Die Engine wählt den richtigen Zeichensatz, was die Gesamteffizienz steigert | + +Denken Sie daran, **die OCR‑Genauigkeit zu verbessern** ist kein One‑Size‑Fits‑All‑Ansatz; Sie müssen möglicherweise die Vorverarbeitungs‑Flags für Ihren spezifischen Datensatz iterativ anpassen. + +--- + +## Vollständiges Skript – Bereit zum Kopieren & Einfügen + +Unten finden Sie das komplette, ausführbare Beispiel, das jeden besprochenen Schritt integriert. Speichern Sie es als `improve_ocr_accuracy.py` und führen Sie es mit `python improve_ocr_accuracy.py` aus. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Starten Sie es, beobachten Sie die Konsole, und Sie sehen sofort das Ergebnis von **Text aus Bild extrahieren**. Wenn die Ausgabe nicht stimmt, justieren Sie die `preprocess_mode`‑Flags wie in der „Pro‑Tipps“-Tabelle beschrieben. + +--- + +## Fazit + +Wir haben gerade ein praktisches Rezept vorgestellt, um **die OCR‑Genauigkeit** mit Python zu **verbessern**. Durch das Erstellen einer `OcrEngine`, das Laden eines PNG, **die Bildvorverarbeitung für OCR** und schließlich **Text aus PNG erkennen**, können Sie zuverlässig **Text aus Bild**‑Dateien extrahieren, selbst wenn die Quelle nicht perfekt ist. + +Nächste Schritte? Versuchen Sie, eine Stapelverarbeitung von Bildern in einer Schleife zu implementieren, speichern Sie jedes Ergebnis in einer CSV‑Datei oder experimentieren Sie mit zusätzlichen Vorverarbeitungs‑Modi wie Kontrastverstärkung. Das gleiche Muster funktioniert für PDFs, gescannte Belege oder handschriftliche Notizen – einfach den Input austauschen und die Einstellungen anpassen. + +Haben Sie Fragen zu einem bestimmten Bildtyp oder möchten wissen, wie Sie das in einen Web‑Service integrieren? Hinterlassen Sie einen Kommentar, und wir erkunden diese Szenarien gemeinsam. Viel Spaß beim Coden, und mögen Ihre OCR‑Ergebnisse stets kristallklar sein! + +## Was sollten Sie als Nächstes lernen? + +- [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 Bild extrahieren – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Wie man Text aus Bild extrahiert, indem man Rechtecke für OCR vorbereitet](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/german/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..9310b1e09 --- /dev/null +++ b/ocr/german/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Erfahren Sie, wie Sie den OCR‑Bereich von Interesse nutzen, um ein Bild + für die OCR zu laden und Text aus einem Rechteck zu extrahieren – ideal, um den + Betrag auf einer Rechnung zu erkennen. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: de +og_description: Beherrschen Sie den OCR‑Bereich von Interesse, um ein Bild für OCR + zu laden, Text aus einem Rechteck zu extrahieren und Text aus einer Rechnung in + einem einzigen Tutorial zu erkennen. +og_title: OCR-Region von Interesse – Schritt‑für‑Schritt Python‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR-Region von Interesse – Text aus einem Rechteck in Python extrahieren +url: /de/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Text aus Rechteck in Python extrahieren + +Haben Sie sich schon einmal gefragt, wie man **ocr region of interest** einen bestimmten Teil einer gescannten Rechnung ausführt, ohne die gesamte Seite an die Engine zu übergeben? Sie sind nicht der Erste, der auf einem verschwommenen Beleg starrt und sich fragt: „Wie extrahiere ich den Betrag, der irgendwo unten rechts steht?“ Die gute Nachricht ist, dass Sie der OCR‑Bibliothek genau sagen können, wo sie suchen soll, was sowohl die Geschwindigkeit als auch die Genauigkeit erheblich steigert. + +In diesem Leitfaden gehen wir Schritt für Schritt durch ein vollständiges, ausführbares Beispiel, das zeigt, wie man **load image for OCR** verwendet, eine **region of interest** definiert und dann **extract text from rectangle** ausführt, um schließlich **recognize text from invoice** zu erledigen und die klassische Frage „wie extrahiere ich den Betrag“ zu beantworten. Keine vagen Verweise – nur konkreter Code, klare Erklärungen und ein paar Pro‑Tipps, die Sie gerne früher gekannt hätten. + +--- + +## Was Sie bauen werden + +Am Ende dieses Tutorials haben Sie ein kleines Python‑Skript, das: + +1. Ein Rechnungs‑Bild von der Festplatte lädt. +2. Ein rechteckiges ROI markiert, in dem der Gesamtbetrag steht. +3. OCR nur innerhalb dieses ROI ausführt. +4. Den bereinigten Betrag‑String ausgibt. + +All das funktioniert mit jeder OCR‑Bibliothek, die ROI unterstützt – hier verwenden wir das fiktive, aber repräsentative `SimpleOCR`‑Paket, das beliebte Werkzeuge wie Tesseract oder EasyOCR nachahmt. Sie können es problemlos austauschen; die Konzepte bleiben gleich. + +--- + +## Voraussetzungen + +- Python 3.8+ installiert (`python --version` sollte ≥3.8 anzeigen). +- Ein per pip installierbares OCR‑Paket (z. B. `pip install simpleocr`). +- Ein Rechnungs‑Bild (PNG oder JPEG) in einem Ordner, auf den Sie verweisen können. +- Grundlegende Kenntnisse von Python‑Funktionen und -Klassen (nichts Besonderes). + +Wenn Sie das bereits haben, großartig – lassen Sie uns loslegen. Wenn nicht, holen Sie zuerst das Bild; die restlichen Schritte sind unabhängig vom eigentlichen Dateiinhalt. + +--- + +## Schritt 1: Bild für OCR laden + +Das Erste, was jeder OCR‑Workflow benötigt, ist ein Bitmap, das gelesen werden kann. Die meisten Bibliotheken stellen eine einfache `load_image`‑Methode bereit, die einen Dateipfad akzeptiert. So geht's mit unserer `SimpleOCR`‑Engine: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro‑Tipp:** Verwenden Sie absolute Pfade oder `os.path.join`, um „Datei nicht gefunden“-Überraschungen zu vermeiden, wenn das Skript aus einem anderen Arbeitsverzeichnis ausgeführt wird. + +--- + +## Schritt 2: OCR Region of Interest definieren + +Anstatt die Engine die gesamte Seite scannen zu lassen, sagen wir ihr *genau*, wo der Betrag steht. Das ist der **ocr region of interest**‑Schritt und der Schlüssel zu zuverlässiger Extraktion, besonders wenn das Dokument laute Kopf‑ oder Fußzeilen enthält. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Warum diese Zahlen? `x` und `y` sind Pixel‑Offsets vom oberen linken Eckpunkt, während `width` und `height` die Größe des Kastens beschreiben. Wenn Sie unsicher sind, öffnen Sie das Bild in einem beliebigen Editor, aktivieren Sie ein Lineal und notieren Sie die Koordinaten. Viele IDEs zeigen sogar die Cursor‑Position beim Überfahren an. + +--- + +## Schritt 3: Text aus Rechteck extrahieren + +Jetzt, wo das ROI gesetzt ist, bitten wir die Engine, **recognize text from invoice** zu erledigen, jedoch nur innerhalb des gerade hinzugefügten Rechtecks. Der Aufruf liefert ein Ergebnis‑Objekt, das typischerweise den Roh‑String, Vertrauenswerte und manchmal Begrenzungsrahmen enthält. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Im Hintergrund iteriert `recognize()` über jedes ROI, schneidet diesen Ausschnitt zu, führt das OCR‑Modell aus und fügt die Ergebnisse zusammen. Deshalb kann das Definieren eines engen **extract text from rectangle**‑Bereichs Sekunden bei Batch‑Jobs einsparen. + +--- + +## Schritt 4: Wie man Betrag extrahiert – Ausgabe bereinigen + +OCR ist nicht perfekt; Sie erhalten häufig überflüssige Leerzeichen, Zeilenumbrüche oder sogar falsch gelesene Zeichen (z. B. „S“ statt „5“). Ein kurzer `strip()` und ein kleiner Regex erledigen das meist für Geldbeträge. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Warum das wichtig ist:** Wenn Sie den Betrag in eine Datenbank oder ein Zahlungsgateway einspeisen wollen, benötigen Sie ein vorhersehbares Format. Das Entfernen von Leerzeichen und das Filtern nicht‑numerischer Zeichen verhindert nachgelagerte Fehler. + +--- + +## Schritt 5: Text aus Rechnung erkennen – Vollständiges Skript + +Alles zusammengeführt, hier das komplette, sofort ausführbare Skript. Speichern Sie es als `extract_amount.py` und führen Sie `python extract_amount.py` aus. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Erwartete Ausgabe + +``` +Amount: 1,245.67 +``` + +Wenn das ROI falsch ausgerichtet ist, sehen Sie möglicherweise etwas wie `Amount: 1245.6S` – beachten Sie das überflüssige „S“. Passen Sie die Rechteck‑Koordinaten an und wiederholen Sie den Vorgang, bis die Ausgabe sauber aussieht. + +--- + +## Häufige Fallstricke & Randfälle + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| **ROI zu klein** | Der Betragstext wird abgeschnitten, was zu teilweiser Erkennung führt. | Erweitern Sie `width`/`height` um ca. 10‑20 % und testen Sie erneut. | +| **Falsche DPI** | Scans mit niedriger Auflösung (≤150 dpi) verringern die OCR‑Genauigkeit. | Resampeln Sie das Bild auf 300 dpi vor dem Laden oder bitten Sie den Scanner um höhere DPI. | +| **Mehrere Währungen** | Der Regex wählt die erste Zahlenfolge, die möglicherweise eine Rechnungsnummer ist. | Verfeinern Sie den Regex, um nach Währungssymbolen (`$`, `€`, `£`) vor den Ziffern zu suchen. | +| **Gedrehte Rechnungen** | OCR‑Engines gehen von aufrechtem Text aus; gedrehte Seiten brechen die Erkennung. | Wenden Sie eine Rotationskorrektur (`ocr_engine.rotate(90)`) an, bevor Sie die ROI hinzufügen. | +| **Rauschen im Hintergrund** | Schatten oder Stempel verwirren das Modell. | Vorverarbeiten mit einem einfachen Schwellenwert (`cv2.threshold`) oder einen Rauschfilter verwenden. | + +--- + +## Pro‑Tipps für reale Projekte + +- **Stapelverarbeitung:** Durchlaufen Sie einen Ordner mit Rechnungen, berechnen Sie das ROI dynamisch (z. B. basierend auf Vorlagenerkennung) und speichern Sie die Ergebnisse in einer CSV‑Datei. +- **Vorlagenabgleich:** Wenn Sie mehrere Rechnungs‑Layouts bearbeiten, führen Sie eine JSON‑Map `template_id → ROI‑Koordinaten` ein. Wechseln Sie das ROI basierend auf einem schnellen Layout‑Klassifikator. +- **Parallele Ausführung:** Nutzen Sie `concurrent.futures.ThreadPoolExecutor`, um mehrere OCR‑Instanzen gleichzeitig laufen zu lassen – ideal für hochvolumige Back‑Office‑Pipelines. +- **Vertrauensfilterung:** Die meisten OCR‑Ergebnisse enthalten einen Confidence‑Score. Verwerfen Sie Ergebnisse unter einem Schwellenwert (z. B. 85 %) und markieren Sie sie zur manuellen Prüfung. + +--- + +## Fazit + +Wir haben alles behandelt, was Sie benötigen, um **ocr region of interest**, **load image for OCR**, **extract text from rectangle** und schließlich **recognize text from invoice** zu nutzen, um die klassische **how to extract amount**‑Frage zu beantworten. Das Skript ist kompakt, aber flexibel genug, um sich an verschiedene Dokumentformate, Sprachen und OCR‑Back‑Ends anzupassen. + +Jetzt, wo Sie die Grundlagen beherrschen, überlegen Sie, den Workflow zu erweitern: Barcode‑Scanning hinzufügen, mit einem PDF‑Parser integrieren oder den extrahierten Betrag an eine Buchhaltungs‑API senden. Der Himmel ist die Grenze, und mit einem gut definierten ROI erhalten Sie stets schnellere, sauberere Ergebnisse. + +Wenn Sie auf ein Problem stoßen, hinterlassen Sie unten einen Kommentar – happy OCRing! + +![Beispiel für OCR Region of Interest](https://example.com/ocr_roi_example.png "Beispiel für OCR Region of Interest") + + +## Was sollten Sie als Nächstes lernen? + +- [Wie man Text aus Bild extrahiert, indem man Rechtecke für OCR vorbereitet](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Text aus Bild Java mit Aspose.OCR Detect Areas Mode extrahieren](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/greek/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/greek/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..5a80c985a --- /dev/null +++ b/ocr/greek/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Μάθημα ασύγχρονης OCR που δείχνει πώς να χρησιμοποιήσετε το Aspose OCR + στην Python με asyncio για γρήγορη εξαγωγή κειμένου από εικόνες. Μάθετε βήμα‑βήμα + την υλοποίηση ασύγχρονης OCR. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: el +og_description: Το ασύγχρονο σεμινάριο OCR σας καθοδηγεί στη χρήση του Aspose OCR + στην Python με asyncio για αποδοτική εξαγωγή κειμένου από εικόνες. +og_title: Οδηγός Async OCR – Python asyncio με Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Μάθημα Async OCR – Python asyncio με Aspose OCR +url: /el/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εκπαίδευση Async OCR – Python asyncio με Aspose OCR + +Έχετε αναρωτηθεί ποτέ πώς να εκτελείτε αναγνώριση οπτικών χαρακτήρων χωρίς να μπλοκάρετε την εφαρμογή σας; Σε ένα **async OCR tutorial** θα δείτε ακριβώς αυτό—μη‑μπλοκαριστική εξαγωγή κειμένου χρησιμοποιώντας το `asyncio` της Python και τη βιβλιοθήκη Aspose OCR. + +Αν έχετε κολλήσει περιμένοντας να επεξεργαστεί μια βαριά εικόνα, αυτός ο οδηγός σας παρέχει μια καθαρή, ασύγχρονη λύση που διατηρεί το event loop σας σε λειτουργία. + +Στις επόμενες ενότητες θα καλύψουμε όλα όσα χρειάζεστε: εγκατάσταση της βιβλιοθήκης, δημιουργία ενός ασύγχρονου βοηθού, διαχείριση του αποτελέσματος, και ακόμη μια γρήγορη συμβουλή για κλιμάκωση σε πολλαπλές εικόνες. Στο τέλος θα μπορείτε να ενσωματώσετε ένα **async OCR tutorial** σε οποιοδήποτε έργο Python που ήδη χρησιμοποιεί `asyncio`. + +## Τι Θα Χρειαστείτε + +Πριν προχωρήσουμε, βεβαιωθείτε ότι έχετε: + +* Python 3.9+ (το API `asyncio` που χρησιμοποιούμε είναι σταθερό από την έκδοση 3.7 και μετά) +* Ένα ενεργό license Aspose OCR ή μια δωρεάν δοκιμή (η βιβλιοθήκη είναι καθαρά Python, χωρίς εγγενή δυαδικά αρχεία) +* Ένα μικρό αρχείο εικόνας (`.jpg`, `.png`, κ.λπ.) που θέλετε να διαβάσετε – κρατήστε το σε γνωστό φάκελο + +Δεν απαιτούνται άλλα εξωτερικά εργαλεία· όλα τρέχουν σε καθαρή Python. + +## Βήμα 1: Εγκατάσταση του Πακέτου Aspose OCR + +Πρώτα απ’ όλα, πάρτε το πακέτο Aspose OCR από το PyPI. Ανοίξτε ένα τερματικό και τρέξτε: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Αν εργάζεστε μέσα σε εικονικό περιβάλλον (συνιστάται έντονα), ενεργοποιήστε το πρώτα. Αυτό διατηρεί τις εξαρτήσεις απομονωμένες και αποτρέπει συγκρούσεις εκδόσεων. + +## Βήμα 2: Αρχικοποίηση του OCR Engine Ασύγχρονα + +Η καρδιά του **async OCR tutorial** μας είναι μια ασύγχρονη βοηθητική συνάρτηση. Δημιουργεί ένα αντικείμενο `OcrEngine`, φορτώνει μια εικόνα και στη συνέχεια καλεί το `recognize_async()`. Το engine είναι ίδιο συγχρονικό, αλλά η μέθοδος περιτυλίγματος επιστρέφει ένα awaitable, επιτρέποντας στο event loop να παραμείνει ανταποκριτικό. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Γιατί το κάνουμε με αυτόν τον τρόπο:** +*Δημιουργώντας το engine μέσα στον βοηθό εξασφαλίζουμε thread‑safety αν αργότερα τρέξετε πολλά OCR jobs παράλληλα. Η λέξη‑κλειδί `await` επιστρέφει τον έλεγχο στο event loop ενώ η βαριά δουλειά εκτελείται στην εσωτερική ομάδα νημάτων της βιβλιοθήκης.* + +## Βήμα 3: Εκτέλεση του Helper από μια Async Main Συνάρτηση + +Τώρα χρειαζόμαστε μια μικρή coroutine `main()` που καλεί το `async_ocr()` και εκτυπώνει το αποτέλεσμα. Αυτό αντικατοπτρίζει το τυπικό σημείο εισόδου για ένα script `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Τι συμβαίνει στο παρασκήνιο;** +`asyncio.run()` δημιουργεί ένα νέο event loop, προγραμματίζει το `main()` και κλείνει το loop καθαρά όταν το `main()` ολοκληρωθεί. Αυτό το μοτίβο είναι ο προτεινόμενος τρόπος εκκίνησης ασύγχρονων προγραμμάτων στην Python 3.7+. + +## Βήμα 4: Δοκιμή του Πλήρους Σεναρίου + +Αποθηκεύστε τα δύο παραπάνω μπλοκ κώδικα σε ένα ενιαίο αρχείο, π.χ. `async_ocr_demo.py`. Εκτελέστε το από τη γραμμή εντολών: + +```bash +python async_ocr_demo.py +``` + +Αν όλα είναι ρυθμισμένα σωστά, θα δείτε κάτι σαν: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Η ακριβής έξοδος θα εξαρτηθεί από το περιεχόμενο του `photo.jpg`. Το βασικό σημείο είναι ότι το script ολοκληρώνεται γρήγορα, ακόμη και αν η εικόνα είναι μεγάλη, επειδή η εργασία OCR εκτελείται στο παρασκήνιο. + +## Βήμα 5: Κλιμάκωση – Επεξεργασία Πολλαπλών Εικόνων Συγχρόνως + +Μια συχνή επόμενη ερώτηση είναι, *«Μπορώ να κάνω OCR σε μια δέσμη αρχείων χωρίς να εκκινώ νέο process για κάθε ένα;»* Απόλυτα. Επειδή ο βοηθός μας είναι πλήρως ασύγχρονος, μπορούμε να συγκεντρώσουμε πολλές coroutines με το `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Γιατί αυτό λειτουργεί:** `asyncio.gather()` προγραμματίζει όλα τα OCR tasks ταυτόχρονα. Η υποκείμενη βιβλιοθήκη Aspose OCR εξακολουθεί να χρησιμοποιεί τη δική της ομάδα νημάτων, αλλά από την προοπτική της Python όλα παραμένουν μη‑μπλοκαρισμένα, επιτρέποντάς σας να διαχειριστείτε δεκάδες εικόνες στο χρόνο που θα έπαιρνε μια μόνο συγχρονική κλήση. + +## Βήμα 6: Χειρισμός Σφαλμάτων με Ευγένεια + +Όταν δουλεύετε με εξωτερικά αρχεία, είναι αναπόφευκτο να αντιμετωπίσετε ελλιπή αρχεία, κατεστραμμένες εικόνες ή προβλήματα άδειας. Τυλίξτε την κλήση OCR σε ένα μπλοκ `try/except` για να κρατήσετε το event loop ζωντανό: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Τώρα το `batch_ocr()` μπορεί να καλέσει το `safe_async_ocr` αντί για το κανονικό, διασφαλίζοντας ότι ένα κακό αρχείο δεν θα διακόψει ολόκληρη τη δέσμη. + +## Οπτική Επισκόπηση + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Διάγραμμα ροής του tutorial Async OCR που δείχνει τον βοηθό async_ocr, το event loop και το engine Aspose OCR"} + +Το παραπάνω διάγραμμα οπτικοποιεί τη ροή: το event loop → `async_ocr` → `OcrEngine` → νήμα παρασκηνίου → αποτέλεσμα πίσω στο loop. + +## Συνηθισμένα Πιθανά Σφάλματα & Πώς να τα Αποφύγετε + +| Πιθανό Σφάλμα | Γιατί Συμβαίνει | Διόρθωση | +|---------------|----------------|----------| +| **Blocking I/O μέσα στον helper** | Η τυχαία χρήση του `open()` χωρίς `await` μπορεί να μπλοκάρει το loop. | Χρησιμοποιήστε `aiofiles` για ανάγνωση αρχείων, ή αφήστε το `engine.load_image` να το διαχειριστεί (είναι ήδη μη‑μπλοκαριστικό). | +| **Επαναχρησιμοποίηση ενός μόνο `OcrEngine` μεταξύ coroutines** | Το engine δεν είναι thread‑safe· οι ταυτόχρονες κλήσεις μπορεί να καταστρέψουν την κατάσταση. | Δημιουργήστε ένα νέο engine μέσα σε κάθε κλήση `async_ocr` (όπως φαίνεται). | +| **Απουσία άδειας** | Το Aspose OCR πετάει εξαίρεση σχετική με την άδεια κατά την εκτέλεση. | Καταχωρίστε την άδειά σας νωρίς (`OcrEngine.set_license("license.json")`). | +| **Μεγάλες εικόνες που προκαλούν άλματα μνήμης** | Η βιβλιοθήκη φορτώνει ολόκληρη την εικόνα στη RAM. | Μειώστε το μέγεθος των εικόνων πριν το OCR αν η μνήμη είναι πρόβλημα. | + +## Ανακεφαλαίωση: Τι Καταφέραμε + +Σε αυτό το **async OCR tutorial** κάναμε: + +1. Εγκαταστήσαμε τη βιβλιοθήκη Aspose OCR. +2. Δημιουργήσαμε έναν βοηθό `async_ocr` που εκτελεί την αναγνώριση χωρίς μπλοκάρισμα. +3. Τρέξαμε τον βοηθό από ένα καθαρό σημείο εισόδου `asyncio`. +4. Δείξαμε επεξεργασία δέσμης με `asyncio.gather`. +5. Προσθέσαμε διαχείριση σφαλμάτων και συμβουλές βέλτιστων πρακτικών. + +Όλα αυτά είναι καθαρή Python, οπότε μπορείτε να τα ενσωματώσετε σε web server, CLI εργαλείο ή data‑pipeline χωρίς να ξαναγράψετε υπάρχον κώδικα async. + +## Επόμενα Βήματα & Σχετικά Θέματα + +* **Ασύγχρονη προεπεξεργασία εικόνας** – χρησιμοποιήστε `aiohttp` για ταυτόχρονη λήψη εικόνων πριν το OCR. +* **Αποθήκευση αποτελεσμάτων OCR** – συνδυάστε αυτόν τον οδηγό με έναν ασύγχρονο οδηγό βάσης δεδομένων όπως `asyncpg` για PostgreSQL. +* **Βελτιστοποίηση απόδοσης** – πειραματιστείτε με `engine.recognize_async(max_threads=4)` αν η βιβλιοθήκη προσφέρει τέτοια επιλογή. +* **Εναλλακτικές μηχανές OCR** – συγκρίνετε το Aspose OCR με τα async wrappers του Tesseract για ανάλυση κόστους‑οφέλους. + +Νιώστε ελεύθεροι να πειραματιστείτε: δοκιμάστε να τροφοδοτήσετε PDFs, ρυθμίστε τις γλωσσικές ρυθμίσεις ή συνδέστε τα αποτελέσματα σε chatbot. Ο ουρανός είναι το όριο μόλις έχετε μια σταθερή βάση **async OCR tutorial**. + +Καλή προγραμματιστική, και εύχομαι η εξαγωγή κειμένου σας να είναι πάντα γρήγορη! + +## Τι Θα Μάθεις Στη Σειρά; + +- [Εξαγωγή Κειμένου από Εικόνα με Aspose OCR – Οδηγός Βήμα‑βήμα](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [Πώς να Κάνετε OCR Κειμένου Εικόνας με Γλώσσα Χρησιμοποιώντας Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/greek/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..b28a7d626 --- /dev/null +++ b/ocr/greek/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Η αυτόματη ανίχνευση γλώσσας στο OCR έγινε εύκολη. Μάθετε πώς να φορτώνετε + εικόνα OCR, να ενεργοποιείτε την αυτόματη ανίχνευση γλώσσας και να αναγνωρίζετε + κείμενο σε εικόνα σε λίγα μόνο βήματα. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: el +og_description: Η αυτόματη ανίχνευση γλώσσας στο OCR έγινε εύκολη. Ακολουθήστε αυτό + το βήμα‑βήμα οδηγό για να ενεργοποιήσετε την αυτόματη ανίχνευση γλώσσας, να φορτώσετε + OCR εικόνας και να αναγνωρίσετε το κείμενο της εικόνας. +og_title: Αυτόματη ανίχνευση γλώσσας με OCR – Πλήρης οδηγός Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Αυτόματη Ανίχνευση Γλώσσας με OCR – Πλήρης Οδηγός Python +url: /el/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Αυτόματη Ανίχνευση Γλώσσας με OCR – Πλήρης Οδηγός Python + +Έχετε αναρωτηθεί ποτέ πώς να κάνετε μια μηχανή OCR *να μαντέψει* τη γλώσσα ενός σαρωμένου εγγράφου χωρίς να της λέτε τι να ψάξει; Αυτό ακριβώς κάνει η **αυτόματη ανίχνευση γλώσσας**, και είναι πραγματικά αλλαγή παιχνιδιού όταν εργάζεστε με πολυγλωσσικά PDF, φωτογραφίες πινακίδων δρόμου ή οποιαδήποτε εικόνα που συνδυάζει διαφορετικά αλφάβητα. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα ένα πρακτικό παράδειγμα που δείχνει πώς να **ενεργοποιήσετε την αυτόματη ανίχνευση γλώσσας**, **φορτώσετε OCR εικόνας**, και **αναγνωρίσετε κείμενο από εικόνα** χρησιμοποιώντας ένα API τύπου Python. Στο τέλος θα έχετε ένα αυτόνομο script που εκτυπώνει τόσο τον κωδικό της ανιχνευμένης γλώσσας όσο και το εξαγόμενο κείμενο — χωρίς να χρειάζονται χειροκίνητες ρυθμίσεις γλώσσας. + +## Τι Θα Μάθετε + +- Πώς να δημιουργήσετε μια παρουσία του OCR engine και να ενεργοποιήσετε την **αυτόματη ανίχνευση γλώσσας**. +- Τα ακριβή βήματα για **φόρτωση OCR εικόνας** από το δίσκο. +- Πώς να καλέσετε τη μέθοδο `recognize()` του engine και να λάβετε ένα αποτέλεσμα που περιλαμβάνει τον κωδικό γλώσσας. +- Συμβουλές για την αντιμετώπιση ειδικών περιπτώσεων όπως εικόνες χαμηλής ανάλυσης ή μη υποστηριζόμενα αλφάβητα. + +Δεν απαιτείται προηγούμενη εμπειρία με πολυγλωσσικό OCR· αρκεί μια βασική εγκατάσταση Python και ένα αρχείο εικόνας. + +--- + +## Προαπαιτούμενα + +1. Python 3.8+ εγκατεστημένο (οποιαδήποτε πρόσφατη έκδοση λειτουργεί). +2. Η βιβλιοθήκη OCR που παρέχει `OcrEngine`, `LanguageAutoDetectMode`, κ.λπ. – για αυτόν τον οδηγό θα υποθέσουμε ένα υποθετικό πακέτο που ονομάζεται `myocr`. Εγκαταστήστε το με: + + ```bash + pip install myocr + ``` + +3. Ένα αρχείο εικόνας (`multilingual_sample.png`) που περιέχει κείμενο τουλάχιστον σε δύο διαφορετικές γλώσσες. +4. Λίγη περιέργεια—αν δεν έχετε ξαναδουλέψει με OCR, μην ανησυχείτε· ο κώδικας είναι σκόπιμα απλός. + +--- + +## Βήμα 1: Ενεργοποίηση Αυτόματης Ανίχνευσης Γλώσσας + +Το πρώτο που πρέπει να κάνετε είναι να πείτε στο engine ότι πρέπει να *καθορίσει* τη γλώσσα μόνο του. Εδώ έρχεται σε εφαρμογή η σημαία **αυτόματης ανίχνευσης γλώσσας**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Γιατί είναι σημαντικό:** +> Όταν ορίζεται το `AUTO_DETECT`, το engine εκτελεί έναν ελαφρύ ταξινομητή γλώσσας στην εικόνα πριν ενεργοποιηθεί η βαριά αναγνώριση χαρακτήρων. Αυτό σημαίνει ότι δεν χρειάζεται να μαντέψετε αν το κείμενο είναι αγγλικά, ρωσικά, γαλλικά ή οποιοσδήποτε συνδυασμός αυτών. Το engine θα επιλέξει αυτόματα το καλύτερο μοντέλο γλώσσας για κάθε περιοχή της εικόνας. + +--- + +## Βήμα 2: Φόρτωση OCR Εικόνας + +Τώρα που το engine ξέρει ότι πρέπει να ανιχνεύει αυτόματα τις γλώσσες, πρέπει να του δώσουμε κάτι πάνω στο οποίο να εργαστεί. Το βήμα **φόρτωση OCR εικόνας** διαβάζει το bitmap και προετοιμάζει εσωτερικές μνήμες. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Συμβουλή:** +> Αν η εικόνα σας είναι μεγαλύτερη από 300 dpi, σκεφτείτε να τη μειώσετε σε περίπου 150‑200 dpi. Πάρα πολλές λεπτομέρειες μπορούν στην πραγματικότητα να *αργήσουν* το στάδιο ανίχνευσης γλώσσας χωρίς να βελτιώσουν την ακρίβεια. + +--- + +## Βήμα 3: Αναγνώριση Κειμένου από Εικόνα + +Με την εικόνα στη μνήμη και την ανίχνευση γλώσσας ενεργοποιημένη, το τελευταίο βήμα είναι να ζητήσουμε από το engine να **αναγνωρίσει κείμενο από εικόνα**. Αυτή η ενιαία κλήση κάνει όλη τη βαριά δουλειά. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` είναι ένα αντικείμενο που συνήθως περιέχει τουλάχιστον δύο ιδιότητες: + +| Attribute | Description | +|-----------|-------------| +| `language` | Κωδικός ISO‑639‑1 της ανιχνευμένης γλώσσας (π.χ., `"en"` για Αγγλικά). | +| `text` | Η απλή κειμενική μεταγραφή της εικόνας. | + +--- + +## Βήμα 4: Ανάκτηση Ανιχνευμένης Γλώσσας και Εξαγόμενου Κειμένου + +Τώρα απλώς εκτυπώνουμε ό,τι ανακάλυψε το engine. Αυτό δείχνει τη δυνατότητα **detect language OCR** σε δράση. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Δείγμα εξόδου** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Τι γίνεται αν το engine επιστρέψει `None`;** +> Αυτό συνήθως σημαίνει ότι η εικόνα είναι πολύ θολή ή το κείμενο πολύ μικρό (< 8 pt). Δοκιμάστε να αυξήσετε την αντίθεση ή να χρησιμοποιήσετε πηγή υψηλότερης ανάλυσης. + +--- + +## Πλήρες Παράδειγμα Λειτουργίας (Ενεργοποίηση Αυτόματης Ανίχνευσης Γλώσσας Από Αρχή έως Τέλος) + +Συνδυάζοντας όλα, εδώ είναι ένα έτοιμο‑για‑εκτέλεση script που καλύπτει **ενεργοποίηση αυτόματης ανίχνευσης γλώσσας**, **φόρτωση OCR εικόνας**, **αναγνώριση κειμένου από εικόνα**, και **detect language OCR** σε ένα βήμα. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Αποθηκεύστε το ως `automatic_language_detection_ocr.py`, αντικαταστήστε το `YOUR_DIRECTORY` με το φάκελο που περιέχει το PNG σας, και εκτελέστε: + +```bash +python automatic_language_detection_ocr.py +``` + +Θα πρέπει να δείτε τον κωδικό γλώσσας ακολουθούμενο από το εξαγόμενο κείμενο, όπως στο παραπάνω δείγμα εξόδου. + +--- + +## Διαχείριση Συνηθισμένων Ειδικών Περιπτώσεων + +| Situation | Suggested Fix | +|-----------|----------------| +| **Πολύ χαμηλής ανάλυσης εικόνα** (κάτω από 100 dpi) | Αυξήστε την ανάλυση με φίλτρο bicubic πριν τη φόρτωση, ή ζητήστε πηγή υψηλότερης ανάλυσης. | +| **Μικτά αλφάβητα σε μία εικόνα** (π.χ., Αγγλικά + Κυριλλικά) | Το engine συνήθως χωρίζει τη σελίδα σε περιοχές· αν παρατηρήσετε λανθασμένες ανιχνεύσεις, ορίστε `engine.enable_region_split = True`. | +| **Μη υποστηριζόμενη γλώσσα** | Επαληθεύστε ότι η βιβλιοθήκη OCR περιλαμβάνει πακέτο γλώσσας για το αλφάβητο που χρειάζεστε· ίσως χρειαστεί να κατεβάσετε επιπλέον μοντέλα. | +| **Μεγάλη επεξεργασία παρτίδας** | Αρχικοποιήστε το engine μία φορά, και στη συνέχεια επαναχρησιμοποιήστε το σε πολλαπλούς κύκλους `load_image` / `recognize` για να αποφύγετε επαναλαμβανόμενη φόρτωση μοντέλων. | + +--- + +## Οπτική Επισκόπηση + +![παράδειγμα εξόδου αυτόματης ανίχνευσης γλώσσας](https://example.com/auto-lang-detect.png "αυτόματη ανίχνευση γλώσσας") + +*Alt text:* παράδειγμα εξόδου αυτόματης ανίχνευσης γλώσσας που δείχνει τον κωδικό της ανιχνευμένης γλώσσας και το εξαγόμενο πολυγλωσσικό κείμενο. + +--- + +## Συμπέρασμα + +Μόλις καλύψαμε την **αυτόματη ανίχνευση γλώσσας** από την αρχή μέχρι το τέλος—δημιουργία του engine, ενεργοποίηση αυτόματης ανίχνευσης γλώσσας, φόρτωση εικόνας για OCR, αναγνώριση του κειμένου, και τελικά ανάκτηση της ανιχνευμένης γλώσσας. Αυτή η ροή από άκρο σε άκρο σας επιτρέπει να επεξεργάζεστε πολυγλωσσικά έγγραφα χωρίς να χρειάζεται να ρυθμίζετε χειροκίνητα μοντέλα γλώσσας κάθε φορά. + +Αν είστε έτοιμοι να προχωρήσετε παραπέρα, σκεφτείτε: + +- **Batching** εκατοντάδες εικόνες με έναν βρόχο που επαναχρησιμοποιεί την ίδια παρουσία `OcrEngine`. +- **Post‑processing** του εξαγόμενου κειμένου με ελεγκτή ορθογραφίας ή διαχωριστή ειδικό για τη γλώσσα. +- **Integrating** το script σε μια υπηρεσία web που δέχεται μεταφορτώσεις χρηστών και επιστρέφει JSON με πεδία `language` και `text`. + +Μη διστάσετε να πειραματιστείτε με διαφορετικές μορφές εικόνας (`.jpg`, `.tif`) και δείτε πώς αλλάζει η ακρίβεια της ανίχνευσης. Έχετε ερωτήσεις ή μια δύσκολη εικόνα που δεν διαβάζεται; Αφήστε ένα σχόλιο παρακάτω—καλή κωδικοποίηση! + +## Τι Θα Μάθετε Στη Σύντομη Επόμενη + +- [Πώς να κάνετε OCR κειμένου εικόνας με γλώσσα χρησιμοποιώντας Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [αναγνώριση κειμένου εικόνας με Aspose OCR για πολλαπλές γλώσσες](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/greek/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..a997b7ad1 --- /dev/null +++ b/ocr/greek/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Μάθετε πώς να μετατρέπετε εικόνες σε κείμενο με Python χρησιμοποιώντας + ένα script μαζικής μετατροπής εικόνων σε κείμενο. Αναγνωρίστε κείμενο από σαρωμένες + εικόνες με το Aspose.OCR σε λίγα λεπτά. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: el +og_description: Μετατρέψτε εικόνες σε κείμενο με Python άμεσα. Αυτός ο οδηγός δείχνει + τη μαζική μετατροπή εικόνων σε κείμενο και πώς να αναγνωρίζετε κείμενο από σαρωμένες + εικόνες με το Aspose.OCR. +og_title: Μετατροπή Εικόνων σε Κείμενο με Python – Πλήρης Οδηγός +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Μετατροπή Εικόνων σε Κείμενο με Python – Πλήρης Οδηγός Βήμα‑βήμα +url: /el/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή Εικόνων σε Κείμενο με Python – Πλήρης Οδηγός Βήμα‑βήμα + +Έχετε αναρωτηθεί ποτέ πώς να **convert images to text python** χωρίς να ψάχνετε σε δεκάδες βιβλιοθήκες; Δεν είστε οι μόνοι. Είτε ψηφιοποιείτε παλιές αποδείξεις, εξάγετε δεδομένα από σαρωμένα τιμολόγια, είτε δημιουργείτε ένα ευρετήριο PDF με δυνατότητα αναζήτησης, η μετατροπή εικόνων σε απλά αρχεία κειμένου είναι καθημερινή εργασία για πολλούς προγραμματιστές. + +Σε αυτό το tutorial θα περάσουμε από μια **bulk image to text conversion** pipeline που αναγνωρίζει κείμενο από σαρωμένες εικόνες, αποθηκεύει κάθε αποτέλεσμα ως ξεχωριστό αρχείο `.txt`, και το κάνει όλο με μερικές μόνο γραμμές Python. Χωρίς να ψάχνετε για σπάνιες APIs—το Aspose.OCR κάνει το σκληρό κομμάτι, και θα σας δείξουμε ακριβώς πώς να το ενσωματώσετε. + +## Τι Θα Μάθετε + +- Πώς να εγκαταστήσετε και να ρυθμίσετε το πακέτο Aspose.OCR for Python. +- Τον ακριβή κώδικα που απαιτείται για **convert images to text python** χρησιμοποιώντας το `BatchOcrEngine`. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων όπως μη υποστηριζόμενες μορφές ή κατεστραμμένα αρχεία. +- Τρόπους επαλήθευσης ότι το βήμα **recognize text from scanned images** ολοκληρώθηκε επιτυχώς. + +Στο τέλος αυτού του οδηγού θα έχετε ένα έτοιμο‑να‑τρέξει script που μπορεί να επεξεργαστεί χιλιάδες εικόνες σε μία φορά—ιδανικό για οποιοδήποτε σενάριο επεξεργασίας παρτίδας. + +## Προαπαιτούμενα + +- Python 3.8+ εγκατεστημένο στο σύστημά σας. +- Ένας φάκελος με αρχεία εικόνας (PNG, JPEG, TIFF, κ.λπ.) που θέλετε να μετατρέψετε σε κείμενο. +- Ένας ενεργός λογαριασμός Aspose Cloud ή μια δωρεάν δοκιμαστική άδεια (το δωρεάν επίπεδο αρκεί για δοκιμές). + +Αν έχετε όλα αυτά, ας βουτήξουμε. + +--- + +## Step 1 – Set Up Your Python Environment + +Πριν αρχίσουμε να γράφουμε κώδικα OCR, βεβαιωθείτε ότι εργάζεστε μέσα σε ένα καθαρό virtual environment. Αυτό απομονώνει τις εξαρτήσεις και αποτρέπει συγκρούσεις εκδόσεων. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Κρατήστε τον φάκελο του έργου σας τακτοποιημένο—δημιουργήστε ένα υποφάκελο που ονομάζεται `ocr_project` και τοποθετήστε το script εκεί. Έτσι η διαχείριση διαδρομών γίνεται παιχνιδάκι αργότερα. + +## Step 2 – Install Aspose.OCR for Python + +Το Aspose.OCR είναι εμπορική βιβλιοθήκη, αλλά διανέμεται με ένα δωρεάν wheel τύπου NuGet που μπορείτε να κατεβάσετε από το PyPI. Εκτελέστε την παρακάτω εντολή μέσα στο ενεργοποιημένο virtual environment: + +```bash +pip install aspose-ocr +``` + +Αν αντιμετωπίσετε σφάλμα δικαιωμάτων, προσθέστε τη σημαία `--user` ή τρέξτε την εντολή με `sudo` (μόνο Linux/macOS). Μετά την εγκατάσταση θα πρέπει να δείτε κάτι σαν: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** Σε αντίθεση με πολλά ανοιχτού κώδικα OCR εργαλεία, το Aspose.OCR υποστηρίζει **bulk image to text conversion** έτοιμο από την αρχή και διαχειρίζεται ένα ευρύ φάσμα μορφών εικόνας χωρίς επιπλέον ρυθμίσεις. Επιπλέον προσφέρει την κλάση `BatchOcrEngine` που κάνει το έργο **convert images to text python** μια εντολή‑μια‑γραμμή. + +## Step 3 – Convert Images to Text Python with Batch OCR + +Τώρα για την καρδιά του tutorial. Παρακάτω υπάρχει ένα πλήρως εκτελέσιμο script που: + +1. Εισάγει τις κλάσεις του OCR engine. +2. Δημιουργεί ένα αντικείμενο `BatchOcrEngine`. +3. Κατευθύνει το engine σε έναν φάκελο εισόδου με εικόνες. +4. Οδηγεί το engine να γράψει κάθε εξαγόμενο αρχείο κειμένου σε έναν φάκελο εξόδου. +5. Εκκινεί τη μέθοδο `recognize()`, η οποία **recognize text from scanned images** μία-μία. + +Αποθηκεύστε το παρακάτω ως `batch_ocr.py` μέσα στον φάκελο του έργου σας: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### How It Works + +- **`BatchOcrEngine`** περιβάλλει το κανονικό `OcrEngine` αλλά προσθέτει ορχήστρωση επι επίπεδο φακέλου, κάτι που είναι ακριβώς αυτό που χρειάζεστε όταν θέλετε να **convert images to text python** μαζικά. +- Η ιδιότητα `input_folder` λέει στο engine πού να ψάξει για τις πηγαίες εικόνες. Σαρώνει αυτόματα τον κατάλογο και προσθέτει σε ουρά κάθε υποστηριζόμενο τύπο αρχείου. +- Η ιδιότητα `output_folder` καθορίζει πού θα τοποθετηθεί κάθε αρχείο `.txt`. Το engine διατηρεί το αρχικό όνομα αρχείου, έτσι το `receipt1.png` γίνεται `receipt1.txt`. +- Η κλήση `recognize()` ενεργοποιεί τον εσωτερικό βρόχο που φορτώνει κάθε εικόνα, εκτελεί OCR και γράφει το αποτέλεσμα. Η μέθοδος μπλοκάρει μέχρι να επεξεργαστούν όλα τα αρχεία, καθιστώντας εύκολο το συνδυασμό με περαιτέρω ενέργειες (π.χ., συμπίεση του φακέλου εξόδου). + +#### Expected Output + +Όταν τρέξετε το script: + +```bash +python batch_ocr.py +``` + +Θα πρέπει να δείτε: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Στο `output_texts` θα βρείτε ένα αρχείο κειμένου για κάθε εικόνα. Ανοίξτε οποιοδήποτε με έναν επεξεργαστή κειμένου και θα δείτε το ακατέργαστο αποτέλεσμα OCR—συνήθως μια κοντινή προσέγγιση του αρχικού τυπωμένου κειμένου. + +## Step 4 – Verify the Results and Handle Errors + +Ακόμη και οι καλύτεροι OCR engines μπορούν να δυσκολευτούν με χαμηλής ανάλυσης σάρωση ή πολύ κεκλιμένες σελίδες. Εδώ είναι ένας γρήγορος τρόπος για να ελέγξετε την έξοδο και να καταγράψετε τυχόν αποτυχίες. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Why add this?** +- Συλλαμβάνει περιπτώσεις όπου το engine παράγει σιωπηλά μια κενή συμβολοσειρά (συνηθισμένο με μη αναγνώσιμες εικόνες). +- Σας δίνει μια λίστα προβληματικών αρχείων ώστε να τα ελέγξετε χειροκίνητα ή να τρέξετε ξανά με διαφορετικές ρυθμίσεις (π.χ., αυξήστε τις επιλογές `OcrEngine.preprocess`). + +### Edge Cases & Tweaks + +| Situation | Suggested Fix | +|-----------|----------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Step 5 – Automate the Whole Workflow (Optional) + +Αν χρειάζεται να τρέχετε αυτή τη μετατροπή καθημερινά, τυλίξτε το script σε ένα απλό shell ή Windows batch αρχείο, και προγραμματίστε το με `cron` (Linux/macOS) ή Task Scheduler (Windows). Εδώ είναι ένα ελάχιστο `run_ocr.sh` για Unix‑like συστήματα: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Κάντε το εκτελέσιμο (`chmod +x run_ocr.sh`) και προσθέστε μια καταχώρηση cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Αυτό τρέχει τη μετατροπή κάθε μέρα στις 2 π.μ. και καταγράφει τυχόν έξοδο για μεταγενέστερη ανασκόπηση. + +--- + +## Conclusion + +Τώρα έχετε μια αποδεδειγμένη, έτοιμη για παραγωγή μέθοδο να **convert images to text python** χρησιμοποιώντας το `BatchOcrEngine` του Aspose.OCR. Το script διαχειρίζεται **bulk image to text conversion**, γράφει κάθε αποτέλεσμα σε ξεχωριστό αρχείο, και περιλαμβάνει βήματα επαλήθευσης ώστε να βεβαιωθείτε ότι πραγματικά **recognize text from scanned images** σωστά. + +Από εδώ μπορείτε: + +- Να πειραματιστείτε με διαφορετικές ρυθμίσεις OCR (πακέτα γλώσσας, deskew, μείωση θορύβου). +- Να διοχετεύσετε το παραγόμενο κείμενο σε έναν δείκτη αναζήτησης όπως το Elasticsearch για άμεση πλήρη αναζήτηση κειμένου. +- Να συνδυάσετε αυτή τη γραμμή παραγωγής με εργαλεία μετατροπής PDF για επεξεργασία σαρωμένων PDF σε μία ενέργεια. + +Έχετε ερωτήσεις ή εντοπίσατε κάποιο πρόβλημα με συγκεκριμένο τύπο αρχείου; Αφήστε ένα σχόλιο παρακάτω και ας το λύσουμε μαζί. Καλό κώδικα, και εύχομαι οι OCR εκτελέσεις σας να είναι γρήγορες και χωρίς σφάλματα! + +## What Should You Learn Next? + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/greek/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..b7e7fb41b --- /dev/null +++ b/ocr/greek/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Δημιουργήστε αντικείμενο άδειας στην Python και ρυθμίστε εύκολα τη διαδρομή + της άδειας. Μάθετε πώς να ρυθμίσετε την άδεια Aspose OCR με σαφή παραδείγματα κώδικα. +draft: false +keywords: +- create license instance +- configure license path +language: el +og_description: Δημιουργήστε ένα αντικείμενο άδειας στην Python και διαμορφώστε τη + διαδρομή της άδειας άμεσα. Ακολουθήστε αυτό το σεμινάριο για να ενεργοποιήσετε το + Aspose OCR με σιγουριά. +og_title: Δημιουργία αντικειμένου άδειας σε Python – Πλήρης οδηγός εγκατάστασης +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Δημιουργία αντικειμένου άδειας σε Python – Οδηγός βήμα‑προς‑βήμα +url: /el/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία αντικειμένου άδειας σε Python – Οδηγός πλήρους ρύθμισης + +Χρειάζεστε **create license instance** για το Aspose OCR σε Python; Βρίσκεστε στο σωστό μέρος. Σε αυτό το tutorial θα σας δείξουμε επίσης πώς να **configure license path** ώστε το SDK να γνωρίζει πού βρίσκεται το αρχείο `.lic` σας. + +Αν έχετε ποτέ κολλήσει μπροστά σε ένα κενό script αναρωτιέται γιατί η μηχανή OCR συνεχίζει να παραπονιέται για μη αδειοδοτημένο προϊόν, δεν είστε μόνοι. Η λύση είναι συνήθως μόνο μερικές γραμμές κώδικα — μόλις ξέρετε ακριβώς πού να τις τοποθετήσετε. Στο τέλος αυτού του οδηγού θα έχετε ένα πλήρως αδειοδοτημένο περιβάλλον Aspose OCR έτοιμο να αναγνωρίζει κείμενο, εικόνες και PDF χωρίς προβλήματα. + +## Τι θα μάθετε + +- Πώς να **create license instance** χρησιμοποιώντας το πακέτο `asposeocr`. +- Ο σωστός τρόπος για **configure license path** τόσο στην ανάπτυξη όσο και στην παραγωγή. +- Συνηθισμένα προβλήματα (απουσία αρχείου, λανθασμένα δικαιώματα) και πώς να τα αποφύγετε. +- Ένα πλήρες, εκτελέσιμο script που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο. + +Δεν απαιτείται προηγούμενη εμπειρία με το Aspose OCR, μόνο μια λειτουργική εγκατάσταση Python 3 και ένα έγκυρο αρχείο άδειας. + +--- + +## Βήμα 1: Εγκατάσταση του πακέτου Aspose OCR για Python + +Πριν μπορέσουμε να **create license instance**, η βιβλιοθήκη πρέπει να είναι παρούσα. Ανοίξτε ένα τερματικό και εκτελέστε: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Αν χρησιμοποιείτε εικονικό περιβάλλον (συνετά προτείνεται), ενεργοποιήστε το πρώτα. Αυτό διατηρεί τις εξαρτήσεις σας οργανωμένες και αποτρέπει συγκρούσεις εκδόσεων. + +## Βήμα 2: Εισαγωγή της κλάσης License + +Τώρα που το SDK είναι διαθέσιμο, η πρώτη γραμμή του script σας πρέπει να εισάγει την κλάση `License`. Αυτό είναι το αντικείμενο που θα χρησιμοποιήσουμε για **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Γιατί να το εισάγετε αμέσως; Επειδή το αντικείμενο `License` πρέπει να δημιουργηθεί **πριν** από οποιεσδήποτε κλήσεις OCR· διαφορετικά το SDK θα πετάξει σφάλμα αδειοδότησης τη στιγμή που θα προσπαθήσετε να επεξεργαστείτε μια εικόνα. + +## Βήμα 3: Δημιουργία αντικειμένου άδειας + +Εδώ είναι η στιγμή που περιμένατε — πραγματικά **create license instance**. Είναι μια μόνο γραμμή, αλλά το περιβάλλον γύρω από αυτήν έχει σημασία. + +```python +# Step 3: Create a License instance +license = License() +``` + +Η μεταβλητή `license` τώρα κρατά ένα αντικείμενο που ελέγχει όλη τη συμπεριφορά αδειοδότησης για τη τρέχουσα διεργασία Python. Σκεφτείτε το ως τον φύλακα που λέει στο Aspose OCR: «Έχω το δικαίωμα να τρέξω». + +## Βήμα 4: Διαμόρφωση διαδρομής άδειας + +Με το αντικείμενο έτοιμο, πρέπει να το κατευθύνουμε προς το αρχείο `.lic`. Εδώ έρχεται η **configure license path** σε δράση. Αντικαταστήστε το placeholder με την απόλυτη διαδρομή προς το αρχείο άδειας σας. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Μερικά σημεία που πρέπει να σημειώσετε: + +1. **Raw strings (`r"…"`)** αποτρέπουν την ερμηνεία των backslashes ως χαρακτήρων διαφυγής στα Windows. +2. Χρησιμοποιήστε **απόλυτη διαδρομή** για να αποφύγετε σύγχυση όταν το script εκτελείται από διαφορετικό φάκελο εργασίας. +3. Αν προτιμάτε σχετική διαδρομή (π.χ., όταν ενσωματώνετε την άδεια στο έργο σας), βεβαιωθείτε ότι η βάση είναι η θέση του script, όχι ο τρέχων φάκελος του κελύφους. + +### Διαχείριση ελλιπών αρχείων + +Αν η διαδρομή είναι λανθασμένη ή το αρχείο δεν είναι αναγνώσιμο, το `set_license` θα πετάξει εξαίρεση. Τυλίξτε την κλήση σε ένα μπλοκ `try/except` για φιλικό μήνυμα σφάλματος: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Αυτό το απόσπασμα **configures license path** με ασφάλεια και σας λέει ακριβώς τι πήγε στραβά — χωρίς μυστηριώδεις στοίβες σφαλμάτων. + +## Βήμα 5: Επαλήθευση ότι η άδεια είναι ενεργή + +Μια γρήγορη δοκιμή αποφεύγει ώρες εντοπισμού σφαλμάτων αργότερα. Αφού καλέσετε το `set_license`, δοκιμάστε μια απλή λειτουργία OCR. Αν η άδεια είναι έγκυρη, το SDK θα επεξεργαστεί την εικόνα χωρίς να πετάξει σφάλμα αδειοδότησης. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Αν δείτε το αναγνωρισμένο κείμενο να εκτυπώνεται, συγχαρητήρια — έχετε επιτυχώς **create license instance** και **configure license path**. Αν λάβετε εξαίρεση αδειοδότησης, ελέγξτε ξανά τη διαδρομή και τα δικαιώματα του αρχείου. + +## Edge Cases & Best Practices + +| Situation | What to Do | +|-----------|------------| +| **Το αρχείο άδειας βρίσκεται σε κοινόχρηστο δίκτυο** | Χαρτογραφήστε το share σε γράμμα μονάδας ή χρησιμοποιήστε UNC διαδρομή (`\\server\share\license.lic`). Βεβαιωθείτε ότι η διεργασία Python έχει δικαίωμα ανάγνωσης. | +| **Εκτέλεση μέσα σε Docker container** | Αντιγράψτε το `.lic` αρχείο στο image και αναφερθείτε σε αυτό με απόλυτη διαδρομή όπως `/app/license/Aspose.OCR.Java.lic`. | +| **Πολλαπλοί διερμηνείς Python** (π.χ., περιβάλλοντα conda) | Εγκαταστήστε το αρχείο άδειας μία φορά ανά περιβάλλον ή κρατήστε κεντρική τοποθεσία και κατευθύνετε κάθε διερμηνέα σε αυτήν. | +| **Απουσία αρχείου άδειας κατά την εκτέλεση** | Επιστρέψτε με χάρη σε λειτουργία δοκιμής (αν υποστηρίζεται) ή τερματίστε με σαφές μήνυμα καταγραφής. | + +### Common Pitfalls + +- **Χρήση διαγώνιων καθέτων σε Windows** – Η Python τα αποδέχεται, αλλά κάποιες παλαιότερες εκδόσεις του SDK μπορεί να τα ερμηνεύσουν λανθασμένα. Μείνετε σε raw strings ή διπλά backslashes. +- **Ξέχασα να εισάγω `License`** – Το script θα καταρρεύσει με `NameError`. Πάντα εισάγετε πριν δημιουργήσετε το αντικείμενο. +- **Κλήση `set_license` μετά από μεθόδους OCR** – Το SDK ελέγχει την άδεια στην πρώτη χρήση, οπότε ορίστε τη διαδρομή **πρώτα**. + +## Full Working Example + +Παρακάτω υπάρχει ένα πλήρες script που ενώνει όλα τα παραπάνω. Αποθηκεύστε το ως `ocr_setup.py` και τρέξτε το από τη γραμμή εντολών. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Αναμενόμενη έξοδος** (υποθέτοντας έγκυρη εικόνα): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Αν το αρχείο άδειας δεν βρεθεί, θα δείτε ένα σαφές μήνυμα σφάλματος αντί για μια ασαφή εξαίρεση “License not found”. + +--- + +## Conclusion + +Τώρα ξέρετε ακριβώς πώς να **create license instance** σε Python και **configure license path** για το Aspose OCR SDK. Τα βήματα είναι απλά: εγκαταστήστε το πακέτο, εισάγετε το `License`, δημιουργήστε το αντικείμενο, κατευθύνετε το προς το `.lic` αρχείο και επαληθεύστε με μια μικρή δοκιμή OCR. + +Με αυτή τη γνώση μπορείτε να ενσωματώσετε δυνατότητες OCR σε web services, desktop εφαρμογές ή αυτοματοποιημένες pipelines χωρίς προβλήματα αδειοδότησης. Στη συνέχεια, εξερευνήστε προχωρημένες ρυθμίσεις OCR — πακέτα γλωσσών, προεπεξεργασία εικόνας ή επεξεργασία παρτίδας — τα οποία βασίζονται όλα στο σταθερό θεμέλιο που μόλις δημιουργήσατε. + +Έχετε ερωτήσεις σχετικά με την ανάπτυξη, το Docker ή τη διαχείριση πολλαπλών αδειών; Αφήστε ένα σχόλιο, και καλή προγραμματιστική! + +## What Should You Learn Next? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/greek/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..5812742ec --- /dev/null +++ b/ocr/greek/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Δημιουργήστε αναζητήσιμο PDF από σαρωμένες εικόνες χρησιμοποιώντας Python + OCR. Μάθετε πώς να μετατρέψετε PDF από σαρωμένες εικόνες, να μετατρέψετε TIFF σε + PDF και να προσθέσετε στρώση κειμένου OCR σε λίγα λεπτά. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: el +og_description: Δημιουργήστε άμεσα PDF με δυνατότητα αναζήτησης. Αυτός ο οδηγός δείχνει + πώς να εκτελέσετε OCR, να μετατρέψετε PDF σαρωμένης εικόνας και να προσθέσετε στρώση + κειμένου OCR χρησιμοποιώντας ένα μόνο script Python. +og_title: Δημιουργία Αναζητήσιμου PDF με Python – Πλήρης Οδηγός +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Δημιουργία Αναζητήσιμου PDF με Python – Οδηγός Βήμα‑βήμα +url: /el/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Αναζητήσιμου PDF με Python – Οδηγός Βήμα‑Βήμα + +Έχετε αναρωτηθεί ποτέ πώς να **δημιουργήσετε αναζητήσιμο PDF** από μια σαρωμένη σελίδα χωρίς να χρειάζεται να χειρίζεστε δεκάδες εργαλεία; Δεν είστε μόνοι. Σε πολλές εργασιακές ροές, ένα σαρωμένο TIFF ή JPEG αποθηκεύεται σε κοινόχρηστο δίσκο, και το επόμενο άτομο πρέπει να αντιγράψει‑επικολλήσει το κείμενο χειροκίνητα—πρόσφορο, επιρρεπές σε σφάλματα και χρονοβόρο. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα μια καθαρή, προγραμματιστική λύση που σας επιτρέπει να **μετατρέψετε σαρωμένο PDF εικόνας**, **μετατρέψετε TIFF σε PDF**, και **προσθέσετε στρώση κειμένου OCR** σε μία ενέργεια. Στο τέλος θα έχετε ένα έτοιμο‑για‑χρήση script που εκτελεί OCR, ενσωματώνει το κρυφό κείμενο, και παράγει ένα αναζητήσιμο PDF που μπορείτε να ευρετήσετε, να αναζητήσετε ή να μοιραστείτε με σιγουριά. + +## Τι Θα Χρειαστεί + +- Python 3.9+ (οποιαδήποτε πρόσφατη έκδοση λειτουργεί) +- `aspose-ocr` and `aspose-pdf` packages (εγκαθίστανται μέσω `pip install aspose-ocr aspose-pdf`) +- Ένα αρχείο σαρωμένης εικόνας (`.tif`, `.png`, `.jpg`, ή ακόμη και μια σελίδα PDF που είναι μόνο εικόνα) +- Μέτρια ποσότητα RAM (η μηχανή OCR είναι ελαφριά· ακόμη και ένα laptop το διαχειρίζεται) + +> **Συμβουλή:** Αν χρησιμοποιείτε Windows, ο πιο εύκολος τρόπος για να αποκτήσετε τα πακέτα είναι να εκτελέσετε την εντολή σε ένα ανυψωμένο παράθυρο PowerShell. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Τώρα που οι προαπαιτήσεις έχουν καλυφθεί, ας βουτήξουμε στον κώδικα. + +## Βήμα 1: Δημιουργία Παραδείγματος Μηχανής OCR – *create searchable pdf* + +Το πρώτο που κάνουμε είναι να εκκινήσουμε τη μηχανή OCR. Σκεφτείτε τη ως τον εγκέφαλο που θα διαβάσει κάθε pixel και θα το μετατρέψει σε χαρακτήρες. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Γιατί είναι σημαντικό:** Η αρχικοποίηση της μηχανής μόνο μία φορά διατηρεί τη χρήση μνήμης χαμηλή. Αν καλούσατε `OcrEngine()` μέσα σε βρόχο για κάθε σελίδα, θα εξαντλούσατε γρήγορα τους πόρους. + +## Βήμα 2: Φόρτωση Σαρωμένης Εικόνας – *convert tiff to pdf* & *convert scanned image pdf* + +Στη συνέχεια, δείξτε τη μηχανή στο αρχείο που θέλετε να επεξεργαστείτε. Το API δέχεται οποιαδήποτε raster εικόνα, έτσι ένα TIFF λειτουργεί εξίσου καλά με ένα JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Αν έχετε ένα PDF που περιέχει μόνο μια σαρωμένη εικόνα, μπορείτε ακόμη να χρησιμοποιήσετε το `load_image` επειδή το Aspose θα εξάγει αυτόματα την πρώτη σελίδα. + +## Βήμα 3: Προετοιμασία Επιλογών Αποθήκευσης PDF – *add OCR text layer* + +Εδώ διαμορφώνουμε πώς θα πρέπει να φαίνεται το τελικό PDF. Η κρίσιμη σημαία είναι `create_searchable_pdf`; ορίζοντάς την σε `True` λέμε στη βιβλιοθήκη να ενσωματώσει μια αόρατη στρώση κειμένου που αντικατοπτρίζει το οπτικό περιεχόμενο. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Τι κάνει η στρώση κειμένου:** Όταν ανοίξετε το παραγόμενο αρχείο στο Adobe Reader και προσπαθήσετε να επιλέξετε κείμενο, θα δείτε τους κρυφούς χαρακτήρες. Οι μηχανές αναζήτησης μπορούν επίσης να τα ευρετηριάσουν—τέλειο για συμμόρφωση ή αρχειοθέτηση. + +## Βήμα 4: Εκτέλεση OCR και Αποθήκευση – *how to run OCR* σε μία κλήση + +Τώρα συμβαίνει η μαγεία. Μία κλήση μεθόδου εκτελεί τη μηχανή αναγνώρισης και γράφει το αναζητήσιμο PDF στο δίσκο. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Η μέθοδος `recognize` επιστρέφει ένα αντικείμενο κατάστασης που μπορείτε να ελέγξετε για σφάλματα, αλλά για τις περισσότερες απλές περιπτώσεις η απλή κλήση παραπάνω είναι επαρκής. + +### Αναμενόμενο Αποτέλεσμα + +Η εκτέλεση του script εμφανίζει: + +``` +PDF saved as searchable PDF. +``` + +Αν ανοίξετε το `scanned_page_searchable.pdf` θα παρατηρήσετε ότι μπορείτε να επιλέξετε κείμενο, να το αντιγράψετε‑επικολλήσετε, και ακόμη να εκτελέσετε αναζήτηση `Ctrl+F`. Αυτό είναι το χαρακτηριστικό μιας ροής εργασίας **create searchable pdf**. + +## Πλήρες Λειτουργικό Script + +Παρακάτω είναι το πλήρες, έτοιμο‑για‑εκτέλεση script. Απλώς αντικαταστήστε τις διαδρομές placeholder με τις πραγματικές τοποθεσίες των αρχείων σας. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Αποθηκεύστε το ως `create_searchable_pdf.py` και εκτελέστε: + +```bash +python create_searchable_pdf.py +``` + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### 1️⃣ Μπορώ να επεξεργαστώ PDF πολλαπλών σελίδων; + +Ναι. Χρησιμοποιήστε `ocr_engine.load_image("file.pdf")` και στη συνέχεια κάντε βρόχο σε κάθε σελίδα με `ocr_engine.recognize(pdf_save_options, page_number)`. Η βιβλιοθήκη θα δημιουργήσει αυτόματα ένα PDF πολλαπλών σελίδων αναζητήσιμο. + +### 2️⃣ Τι γίνεται αν το αρχείο προέλευσης είναι TIFF υψηλής ανάλυσης (300 dpi+)? + +Υψηλότερο DPI προσφέρει καλύτερη ακρίβεια OCR αλλά και μεγαλύτερη χρήση μνήμης. Αν αντιμετωπίσετε `MemoryError`, μειώστε πρώτα την ανάλυση της εικόνας: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Πώς αλλάζω τη γλώσσα του OCR; + +Ορίστε την ιδιότητα `language` στη μηχανή πριν φορτώσετε την εικόνα: + +```python +ocr_engine.language = "fra" # French +``` + +Μια πλήρης λίστα των υποστηριζόμενων κωδικών γλώσσας βρίσκεται στην τεκμηρίωση του Aspose. + +### 4️⃣ Τι κάνω αν χρειάζεται να διατηρήσω την αρχική ποιότητα εικόνας; + +Η κλάση `PdfSaveOptions` έχει ιδιότητα `compression`. Ορίστε την σε `PdfCompression.None` για να διατηρήσετε τα raster δεδομένα ακριβώς όπως ήταν. + +```python +pdf_save_options.compression = "None" +``` + +## Συμβουλές για Παραγωγικές Αναπτύξεις + +- **Batch processing:** Τυλίξτε τη βασική λογική σε μια συνάρτηση που δέχεται μια λίστα διαδρομών αρχείων. Καταγράψτε κάθε επιτυχία/αποτυχία σε CSV για γραμμές ελέγχου. +- **Parallelism:** Χρησιμοποιήστε `concurrent.futures.ThreadPoolExecutor` για να εκτελέσετε OCR σε πολλούς πυρήνες. Απλώς θυμηθείτε ότι κάθε νήμα χρειάζεται το δικό του παράδειγμα `OcrEngine`. +- **Security:** Αν χειρίζεστε ευαίσθητα έγγραφα, εκτελέστε το script σε περιβάλλον sandbox και διαγράψτε τα προσωρινά αρχεία αμέσως μετά την επεξεργασία. + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **δημιουργήσετε αναζητήσιμα PDF** αρχεία από σαρωμένες εικόνες χρησιμοποιώντας ένα σύντομο script Python. Αρχικοποιώντας μια μηχανή OCR, φορτώνοντας ένα TIFF (ή οποιοδήποτε raster), διαμορφώνοντας το `PdfSaveOptions` για **add OCR text layer**, και τελικά καλώντας το `recognize`, ολόκληρη η αλυσίδα **convert scanned image pdf** και **convert TIFF to PDF** γίνεται μια ενιαία, επαναλαμβανόμενη εντολή. + +Επόμενα βήματα; Δοκιμάστε να συνδέσετε αυτό το script με έναν παρατηρητή αρχείων ώστε κάθε νέα σάρωση που τοποθετείται σε φάκελο να γίνεται αυτόματα αναζητήσιμη. Ή πειραματιστείτε με διαφορετικές γλώσσες OCR για να υποστηρίξετε πολύγλωσσικά αρχεία. Ο ουρανός είναι το όριο όταν συνδυάζετε OCR με δημιουργία PDF. + +Έχετε περισσότερες ερωτήσεις σχετικά με το **how to run OCR** σε άλλες γλώσσες ή πλαίσια; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +![Διάγραμμα που δείχνει τη ροή από σαρωμένη εικόνα → μηχανή OCR → αναζητήσιμο PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## Τι Θα Πρέπει Να Μάθετε Στη Σειρά; + +- [Πώς να κάνετε OCR PDF σε .NET με Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Μετατροπή Εικόνων σε PDF C# – Αποθήκευση Αποτελέσματος OCR Πολλαπλών Σελίδων](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Πώς να κάνετε OCR Κειμένου Εικόνας με Γλώσσα Χρησιμοποιώντας Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/greek/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..955bce739 --- /dev/null +++ b/ocr/greek/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Βελτιώστε την ακρίβεια του OCR με Python, προεπεξεργάζοντας εικόνες για + OCR. Μάθετε πώς να εξάγετε κείμενο από αρχεία εικόνας, να αναγνωρίζετε κείμενο από + PNG και να ενισχύετε τα αποτελέσματα. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: el +og_description: Βελτιώστε την ακρίβεια OCR στην Python εφαρμόζοντας προεπεξεργασία + εικόνας για κείμενο. Ακολουθήστε αυτόν τον οδηγό για να εξάγετε κείμενο από αρχεία + εικόνας και να αναγνωρίζετε κείμενο από PNG χωρίς κόπο. +og_title: Βελτιώστε την ακρίβεια OCR στην Python – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Βελτιώστε την ακρίβεια του OCR στην Python – Πλήρης οδηγός βήμα‑βήμα +url: /el/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Βελτιώστε την Ακρίβεια OCR σε Python – Πλήρης Οδηγός Βήμα‑βήμα + +Προσπαθήσατε ποτέ να **βελτιώσετε την ακρίβεια OCR** και να λάβετε ακατάστατο αποτέλεσμα; Δεν είστε οι μόνοι. Οι περισσότεροι προγραμματιστές συναντούν προβλήματα όταν η ακατέργαστη εικόνα είναι θορυβώδης, λοξή ή απλώς χαμηλής αντίθεσης. Τα καλά νέα; Μερικές τεχνικές προεπεξεργασίας μπορούν να μετατρέψουν ένα θολό στιγμιότυπο σε καθαρό, μηχανικά αναγνώσιμο κείμενο. + +Σε αυτό το tutorial θα περάσουμε από ένα πραγματικό παράδειγμα που **προετοιμάζει μια εικόνα για OCR**, εκτελεί τη μηχανή αναγνώρισης και τελικά **εξάγει κείμενο από αρχεία εικόνας**—συγκεκριμένα PNG. Στο τέλος θα ξέρετε ακριβώς πώς να **αναγνωρίσετε κείμενο από PNG** με υψηλότερο ποσοστό επιτυχίας και θα έχετε ένα επαναχρησιμοποιήσιμο απόσπασμα κώδικα που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο. + +## Τι Θα Μάθετε + +- Γιατί η προεπεξεργασία εικόνας είναι σημαντική για τις μηχανές OCR +- Ποιες λειτουργίες προεπεξεργασίας (denoise, deskew) προσφέρουν τη μεγαλύτερη βελτίωση +- Πώς να διαμορφώσετε μια παρουσία `OcrEngine` σε Python +- Το πλήρες, εκτελέσιμο script που **εξάγει κείμενο από αρχεία εικόνας** +- Συμβουλές για την αντιμετώπιση ειδικών περιπτώσεων όπως περιστρεφόμενες σαρώσεις ή εικόνες χαμηλής ανάλυσης + +Δεν απαιτούνται εξωτερικές βιβλιοθήκες πέρα από το OCR SDK, αλλά θα χρειαστείτε Python 3.8+ και μια εικόνα PNG που θέλετε να διαβάσετε. + +--- + +![Διάγραμμα που δείχνει τα βήματα για βελτίωση της ακρίβειας OCR σε Python](image.png "Ροή εργασίας βελτίωσης ακρίβειας OCR") + +*Alt text: διάγραμμα ροής βελτίωσης ακρίβειας OCR που απεικονίζει τα βήματα προεπεξεργασίας και αναγνώρισης.* + +## Προαπαιτούμενα + +- Python 3.8 ή νεότερη έκδοση εγκατεστημένη +- Πρόσβαση στο OCR SDK που παρέχει `OcrEngine`, `OcrEngineSettings` και `ImagePreprocessMode` (ο κώδικας παρακάτω χρησιμοποιεί μια γενική API· αντικαταστήστε το με τις κλάσεις του προμηθευτή σας αν χρειάζεται) +- Μια εικόνα PNG (`input.png`) τοποθετημένη σε φάκελο που μπορείτε να αναφέρετε + +Αν χρησιμοποιείτε εικονικό περιβάλλον, ενεργοποιήστε το τώρα—δεν χρειάζεται κάτι περίπλοκο, απλώς `python -m venv venv && source venv/bin/activate`. + +--- + +## Βήμα 1: Δημιουργία της Παρουσίας του OCR Engine – Έναρξη Βελτίωσης της Ακρίβειας OCR + +Το πρώτο που χρειάζεστε είναι ένα αντικείμενο OCR engine. Σκεφτείτε το ως τον εγκέφαλο που θα διαβάσει τα pixel και θα εκτυπώσει χαρακτήρες. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Γιατί είναι σημαντικό: χωρίς engine δεν μπορείτε να εφαρμόσετε προεπεξεργασία, και η ακατέργαστη εικόνα θα τροφοδοτηθεί απευθείας στον αναγνώστη—συνήθως η χειρότερη περίπτωση για την ακρίβεια. + +--- + +## Βήμα 2: Φόρτωση του Στόχου PNG – Προετοιμασία για Αναγνώριση Κειμένου από PNG + +Τώρα λέμε στο engine ποιο αρχείο θα επεξεργαστεί. Το PNG είναι lossless, κάτι που μας δίνει μικρό πλεονέκτημα έναντι του JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Αν η εικόνα βρίσκεται κάπου αλλού, απλώς προσαρμόστε τη διαδρομή. Το engine δέχεται οποιαδήποτε υποστηριζόμενη μορφή, αλλά το PNG συχνά διατηρεί τις λεπτές λεπτομέρειες που χρειάζονται για καθαρά άκρα χαρακτήρων. + +--- + +## Βήμα 3: Διαμόρφωση Προεπεξεργασίας – Preprocess Image for OCR + +Εδώ συμβαίνει η μαγεία. Δημιουργούμε ένα αντικείμενο ρυθμίσεων, ενεργοποιούμε το denoise για να αφαιρέσουμε τις κηλίδες και ενεργοποιούμε το deskew ώστε το κεκλιμένο κείμενο να ευθυγραμμιστεί αυτόματα. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Γιατί Denoise + Deskew; + +- **Denoise**: Ο τυχαίος θόρυβος pixel μπερδεύει τους αλγόριθμους αντιστοίχισης προτύπων. Η αφαίρεσή του καθαρίζει τα γράμματα. +- **Deskew**: Ακόμη και μια κλίση 2 μπορεί να μειώσει δραματικά τις βαθμολογίες εμπιστοσύνης. Το deskew ευθυγραμμίζει τη βάση γραμμής, επιτρέποντας στον αναγνώστη να ταιριάξει τις γραμματοσειρές πιο αξιόπιστα. + +Μπορείτε να πειραματιστείτε με πρόσθετες σημαίες (π.χ., `ImagePreprocessMode.CONTRAST_ENHANCE`) αν οι εικόνες σας είναι ιδιαίτερα σκοτεινές. Η τεκμηρίωση του SDK συνήθως παραθέτει όλες τις διαθέσιμες λειτουργίες. + +--- + +## Βήμα 4: Εφαρμογή των Ρυθμίσεων στο Engine – Σύνδεση Προεπεξεργασίας με OCR + +Αναθέστε το αντικείμενο ρυθμίσεων στο engine ώστε η επόμενη εκτέλεση αναγνώρισης να χρησιμοποιεί τις μετασχηματισμούς που ορίσαμε. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Αν παραλείψετε αυτό το βήμα, το engine θα επιστρέψει στις προεπιλογές του (συχνά «χωρίς προεπεξεργασία») και θα δείτε **χαμηλότερη ακρίβεια OCR**. + +--- + +## Βήμα 5: Εκτέλεση της Διαδικασίας Αναγνώρισης – Extract Text from Image + +Με όλα συνδεδεμένα, ζητάμε τελικά από το engine να κάνει τη δουλειά του. Η κλήση είναι συγχρονική, επιστρέφοντας ένα αντικείμενο αποτελέσματος που περιέχει το αναγνωρισμένο κείμενο. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Πίσω από τις σκηνές το engine: + +1. Φορτώνει το PNG στη μνήμη +2. Εφαρμόζει denoise και deskew βάσει των ρυθμίσεών μας +3. Εκτελεί το νευρωνικό δίκτυο ή τον κλασικό αλγόριθμο αντιστοίχισης προτύπων +4. Συσκευάζει το αποτέλεσμα στο `recognition_result` + +--- + +## Βήμα 6: Εμφάνιση του Αναγνωρισμένου Κειμένου – Επαλήθευση της Βελτίωσης + +Ας τυπώσουμε το εξαγόμενο κείμενο. Σε μια πραγματική εφαρμογή μπορεί να το γράψετε σε αρχείο, βάση δεδομένων ή να το περάσετε σε άλλη υπηρεσία. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Αναμενόμενο Αποτέλεσμα + +Αν η εικόνα περιέχει τη φράση «Hello, OCR World!», θα πρέπει να δείτε: + +``` +Hello, OCR World! +``` + +Παρατηρήστε πόσο καθαρό είναι το κείμενο—χωρίς τυχαία σύμβολα ή σπασμένους χαρακτήρες. Αυτό είναι το αποτέλεσμα της σωστής **προεπεξεργασίας εικόνας για κείμενο**. + +--- + +## Pro Tips & Edge Cases + +| Κατάσταση | Τι να Ρυθμίσετε | Γιατί | +|-----------|----------------|------| +| Πολύ χαμηλή ανάλυση PNG (≤ 72 dpi) | Προσθέστε `ImagePreprocessMode.SUPER_RESOLUTION` αν είναι διαθέσιμο | Η ανύψωση μπορεί να δώσει στον αναγνώστη περισσότερα pixel για επεξεργασία | +| Το κείμενο είναι περιστραμμένο > 5° | Αυξήστε την ανοχή του deskew ή περιστρέψτε χειροκίνητα με `Pillow` πριν το δώσετε στο engine | Οι ακραίες γωνίες μερικές φορές παρακάμπτουν το αυτόματο deskew | +| Έντονα μοτίβα φόντου | Ενεργοποιήστε `ImagePreprocessMode.BACKGROUND_REMOVAL` | Αφαιρεί το μη‑κείμενο που θα μπορούσε να διαβαστεί λανθασμένα | +| Έγγραφο πολλαπλών γλωσσών | Ορίστε `ocr_engine.language = "eng+spa"` (ή παρόμοιο) | Το engine επιλέγει το σωστό σύνολο χαρακτήρων, βελτιώνοντας τη συνολική ακρίβεια | + +Θυμηθείτε, **βελτιώστε την ακρίβεια OCR** δεν είναι μια λύση «ένα μέγεθος για όλους»· ίσως χρειαστεί να επαναλάβετε τις σημαίες προεπεξεργασίας για το συγκεκριμένο σας σύνολο δεδομένων. + +--- + +## Πλήρες Script – Έτοιμο για Αντιγραφή & Επικόλληση + +Παρακάτω βρίσκεται το πλήρες, εκτελέσιμο παράδειγμα που ενσωματώνει κάθε βήμα που συζητήσαμε. Αποθηκεύστε το ως `improve_ocr_accuracy.py` και τρέξτε το με `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Τρέξτε το, παρακολουθήστε την κονσόλα, και θα δείτε αμέσως το αποτέλεσμα **extract text from image**. Αν το αποτέλεσμα φαίνεται λανθασμένο, προσαρμόστε τις σημαίες `preprocess_mode` όπως περιγράφεται στον πίνακα «Pro Tips». + +--- + +## Συμπέρασμα + +Μόλις περάσαμε από μια πρακτική συνταγή για **βελτίωση της ακρίβειας OCR** χρησιμοποιώντας Python. Δημιουργώντας ένα `OcrEngine`, φορτώνοντας ένα PNG, **προετοιμάζοντας την εικόνα για OCR**, και τελικά **αναγνωρίζοντας κείμενο από PNG**, μπορείτε αξιόπιστα **να εξάγετε κείμενο από αρχεία εικόνας** ακόμη και όταν η πηγή δεν είναι τέλεια. + +Τι θα κάνετε στη συνέχεια; Δοκιμάστε να επεξεργαστείτε μια δέσμη εικόνων μέσα σε βρόχο, αποθηκεύστε κάθε αποτέλεσμα σε CSV, ή πειραματιστείτε με πρόσθετες λειτουργίες προεπεξεργασίας όπως η ενίσχυση αντίθεσης. Το ίδιο μοτίβο λειτουργεί για PDF, σαρωμένα αποδείξεις ή χειρόγραφες σημειώσεις—απλώς αλλάξτε την είσοδο και προσαρμόστε τις ρυθμίσεις. + +Έχετε ερωτήσεις για συγκεκριμένο τύπο εικόνας ή θέλετε να μάθετε πώς να το ενσωματώσετε σε μια web υπηρεσία; Αφήστε ένα σχόλιο και θα εξερευνήσουμε αυτά τα σενάρια μαζί. Καλό κώδικα, και εύχομαι τα αποτελέσματα OCR σας να είναι πάντα kristall‑καθαρά! + +## Τι Να Μάθετε Στη Σύντομη Μελλοντική + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/greek/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..3f6118da7 --- /dev/null +++ b/ocr/greek/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Μάθετε πώς να χρησιμοποιείτε την περιοχή ενδιαφέροντος OCR για να φορτώνετε + εικόνα για OCR και να εξάγετε κείμενο από το ορθογώνιο, ιδανικό για την αναγνώριση + του ποσού σε τιμολόγιο. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: el +og_description: Κατακτήστε την περιοχή ενδιαφέροντος OCR για τη φόρτωση εικόνας, εξαγωγή + κειμένου από το ορθογώνιο και αναγνώριση κειμένου από τιμολόγιο σε ένα ενιαίο σεμινάριο. +og_title: OCR Περιοχή Ενδιαφέροντος – Οδηγός Python βήμα‑βήμα +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Περιοχή Ενδιαφέροντος – Εξαγωγή Κειμένου από Ορθογώνιο σε Python +url: /el/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Περιοχή Ενδιαφέροντος – Εξαγωγή Κειμένου από Ορθογώνιο σε Python + +Έχετε αναρωτηθεί ποτέ πώς να **ocr region of interest** ένα συγκεκριμένο τμήμα μιας σαρωμένης απόδειξης χωρίς να τροφοδοτείτε ολόκληρη τη σελίδα στη μηχανή; Δεν είστε ο πρώτος που κοιτάζει ένα θολό απόδειξη και σκέφτεται, “Πώς μπορώ να εξάγω το ποσό που βρίσκεται κάπου κάτω δεξιά;” Τα καλά νέα είναι ότι μπορείτε να πείτε στη βιβλιοθήκη OCR ακριβώς πού να κοιτάξει, βελτιώνοντας δραματικά τόσο την ταχύτητα όσο και την ακρίβεια. + +Σε αυτόν τον οδηγό θα περάσουμε από ένα πλήρες, εκτελέσιμο παράδειγμα που δείχνει πώς να **load image for OCR**, να ορίσετε μια **region of interest**, και στη συνέχεια να **extract text from rectangle** για να **recognize text from invoice** και να απαντήσετε στην κλασική ερώτηση “πώς να εξάγετε το ποσό”. Χωρίς ασαφείς αναφορές—μόνο συγκεκριμένος κώδικας, σαφείς εξηγήσεις, και μερικές συμβουλές που θα θέλατε να γνωρίζατε νωρίτερα. + +--- + +## Τι Θα Δημιουργήσετε + +Στο τέλος αυτού του tutorial θα έχετε ένα μικρό script Python που: + +1. Φορτώνει μια εικόνα απόδειξης από το δίσκο. +2. Σημαδεύει ένα ορθογώνιο ROI όπου βρίσκεται το συνολικό ποσό. +3. Εκτελεί OCR μόνο μέσα σε αυτό το ROI. +4. Εκτυπώνει το καθαρισμένο string του ποσού. + +Όλα αυτά λειτουργούν με οποιαδήποτε βιβλιοθήκη OCR που υποστηρίζει ROI—εδώ θα χρησιμοποιήσουμε ένα φανταστικό αλλά αντιπροσωπευτικό πακέτο `SimpleOCR` που μιμείται δημοφιλή εργαλεία όπως το Tesseract ή το EasyOCR. Μπορείτε να το αντικαταστήσετε ελεύθερα· οι έννοιες παραμένουν ίδιες. + +--- + +## Προαπαιτούμενα + +- Python 3.8+ εγκατεστημένο (`python --version` πρέπει να δείχνει ≥3.8). +- Ένα πακέτο OCR που μπορεί να εγκατασταθεί μέσω pip (π.χ., `pip install simpleocr`). +- Μια εικόνα απόδειξης (PNG ή JPEG) τοποθετημένη σε φάκελο που μπορείτε να αναφέρετε. +- Βασική εξοικείωση με συναρτήσεις και κλάσεις Python (τίποτα περίπλοκο). + +Αν έχετε ήδη όλα αυτά, τέλεια—ας βουτήξουμε. Αν όχι, πάρτε πρώτα την εικόνα· τα υπόλοιπα βήματα είναι ανεξάρτητα από το περιεχόμενο του αρχείου. + +--- + +## Βήμα 1: Φόρτωση Εικόνας για OCR + +Το πρώτο πράγμα που χρειάζεται οποιαδήποτε ροή εργασίας OCR είναι ένα bitmap για ανάγνωση. Οι περισσότερες βιβλιοθήκες εκθέτουν μια απλή μέθοδο `load_image` που δέχεται διαδρομή αρχείου. Να πώς το κάνετε με τη μηχανή `SimpleOCR` μας: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Χρησιμοποιήστε απόλυτες διαδρομές ή `os.path.join` για να αποφύγετε εκπλήξεις τύπου “file not found” όταν τρέχετε το script από διαφορετικό φάκελο εργασίας. + +--- + +## Βήμα 2: Ορισμός Περιοχής Ενδιαφέροντος OCR + +Αντί να αφήσουμε τη μηχανή να σαρώσει ολόκληρη τη σελίδα, της λέμε *ακριβώς* πού βρίσκεται το ποσό. Αυτό είναι το βήμα **ocr region of interest** και είναι το κλειδί για αξιόπιστη εξαγωγή, ειδικά όταν το έγγραφο περιέχει θορυβώδεις κεφαλίδες ή υποσέλιδα. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Γιατί αυτά τα νούμερα; `x` και `y` είναι μετατοπίσεις εικονοστοιχείων από την πάνω‑αριστερή γωνία, ενώ `width` και `height` περιγράφουν το μέγεθος του κουτιού. Αν δεν είστε σίγουροι, ανοίξτε την εικόνα σε οποιονδήποτε επεξεργαστή, ενεργοποιήστε το χάρακα και σημειώστε τις συντεταγμένες. Πολλά IDE επιτρέπουν ακόμη να εκτυπώνετε τη θέση του κέρσορα ενώ αιωρείται. + +--- + +## Βήμα 3: Εξαγωγή Κειμένου από Ορθογώνιο + +Τώρα που το ROI είναι ορισμένο, ζητάμε από τη μηχανή να **recognize text from invoice** αλλά περιορισμένα στο ορθογώνιο που μόλις προσθέσαμε. Η κλήση επιστρέφει ένα αντικείμενο αποτελέσματος που συνήθως περιέχει το ακατέργαστο string, βαθμολογίες εμπιστοσύνης, και μερικές φορές τα πλαίσια περιγράμματος. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Στο παρασκήνιο, η `recognize()` διατρέχει κάθε ROI, κόβει το αντίστοιχο τμήμα, τρέχει το μοντέλο OCR, και ενώνει τα αποτελέσματα. Γι' αυτό ο ορισμός μιας στενής **extract text from rectangle** περιοχής μπορεί να μειώσει δευτερόλεπτα από τον χρόνο επεξεργασίας για παρτίδες εργασιών. + +--- + +## Βήμα 4: Πώς να Εξάγετε το Ποσό – Καθαρισμός της Εξόδου + +Το OCR δεν είναι τέλειο· συχνά παίρνετε περιττά κενά, αλλαγές γραμμής, ή ακόμη και λανθασμένους χαρακτήρες (π.χ., “S” αντί για “5”). Ένα γρήγορο `strip()` και μια μικρή regex συνήθως λύνουν το πρόβλημα για χρηματικές τιμές. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Γιατί είναι σημαντικό:** Αν σκοπεύετε να στείλετε το ποσό σε βάση δεδομένων ή σε gateway πληρωμών, χρειάζεστε προβλέψιμη μορφή. Η αφαίρεση κενών και η φιλτράρισμα μη‑αριθμητικών χαρακτήρων αποτρέπει σφάλματα σε επόμενα βήματα. + +--- + +## Βήμα 5: Αναγνώριση Κειμένου από Απόδειξη – Πλήρες Script + +Συνδυάζοντας όλα τα παραπάνω, εδώ είναι το πλήρες, έτοιμο‑για‑εκτέλεση script. Αποθηκεύστε το ως `extract_amount.py` και τρέξτε `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Αναμενόμενη Έξοδος + +``` +Amount: 1,245.67 +``` + +Αν το ROI είναι λανθασμένα ευθυγραμμισμένο, μπορεί να δείτε κάτι σαν `Amount: 1245.6S`—σημειώστε το περιττό “S”. Ρυθμίστε τις συντεταγμένες του ορθογωνίου και ξανατρέξτε μέχρι η έξοδος να φαίνεται καθαρή. + +--- + +## Κοινά Προβλήματα & Ακραίες Περιπτώσεις + +| Πρόβλημα | Γιατί Συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **ROI πολύ μικρό** | Το κείμενο του ποσού περικόπτεται, οδηγώντας σε μερική αναγνώριση. | Αυξήστε το `width`/`height` κατά ~10‑20 % και δοκιμάστε ξανά. | +| **Λανθασμένο DPI** | Σαρώσεις χαμηλής ανάλυσης (≤150 dpi) μειώνουν την ακρίβεια του OCR. | Επαναδειγματοληπτήστε την εικόνα στα 300 dpi πριν τη φόρτωση, ή ζητήστε από το scanner υψηλότερο DPI. | +| **Πολλαπλά νομίσματα** | Η regex παίρνει την πρώτη αριθμητική ομάδα, η οποία μπορεί να είναι αριθμός απόδειξης. | Βελτιώστε τη regex ώστε να ψάχνει για σύμβολα νομισμάτων (`$`, `€`, `£`) πριν από τα ψηφία. | +| **Περιστροφές στις αποδείξεις** | Οι μηχανές OCR υποθέτουν ευθεία γραφή· οι περιστρεφόμενες σελίδες διακόπτουν την αναγνώριση. | Εφαρμόστε διόρθωση περιστροφής (`ocr_engine.rotate(90)`) πριν προσθέσετε ROI. | +| **Θόρυβος στο φόντο** | Σκιές ή σφραγίδες μπερδεύουν το μοντέλο. | Προεπεξεργαστείτε με απλό κατώφλι (`cv2.threshold`) ή χρησιμοποιήστε φίλτρο αποθορυβοποίησης. | + +Η αντιμετώπιση αυτών των ακραίων περιπτώσεων νωρίς σας εξοικονομεί ώρες εντοπισμού σφαλμάτων αργότερα. + +--- + +## Συμβουλές για Πραγματικά Έργα + +- **Επεξεργασία σε Παρτίδες:** Επανάληψη πάνω σε φάκελο αποδείξεων, υπολογισμός ROI δυναμικά (π.χ., βάσει ανίχνευσης προτύπου), και αποθήκευση αποτελεσμάτων σε CSV. +- **Ανίχνευση Προτύπου:** Αν διαχειρίζεστε πολλαπλά layout αποδείξεων, διατηρήστε έναν χάρτη JSON `template_id → ROI coordinates`. Αλλάξτε ROI βάσει γρήγορου ταξινομητή layout. +- **Παράλληλη Εκτέλεση:** Χρησιμοποιήστε `concurrent.futures.ThreadPoolExecutor` για να τρέξετε πολλαπλές περιπτώσεις OCR ταυτόχρονα—ιδανικό για υψηλού όγκου pipelines back‑office. +- **Φίλτρο Εμπιστοσύνης:** Τα περισσότερα αποτελέσματα OCR περιλαμβάνουν βαθμό εμπιστοσύνης. Απορρίψτε αποτελέσματα κάτω από ένα όριο (π.χ., 85 %) και σημαδέψτε τα για χειροκίνητη επανεξέταση. + +--- + +## Συμπέρασμα + +Καλύψαμε τα πάντα που χρειάζεστε για **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, και τελικά **recognize text from invoice** ώστε να απαντήσετε στην κλασική ερώτηση **how to extract amount**. Το script είναι σύντομο, αλλά αρκετά ευέλικτο ώστε να προσαρμοστεί σε διαφορετικές μορφές εγγράφων, γλώσσες, και OCR back‑ends. + +Τώρα που έχετε κατακτήσει τα βασικά, σκεφτείτε να επεκτείνετε τη ροή: προσθέστε σάρωση barcode, ενσωματώστε έναν parser PDF, ή στείλτε το εξαγόμενο ποσό σε API λογισμικού. Ο ουρανός είναι το όριο, και με καλά ορισμένο ROI θα έχετε πάντα πιο γρήγορα και καθαρά αποτελέσματα. + +Αν αντιμετωπίσετε κάποιο πρόβλημα, αφήστε ένα σχόλιο παρακάτω—καλή OCR εμπειρία! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## Τι Θα Πρέπει να Μάθετε Στη Σειρά; + +- [Πώς να Εξάγετε Κείμενο από Εικόνα Προετοιμάζοντας Ορθογώνια στο OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Εξαγωγή Κειμένου από Εικόνα Java με Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Εξαγωγή Κειμένου από Εικόνα – Βελτιστοποίηση OCR με Aspose.OCR για .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/hindi/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..3a94bff91 --- /dev/null +++ b/ocr/hindi/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: असिंक्रोनस OCR ट्यूटोरियल जो दिखाता है कि Python में asyncio के साथ Aspose + OCR का उपयोग करके तेज़ इमेज टेक्स्ट एक्सट्रैक्शन कैसे किया जाए। चरण‑दर‑चरण असिंक्रोनस + OCR इम्प्लीमेंटेशन सीखें। +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: hi +og_description: Async OCR ट्यूटोरियल आपको Python में asyncio के साथ Aspose OCR का + उपयोग करके प्रभावी इमेज टेक्स्ट एक्सट्रैक्शन के लिए मार्गदर्शन करता है। +og_title: असिंक्रोनस OCR ट्यूटोरियल – Aspose OCR के साथ Python asyncio +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: असिंक्रोनस OCR ट्यूटोरियल – Aspose OCR के साथ Python asyncio +url: /hi/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR ट्यूटोरियल – Python asyncio with Aspose OCR + +क्या आप कभी सोचते थे कि ऑप्टिकल कैरेक्टर रिकग्निशन को बिना आपके ऐप को ब्लॉक किए कैसे चलाया जाए? एक **async OCR ट्यूटोरियल** में आप ठीक यही देखेंगे—Python के `asyncio` और Aspose OCR लाइब्रेरी का उपयोग करके नॉन‑ब्लॉकिंग टेक्स्ट एक्सट्रैक्शन। + +यदि आप भारी इमेज के प्रोसेस होने का इंतजार करते-करते फँसे हुए हैं, तो यह गाइड आपको एक साफ़, असिंक्रोनस समाधान देता है जो आपके इवेंट लूप को सुचारू रूप से चलाता रहता है। + +आगे के सेक्शन्स में हम सब कुछ कवर करेंगे जो आपको चाहिए: लाइब्रेरी इंस्टॉल करना, एक असिंक्रोनस हेल्पर सेट अप करना, परिणाम को हैंडल करना, और कई इमेजेज़ को स्केल करने के लिए एक त्वरित टिप भी। अंत तक आप किसी भी Python प्रोजेक्ट में जो पहले से `asyncio` उपयोग करता है, एक **async OCR ट्यूटोरियल** डाल सकेंगे। + +## आपको क्या चाहिए + +* Python 3.9+ (हमारा उपयोग किया गया `asyncio` API 3.7 से स्थिर है) +* एक सक्रिय Aspose OCR लाइसेंस या फ्री ट्रायल (लाइब्रेरी शुद्ध‑Python है, कोई नेटिव बाइनरी नहीं) +* एक छोटी इमेज फ़ाइल (`.jpg`, `.png`, आदि) जिसे आप पढ़ना चाहते हैं – इसे किसी ज्ञात फ़ोल्डर में रखें + +कोई अन्य बाहरी टूल्स आवश्यक नहीं हैं; सब कुछ शुद्ध Python में चलता है। + +## चरण 1: Aspose OCR पैकेज इंस्टॉल करें + +सबसे पहले, PyPI से Aspose OCR पैकेज प्राप्त करें। एक टर्मिनल खोलें और चलाएँ: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** यदि आप एक वर्चुअल एनवायरनमेंट में काम कर रहे हैं (बहुत अनुशंसित), तो पहले उसे सक्रिय करें। यह डिपेंडेंसीज़ को अलग रखता है और संस्करण टकराव से बचाता है। + +## चरण 2: OCR इंजन को असिंक्रोनसली इनिशियलाइज़ करें + +हमारे **async OCR ट्यूटोरियल** का मुख्य भाग एक असिंक्रोनस हेल्पर फ़ंक्शन है। यह एक `OcrEngine` इंस्टेंस बनाता है, इमेज लोड करता है, और फिर `recognize_async()` को कॉल करता है। इंजन स्वयं सिंक्रोनस है, लेकिन रैपर मेथड एक awaitable लौटाता है, जिससे इवेंट लूप प्रतिक्रियाशील बना रहता है। + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**हम इसे इस तरह क्यों करते हैं:** +*हेल्पर के अंदर इंजन बनाना थ्रेड‑सेफ़्टी सुनिश्चित करता है यदि आप बाद में कई OCR जॉब्स को समानांतर चलाते हैं। `await` कीवर्ड नियंत्रण को इवेंट लूप को वापस सौंप देता है जबकि भारी काम लाइब्रेरी के आंतरिक थ्रेड पूल में होता है।* + +## चरण 3: असिंक्रोनस मुख्य फ़ंक्शन से हेल्पर को चलाएँ + +अब हमें एक छोटा `main()` कोरूटीन चाहिए जो `async_ocr()` को कॉल करे और परिणाम प्रिंट करे। यह एक `asyncio` स्क्रिप्ट के सामान्य एंट्री पॉइंट को दर्शाता है। + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**आंतरिक रूप से क्या हो रहा है?** +`asyncio.run()` एक नया इवेंट लूप बनाता है, `main()` को शेड्यूल करता है, और जब `main()` समाप्त हो जाता है तो लूप को साफ़ तौर पर बंद कर देता है। यह पैटर्न Python 3.7+ में असिंक्रोनस प्रोग्राम शुरू करने का अनुशंसित तरीका है। + +## चरण 4: पूरी स्क्रिप्ट का परीक्षण करें + +ऊपर के दो कोड ब्लॉक्स को एक ही फ़ाइल में सेव करें, उदाहरण के लिए `async_ocr_demo.py`। कमांड लाइन से इसे चलाएँ: + +```bash +python async_ocr_demo.py +``` + +यदि सब कुछ सही ढंग से सेट है तो आपको कुछ इस तरह दिखना चाहिए: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +सटीक आउटपुट `photo.jpg` की सामग्री पर निर्भर करेगा। मुख्य बात यह है कि स्क्रिप्ट जल्दी समाप्त हो जाती है, चाहे इमेज बड़ी ही क्यों न हो, क्योंकि OCR कार्य बैकग्राउंड में होता है। + +## चरण 5: स्केल अप – कई इमेजेज़ को एक साथ प्रोसेस करें + +एक सामान्य फॉलो‑अप प्रश्न है, *“क्या मैं प्रत्येक फ़ाइल के लिए नया प्रोसेस लॉन्च किए बिना फ़ाइलों का बैच OCR कर सकता हूँ?”* बिल्कुल। क्योंकि हमारा हेल्पर पूरी तरह असिंक्रोनस है, हम कई कोरूटीन को `asyncio.gather()` से इकट्ठा कर सकते हैं: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**यह क्यों काम करता है:** `asyncio.gather()` सभी OCR टास्क को एक साथ शेड्यूल करता है। अंतर्निहित Aspose OCR लाइब्रेरी अभी भी अपना थ्रेड पूल उपयोग करती है, लेकिन Python की दृष्टि से सब कुछ नॉन‑ब्लॉकिंग रहता है, जिससे आप एक सिंगल सिंक्रोनस कॉल के समय में दर्जनों इमेजेज़ को संभाल सकते हैं। + +## चरण 6: त्रुटियों को सहजता से संभालना + +जब आप बाहरी फ़ाइलों के साथ काम करते हैं, तो आप अनिवार्य रूप से गायब फ़ाइलें, भ्रष्ट इमेजेज़, या लाइसेंस समस्याओं का सामना करेंगे। OCR कॉल को `try/except` ब्लॉक में रैप करें ताकि इवेंट लूप जीवित रहे: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +अब `batch_ocr()` `safe_async_ocr` को कॉल कर सकता है, जिससे एक बुरी फ़ाइल पूरी बैच को समाप्त नहीं करेगी। + +## विज़ुअल ओवरव्यू + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR ट्यूटोरियल फ्लोचार्ट जिसमें async_ocr हेल्पर, इवेंट लूप, और Aspose OCR इंजन दिखाया गया है"} + +ऊपर का डायग्राम फ्लो को विज़ुअलाइज़ करता है: इवेंट लूप → `async_ocr` → `OcrEngine` → बैकग्राउंड थ्रेड → परिणाम लूप में वापस। + +## सामान्य समस्याएँ और उन्हें कैसे टालें + +| समस्या | क्यों होता है | समाधान | +|---------|----------------|-----| +| **हेल्पर के अंदर ब्लॉकिंग I/O** | बिना `await` के `open()` का उपयोग अनजाने में लूप को ब्लॉक कर सकता है। | `aiofiles` का उपयोग फ़ाइल पढ़ने के लिए करें, या `engine.load_image` को संभालने दें (यह पहले से ही नॉन‑ब्लॉकिंग है)। | +| **कोरूटीन के बीच एक ही `OcrEngine` का पुन: उपयोग** | इंजन थ्रेड‑सेफ़ नहीं है; समानांतर कॉल्स स्थिति को भ्रष्ट कर सकते हैं। | प्रत्येक `async_ocr` कॉल में एक नया इंजन बनाएं (जैसा दिखाया गया है)। | +| **लाइसेंस गायब** | Aspose OCR रनटाइम पर लाइसेंस‑संबंधी अपवाद फेंकता है। | लाइसेंस को जल्दी रजिस्टर करें (`OcrEngine.set_license("license.json")`). | +| **बड़ी इमेजेज़ से मेमोरी स्पाइक** | लाइब्रेरी पूरी इमेज को RAM में लोड करती है। | यदि मेमोरी की चिंता है तो OCR से पहले इमेज को डाउनस्केल करें। | + +## पुनरावलोकन: हमने क्या हासिल किया + +इस **async OCR ट्यूटोरियल** में हमने: + +1. Aspose OCR लाइब्रेरी इंस्टॉल की। +2. एक `async_ocr` हेल्पर बनाया जो बिना ब्लॉक किए रिकग्निशन चलाता है। +3. हेल्पर को एक साफ़ `asyncio` एंट्री पॉइंट से चलाया। +4. `asyncio.gather` के साथ बैच प्रोसेसिंग दिखाया। +5. त्रुटि हैंडलिंग और बेस्ट‑प्रैक्टिस टिप्स जोड़े। + +यह सब शुद्ध Python है, इसलिए आप इसे वेब सर्वर, CLI टूल, या डेटा‑पाइपलाइन में बिना मौजूदा async कोड को फिर से लिखे डाल सकते हैं। + +## अगले कदम और संबंधित विषय + +* **असिंक्रोनस इमेज प्रीप्रोसेसिंग** – OCR से पहले इमेजेज़ को समानांतर डाउनलोड करने के लिए `aiohttp` का उपयोग करें। +* **OCR परिणाम संग्रहीत करना** – इस ट्यूटोरियल को `asyncpg` जैसे async डेटाबेस ड्राइवर के साथ PostgreSQL के लिए संयोजित करें। +* **परफॉर्मेंस ट्यूनिंग** – यदि लाइब्रेरी ऐसा विकल्प देती है तो `engine.recognize_async(max_threads=4)` के साथ प्रयोग करें। +* **वैकल्पिक OCR इंजन** – लागत‑लाभ विश्लेषण के लिए Aspose OCR की तुलना Tesseract के async रैपर्स से करें। + +बिना झिझक प्रयोग करें: PDFs फीड करने की कोशिश करें, भाषा सेटिंग्स समायोजित करें, या परिणामों को एक चैटबॉट में जोड़ें। एक ठोस **async OCR ट्यूटोरियल** आधार होने पर संभावनाएँ असीमित हैं। + +कोडिंग का आनंद लें, और आपका टेक्स्ट एक्सट्रैक्शन हमेशा तेज़ रहे! + +## आगे आप क्या सीखें? + +- [Aspose OCR के साथ इमेज से टेक्स्ट निकालें – चरण‑दर‑चरण गाइड](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR ट्यूटोरियल – ऑप्टिकल कैरेक्टर रिकग्निशन](/ocr/english/) +- [Aspose.OCR का उपयोग करके भाषा के साथ इमेज टेक्स्ट OCR कैसे करें](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/hindi/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..964ad6d4c --- /dev/null +++ b/ocr/hindi/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-05-31 +description: ऑसीआर में स्वचालित भाषा पहचान को आसान बनाया गया है। सीखें कैसे इमेज ओसीआर + लोड करें, ऑटो भाषा पहचान सक्षम करें, और कुछ ही चरणों में टेक्स्ट इमेज को पहचानें। +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: hi +og_description: OCR में स्वचालित भाषा पहचान को आसान बनाया गया है। स्वचालित भाषा पहचान + सक्षम करने, इमेज OCR लोड करने और टेक्स्ट इमेज को पहचानने के लिए इस चरण‑दर‑चरण ट्यूटोरियल + का पालन करें। +og_title: OCR के साथ स्वचालित भाषा पहचान – पूर्ण पायथन गाइड +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: OCR के साथ स्वचालित भाषा पहचान – पूर्ण पायथन गाइड +url: /hi/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# स्वचालित भाषा पहचान OCR के साथ – पूर्ण Python गाइड + +क्या आपने कभी सोचा है कि OCR इंजन को *स्कैन किए गए दस्तावेज़* की भाषा का अनुमान कैसे लगवाया जाए बिना आपको बताये कि क्या देखना है? यही **स्वचालित भाषा पहचान** करती है, और यह बहुभाषी PDFs, सड़क संकेतों की तस्वीरें, या किसी भी छवि जो विभिन्न लिपियों को मिलाती है, के साथ काम करते समय एक बड़ा बदलाव लाती है। + +इस ट्यूटोरियल में हम एक व्यावहारिक उदाहरण के माध्यम से दिखाएंगे कि **ऑटो भाषा पहचान** को कैसे सक्षम किया जाए, **इमेज OCR लोड** किया जाए, और **टेक्स्ट इमेज को पहचान** किया जाए Python‑स्टाइल API का उपयोग करके। अंत तक आपके पास एक स्वतंत्र स्क्रिप्ट होगी जो पता लगी भाषा कोड और निकाले गए टेक्स्ट दोनों को प्रिंट करेगी—कोई मैन्युअल भाषा सेटिंग की आवश्यकता नहीं। + +## आप क्या सीखेंगे + +- कैसे एक OCR इंजन इंस्टेंस बनाएं और **स्वचालित भाषा पहचान** को चालू करें। +- डिस्क से **इमेज OCR लोड** करने के सटीक चरण। +- इंजन की `recognize()` मेथड को कॉल करके परिणाम प्राप्त करना जिसमें भाषा कोड शामिल हो। +- कम‑रिज़ॉल्यूशन वाली छवियों या असमर्थित लिपियों जैसे किनारे के मामलों को संभालने के टिप्स। + +बहुभाषी OCR का कोई पूर्व अनुभव आवश्यक नहीं; बस एक बेसिक Python सेटअप और एक इमेज फ़ाइल चाहिए। + +--- + +## आवश्यकताएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास है: + +1. Python 3.8+ स्थापित (कोई भी हालिया संस्करण चलेगा)। +2. वह OCR लाइब्रेरी जो `OcrEngine`, `LanguageAutoDetectMode` आदि प्रदान करती है – इस गाइड के लिए हम मान लेते हैं कि पैकेज का नाम `myocr` है। इसे इस तरह इंस्टॉल करें: + + ```bash + pip install myocr + ``` + +3. एक इमेज फ़ाइल (`multilingual_sample.png`) जिसमें कम से कम दो अलग‑अलग भाषाओं में टेक्स्ट हो। +4. थोड़ी जिज्ञासा—यदि आपने पहले OCR नहीं छुआ है, तो चिंता न करें; कोड जानबूझकर सरल रखा गया है। + +--- + +## चरण 1: स्वचालित भाषा पहचान सक्षम करें + +सबसे पहला काम है इंजन को बताना कि उसे भाषा *खुद* पता करनी चाहिए। यही वह जगह है जहाँ **स्वचालित भाषा पहचान** फ़्लैग काम आता है। + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **यह क्यों महत्वपूर्ण है:** +> जब `AUTO_DETECT` सेट किया जाता है, तो इंजन इमेज पर एक हल्का भाषा वर्गीकरण चलाता है, उसके बाद भारी‑वजन वाले कैरेक्टर रिकग्निशन को शुरू करता है। इसका मतलब है कि आपको यह अनुमान लगाने की जरूरत नहीं कि टेक्स्ट अंग्रेज़ी, रूसी, फ्रेंच या किसी भी संयोजन में है। इंजन स्वचालित रूप से प्रत्येक क्षेत्र के लिए सबसे उपयुक्त भाषा मॉडल चुन लेगा। + +--- + +## चरण 2: इमेज OCR लोड करें + +अब जब इंजन जानता है कि उसे ऑटो‑डिटेक्ट करना है, हमें उसे काम करने के लिए कुछ देना होगा। **इमेज OCR लोड** चरण बिटमैप को पढ़ता है और आंतरिक बफ़र्स तैयार करता है। + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **प्रो टिप:** +> यदि आपकी इमेज 300 dpi से बड़ी है, तो इसे लगभग 150‑200 dpi तक डाउनस्केल करने पर विचार करें। बहुत अधिक विवरण भाषा पहचान चरण को *धीमा* कर सकता है बिना सटीकता बढ़ाए। + +--- + +## चरण 3: इमेज से टेक्स्ट पहचानें + +इमेज मेमोरी में लोड हो गई है और भाषा पहचान सक्षम है, अब अंतिम कदम है इंजन को **टेक्स्ट इमेज को पहचान** करने के लिए कहना। यह एक ही कॉल सभी भारी काम कर देती है। + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` एक ऑब्जेक्ट है जिसमें आमतौर पर कम से कम दो एट्रिब्यूट होते हैं: + +| एट्रिब्यूट | विवरण | +|-----------|-------| +| `language` | पता लगी भाषा का ISO‑639‑1 कोड (उदा., अंग्रेज़ी के लिए `"en"`). | +| `text` | इमेज का प्लेन‑टेक्स्ट ट्रांसक्रिप्शन. | + +--- + +## चरण 4: पता लगी भाषा और निकाला गया टेक्स्ट प्राप्त करें + +अब हम बस वह प्रिंट करते हैं जो इंजन ने खोजा। यह **डिटेक्ट लैंग्वेज OCR** क्षमता को कार्रवाई में दिखाता है। + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**नमूना आउटपुट** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **यदि इंजन `None` लौटाता है तो क्या करें?** +> आमतौर पर इसका मतलब है कि इमेज बहुत धुंधली है या टेक्स्ट बहुत छोटा है (< 8 pt). कंट्रास्ट बढ़ाएँ या उच्च‑रिज़ॉल्यूशन स्रोत का उपयोग करें। + +--- + +## पूर्ण कार्यशील उदाहरण (ऑटो भाषा पहचान अंत‑से‑अंत) + +सब कुछ एक साथ जोड़ते हुए, यहाँ एक तैयार‑चलाने‑योग्य स्क्रिप्ट है जो **ऑटो भाषा पहचान सक्षम करना**, **इमेज OCR लोड करना**, **टेक्स्ट इमेज को पहचानना**, और **भाषा पहचान OCR** को एक ही बार में करता है। + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +इसे `automatic_language_detection_ocr.py` के रूप में सेव करें, `YOUR_DIRECTORY` को उस फ़ोल्डर से बदलें जहाँ आपका PNG स्थित है, और चलाएँ: + +```bash +python automatic_language_detection_ocr.py +``` + +आपको भाषा कोड के बाद निकाला गया टेक्स्ट दिखेगा, ठीक उसी तरह जैसा ऊपर के नमूना आउटपुट में है। + +--- + +## सामान्य किनारे के मामलों का समाधान + +| स्थिति | सुझाया गया समाधान | +|--------|-------------------| +| **बहुत कम‑रिज़ॉल्यूशन इमेज** (100 dpi से कम) | लोड करने से पहले बाइक्यूबिक फ़िल्टर से अपस्केल करें, या उच्च‑रिज़ॉल्यूशन स्रोत माँगें। | +| **एक ही इमेज में मिश्रित लिपियाँ** (जैसे, अंग्रेज़ी + सिरिलिक) | इंजन आमतौर पर पेज को क्षेत्रों में विभाजित कर देता है; यदि आप गलत पहचान देखते हैं, तो `engine.enable_region_split = True` सेट करें। | +| **असमर्थित भाषा** | जांचें कि OCR लाइब्रेरी में उस लिपि के लिए भाषा पैक उपलब्ध है या नहीं; अतिरिक्त मॉडल डाउनलोड करने पड़ सकते हैं। | +| **बड़ी बैच प्रोसेसिंग** | इंजन को एक बार इनिशियलाइज़ करें, फिर कई `load_image` / `recognize` चक्रों में पुन: उपयोग करें ताकि मॉडल लोडिंग दोहराई न जाए। | + +--- + +## दृश्य सारांश + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt text:* स्वचालित भाषा पहचान का उदाहरण आउटपुट, जिसमें पता लगी भाषा कोड और निकाला गया बहुभाषी टेक्स्ट दिखाया गया है। + +--- + +## निष्कर्ष + +हमने **स्वचालित भाषा पहचान** को शुरू से अंत तक कवर किया—इंजन बनाना, ऑटो भाषा पहचान सक्षम करना, OCR के लिए इमेज लोड करना, टेक्स्ट पहचानना, और अंत में पता लगी भाषा प्राप्त करना। यह एंड‑टू‑एंड फ्लो आपको बहुभाषी दस्तावेज़ों को बिना हर बार भाषा मॉडल मैन्युअली कॉन्फ़िगर किए प्रोसेस करने देता है। + +यदि आप आगे बढ़ना चाहते हैं, तो विचार करें: + +- **बैचिंग**: सैकड़ों इमेज को लूप में प्रोसेस करें और वही `OcrEngine` इंस्टेंस पुन: उपयोग करें। +- **पोस्ट‑प्रोसेसिंग**: निकाले गए टेक्स्ट को स्पेल‑चेकर या भाषा‑विशिष्ट टोकनाइज़र से साफ़ करें। +- **इंटीग्रेशन**: स्क्रिप्ट को वेब सर्विस में एम्बेड करें जो यूज़र अपलोड ले और `language` और `text` फ़ील्ड वाले JSON रिटर्न करे। + +विभिन्न इमेज फ़ॉर्मेट (`.jpg`, `.tif`) के साथ प्रयोग करें और देखें कि पहचान सटीकता कैसे बदलती है। कोई सवाल या ऐसी जटिल इमेज जो पढ़ी नहीं जा रही? नीचे कमेंट करें—हैप्पी कोडिंग! + +## आगे आप क्या सीखें? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..dfbf3fa31 --- /dev/null +++ b/ocr/hindi/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: जाने कैसे पायथन के साथ बल्क इमेज‑टू‑टेक्स्ट कन्वर्ज़न स्क्रिप्ट का उपयोग + करके छवियों को टेक्स्ट में बदलें। Aspose.OCR का उपयोग करके स्कैन की गई छवियों से + टेक्स्ट को मिनटों में पहचानें। +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: hi +og_description: इमेज को तुरंत पायथन में टेक्स्ट में बदलें। यह गाइड बड़े पैमाने पर + इमेज‑से‑टेक्स्ट रूपांतरण और Aspose.OCR के साथ स्कैन की गई इमेज से टेक्स्ट पहचानने + का तरीका दिखाता है। +og_title: छवियों को टेक्स्ट में बदलें पायथन – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: इमेज को टेक्स्ट में बदलें Python – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेज को टेक्स्ट में बदलें Python – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपने कभी सोचा है कि **convert images to text python** कैसे किया जाए बिना दर्जनों लाइब्रेरीज़ की तलाश किए? आप अकेले नहीं हैं। चाहे आप पुराने रसीदों को डिजिटल बना रहे हों, स्कैन किए गए इनवॉइस से डेटा निकाल रहे हों, या PDFs का खोज योग्य आर्काइव बना रहे हों, तस्वीरों को साधारण‑टेक्स्ट फ़ाइलों में बदलना कई डेवलपर्स के लिए रोज़मर्रा का काम है। + +इस ट्यूटोरियल में हम एक **bulk image to text conversion** पाइपलाइन को चरण‑दर‑चरण देखेंगे जो स्कैन किए गए इमेज से टेक्स्ट पहचानता है, प्रत्येक परिणाम को अलग‑अलग `.txt` फ़ाइल में सहेजता है, और यह सब सिर्फ कुछ लाइनों के Python कोड से करता है। कोई रहस्यमय API नहीं—Aspose.OCR भारी काम करता है, और हम आपको दिखाएंगे कि इसे कैसे सेट‑अप करें। + +## What You’ll Learn + +- Aspose.OCR for Python पैकेज को कैसे इंस्टॉल और कॉन्फ़िगर करें। +- `BatchOcrEngine` का उपयोग करके **convert images to text python** करने के लिए आवश्यक सटीक कोड। +- असमर्थित फ़ॉर्मेट या करप्ट फ़ाइलों जैसी सामान्य समस्याओं को संभालने के टिप्स। +- यह सत्यापित करने के तरीके कि **recognize text from scanned images** चरण वास्तव में सफल रहा या नहीं। + +इस गाइड के अंत तक आपके पास एक तैयार‑स्क्रिप्ट होगी जो एक बार में हजारों इमेज प्रोसेस कर सके—किसी भी बैच‑प्रोसेसिंग परिदृश्य के लिए एकदम उपयुक्त। + +## Prerequisites + +- आपके मशीन पर Python 3.8+ स्थापित हो। +- इमेज फ़ाइलों (PNG, JPEG, TIFF, आदि) की एक फ़ोल्डर जिसे आप टेक्स्ट में बदलना चाहते हैं। +- एक सक्रिय Aspose Cloud अकाउंट या फ्री ट्रायल लाइसेंस (टेस्टिंग के लिए फ्री टियर पर्याप्त है)। + +यदि आपके पास ये सब है, तो चलिए शुरू करते हैं। + +--- + +## Step 1 – Set Up Your Python Environment + +कोई OCR कोड लिखने से पहले, सुनिश्चित करें कि आप एक साफ़ वर्चुअल एनवायरनमेंट के अंदर काम कर रहे हैं। यह डिपेंडेंसीज़ को अलग रखता है और वर्ज़न कॉन्फ्लिक्ट से बचाता है। + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** अपने प्रोजेक्ट डायरेक्टरी को व्यवस्थित रखें—`ocr_project` नाम का एक सबफ़ोल्डर बनाएं और स्क्रिप्ट वहीं रखें। इससे बाद में पाथ हैंडलिंग बहुत आसान हो जाएगी। + +## Step 2 – Install Aspose.OCR for Python + +Aspose.OCR एक कमर्शियल लाइब्रेरी है, लेकिन यह PyPI से एक फ्री NuGet‑स्टाइल व्हील के साथ आती है। सक्रिय वर्चुअल एनवायरनमेंट में नीचे दिया गया कमांड चलाएँ: + +```bash +pip install aspose-ocr +``` + +यदि आपको परमिशन एरर मिलता है, तो `--user` फ़्लैग जोड़ें या `sudo` के साथ कमांड चलाएँ (Linux/macOS के लिए)। इंस्टॉलेशन के बाद आपको कुछ इस तरह दिखना चाहिए: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** कई ओपन‑सोर्स OCR टूल्स के विपरीत, Aspose.OCR बॉक्स से बाहर **bulk image to text conversion** को सपोर्ट करता है और अतिरिक्त कॉन्फ़िगरेशन के बिना विभिन्न इमेज फ़ॉर्मेट्स को संभालता है। यह `BatchOcrEngine` क्लास भी प्रदान करता है जो “convert images to text python” कार्य को एक‑लाइन ऑपरेशन बनाता है। + +## Step 3 – Convert Images to Text Python with Batch OCR + +अब ट्यूटोरियल का मुख्य भाग। नीचे एक पूरी‑चलाने‑योग्य स्क्रिप्ट है जो: + +1. OCR इंजन क्लासेज़ को इम्पोर्ट करती है। +2. `BatchOcrEngine` का एक इंस्टेंस बनाती है। +3. इंजन को इमेज की इनपुट फ़ोल्डर की ओर पॉइंट करती है। +4. प्रत्येक निकाले गए टेक्स्ट फ़ाइल को आउटपुट फ़ोल्डर में लिखने के लिए निर्देश देती है। +5. `recognize()` मेथड को कॉल करती है, जो **recognize text from scanned images** को एक‑एक करके चलाता है। + +नीचे दिया गया कोड `batch_ocr.py` के रूप में अपने प्रोजेक्ट फ़ोल्डर में सेव करें: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### How It Works + +- **`BatchOcrEngine`** सामान्य `OcrEngine` को रैप करता है लेकिन फ़ोल्डर‑लेवल ऑर्केस्ट्रेशन जोड़ता है, जो बिल्कुल वही है जिसकी आपको **convert images to text python** बैच में करने की जरूरत है। +- `input_folder` प्रॉपर्टी इंजन को बताती है कि स्रोत इमेज कहाँ खोजनी है। यह डायरेक्टरी को स्वचालित रूप से स्कैन करता है और हर सपोर्टेड फ़ाइल टाइप को क्यू में डालता है। +- `output_folder` प्रॉपर्टी तय करती है कि प्रत्येक `.txt` फ़ाइल कहाँ रखी जाएगी। इंजन मूल फ़ाइल नाम को बनाए रखता है, इसलिए `receipt1.png` बन जाता है `receipt1.txt`। +- `recognize()` को कॉल करने से वह आंतरिक लूप शुरू होता है जो प्रत्येक इमेज को लोड करता है, OCR चलाता है, और परिणाम लिखता है। यह मेथड तब तक ब्लॉक रहता है जब तक सभी फ़ाइलें प्रोसेस नहीं हो जातीं, जिससे आगे की क्रियाएँ (जैसे आउटपुट फ़ोल्डर को ज़िप करना) आसान हो जाती हैं। + +#### Expected Output + +जब आप स्क्रिप्ट चलाएँगे: + +```bash +python batch_ocr.py +``` + +आपको यह दिखना चाहिए: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +`output_texts` फ़ोल्डर के अंदर आपको हर इमेज के लिए एक प्लेन‑टेक्स्ट फ़ाइल मिलेगी। किसी भी फ़ाइल को टेक्स्ट एडिटर में खोलें और आप कच्चा OCR परिणाम देखेंगे—आमतौर पर मूल प्रिंटेड टेक्स्ट का निकटतम अनुमान। + +## Step 4 – Verify the Results and Handle Errors + +सबसे अच्छे OCR इंजन भी लो‑रिज़ॉल्यूशन स्कैन या अत्यधिक स्क्यूड पेज़ पर फिसल सकते हैं। यहाँ आउटपुट को जल्दी‑से‑जाँचने और किसी भी फेल्योर को लॉग करने का एक सरल तरीका है। + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Why add this?** +- यह उन मामलों को पकड़ता है जहाँ इंजन चुपचाप खाली स्ट्रिंग देता है (अपठनीय इमेज के साथ आम)। +- यह आपको समस्याग्रस्त फ़ाइलों की सूची देता है ताकि आप मैन्युअली जांच सकें या अलग सेटिंग्स (जैसे `OcrEngine.preprocess` विकल्प बढ़ाना) के साथ पुनः चलाएँ। + +### Edge Cases & Tweaks + +| Situation | Suggested Fix | +|-----------|----------------| +| Images are rotated 90° | `batch_engine.ocr_engine.rotation_correction = True` सेट करें। | +| Mixed languages (English + French) | `batch_engine.ocr_engine.language = "eng+fra"` को `recognize()` से पहले सेट करें। | +| Huge PDFs converted to images first | PDFs को सिंगल‑पेज इमेज में विभाजित करें, फिर फ़ोल्डर को बैच इंजन को दें। | +| Memory errors on very large batches | छोटे‑छोटे सब‑फ़ोल्डर क्रमशः प्रोसेस करें, या `batch_engine.max_memory_usage` बढ़ाएँ। | + +## Step 5 – Automate the Whole Workflow (Optional) + +यदि आपको यह कन्वर्ज़न रात‑भर चलाना है, तो स्क्रिप्ट को एक साधारण शेल या Windows बैच फ़ाइल में रैप करें, और `cron` (Linux/macOS) या Task Scheduler (Windows) के साथ शेड्यूल करें। Unix‑जैसे सिस्टम के लिए यहाँ एक न्यूनतम `run_ocr.sh` है: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +इसे executable बनाएं (`chmod +x run_ocr.sh`) और एक cron एंट्री जोड़ें: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +यह हर दिन सुबह 2 AM पर कन्वर्ज़न चलाएगा और बाद में समीक्षा के लिए आउटपुट लॉग करेगा। + +--- + +## Conclusion + +अब आपके पास Aspose.OCR के `BatchOcrEngine` का उपयोग करके **convert images to text python** करने की एक सिद्ध, प्रोडक्शन‑रेडी विधि है। स्क्रिप्ट **bulk image to text conversion** को सहजता से संभालती है, प्रत्येक परिणाम को अलग फ़ाइल में लिखती है, और यह सुनिश्चित करने के लिए वेरिफिकेशन स्टेप्स भी शामिल करती है कि आप वास्तव में **recognize text from scanned images** सही ढंग से कर रहे हैं। + +अब आप आगे कर सकते हैं: + +- विभिन्न OCR सेटिंग्स (भाषा पैक, डेस्क्यू, नॉइज़ रिडक्शन) के साथ प्रयोग करें। +- उत्पन्न टेक्स्ट को Elasticsearch जैसे सर्च इंडेक्स में पाइप करें ताकि तुरंत फुल‑टेक्स्ट सर्च मिल सके। +- इस पाइपलाइन को PDF कन्वर्ज़न टूल्स के साथ मिलाकर स्कैन किए गए PDFs को एक ही बार में प्रोसेस करें। + +कोई प्रश्न है, या किसी विशेष फ़ाइल टाइप में समस्या आई? नीचे कमेंट करें, और हम मिलकर ट्रबलशूट करेंगे। Happy coding, और आपके OCR रन तेज़ और त्रुटि‑रहित हों! + +## What Should You Learn Next? + +- [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 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/hindi/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..34cdf6a3a --- /dev/null +++ b/ocr/hindi/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Python में लाइसेंस इंस्टेंस बनाएं और लाइसेंस पाथ को आसानी से कॉन्फ़िगर + करें। स्पष्ट कोड उदाहरणों के साथ Aspose OCR लाइसेंसिंग सेटअप करना सीखें। +draft: false +keywords: +- create license instance +- configure license path +language: hi +og_description: Python में लाइसेंस इंस्टेंस बनाएं और तुरंत लाइसेंस पाथ कॉन्फ़िगर करें। + इस ट्यूटोरियल का पालन करके Aspose OCR को आत्मविश्वास के साथ सक्रिय करें। +og_title: Python में लाइसेंस इंस्टेंस बनाएं – पूर्ण सेटअप गाइड +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Python में लाइसेंस इंस्टेंस बनाएं – चरण‑दर‑चरण गाइड +url: /hi/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में लाइसेंस इंस्टेंस बनाएं – पूर्ण सेटअप गाइड + +Need to **create license instance** for Aspose OCR in Python? You’re in the right spot. In this tutorial we’ll also show you how to **configure license path** so the SDK knows where to find your `.lic` file. + +यदि आपने कभी खाली स्क्रिप्ट को घूरते हुए सोचा है कि OCR इंजन बिना लाइसेंस वाले प्रोडक्ट के बारे में क्यों शिकायत कर रहा है, तो आप अकेले नहीं हैं। समाधान आमतौर पर कुछ ही लाइनों का कोड होता है—जब आप ठीक जानते हैं कि उन्हें कहाँ रखना है। इस गाइड के अंत तक आपके पास एक पूरी तरह लाइसेंस्ड Aspose OCR वातावरण होगा जो बिना किसी समस्या के टेक्स्ट, इमेज और PDF को पहचान सकेगा। + +## आप क्या सीखेंगे + +- `asposeocr` पैकेज का उपयोग करके **create license instance** कैसे बनाएं। +- विकास और प्रोडक्शन दोनों के लिए **configure license path** का सही तरीका। +- सामान्य समस्याएँ (फ़ाइल नहीं मिलना, गलत परमिशन) और उन्हें कैसे टालें। +- एक पूर्ण, चलाने योग्य स्क्रिप्ट जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं। + +Aspose OCR का कोई पूर्व अनुभव आवश्यक नहीं है, बस एक कार्यशील Python 3 इंस्टॉलेशन और एक वैध लाइसेंस फ़ाइल चाहिए। + +--- + +## Step 1: Install the Aspose OCR Python Package + +Before we can **create license instance**, the library itself must be present. Open a terminal and run: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** If you’re using a virtual environment (highly recommended), activate it first. This keeps your dependencies tidy and prevents version clashes. + +## Step 2: Import the License Class + +Now that the SDK is available, the very first line of your script should import the `License` class. This is the object we’ll use to **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Why import it right away? Because the `License` object must be instantiated **before** any OCR calls; otherwise the SDK will throw a licensing error the moment you try to process an image. + +## Step 3: Create License Instance + +Here’s the moment you’ve been waiting for—actually **create license instance**. It’s a single line, but the surrounding context matters. + +```python +# Step 3: Create a License instance +license = License() +``` + +The variable `license` now holds an object that controls all licensing behavior for the current Python process. Think of it as the gatekeeper that tells Aspose OCR, “Hey, I’ve got the right to run.” + +## Step 4: Configure License Path + +With the instance ready, we need to point it at our `.lic` file. That’s where **configure license path** comes into play. Replace the placeholder with the absolute path to your license file. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +A few things to note: + +1. **Raw strings (`r"…"`)** prevent backslashes from being interpreted as escape characters on Windows. +2. Use an **absolute path** to avoid confusion when the script is launched from a different working directory. +3. If you prefer a relative path (e.g., when bundling the license with your project), make sure the relative base is the script’s location, not the current shell directory. + +### Handling Missing Files + +If the path is wrong or the file is unreadable, `set_license` will raise an exception. Wrap the call in a `try/except` block to give a friendly error message: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +This snippet **configures license path** safely and tells you exactly what went wrong—no mysterious stack traces. + +## Step 5: Verify the License Is Active + +A quick sanity check saves hours of debugging later. After you’ve called `set_license`, try a simple OCR operation. If the license is valid, the SDK will process the image without throwing a licensing error. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +If you see the recognized text printed, congratulations—you’ve successfully **create license instance** and **configure license path**. If you get a licensing exception, double‑check the path and file permissions. + +## Edge Cases & Best Practices + +| Situation | What to Do | +|-----------|------------| +| **License file lives in a network share** | Map the share to a drive letter or use a UNC path (`\\server\share\license.lic`). Ensure the Python process has read access. | +| **Running inside a Docker container** | Copy the `.lic` file into the image and reference it with an absolute path like `/app/license/Aspose.OCR.Java.lic`. | +| **Multiple Python interpreters** (e.g., conda envs) | Install the license file once per environment or keep a central location and point each interpreter to it. | +| **License file missing at runtime** | Gracefully fallback to a trial mode (if supported) or abort with a clear log message. | + +### Common Pitfalls + +- **Using forward slashes on Windows** – Python accepts them, but some older versions of the SDK might misinterpret them. Stick with raw strings or double backslashes. +- **Forgot to import `License`** – The script will crash with `NameError`. Always import before you instantiate. +- **Calling `set_license` after OCR methods** – The SDK checks licensing on first use, so set the path **first**. + +## Full Working Example + +Below is a complete script that ties everything together. Save it as `ocr_setup.py` and run it from the command line. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Expected output** (assuming a valid image): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +If the license file can’t be found, you’ll see a clear error message instead of a cryptic “License not found” exception. + +--- + +## Conclusion + +You now know exactly how to **create license instance** in Python and **configure license path** for the Aspose OCR SDK. The steps are straightforward: install the package, import `License`, instantiate it, point it at your `.lic` file, and verify with a tiny OCR test. + +Armed with this knowledge you can embed OCR capabilities into web services, desktop apps, or automated pipelines without stumbling over licensing errors. Next, consider exploring advanced OCR settings—language packs, image preprocessing, or batch processing—each of which builds on the solid foundation you’ve just set up. + +Got questions about deployment, Docker, or handling multiple licenses? Drop a comment, and happy coding! + + +## What Should You Learn Next? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..8b9a97a29 --- /dev/null +++ b/ocr/hindi/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Python OCR का उपयोग करके स्कैन की गई छवियों से खोज योग्य PDF बनाएं। सीखें + कि स्कैन की गई इमेज PDF को कैसे बदलें, TIFF को PDF में कैसे परिवर्तित करें, और मिनटों + में OCR टेक्स्ट लेयर कैसे जोड़ें। +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: hi +og_description: तुरंत खोज योग्य PDF बनाएं। यह गाइड दिखाता है कि कैसे OCR चलाएँ, स्कैन + किए गए इमेज PDF को परिवर्तित करें, और एक ही पायथन स्क्रिप्ट का उपयोग करके OCR टेक्स्ट + लेयर जोड़ें। +og_title: Python के साथ खोज योग्य PDF बनाएं – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Python के साथ खोज योग्य PDF बनाएं – चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python से Searchable PDF बनाएं – चरण‑दर‑चरण गाइड + +क्या आपने कभी सोचा है कि **स्कैन की गई पेज से searchable PDF** कैसे बनाएं बिना कई टूल्स के झंझट के? आप अकेले नहीं हैं। कई ऑफिस वर्कफ़्लो में एक स्कैन किया हुआ TIFF या JPEG साझा ड्राइव पर आता है, और अगला व्यक्ति टेक्स्ट को मैन्युअली कॉपी‑पेस्ट करता है—दुखद, त्रुटिप्रवण, और समय‑सापेक्ष। + +इस ट्यूटोरियल में हम एक साफ़, प्रोग्रामेटिक समाधान देखेंगे जो आपको **स्कैन की गई इमेज PDF को कन्वर्ट**, **TIFF को PDF में बदल**, और **OCR टेक्स्ट लेयर जोड़** एक ही बार में देता है। अंत तक आपके पास एक तैयार‑स्क्रिप्ट होगा जो OCR चलाता है, छिपा हुआ टेक्स्ट एम्बेड करता है, और एक searchable PDF आउटपुट करता है जिसे आप इंडेक्स, सर्च या भरोसे के साथ शेयर कर सकते हैं। + +## आपको क्या चाहिए + +- Python 3.9+ (कोई भी हालिया संस्करण चलेगा) +- `aspose-ocr` और `aspose-pdf` पैकेज ( `pip install aspose-ocr aspose-pdf` के माध्यम से इंस्टॉल) +- एक स्कैन की गई इमेज फ़ाइल (`.tif`, `.png`, `.jpg`, या यहाँ तक कि एक PDF पेज जो सिर्फ इमेज है) +- थोड़ा RAM (OCR इंजन हल्का है; लैपटॉप भी संभाल सकता है) + +> **Pro tip:** यदि आप Windows पर हैं, तो पैकेज प्राप्त करने का सबसे आसान तरीका है कि आप कमांड को एक एलेवेटेड PowerShell विंडो में चलाएँ। + +```bash +pip install aspose-ocr aspose-pdf +``` + +अब जब प्री‑रिक्विज़िट्स समाप्त हो गए हैं, चलिए कोड में डुबकी लगाते हैं। + +## Step 1: OCR Engine इंस्टेंस बनाएं – *create searchable pdf* + +सबसे पहले हम OCR इंजन को स्पिन‑अप करते हैं। इसे वह दिमाग समझें जो हर पिक्सेल को पढ़ेगा और उसे अक्षरों में बदल देगा। + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **यह क्यों महत्वपूर्ण है:** इंजन को केवल एक बार इनिशियलाइज़ करने से मेमोरी उपयोग कम रहता है। यदि आप प्रत्येक पेज के लिए `OcrEngine()` को लूप में कॉल करेंगे, तो जल्दी ही रिसोर्सेज ख़त्म हो जाएंगे। + +## Step 2: स्कैन की गई इमेज लोड करें – *convert tiff to pdf* & *convert scanned image pdf* + +अब, इंजन को उस फ़ाइल की ओर इंगित करें जिसे आप प्रोसेस करना चाहते हैं। API किसी भी रास्टर इमेज को स्वीकार करता है, इसलिए TIFF भी JPEG की तरह काम करेगा। + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +यदि आपके पास ऐसा PDF है जिसमें केवल स्कैन की गई इमेज है, तो आप अभी भी `load_image` का उपयोग कर सकते हैं क्योंकि Aspose स्वचालित रूप से पहला पेज एक्सट्रैक्ट कर लेगा। + +## Step 3: PDF Save Options तैयार करें – *add OCR text layer* + +यहाँ हम यह कॉन्फ़िगर करते हैं कि अंतिम PDF कैसे दिखेगा। मुख्य फ़्लैग है `create_searchable_pdf`; इसे `True` सेट करने से लाइब्रेरी एक अदृश्य टेक्स्ट लेयर एम्बेड करती है जो विज़ुअल कंटेंट को मिरर करती है। + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **टेक्स्ट लेयर क्या करती है:** जब आप परिणामी फ़ाइल को Adobe Reader में खोलते हैं और टेक्स्ट सिलेक्ट करने की कोशिश करते हैं, तो आपको छिपे हुए कैरेक्टर्स दिखेंगे। सर्च इंजन भी इन्हें इंडेक्स कर सकते हैं—कम्प्लायंस या आर्काइविंग के लिए परफेक्ट। + +## Step 4: OCR चलाएँ और सेव करें – *how to run OCR* in a single call + +अब जादू होता है। एक मेथड कॉल पूरे रिकग्निशन इंजन को चलाता है और searchable PDF को डिस्क पर लिख देता है। + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize` मेथड एक स्टेटस ऑब्जेक्ट रिटर्न करता है जिसे आप एरर्स के लिए जांच सकते हैं, लेकिन अधिकांश सरल परिदृश्यों में ऊपर दिया गया सिंगल कॉल पर्याप्त है। + +### Expected Output + +स्क्रिप्ट चलाने पर प्रिंट होगा: + +``` +PDF saved as searchable PDF. +``` + +यदि आप `scanned_page_searchable.pdf` खोलते हैं तो आप देखेंगे कि आप टेक्स्ट सिलेक्ट, कॉपी‑पेस्ट कर सकते हैं, और `Ctrl+F` सर्च भी चला सकते हैं। यही **create searchable pdf** वर्कफ़्लो की पहचान है। + +## Full Working Script + +नीचे पूरा, तैयार‑चलाने योग्य स्क्रिप्ट दिया गया है। प्लेसहोल्डर पाथ्स को अपने वास्तविक फ़ाइल लोकेशन से बदलें। + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +इसे `create_searchable_pdf.py` के रूप में सेव करें और चलाएँ: + +```bash +python create_searchable_pdf.py +``` + +## सामान्य प्रश्न और एज केस + +### 1️⃣ क्या मैं मल्टी‑पेज PDFs प्रोसेस कर सकता हूँ? + +हां। `ocr_engine.load_image("file.pdf")` उपयोग करें और फिर प्रत्येक पेज के लिए `ocr_engine.recognize(pdf_save_options, page_number)` लूप में कॉल करें। लाइब्रेरी स्वचालित रूप से मल्टी‑पेज searchable PDF जेनरेट करेगी। + +### 2️⃣ यदि मेरा स्रोत फ़ाइल हाई‑रेज़ोल्यूशन TIFF (300 dpi+) है तो क्या करें? + +उच्च DPI बेहतर OCR सटीकता देता है लेकिन मेमोरी उपयोग भी बढ़ाता है। यदि आप `MemoryError` का सामना करते हैं, तो पहले इमेज को डाउनस्केल करें: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ OCR की भाषा कैसे बदलूँ? + +इंजन को इमेज लोड करने से पहले `language` प्रॉपर्टी सेट करें: + +```python +ocr_engine.language = "fra" # French +``` + +समर्थित भाषा कोड की पूरी सूची Aspose डॉक्यूमेंटेशन में उपलब्ध है। + +### 4️⃣ यदि मुझे मूल इमेज क्वालिटी बनाए रखनी है तो क्या करें? + +`PdfSaveOptions` क्लास में `compression` प्रॉपर्टी है। इसे `PdfCompression.None` सेट करने से रास्टर डेटा बिल्कुल वैसा ही रहेगा जैसा था। + +```python +pdf_save_options.compression = "None" +``` + +## प्रोडक्शन‑रेडी डिप्लॉयमेंट के टिप्स + +- **बैच प्रोसेसिंग:** कोर लॉजिक को एक फ़ंक्शन में रैप करें जो फ़ाइल पाथ्स की लिस्ट लेता हो। प्रत्येक सफलता/विफलता को ऑडिट ट्रेल के लिए CSV में लॉग करें। +- **पैरालेलिज़्म:** `concurrent.futures.ThreadPoolExecutor` का उपयोग करके कई कोर पर OCR चलाएँ। बस याद रखें कि प्रत्येक थ्रेड को अपना `OcrEngine` इंस्टेंस चाहिए। +- **सिक्योरिटी:** यदि आप संवेदनशील दस्तावेज़ों को हैंडल कर रहे हैं, तो स्क्रिप्ट को सैंडबॉक्स्ड एनवायरनमेंट में चलाएँ और प्रोसेसिंग के बाद टेम्प फ़ाइलें तुरंत डिलीट कर दें। + +## निष्कर्ष + +अब आप जानते हैं कि कैसे **create searchable PDF** फ़ाइलें स्कैन की गई इमेजेज़ से एक संक्षिप्त Python स्क्रिप्ट के माध्यम से बनाएं। OCR इंजन को इनिशियलाइज़ करके, TIFF (या कोई भी रास्टर) लोड करके, `PdfSaveOptions` को **add OCR text layer** के लिए कॉन्फ़िगर करके, और अंत में `recognize` कॉल करके, पूरा **convert scanned image pdf** और **convert TIFF to PDF** पाइपलाइन एक ही दोहराने योग्य कमांड बन जाता है। + +अगला कदम? इस स्क्रिप्ट को एक फ़ाइल‑वॉचर के साथ जोड़ें ताकि कोई भी नई स्कैन फ़ोल्डर में डाली जाए तो वह स्वचालित रूप से searchable बन जाए। या विभिन्न OCR भाषाओं के साथ प्रयोग करें ताकि बहुभाषी आर्काइव्स को सपोर्ट किया जा सके। OCR को PDF जेनरेशन के साथ मिलाकर संभावनाएँ असीमित हैं। + +**how to run OCR** को अन्य भाषाओं या फ्रेमवर्क में उपयोग करने के बारे में और सवाल हैं? नीचे कमेंट करें, और हैप्पी कोडिंग! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## आगे आप क्या सीखें? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/hindi/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..d6a6a2a2a --- /dev/null +++ b/ocr/hindi/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Python के साथ OCR की सटीकता को सुधारें, OCR के लिए छवियों की पूर्व-प्रसंस्करण + करके। जानें कि इमेज फ़ाइलों से टेक्स्ट कैसे निकालें, PNG से टेक्स्ट कैसे पहचानें, + और परिणामों को कैसे बढ़ाएँ। +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: hi +og_description: Python में इमेज प्रीप्रोसेसिंग लागू करके OCR की सटीकता बढ़ाएँ। इस + गाइड का पालन करके इमेज फ़ाइलों से टेक्स्ट निकालें और PNG से टेक्स्ट को आसानी से + पहचानें। +og_title: Python में OCR की सटीकता सुधारें – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python में OCR की सटीकता बढ़ाएँ – पूर्ण चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में OCR सटीकता सुधारें – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपने कभी **OCR सटीकता सुधारने** की कोशिश की है और फिर भी गड़बड़ आउटपुट मिला है? आप अकेले नहीं हैं। अधिकांश डेवलपर्स को तब समस्या आती है जब मूल छवि शोरयुक्त, तिरछी, या बस कम‑कॉन्ट्रास्ट वाली होती है। अच्छी खबर? कुछ प्री‑प्रोसेसिंग ट्रिक्स धुंधली स्क्रीनशॉट को साफ, मशीन‑पढ़ने योग्य टेक्स्ट में बदल सकती हैं। + +इस ट्यूटोरियल में हम एक वास्तविक उदाहरण के माध्यम से चलते हैं जो **OCR के लिए इमेज को प्री‑प्रोसेस** करता है, पहचान इंजन चलाता है, और अंत में **इमेज फ़ाइलों से टेक्स्ट निकालता** है—विशेष रूप से एक PNG। अंत तक आप ठीक‑ठीक जान पाएँगे कि **PNG से टेक्स्ट कैसे पहचानें** उच्च सफलता दर के साथ, और आपके पास एक पुन: उपयोग योग्य कोड स्निपेट होगा जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं। + +## आप क्या सीखेंगे + +- OCR इंजन के लिए इमेज प्री‑प्रोसेसिंग क्यों महत्वपूर्ण है +- कौन से प्री‑प्रोसेसिंग मोड (डेनॉइज़, डेस्क्यू) सबसे बड़ा सुधार देते हैं +- Python में `OcrEngine` इंस्टेंस को कैसे कॉन्फ़िगर करें +- पूरा, चलाने योग्य स्क्रिप्ट जो **इमेज फ़ाइलों से टेक्स्ट निकालता** है +- घुमाए गए स्कैन या कम‑रिज़ॉल्यूशन तस्वीरों जैसे एज केस को संभालने के टिप्स + +कोई बाहरी लाइब्रेरी OCR SDK के अलावा आवश्यक नहीं है, लेकिन आपको Python 3.8+ और एक PNG इमेज चाहिए जिसे आप पढ़ना चाहते हैं। + +--- + +![Python में OCR सटीकता सुधारने के चरण दर्शाने वाला आरेख](image.png "OCR सटीकता सुधार कार्यप्रवाह") + +*Alt text: Python में OCR सटीकता सुधारने के चरण दर्शाने वाला आरेख, जिसमें प्री‑प्रोसेसिंग और पहचान चरण दिखाए गए हैं।* + +## आवश्यकताएँ + +- Python 3.8 या उससे नया स्थापित +- `OcrEngine`, `OcrEngineSettings`, और `ImagePreprocessMode` प्रदान करने वाले OCR SDK तक पहुंच (नीचे दिया गया कोड एक सामान्य API का उपयोग करता है; आवश्यकता पड़ने पर अपने विक्रेता की क्लासेज़ से बदलें) +- एक PNG इमेज (`input.png`) जिसे आप किसी फ़ोल्डर में रख सकते हैं + +यदि आप वर्चुअल एनवायरनमेंट का उपयोग कर रहे हैं, तो अभी इसे सक्रिय करें—कोई जटिल चीज़ नहीं, बस `python -m venv venv && source venv/bin/activate`। + +--- + +## चरण 1: OCR इंजन इंस्टेंस बनाएं – OCR सटीकता सुधारना शुरू करें + +पहली चीज़ जो आपको चाहिए वह है OCR इंजन ऑब्जेक्ट। इसे ऐसे सोचें जैसे वह दिमाग जो बाद में पिक्सेल पढ़ेगा और अक्षर निकालेगा। + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +क्यों यह महत्वपूर्ण है: बिना इंजन के आप कोई भी प्री‑प्रोसेसिंग नहीं लगा सकते, और कच्ची इमेज सीधे recogniser को फीड हो जाएगी—आमतौर पर सटीकता के लिए सबसे बुरा परिदृश्य। + +--- + +## चरण 2: लक्ष्य PNG लोड करें – PNG से टेक्स्ट पहचानने के लिए मंच तैयार करें + +अब हम इंजन को बताते हैं कि किस फ़ाइल पर काम करना है। PNG lossless है, जो JPEG की तुलना में हमें थोड़ा फायदा देता है। + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +यदि इमेज कहीं और स्थित है, तो बस पाथ समायोजित करें। इंजन किसी भी समर्थित फ़ॉर्मेट को स्वीकार करता है, लेकिन PNG अक्सर तीखे अक्षर किनारों के लिए आवश्यक बारीक विवरण संरक्षित रखता है। + +--- + +## चरण 3: प्री‑प्रोसेसिंग कॉन्फ़िगर करें – OCR के लिए इमेज प्री‑प्रोसेस करें + +यहाँ जादू होता है। हम एक सेटिंग्स ऑब्जेक्ट बनाते हैं, डेनॉइज़िंग को सक्षम करते हैं ताकि धब्बे हट जाएँ, और डेस्क्यू को चालू करते हैं ताकि झुके हुए टेक्स्ट को स्वतः सीधा किया जा सके। + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### डेनॉइज़ + डेस्क्यू क्यों? + +- **Denoise**: रैंडम पिक्सेल शोर पैटर्न‑मैचिंग एल्गोरिदम को भ्रमित करता है। इसे हटाने से अक्षर तेज़ हो जाते हैं। +- **Deskew**: केवल 2‑डिग्री का झुकाव भी confidence स्कोर को काफी घटा सकता है। डेस्क्यू बेसलाइन को संरेखित करता है, जिससे recogniser फ़ॉन्ट को अधिक विश्वसनीय रूप से मिलाता है। + +यदि आपकी इमेज विशेष रूप से डार्क है, तो अतिरिक्त फ़्लैग (जैसे `ImagePreprocessMode.CONTRAST_ENHANCE`) के साथ प्रयोग कर सकते हैं। SDK दस्तावेज़ आमतौर पर सभी उपलब्ध मोड सूचीबद्ध करता है। + +--- + +## चरण 4: सेटिंग्स को इंजन पर लागू करें – प्री‑प्रोसेसिंग को OCR से जोड़ें + +सेटिंग्स ऑब्जेक्ट को इंजन को असाइन करें ताकि अगली पहचान रन में हमने परिभाषित ट्रांसफ़ॉर्मेशन उपयोग हों। + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +यदि आप इस चरण को छोड़ देते हैं, तो इंजन अपने डिफ़ॉल्ट (अक्सर “कोई प्री‑प्रोसेसिंग नहीं”) पर वापस आ जाएगा, और आप **निचली OCR सटीकता** देखेंगे। + +--- + +## चरण 5: पहचान प्रक्रिया चलाएँ – इमेज से टेक्स्ट निकालें + +सब कुछ कनेक्ट हो जाने के बाद, हम अंततः इंजन को उसका काम करने के लिए कहते हैं। कॉल सिंक्रोनस है, जो एक result ऑब्जेक्ट लौटाता है जिसमें पहचाना गया स्ट्रिंग होता है। + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +पर्दे के पीछे इंजन अब: + +1. PNG को मेमोरी में लोड करता है +2. हमारी सेटिंग्स के आधार पर डेनॉइज़ और डेस्क्यू लागू करता है +3. न्यूरल‑नेटवर्क या क्लासिक पैटर्न मैचर चलाता है +4. आउटपुट को `recognition_result` में पैकेज करता है + +--- + +## चरण 6: पहचाने गए टेक्स्ट को आउटपुट करें – सुधार की पुष्टि करें + +आइए निकाले गए स्ट्रिंग को प्रिंट करें। वास्तविक एप्लिकेशन में आप इसे फ़ाइल, डेटाबेस में लिख सकते हैं, या किसी अन्य सर्विस को पास कर सकते हैं। + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### अपेक्षित आउटपुट + +यदि इमेज में वाक्य “Hello, OCR World!” है तो आपको यह दिखना चाहिए: + +``` +Hello, OCR World! +``` + +ध्यान दें कि टेक्स्ट साफ़ है—कोई अनचाहे प्रतीक या टूटे हुए अक्षर नहीं। यह **टेक्स्ट के लिए इमेज प्री‑प्रोसेसिंग** का सही परिणाम है। + +--- + +## प्रो टिप्स और एज केस + +| Situation | What to Adjust | Why | +|-----------|----------------|-----| +| बहुत कम‑रिज़ॉल्यूशन PNG (≤ 72 dpi) | यदि उपलब्ध हो तो `ImagePreprocessMode.SUPER_RESOLUTION` जोड़ें | अपसैंपलिंग recogniser को काम करने के लिए अधिक पिक्सेल दे सकता है | +| टेक्स्ट 5° से अधिक घुमाया हुआ है | डेस्क्यू टॉलरेंस बढ़ाएँ या इंजन को फीड करने से पहले `Pillow` से मैन्युअली घुमाएँ | अत्यधिक कोण कभी‑कभी ऑटोमैटिक डेस्क्यू को बायपास कर देते हैं | +| भारी बैकग्राउंड पैटर्न | `ImagePreprocessMode.BACKGROUND_REMOVAL` सक्षम करें | गैर‑टेक्स्ट अव्यवस्था को हटाता है जो अन्यथा गलत पढ़ी जा सकती थी | +| बहु‑भाषा दस्तावेज़ | `ocr_engine.language = "eng+spa"` (या समान) सेट करें | इंजन सही कैरेक्टर सेट चुनता है, जिससे कुल सटीकता बढ़ती है | + +याद रखें, **OCR सटीकता सुधारना** एक‑साइज़‑फिट‑ऑल नहीं है; आपको अपने विशेष डेटासेट के लिए प्री‑प्रोसेसिंग फ़्लैग्स पर पुनरावृति करनी पड़ सकती है। + +--- + +## पूर्ण स्क्रिप्ट – कॉपी और पेस्ट करने के लिए तैयार + +नीचे वह पूरा, चलाने योग्य उदाहरण है जिसमें हमने चर्चा किए सभी चरण शामिल हैं। इसे `improve_ocr_accuracy.py` के रूप में सहेजें और `python improve_ocr_accuracy.py` से चलाएँ। + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +इसे चलाएँ, कंसोल देखें, और आप तुरंत **इमेज से टेक्स्ट निकालें** परिणाम देखेंगे। यदि आउटपुट सही नहीं लगता, तो “प्रो टिप्स” तालिका में वर्णित अनुसार `preprocess_mode` फ़्लैग्स को ट्यून करें। + +--- + +## निष्कर्ष + +हमने Python का उपयोग करके **OCR सटीकता सुधारने** की एक व्यावहारिक विधि देखी। `OcrEngine` बनाकर, PNG लोड करके, **OCR के लिए इमेज को प्री‑प्रोसेस** करके, और अंत में **PNG से टेक्स्ट पहचान** करके, आप स्रोत चाहे जितना भी अधूरा हो, **इमेज फ़ाइलों से टेक्स्ट निकाल** सकते हैं। + +अगले कदम? इमेज की एक बैच को लूप में फीड करें, प्रत्येक परिणाम को CSV में सहेजें, या कॉन्ट्रास्ट एन्हांसमेंट जैसे अतिरिक्त प्री‑प्रोसेसिंग मोड्स के साथ प्रयोग करें। वही पैटर्न PDFs, स्कैन किए हुए रसीदों, या हाथ से लिखे नोट्स के लिए भी काम करता है—सिर्फ इनपुट बदलें और सेटिंग्स समायोजित करें। + +क्या आपके पास किसी विशेष इमेज प्रकार के बारे में प्रश्न हैं या इसे वेब सर्विस में इंटीग्रेट करने का तरीका जानना चाहते हैं? कमेंट छोड़ें, और हम उन पर साथ में चर्चा करेंगे। Happy coding, और आपकी OCR परिणाम हमेशा क्रिस्टल‑क्लियर रहें! + +## आगे आप क्या सीखें? + +- [Aspose OCR के साथ इमेज से टेक्स्ट निकालें – चरण‑दर‑चरण गाइड](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [इमेज से टेक्स्ट निकालें – Aspose.OCR for .NET के साथ OCR ऑप्टिमाइज़ेशन](/ocr/english/net/ocr-optimization/) +- [OCR में रेक्टेंगल तैयार करके इमेज से टेक्स्ट कैसे निकालें](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/hindi/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..fcd4096e3 --- /dev/null +++ b/ocr/hindi/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-31 +description: OCR के रुचि क्षेत्र (ROI) का उपयोग करके OCR के लिए छवि लोड करना और आयत + से टेक्स्ट निकालना सीखें, बिल पर राशि पहचानने के लिए एकदम उपयुक्त। +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: hi +og_description: OCR के लिए इमेज लोड करने हेतु ROI (रुचि का क्षेत्र) को मास्टर करें, + आयत से टेक्स्ट निकालें और एक ही ट्यूटोरियल में इनवॉइस से टेक्स्ट पहचानें। +og_title: OCR रुचि क्षेत्र – चरण-दर-चरण पाइथन गाइड +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR रुचि क्षेत्र – पाइथन में आयत से टेक्स्ट निकालें +url: /hi/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – आयत से टेक्स्ट निकालें Python में + +क्या आपने कभी सोचा है कि स्कैन किए गए इनवॉइस के किसी विशिष्ट भाग को **ocr region of interest** कैसे किया जाए बिना पूरी पेज को इंजन में फीड किए? आप पहले व्यक्ति नहीं हैं जो धुंधली रसीद को देखकर सोचते हैं, “निचले दाएँ कोने में मौजूद राशि को कैसे निकालूँ?” अच्छी खबर यह है कि आप OCR लाइब्रेरी को ठीक वही बता सकते हैं जहाँ देखना है, जिससे गति और सटीकता दोनों में काफी सुधार होता है। + +इस गाइड में हम एक पूर्ण, चलाने योग्य उदाहरण के माध्यम से दिखाएंगे कि कैसे **load image for OCR** करें, **region of interest** को परिभाषित करें, और फिर **extract text from rectangle** करके अंत में **recognize text from invoice** करें और क्लासिक “how to extract amount” सवाल का उत्तर दें। कोई अस्पष्ट संदर्भ नहीं—सिर्फ ठोस कोड, स्पष्ट व्याख्याएँ, और कुछ प्रो टिप्स जो आप पहले जानना चाहते थे। + +--- + +## What You’ll Build + +## आप क्या बनाएँगे + +1. डिस्क से इनवॉइस इमेज लोड करता है। +2. एक आयताकार ROI को चिह्नित करता है जहाँ कुल राशि स्थित है। +3. केवल उस ROI के भीतर OCR चलाता है। +4. साफ़ किया गया राशि स्ट्रिंग प्रिंट करता है। + +--- + +## Prerequisites + +## आवश्यकताएँ + +- Python 3.8+ स्थापित हो (`python --version` कमांड ≥3.8 दिखाना चाहिए)। +- एक pip‑installable OCR पैकेज (उदा., `pip install simpleocr`)। +- एक इनवॉइस इमेज (PNG या JPEG) जिसे आप किसी फ़ोल्डर में रख सकते हैं। +- Python फ़ंक्शन्स और क्लासेज़ की बुनियादी परिचितता (कुछ भी जटिल नहीं)। + +यदि आपके पास ये सब है, बढ़िया—आइए शुरू करें। यदि नहीं, पहले इमेज प्राप्त करें; बाकी कदम फ़ाइल की वास्तविक सामग्री से स्वतंत्र हैं। + +--- + +## Step 1: Load Image for OCR + +## चरण 1: OCR के लिए इमेज लोड करें + +किसी भी OCR वर्कफ़्लो को सबसे पहले एक बिटमैप चाहिए जिससे पढ़ा जा सके। अधिकांश लाइब्रेरी एक सरल `load_image` मेथड प्रदान करती हैं जो फ़ाइल पाथ को स्वीकार करती है। यहाँ हमारे `SimpleOCR` इंजन के साथ यह कैसे किया जाता है: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** स्क्रिप्ट को अलग कार्य निर्देशिका से चलाते समय “file not found” जैसी आश्चर्यजनक त्रुटियों से बचने के लिए absolute paths या `os.path.join` का उपयोग करें। + +--- + +## Step 2: Define OCR Region of Interest + +## चरण 2: OCR Region of Interest परिभाषित करें + +पूरे पेज को स्कैन करने के बजाय, हम इंजन को *बिल्कुल* बताते हैं कि राशि कहाँ स्थित है। यही **ocr region of interest** चरण है, और यह विश्वसनीय निष्कर्षण की कुंजी है, विशेषकर जब दस्तावेज़ में शोरयुक्त हेडर या फुटर हों। + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +इन संख्याओं का क्या मतलब है? `x` और `y` पिक्सेल ऑफ़सेट हैं जो शीर्ष‑बाएँ कोने से मापे जाते हैं, जबकि `width` और `height` बॉक्स का आकार दर्शाते हैं। यदि आप अनिश्चित हैं, तो इमेज को किसी भी एडिटर में खोलें, रूलर सक्षम करें, और निर्देशांक नोट करें। कई IDEs कर्सर की स्थिति को होवर करते समय भी दिखा सकते हैं। + +--- + +## Step 3: Extract Text from Rectangle + +## चरण 3: आयत से टेक्स्ट निकालें + +अब ROI सेट हो गया है, हम इंजन से **recognize text from invoice** करने को कहते हैं लेकिन केवल उसी आयत तक सीमित जो हमने अभी जोड़ी है। यह कॉल एक रिज़ल्ट ऑब्जेक्ट लौटाता है जिसमें आमतौर पर कच्चा स्ट्रिंग, confidence स्कोर, और कभी‑कभी बाउंडिंग बॉक्स होते हैं। + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +पर्दे के पीछे, `recognize()` प्रत्येक ROI पर इटररेट करता है, उस स्लाइस को क्रॉप करता है, OCR मॉडल चलाता है, और परिणामों को जोड़ता है। इसलिए एक सटीक **extract text from rectangle** क्षेत्र परिभाषित करने से बैच जॉब्स के प्रोसेसिंग समय में सेकंड बच सकते हैं। + +--- + +## Step 4: How to Extract Amount – Clean the Output + +## चरण 4: राशि निकालें – आउटपुट साफ़ करें + +OCR पूर्ण नहीं है; अक्सर आपको अतिरिक्त स्पेस, लाइन फ़ीड, या गलत‑पढ़े अक्षर (जैसे “S” बनाम “5”) मिलते हैं। एक तेज़ `strip()` और छोटा रेगेक्स आमतौर पर मौद्रिक मानों के लिए काम करता है। + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** यदि आप राशि को डेटाबेस या पेमेंट गेटवे में फीड करने की योजना बनाते हैं, तो आपको एक पूर्वानुमेय फ़ॉर्मेट चाहिए। व्हाइटस्पेस हटाने और गैर‑संख्यात्मक अक्षरों को फ़िल्टर करने से डाउनस्ट्रीम त्रुटियों से बचा जा सकता है। + +--- + +## Step 5: Recognize Text from Invoice – Full Script + +## चरण 5: इनवॉइस से टेक्स्ट पहचानें – पूर्ण स्क्रिप्ट + +सब कुछ एक साथ मिलाकर, यहाँ पूर्ण, तैयार‑चलाने‑योग्य स्क्रिप्ट है। इसे `extract_amount.py` के रूप में सेव करें और `python extract_amount.py` चलाएँ। + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Expected Output + +### अपेक्षित आउटपुट + +``` +Amount: 1,245.67 +``` + +यदि ROI गलत संरेखित है, तो आप `Amount: 1245.6S` जैसा कुछ देख सकते हैं—ध्यान दें stray “S” को। आयत के निर्देशांक को समायोजित करें और आउटपुट साफ़ दिखने तक पुनः चलाएँ। + +--- + +## Common Pitfalls & Edge Cases + +## सामान्य कठिनाइयाँ और किनारे के मामले + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI बहुत छोटा** | राशि का टेक्स्ट कट जाता है, जिससे आंशिक पहचान होती है। | `width`/`height` को लगभग 10‑20 % बढ़ाएँ और पुनः‑परीक्षण करें। | +| **गलत DPI** | कम‑रिज़ॉल्यूशन स्कैन (≤150 dpi) OCR की सटीकता घटाते हैं। | इमेज को लोड करने से पहले 300 dpi पर री‑सैंपल करें, या स्कैनर से उच्च DPI माँगें। | +| **एकाधिक मुद्राएँ** | रेगेक्स पहला संख्यात्मक समूह लेता है, जो इनवॉइस नंबर हो सकता है। | रेगेक्स को मुद्रा प्रतीकों (`$`, `€`, `£`) के सामने खोजने के लिए सुधारें। | +| **घुमाए हुए इनवॉइस** | OCR इंजन मानते हैं कि टेक्स्ट सीधा है; घुमे पेज पहचान बिगड़ते हैं। | ROI जोड़ने से पहले रोटेशन सुधार (`ocr_engine.rotate(90)`) लागू करें। | +| **पृष्ठभूमि में शोर** | छायाएँ या स्टैम्प मॉडल को भ्रमित करते हैं। | सरल थ्रेशोल्ड (`cv2.threshold`) या डिनॉइज़िंग फ़िल्टर से प्री‑प्रोसेस करें। | + +## Pro Tips for Real‑World Projects + +## वास्तविक‑दुनिया प्रोजेक्ट्स के लिए प्रो टिप्स + +- **बैच प्रोसेसिंग:** इनवॉइस के फ़ोल्डर पर लूप करें, ROI को डायनामिक रूप से (जैसे टेम्पलेट डिटेक्शन के आधार पर) गणना करें, और परिणाम CSV में सहेजें। +- **टेम्पलेट मिलान:** यदि आप कई इनवॉइस लेआउट संभालते हैं, तो `template_id → ROI coordinates` का JSON मानचित्र रखें। तेज़ लेआउट क्लासिफायर के आधार पर ROI बदलें। +- **समांतर निष्पादन:** कई OCR इंस्टेंस को एक साथ चलाने के लिए `concurrent.futures.ThreadPoolExecutor` का उपयोग करें—उच्च‑वॉल्यूम बैक‑ऑफ़िस पाइपलाइन के लिए उत्कृष्ट। +- **विश्वास फ़िल्टरिंग:** अधिकांश OCR परिणामों में एक confidence स्कोर होता है। थ्रेशोल्ड (जैसे 85 %) से नीचे के परिणामों को हटाएँ और मैन्युअल रिव्यू के लिए फ़्लैग करें। + +--- + +## Conclusion + +## निष्कर्ष + +हमने सब कुछ कवर किया है जो आपको **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, और अंत में **recognize text from invoice** करने के लिए चाहिए, ताकि क्लासिक **how to extract amount** सवाल का उत्तर मिल सके। स्क्रिप्ट कॉम्पैक्ट है, फिर भी विभिन्न दस्तावेज़ फ़ॉर्मेट, भाषाएँ, और OCR बैक‑एंड के साथ अनुकूलित की जा सकती है। + +अब जब आपने बुनियादी बातों में महारत हासिल कर ली है, तो वर्कफ़्लो को विस्तारित करने पर विचार करें: बारकोड स्कैनिंग जोड़ें, PDF पार्सर के साथ एकीकृत करें, या निकाली गई राशि को अकाउंटिंग API में पुश करें। संभावनाएँ असीमित हैं, और एक अच्छी‑परिभाषित ROI के साथ आप हमेशा तेज़, साफ़ परिणाम पाएँगे। + +यदि कोई समस्या आती है, तो नीचे टिप्पणी करें—हैप्पी OCRing! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + +## What Should You Learn Next? + +## आगे आप क्या सीखें? + +- [OCR में आयतें तैयार करके इमेज से टेक्स्ट निकालना कैसे करें](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Aspose.OCR डिटेक्ट एरिया मोड के साथ जावा में इमेज से टेक्स्ट निकालें](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [इमेज से टेक्स्ट निकालें – .NET के लिए Aspose.OCR के साथ 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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/hongkong/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..790f8042e --- /dev/null +++ b/ocr/hongkong/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-31 +description: 非同步 OCR 教學,示範如何在 Python 中結合 asyncio 使用 Aspose OCR 進行快速圖像文字擷取。一步一步學習非同步 + OCR 實作。 +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: zh-hant +og_description: 非同步 OCR 教學逐步說明如何在 Python 中使用 Aspose OCR 搭配 asyncio 進行高效的圖像文字提取。 +og_title: 非同步 OCR 教程 – Python asyncio 與 Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: 非同步 OCR 教學 – Python asyncio 與 Aspose OCR +url: /zh-hant/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR 教學 – Python asyncio 與 Aspose OCR + +有沒有想過如何在不阻塞應用程式的情況下執行光學字符辨識?在 **async OCR 教學** 中,你將會看到這正是透過 Python 的 `asyncio` 以及 Aspose OCR 函式庫實現的非阻塞文字擷取。 + +如果你一直卡在等待大型影像處理的過程,本指南將提供一個乾淨的非同步解決方案,讓你的事件迴圈持續運作。 + +在以下各節,我們將涵蓋所有必備內容:安裝函式庫、建立非同步輔助函式、處理結果,甚至還有快速擴充至多張影像的技巧。完成後,你就能將 **async OCR 教學** 輕鬆嵌入任何已使用 `asyncio` 的 Python 專案中。 + +## 需要的條件 + +* Python 3.9+(我們使用的 `asyncio` API 從 3.7 起已穩定) +* 有效的 Aspose OCR 授權或免費試用版(此函式庫純 Python,無原生二進位檔) +* 一個想要讀取的小型影像檔案(`.jpg`、`.png` 等),請放在已知的資料夾中 + +不需要其他外部工具;所有操作皆在純 Python 中執行。 + +## 步驟 1:安裝 Aspose OCR 套件 + +首先,從 PyPI 取得 Aspose OCR 套件。開啟終端機並執行以下指令: + +```bash +pip install aspose-ocr +``` + +> **專業提示:** 若你在虛擬環境中工作(強烈建議),請先啟動它。這樣可以讓相依套件彼此隔離,避免版本衝突。 + +## 步驟 2:非同步初始化 OCR 引擎 + +我們的 **async OCR 教學** 核心是一個非同步輔助函式。它會建立 `OcrEngine` 實例、載入影像,然後呼叫 `recognize_async()`。雖然引擎本身是同步的,但包裝方法會回傳可 await 的物件,讓事件迴圈保持回應。 + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**為什麼這樣做:** +*在輔助函式內部建立引擎可確保執行多個 OCR 工作時的執行緒安全。`await` 關鍵字會將控制權交還給事件迴圈,同時繁重的運算在函式庫的內部執行緒池中執行。* + +## 步驟 3:從非同步 main 函式驅動輔助函式 + +現在我們需要一個小型的 `main()` 協程,呼叫 `async_ocr()` 並印出結果。這與 `asyncio` 腳本的典型入口點相呼應。 + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**背後發生了什麼?** +`asyncio.run()` 會建立一個全新的事件迴圈,排程 `main()`,並在 `main()` 完成後乾淨地關閉迴圈。此模式是 Python 3.7+ 推薦的非同步程式啟動方式。 + +## 步驟 4:測試完整腳本 + +將上述兩個程式碼區塊儲存為同一個檔案,例如 `async_ocr_demo.py`。在命令列執行: + +```bash +python async_ocr_demo.py +``` + +如果環境設定正確,你應該會看到類似以下的輸出: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +實際輸出會依 `photo.jpg` 的內容而異。重點是腳本會快速結束,即使影像很大,因為 OCR 工作在背景執行。 + +## 步驟 5:擴充規模 – 同時處理多張影像 + +常見的後續問題是,*「我能否在不為每個檔案啟動新程序的情況下批次 OCR?」* 當然可以。因為我們的輔助函式是完整的非同步,我們可以使用 `asyncio.gather()` 收集多個協程: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**為什麼這會有效:** `asyncio.gather()` 會一次排程所有 OCR 任務。底層的 Aspose OCR 函式庫仍使用自己的執行緒池,但從 Python 的角度看,一切仍保持非阻塞,讓你在單一次同步呼叫所需時間內處理數十張影像。 + +## 步驟 6:優雅地處理錯誤 + +當你處理外部檔案時,必然會遇到檔案遺失、影像損毀或授權問題。將 OCR 呼叫包在 `try/except` 區塊中,以保持事件迴圈持續運作: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +現在 `batch_ocr()` 可以改為呼叫 `safe_async_ocr`,確保單一壞檔案不會中止整個批次。 + +## 視覺概覽 + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR 教學流程圖,顯示 async_ocr 輔助函式、事件迴圈與 Aspose OCR 引擎"} + +上圖視覺化了流程:事件迴圈 → `async_ocr` → `OcrEngine` → 背景執行緒 → 結果回傳至迴圈。 + +## 常見陷阱與避免方法 + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **在輔助函式內的阻塞 I/O** | 不小心使用未加 `await` 的 `open()` 會阻塞迴圈。 | 使用 `aiofiles` 讀取檔案,或讓 `engine.load_image` 處理(它已是非阻塞的)。 | +| **在多個協程間重複使用單一 `OcrEngine`** | 此引擎非執行緒安全;同時呼叫可能會破壞狀態。 | 如示範,在每次 `async_ocr` 呼叫時建立全新引擎。 | +| **缺少授權** | Aspose OCR 於執行時拋出授權相關例外。 | 提前註冊授權 (`OcrEngine.set_license("license.json")`)。 | +| **大型影像導致記憶體激增** | 函式庫會將整張影像載入記憶體。 | 若記憶體受限,請先縮小影像尺寸再進行 OCR。 | + +## 重點回顧:我們完成了什麼 + +在本 **async OCR 教學** 中,我們: + +1. 安裝 Aspose OCR 函式庫。 +2. 建立一個 `async_ocr` 輔助函式,使辨識在不阻塞的情況下執行。 +3. 從乾淨的 `asyncio` 入口點執行輔助函式。 +4. 示範使用 `asyncio.gather` 進行批次處理。 +5. 加入錯誤處理與最佳實踐建議。 + +以上全部皆為純 Python,因而可直接嵌入 Web 伺服器、CLI 工具或資料管線,而無需重寫既有的非同步程式碼。 + +## 往後步驟與相關主題 + +* **非同步影像前處理** – 使用 `aiohttp` 同時下載影像再進行 OCR。 +* **儲存 OCR 結果** – 結合本教學與如 `asyncpg` 的非同步資料庫驅動,以存取 PostgreSQL。 +* **效能調校** – 若函式庫提供此選項,可嘗試 `engine.recognize_async(max_threads=4)`。 +* **其他 OCR 引擎** – 將 Aspose OCR 與 Tesseract 的非同步包裝器做成本效益比較。 + +歡迎自行實驗:嘗試輸入 PDF、調整語言設定,或將結果串接至聊天機器人。只要有堅實的 **async OCR 教學** 基礎,想像空間無限。 + +祝程式開發順利,文字擷取永遠快速! + +## 接下來該學什麼? + +- [使用 Aspose OCR 從影像擷取文字 – 步驟指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR 教學 – 光學字符辨識](/ocr/english/) +- [如何使用 Aspose.OCR 以語言 OCR 影像文字](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/hongkong/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..80ebdba31 --- /dev/null +++ b/ocr/hongkong/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-05-31 +description: 在 OCR 中輕鬆實現自動語言偵測。了解如何載入影像 OCR、啟用自動語言偵測,並在幾個步驟內辨識文字影像。 +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: zh-hant +og_description: 在 OCR 中的自動語言偵測變得簡單。請跟隨本一步一步教學,啟用自動語言偵測、載入影像 OCR,並辨識文字影像。 +og_title: 使用 OCR 的自動語言偵測 – 完整 Python 指南 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: 使用 OCR 的自動語言偵測 – 完整 Python 指南 +url: /zh-hant/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 自動語言偵測與 OCR – 完整 Python 指南 + +有沒有想過如何讓 OCR 引擎 *猜測* 掃描文件的語言,而不需要你事先告訴它要找什麼?這正是 **automatic language detection** 所做的事,當你處理多語言 PDF、街道標誌照片,或任何混合文字的影像時,它會徹底改變遊戲規則。 + +在本教學中,我們將逐步示範一個實作範例,說明如何使用 Python 風格的 API **enable auto language detection**、**load image OCR** 與 **recognize text image**。完成後,你將擁有一個獨立的腳本,能同時印出偵測到的語言代碼與擷取的文字——不需要手動設定語言。 + +## 你將學會 + +- 如何建立 OCR 引擎實例並開啟 **automatic language detection**。 +- 從磁碟載入 **load image OCR** 的確切步驟。 +- 如何呼叫引擎的 `recognize()` 方法,並取得包含語言代碼的結果。 +- 處理低解析度影像或不支援文字等邊緣情況的技巧。 + +不需要任何多語言 OCR 的先前經驗;只要有基本的 Python 環境與一張影像檔即可。 + +--- + +## 前置條件 + +在開始之前,請確保你已具備以下條件: + +1. 已安裝 Python 3.8+(任何較新的版本皆可)。 +2. 提供 `OcrEngine`、`LanguageAutoDetectMode` 等功能的 OCR 函式庫——本教學假設使用名為 `myocr` 的虛構套件。使用以下指令安裝: + + ```bash + pip install myocr + ``` + +3. 一張影像檔 (`multilingual_sample.png`),其中包含至少兩種不同語言的文字。 +4. 一點好奇心——即使你從未接觸過 OCR,也不必擔心;程式碼刻意寫得很直觀。 + +## 步驟 1:啟用自動語言偵測 + +首先,你需要告訴引擎它應該 *自行判斷* 語言。這時 **automatic language detection** 旗標就派上用場了。 + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **為什麼這很重要:** +> 當設定 `AUTO_DETECT` 後,引擎會在進行重量級字元辨識之前,先對影像執行輕量級語言分類器。這表示你不必猜測文字是英文、俄文、法文或其他任何組合。引擎會自動為影像的每個區域挑選最適合的語言模型。 + +## 步驟 2:載入影像 OCR + +既然引擎已知道應自動偵測語言,我們就需要提供它要處理的資料。**load image OCR** 步驟會讀取位圖並準備內部緩衝區。 + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **專業提示:** +> 若影像解析度超過 300 dpi,建議將其縮小至約 150‑200 dpi。過多的細節實際上會 *減慢* 語言偵測階段,且不會提升準確度。 + +## 步驟 3:辨識影像文字 + +在影像已載入記憶體且語言偵測已啟用的情況下,最後一步是請引擎執行 **recognize text image**。這一次呼叫會完成所有繁重的工作。 + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` 是一個物件,通常至少包含兩個屬性: + +| Attribute | Description | +|-----------|-------------| +| `language` | 偵測到的語言之 ISO‑639‑1 代碼(例如 `"en"` 代表英文)。 | +| `text` | 影像的純文字轉錄。 | + +## 步驟 4:取得偵測到的語言與擷取的文字 + +現在只要把引擎發現的結果印出即可。這展示了 **detect language OCR** 功能的實際運作。 + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**範例輸出** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **如果引擎回傳 `None` 會怎樣?** +> 這通常表示影像過於模糊或文字太小(< 8 pt)。請嘗試提升對比度或使用更高解析度的來源。 + +## 完整範例(端對端啟用自動語言偵測) + +將所有步驟整合起來,以下是一個可直接執行的腳本,涵蓋 **enable auto language detection**、**load image OCR**、**recognize text image** 與 **detect language OCR**。 + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +將其儲存為 `automatic_language_detection_ocr.py`,將 `YOUR_DIRECTORY` 替換為存放 PNG 的資料夾路徑,然後執行: + +```bash +python automatic_language_detection_ocr.py +``` + +你應該會看到語言代碼,接著是擷取的文字,與上方的範例輸出相同。 + +## 處理常見邊緣情況 + +| Situation | Suggested Fix | +|-----------|----------------| +| **非常低解析度影像**(低於 100 dpi) | 在載入前使用雙三次濾波器放大,或取得更高解析度的來源。 | +| **單一影像中混合多種文字**(例如 English + Cyrillic) | 引擎通常會將頁面分割成區域;若發現偵測錯誤,可設定 `engine.enable_region_split = True`。 | +| **不支援的語言** | 確認 OCR 函式庫是否提供該文字的語言套件;可能需要下載額外模型。 | +| **大量批次處理** | 僅初始化一次引擎,然後在多次 `load_image` / `recognize` 循環中重複使用,以避免重複載入模型。 | + +## 視覺概覽 + +![自動語言偵測範例輸出](https://example.com/auto-lang-detect.png "自動語言偵測") + +*替代文字:* 顯示偵測到的語言代碼與擷取的多語言文字之自動語言偵測範例輸出。 + +## 結論 + +我們剛剛從頭到尾說明了 **automatic language detection**——建立引擎、啟用自動語言偵測、載入 OCR 影像、辨識文字,最後取得偵測到的語言。這個端對端流程讓你在處理多語言文件時,不必每次手動設定語言模型。 + +如果你已經準備好進一步推進,請考慮: + +- **批次處理** 數百張影像,使用迴圈重複使用相同的 `OcrEngine` 實例。 +- **後處理** 擷取的文字,使用拼字檢查或語言特定的斷詞器。 +- **整合** 此腳本至接受使用者上傳並回傳包含 `language` 與 `text` 欄位之 JSON 的網路服務。 + +隨意嘗試不同的影像格式(`.jpg`、`.tif`),觀察偵測準確度的變化。如有問題或遇到難以辨識的影像,歡迎在下方留言——祝編程愉快! + +## 接下來該學什麼? + +- [如何使用 Aspose.OCR 進行語言 OCR 影像文字](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [使用 Aspose.OCR 於 C# 抽取影像文字並選擇語言](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [使用 Aspose OCR 辨識多語言影像文字](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ab1659436 --- /dev/null +++ b/ocr/hongkong/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-31 +description: 學習如何使用 Python 透過批量圖像轉文字腳本將圖像轉換為文字。使用 Aspose.OCR 在幾分鐘內識別掃描圖像中的文字。 +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: zh-hant +og_description: 即時將圖片轉換為文字(Python)。本指南示範批量圖片轉文字的轉換方式,以及如何使用 Aspose.OCR 從掃描圖像中辨識文字。 +og_title: 將圖像轉換為文字 Python – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: 將圖像轉換為文字(Python)— 完整逐步指南 +url: /zh-hant/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 轉換圖片為文字 Python – 完整步驟指南 + +有沒有想過 **convert images to text python**,卻不想四處搜尋各式各樣的函式庫?你並不是唯一有這個困擾的人。無論是將舊收據數位化、從掃描發票中擷取資料,或是建構可搜尋的 PDF 檔案庫,將圖片轉成純文字檔案都是許多開發者的日常工作。 + +在本教學中,我們將一步步示範 **bulk image to text conversion** 工作流程,從掃描圖片中辨識文字、將每個結果儲存為單獨的 `.txt` 檔案,且只需要幾行 Python 程式碼。無需尋找不明的 API——Aspose.OCR 會負責繁重的工作,我們會告訴你如何正確串接。 + +## 你將學到什麼 + +- 如何安裝與設定 Aspose.OCR for Python 套件。 +- 使用 `BatchOcrEngine` 進行 **convert images to text python** 的完整程式碼。 +- 處理常見問題(如不支援的格式或檔案損毀)的技巧。 +- 驗證 **recognize text from scanned images** 步驟是否成功的方法。 + +完成本指南後,你將擁有一個可一次處理上千張圖片的即時執行腳本——非常適合任何批次處理情境。 + +## 前置條件 + +- 已在機器上安裝 Python 3.8+。 +- 一個放有欲轉換為文字的圖片檔案(PNG、JPEG、TIFF 等)的資料夾。 +- 有效的 Aspose Cloud 帳號或免費試用授權(免費等級足以測試)。 + +只要具備以上條件,讓我們開始吧。 + +--- + +## Step 1 – 設定 Python 環境 + +在撰寫任何 OCR 程式碼之前,請先確保你在乾淨的虛擬環境中工作。這樣可以隔離相依性,避免版本衝突。 + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **專業小技巧:** 請保持專案目錄整潔——建立一個名為 `ocr_project` 的子資料夾,並將腳本放在其中。之後處理路徑時會更方便。 + +## Step 2 – 安裝 Aspose.OCR for Python + +Aspose.OCR 為商業函式庫,但它提供可從 PyPI 取得的免費 NuGet 風格 wheel。請在已啟動的虛擬環境中執行以下指令: + +```bash +pip install aspose-ocr +``` + +如果遇到權限錯誤,可加入 `--user` 參數,或在 Linux/macOS 上以 `sudo` 執行(僅限這兩個平台)。安裝完成後,你應該會看到類似以下的訊息: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **為什麼選擇 Aspose?** 與許多開源 OCR 工具不同,Aspose.OCR 內建支援 **bulk image to text conversion**,且能處理多種圖片格式而不需額外設定。它還提供 `BatchOcrEngine` 類別,讓 **convert images to text python** 任務只需一行程式碼即可完成。 + +## Step 3 – 使用 Batch OCR 進行 Convert Images to Text Python + +接下來就是本教學的核心。以下是一個可直接執行的腳本,功能包括: + +1. 匯入 OCR 引擎類別。 +2. 建立 `BatchOcrEngine` 實例。 +3. 指定輸入圖片資料夾。 +4. 設定輸出文字檔案的資料夾。 +5. 呼叫 `recognize()` 方法,逐一 **recognize text from scanned images**。 + +將以下內容儲存為 `batch_ocr.py`,放在專案資料夾內: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### 工作原理 + +- **`BatchOcrEngine`** 包裝了普通的 `OcrEngine`,並加入資料夾層級的協調功能,正好符合你想要 **convert images to text python** 批次處理的需求。 +- `input_folder` 屬性告訴引擎要從哪裡搜尋來源圖片。它會自動掃描目錄,將所有支援的檔案類型排入佇列。 +- `output_folder` 屬性決定每個 `.txt` 檔案的輸出位置。引擎會保留原始檔名,例如 `receipt1.png` 會變成 `receipt1.txt`。 +- 呼叫 `recognize()` 後,內部迴圈會載入每張圖片、執行 OCR,並寫入結果。此方法會阻塞直至所有檔案處理完畢,方便你在之後接續其他動作(例如壓縮輸出資料夾)。 + +#### 預期輸出 + +執行腳本時: + +```bash +python batch_ocr.py +``` + +你會看到: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +在 `output_texts` 資料夾中,你會找到每張圖片對應的純文字檔。用文字編輯器開啟任一檔案,即可看到 OCR 的原始結果——通常與原本印刷文字相當接近。 + +## Step 4 – 驗證結果與錯誤處理 + +即使是最好的 OCR 引擎,也可能在低解析度掃描或頁面嚴重傾斜時失敗。以下提供一個快速檢查輸出並記錄失敗檔案的方法。 + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**為什麼要加這段?** +- 它會捕捉引擎靜默產生空字串的情況(在無法辨識的圖片中很常見)。 +- 它會列出有問題的檔案,讓你可以手動檢查或使用不同設定重新執行(例如調整 `OcrEngine.preprocess` 選項)。 + +### 邊緣案例與調整 + +| 情境 | 建議解決方式 | +|-----------|----------------| +| 圖片旋轉了 90° | 設定 `batch_engine.ocr_engine.rotation_correction = True`。 | +| 多語言(英文 + 法文) | 在 `recognize()` 前加入 `batch_engine.ocr_engine.language = "eng+fra"`。 | +| 先將大型 PDF 轉為圖片 | 先把 PDF 拆成單頁圖片,再將資料夾交給 batch engine。 | +| 大批次處理時記憶體不足 | 改為分批處理子資料夾,或提升 `batch_engine.max_memory_usage`。 | + +## Step 5 – 自動化整個工作流程(可選) + +如果需要每日夜間執行此轉換,可將腳本包裝成簡易的 shell 或 Windows 批次檔,並使用 `cron`(Linux/macOS)或工作排程器(Windows)排程。以下是一個適用於類 Unix 系統的最小 `run_ocr.sh`: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +將檔案設為可執行 (`chmod +x run_ocr.sh`) 後,加入 cron 任務: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +此設定會在每天凌晨 2 點執行轉換,並將所有輸出寫入日誌供日後檢查。 + +--- + +## 結論 + +現在你已掌握使用 Aspose.OCR 的 `BatchOcrEngine` 進行 **convert images to text python** 的可靠、可投入生產環境的方法。此腳本支援 **bulk image to text conversion**,能將每個結果優雅地寫入獨立檔案,並包含驗證步驟,確保你真的 **recognize text from scanned images** 正確無誤。 + +接下來你可以: + +- 嘗試不同的 OCR 設定(語言套件、去斜、降噪)。 +- 將產生的文字導入 Elasticsearch 等搜尋引擎,實現即時全文搜尋。 +- 結合 PDF 轉圖片工具,一次處理掃描 PDF。 + +有任何問題,或在特定檔案類型上遇到卡關?歡迎在下方留言,我們一起排除故障。祝開發順利,願你的 OCR 執行快速且零錯誤! + +## 接下來該學什麼? + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..54b59c39f --- /dev/null +++ b/ocr/hongkong/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: 在 Python 中建立授權實例並輕鬆設定授權路徑。了解如何使用清晰的程式碼範例設定 Aspose OCR 授權。 +draft: false +keywords: +- create license instance +- configure license path +language: zh-hant +og_description: 在 Python 中建立授權實例並即時設定授權路徑。跟隨本教學,放心啟用 Aspose OCR。 +og_title: 在 Python 中建立授權實例 – 完整設定指南 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: 在 Python 中建立授權實例 – 逐步指南 +url: /zh-hant/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中建立授權實例 – 完整設定指南 + +需要在 Python 中 **create license instance** Aspose OCR 嗎?您來對地方了。在本教學中,我們還會示範如何 **configure license path**,讓 SDK 知道 `.lic` 檔案的所在位置。 + +如果您曾經盯著空白腳本,懷疑為什麼 OCR 引擎一直抱怨未授權的產品,您並不孤單。通常只需要幾行程式碼——只要知道正確放置的位置。完成本指南後,您將擁有完整授權的 Aspose OCR 環境,能順利辨識文字、影像與 PDF。 + +## 您將學習到 + +- 如何使用 `asposeocr` 套件 **create license instance**。 +- 在開發與正式環境中 **configure license path** 的正確做法。 +- 常見陷阱(檔案遺失、權限錯誤)以及避免方式。 +- 一個完整、可直接執行的腳本,您可以隨時放入任何專案。 + +不需要任何 Aspose OCR 的先前經驗,只要有可運作的 Python 3 環境與有效的授權檔案即可。 + +--- + +## 步驟 1:安裝 Aspose OCR Python 套件 + +在我們能 **create license instance** 之前,必須先安裝此函式庫。打開終端機並執行: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** 如果您使用虛擬環境(強烈建議),請先啟動它。這樣可以保持相依性整潔,避免版本衝突。 + +## 步驟 2:匯入 License 類別 + +現在 SDK 已可使用,腳本的第一行應該匯入 `License` 類別。這個物件就是我們用來 **create license instance** 的。 + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +為什麼要立刻匯入?因為必須在任何 OCR 呼叫 **之前** 實例化 `License` 物件;否則一旦嘗試處理影像,SDK 會拋出授權錯誤。 + +## 步驟 3:建立授權實例 + +這就是您一直在等的時刻——實際 **create license instance**。雖然只是一行程式碼,但前後文很重要。 + +```python +# Step 3: Create a License instance +license = License() +``` + +變數 `license` 現在持有一個物件,負責控制目前 Python 行程的所有授權行為。可以把它想像成守門員,告訴 Aspose OCR:「嘿,我有執行的權限。」 + +## 步驟 4:設定授權路徑 + +實例準備好後,我們需要指向 `.lic` 檔案。這就是 **configure license path** 發揮作用的地方。將佔位符替換為授權檔案的絕對路徑。 + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +需要注意的幾點: + +1. **原始字串 (`r"…"`)** 可防止 Windows 上的反斜線被當作跳脫字元。 +2. 使用 **絕對路徑** 可避免腳本從不同工作目錄啟動時產生混淆。 +3. 若偏好相對路徑(例如將授權檔案與專案一起打包),請確保相對基礎是腳本所在位置,而非當前終端機目錄。 + +### 處理檔案遺失 + +如果路徑錯誤或檔案無法讀取,`set_license` 會拋出例外。將呼叫包在 `try/except` 區塊中,以提供友善的錯誤訊息: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +此程式碼片段安全地 **configures license path**,並精確告訴您哪裡出錯——不會出現神祕的堆疊追蹤。 + +## 步驟 5:驗證授權已啟用 + +快速的 sanity check 能在之後節省大量除錯時間。呼叫 `set_license` 後,嘗試執行簡單的 OCR 操作。若授權有效,SDK 會處理影像而不拋出授權錯誤。 + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +如果看到辨識出的文字被印出,恭喜您——已成功 **create license instance** 並 **configure license path**。若出現授權例外,請再次檢查路徑與檔案權限。 + +## 邊緣情況與最佳實踐 + +| 情境 | 處理方式 | +|-----------|------------| +| **License file lives in a network share** | 將共享磁碟映射至磁碟代號,或使用 UNC 路徑 (`\\server\share\license.lic`)。確保 Python 行程具有讀取權限。 | +| **Running inside a Docker container** | 將 `.lic` 檔案複製到映像檔內,並以絕對路徑(如 `/app/license/Aspose.OCR.Java.lic`)引用。 | +| **Multiple Python interpreters** (e.g., conda envs) | 每個環境只需安裝一次授權檔,或保留在集中位置,讓各個直譯器指向同一檔案。 | +| **License file missing at runtime** | 優雅地回退至試用模式(若支援),或以清晰的日誌訊息中止執行。 | + +### 常見陷阱 + +- **Using forward slashes on Windows** – Python 可接受,但某些舊版 SDK 可能會誤判。請使用原始字串或雙反斜線。 +- **Forgot to import `License`** – 腳本會因 `NameError` 而崩潰。務必在實例化前先匯入。 +- **Calling `set_license` after OCR methods** – SDK 會在首次使用時檢查授權,所以必須 **先** 設定路徑。 + +## 完整範例 + +以下是一個完整腳本,將所有步驟串接起來。將其儲存為 `ocr_setup.py`,然後在命令列執行。 + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**預期輸出**(假設使用有效的影像): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +如果找不到授權檔,您會看到清晰的錯誤訊息,而不是神祕的 “License not found” 例外。 + +--- + +## 結論 + +您現在已完全掌握在 Python 中 **create license instance** 以及為 Aspose OCR SDK **configure license path** 的方法。步驟簡單明瞭:安裝套件、匯入 `License`、實例化、指向 `.lic` 檔案,最後以小型 OCR 測試驗證。 + +有了這些知識,您可以將 OCR 功能嵌入 Web 服務、桌面應用或自動化流水線,而不會因授權問題卡關。接下來,建議探索進階 OCR 設定——語言套件、影像前處理或批次處理——這些都建立在您剛完成的堅實基礎上。 + +對部署、Docker 或多授權處理有任何疑問嗎?歡迎留言,祝 coding 愉快! + +## 接下來您可以學習什麼? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..2f0f61515 --- /dev/null +++ b/ocr/hongkong/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: 使用 Python OCR 從掃描影像建立可搜尋的 PDF。學習如何將掃描影像 PDF 轉換、將 TIFF 轉為 PDF,並在數分鐘內加入 + OCR 文字層。 +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: zh-hant +og_description: 即時建立可搜尋的 PDF。本指南示範如何使用單一 Python 程式執行 OCR、將掃描圖像 PDF 轉換,並加入 OCR 文字層。 +og_title: 使用 Python 建立可搜尋 PDF – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: 使用 Python 建立可搜尋的 PDF – 步驟指南 +url: /zh-hant/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Python 建立可搜尋 PDF – 步驟指南 + +有沒有想過 **如何從掃描頁面建立可搜尋 PDF**,卻不需要切換好幾個工具?你並不孤單。在許多辦公流程中,掃描的 TIFF 或 JPEG 會被放到共享磁碟,接下來的人只能手動複製貼上文字——既痛苦又容易出錯,還浪費時間。 + +在本教學中,我們將一步步示範一個乾淨、程式化的解決方案,讓你 **轉換掃描影像 PDF**、**將 TIFF 轉成 PDF**,以及 **加入 OCR 文字層**,一次完成。完成後,你將擁有一支可直接執行 OCR、嵌入隱藏文字,並輸出可搜尋 PDF 的腳本,隨時可以索引、搜尋或自信地分享。 + +## 需要的環境 + +- Python 3.9+(任何較新的版本皆可) +- `aspose-ocr` 與 `aspose-pdf` 套件(使用 `pip install aspose-ocr aspose-pdf` 安裝) +- 一個掃描的影像檔(`.tif`、`.png`、`.jpg`,或僅含影像的 PDF 頁面) +- 一點點記憶體(OCR 引擎相當輕量,筆記型電腦也能應付) + +> **小技巧:** 若你使用 Windows,最簡單的取得套件方式是以系統管理員身分在 PowerShell 視窗執行上述指令。 + +```bash +pip install aspose-ocr aspose-pdf +``` + +現在前置作業已完成,讓我們進入程式碼。 + +## 步驟 1:建立 OCR 引擎實例 – *create searchable pdf* + +首先,我們要啟動 OCR 引擎。它就像大腦,會讀取每個像素並轉換成文字。 + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **為什麼這很重要:** 只初始化一次引擎即可降低記憶體使用量。如果在迴圈裡每頁都呼叫 `OcrEngine()`,資源很快就會耗盡。 + +## 步驟 2:載入掃描影像 – *convert tiff to pdf* & *convert scanned image pdf* + +接著,將引擎指向要處理的檔案。API 接受任何點陣圖,所以 TIFF 與 JPEG 同樣適用。 + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +如果你手上有只包含掃描影像的 PDF,也可以使用 `load_image`,Aspose 會自動擷取第一頁。 + +## 步驟 3:設定 PDF 儲存選項 – *add OCR text layer* + +在這裡我們設定最終 PDF 的樣貌。關鍵的旗標是 `create_searchable_pdf`;將它設為 `True` 即告訴函式庫嵌入一層與視覺內容對應的隱形文字層。 + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **文字層的作用:** 當你在 Adobe Reader 開啟產生的檔案並嘗試選取文字時,會看到隱藏的字元。搜尋引擎也能索引它們——非常適合合規或保存需求。 + +## 步驟 4:執行 OCR 並儲存 – *how to run OCR* in a single call + +現在魔法發生了。只要一次方法呼叫,就會執行辨識引擎並將可搜尋 PDF 寫入磁碟。 + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize` 方法會回傳一個狀態物件,你可以檢查是否有錯誤,但對於大多數簡單情境,上述單行呼叫已足夠。 + +### 預期輸出 + +執行腳本時會印出: + +``` +PDF saved as searchable PDF. +``` + +若開啟 `scanned_page_searchable.pdf`,你會發現可以選取文字、複製貼上,甚至使用 `Ctrl+F` 搜尋。這正是 **create searchable pdf** 工作流程的標誌。 + +## 完整範例腳本 + +以下是可直接執行的完整腳本。只要把佔位路徑換成實際檔案位置即可。 + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +將檔案儲存為 `create_searchable_pdf.py` 後執行: + +```bash +python create_searchable_pdf.py +``` + +## 常見問題與特殊情況 + +### 1️⃣ 可以處理多頁 PDF 嗎? + +可以。使用 `ocr_engine.load_image("file.pdf")` 後,搭配 `ocr_engine.recognize(pdf_save_options, page_number)` 於每一頁迴圈。函式庫會自動產生多頁的可搜尋 PDF。 + +### 2️⃣ 若來源檔案是高解析度 TIFF(300 dpi 以上)怎麼辦? + +較高 DPI 能提升 OCR 正確率,但也會佔用更多記憶體。若遭遇 `MemoryError`,請先將影像縮小: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ 如何變更 OCR 的語言? + +在載入影像前,設定引擎的 `language` 屬性: + +```python +ocr_engine.language = "fra" # French +``` + +完整的語言代碼清單可參考 Aspose 官方文件。 + +### 4️⃣ 若我要保留原始影像品質? + +`PdfSaveOptions` 類別提供 `compression` 屬性。將其設為 `PdfCompression.None` 即可完整保留點陣資料。 + +```python +pdf_save_options.compression = "None" +``` + +## 產品化部署小技巧 + +- **批次處理:** 將核心邏輯封裝成接受檔案路徑清單的函式,並將每筆成功或失敗寫入 CSV,以作稽核。 +- **平行執行:** 使用 `concurrent.futures.ThreadPoolExecutor` 在多核心上同時執行 OCR。記得每個執行緒都需要自己的 `OcrEngine` 實例。 +- **安全性:** 若處理機密文件,請在沙盒環境執行腳本,並在處理完畢後立即刪除暫存檔。 + +## 結論 + +現在你已掌握如何使用簡潔的 Python 腳本 **建立可搜尋 PDF**,只要初始化 OCR 引擎、載入 TIFF(或任何點陣圖)、設定 `PdfSaveOptions` 以 **add OCR text layer**,最後呼叫 `recognize`,整個 **convert scanned image pdf** 與 **convert TIFF to PDF** 流程即可一次完成、可重複執行。 + +接下來的步驟是什麼?可以把此腳本與檔案監控程式結合,讓任何新掃描的檔案一放入資料夾就自動變成可搜尋的 PDF。或是嘗試不同的 OCR 語言,以支援多語言檔案庫。只要結合 OCR 與 PDF 產生,想像空間無限。 + +對 **how to run OCR** 在其他語言或框架有更多疑問嗎?歡迎在下方留言,祝編程愉快! + +![掃描影像 → OCR 引擎 → 可搜尋 PDF(create searchable pdf)流程圖](searchable-pdf-flow.png "建立可搜尋 PDF 流程圖") + + +## 接下來該學什麼? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/hongkong/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..cbb794e94 --- /dev/null +++ b/ocr/hongkong/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-31 +description: 使用 Python 透過影像前處理提升 OCR 準確度。學習如何從影像檔案提取文字、辨識 PNG 圖片中的文字,並提升結果表現。 +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: zh-hant +og_description: 透過對文字進行影像前處理,在 Python 中提升 OCR 準確度。跟隨本指南,即可輕鬆從影像檔案提取文字,並辨識 PNG 中的文字。 +og_title: 提升 Python OCR 準確度 – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: 提升 Python OCR 準確度 – 完整逐步指南 +url: /zh-hant/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 提升 Python OCR 準確度 – 完整逐步指南 + +有沒有嘗試過 **提升 OCR 準確度**,結果卻得到一堆亂碼?你並不是唯一遇到這種情況的人。大多數開發者在原始影像噪點太多、傾斜或對比度低時,都會卡住。好消息是,只要使用幾個前處理技巧,就能把模糊的螢幕截圖變成乾淨、機器可讀的文字。 + +在本教學中,我們將示範一個 **為 OCR 前處理影像** 的真實案例,執行辨識引擎,最後 **從影像中擷取文字**(以 PNG 為例)。完成後,你將清楚知道如何 **從 PNG 辨識文字**,並擁有一段可直接套用到任何專案的可重用程式碼片段。 + +## 你將學到 + +- 為什麼影像前處理對 OCR 引擎至關重要 +- 哪些前處理模式(去噪、去斜)能帶來最大提升 +- 如何在 Python 中配置 `OcrEngine` 實例 +- 完整、可直接執行的腳本,**從影像中擷取文字** +- 處理旋轉掃描或低解析度圖片等邊緣案例的技巧 + +不需要除 OCR SDK 之外的額外函式庫,只要有 Python 3.8+ 與一張想要讀取的 PNG 影像即可。 + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Improve OCR accuracy workflow") + +*Alt text: 展示提升 OCR 準確度工作流程的圖示,說明前處理與辨識步驟。* + +## 前置條件 + +- 已安裝 Python 3.8 或更新版本 +- 取得提供 `OcrEngine`、`OcrEngineSettings` 與 `ImagePreprocessMode` 的 OCR SDK(以下程式碼使用通用 API;如有需要請改為供應商的類別) +- 一張 PNG 影像(`input.png`),放在可參照的資料夾內 + +如果你使用虛擬環境,現在就啟動它——不需要特別的設定,只要執行 `python -m venv venv && source venv/bin/activate` 即可。 + +--- + +## 步驟 1:建立 OCR 引擎實例 – 開始提升 OCR 準確度 + +首先需要一個 OCR 引擎物件。它就像大腦,之後會讀取像素並輸出文字。 + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +為什麼這很重要:沒有引擎就無法套用任何前處理,原始影像會直接送給辨識器——通常是準確度最差的情況。 + +--- + +## 步驟 2:載入目標 PNG – 為 **從 PNG 辨識文字** 做好準備 + +接著告訴引擎要處理哪個檔案。PNG 為無損格式,已經比 JPEG 多了一點優勢。 + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +如果影像放在其他位置,只要調整路徑即可。引擎支援任何相容格式,但 PNG 常能保留文字邊緣的細節。 + +--- + +## 步驟 3:設定前處理 – 為 OCR 前處理影像 + +這裡就是魔法發生的地方。我們建立設定物件,開啟去噪以消除斑點,並啟用去斜讓傾斜的文字自動校正。 + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### 為什麼同時使用去噪 + 去斜? + +- **去噪**:隨機像素雜訊會干擾模式匹配演算法。移除雜訊可讓字母更銳利。 +- **去斜**:即使只有 2 度的傾斜,也會大幅降低信心分數。去斜會校正基線,讓辨識器更可靠地匹配字型。 + +如果你的影像特別暗,還可以嘗試加入其他旗標(例如 `ImagePreprocessMode.CONTRAST_ENHANCE`)。SDK 文件通常會列出所有可用模式。 + +--- + +## 步驟 4:將設定套用至引擎 – 把前處理綁定到 OCR + +把設定物件指派給引擎,讓下一次辨識時會使用我們剛剛定義的轉換。 + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +若跳過此步驟,引擎會回退到預設(通常是「不做前處理」),導致 **OCR 準確度下降**。 + +--- + +## 步驟 5:執行辨識程序 – **從影像中擷取文字** + +所有設定完成後,我們終於請引擎執行工作。此呼叫為同步,會回傳包含辨識結果字串的物件。 + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +在背後,引擎會依序: + +1. 將 PNG 載入記憶體 +2. 依設定套用去噪與去斜 +3. 執行神經網路或傳統模式匹配 +4. 把輸出封裝成 `recognition_result` + +--- + +## 步驟 6:輸出辨識文字 – 驗證提升效果 + +把擷取出的字串印出來。實際應用中,你可能會寫入檔案、資料庫,或傳給其他服務。 + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### 預期輸出 + +如果影像內的句子是 “Hello, OCR World!” 則應看到: + +``` +Hello, OCR World! +``` + +可以看到文字乾淨整齊——沒有雜訊或斷裂的字元。這正是正確 **影像前處理** 所帶來的效果。 + +--- + +## 專業技巧與邊緣案例 + +| 情境 | 調整方式 | 原因 | +|-----------|----------------|-----| +| 非常低解析度的 PNG(≤ 72 dpi) | 若支援,加入 `ImagePreprocessMode.SUPER_RESOLUTION` | 放大後可提供辨識器更多像素供分析 | +| 文字旋轉 > 5° | 提高去斜容忍度或使用 `Pillow` 先手動旋轉後再送入引擎 | 大角度可能會跳過自動去斜 | +| 背景圖案繁雜 | 開啟 `ImagePreprocessMode.BACKGROUND_REMOVAL` | 去除非文字雜訊,避免誤讀 | +| 多語言文件 | 設定 `ocr_engine.language = "eng+spa"`(或類似) | 引擎會載入正確的字元集,提升整體準確度 | + +記住,**提升 OCR 準確度** 並非一刀切;你可能需要針對自己的資料集不斷調整前處理旗標。 + +--- + +## 完整腳本 – 直接複製貼上使用 + +以下是結合所有步驟的完整、可執行範例。將它存為 `improve_ocr_accuracy.py`,再以 `python improve_ocr_accuracy.py` 執行。 + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +執行後觀察主控台,你會立即看到 **從影像中擷取文字** 的結果。若輸出不理想,請依照「專業技巧」表格調整 `preprocess_mode` 旗標。 + +--- + +## 結論 + +我們剛剛示範了一套實用配方,透過 Python **提升 OCR 準確度**。只要建立 `OcrEngine`、載入 PNG、**為 OCR 前處理影像**,最後 **從 PNG 辨識文字**,即使來源影像不完美,也能可靠地 **從影像中擷取文字**。 + +接下來可以嘗試將多張影像放入迴圈處理、把結果寫入 CSV,或測試其他前處理模式(如對比度增強)。相同流程同樣適用於 PDF、掃描收據或手寫筆記——只要換掉輸入來源並調整設定即可。 + +對特定影像類型有疑問,或想了解如何整合到 Web 服務中?歡迎留言,我們一起探討。祝程式開發順利,OCR 結果永遠清晰無誤! + +## 接下來該學什麼? + +- [從影像中擷取文字 – Aspose OCR 步驟指南](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [從影像中擷取文字 – Aspose.OCR for .NET OCR 最佳化](/ocr/english/net/ocr-optimization/) +- [如何透過在 OCR 中準備矩形來擷取文字](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/hongkong/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..76f582950 --- /dev/null +++ b/ocr/hongkong/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-31 +description: 使用 OCR 感興趣區域載入影像,從矩形中擷取文字,完美適用於辨識發票金額。 +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: zh-hant +og_description: 精通 OCR 感興趣區域,載入影像進行 OCR,從矩形提取文字,並在單一教學中辨識發票文字。 +og_title: OCR 感興趣區域 – 逐步 Python 指南 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR 感興趣區域 – 在 Python 中從矩形提取文字 +url: /zh-hant/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – 在 Python 中從矩形提取文字 + +有沒有想過如何 **ocr region of interest** 掃描發票的特定部份,而不必把整頁送入引擎?你不是第一個盯著模糊收據想著「要怎樣提取位於右下角的金額?」的人。好消息是,你可以告訴 OCR 函式庫精確的搜尋位置,從而大幅提升速度與準確度。 + +在本指南中,我們將逐步演示一個完整且可執行的範例,說明如何 **load image for OCR**、定義 **region of interest**,再 **extract text from rectangle**,最終 **recognize text from invoice**,解答那個經典的「如何提取金額」問題。沒有模糊的參考——只有具體程式碼、清晰說明,以及一些你會希望早點知道的專業小技巧。 + +--- + +## 您將構建的內容 + +完成本教學後,你將擁有一個小型的 Python 腳本,能夠: + +1. 從磁碟載入發票影像。 +2. 標記出總金額所在的矩形 ROI。 +3. 僅在該 ROI 內執行 OCR。 +4. 輸出已清理的金額字串。 + +以上流程適用於任何支援 ROI 的 OCR 函式庫——此處我們使用一個虛構但具代表性的 `SimpleOCR` 套件,模仿 Tesseract 或 EasyOCR 等常見工具。你可以自行替換;概念保持不變。 + +--- + +## 前置條件 + +- 已安裝 Python 3.8+(執行 `python --version` 應顯示 ≥3.8)。 +- 可透過 pip 安裝的 OCR 套件(例如 `pip install simpleocr`)。 +- 一張發票影像(PNG 或 JPEG),放在可參考的資料夾中。 +- 具備基本的 Python 函式與類別概念(不需要進階知識)。 + +如果你已具備上述條件,太好了——讓我們直接進入。如果還沒有,先取得影像檔;其餘步驟與實際檔案內容無關。 + +--- + +## Step 1: Load Image for OCR + +任何 OCR 工作流程的第一步都是取得可讀取的點陣圖。大多數函式庫都提供簡單的 `load_image` 方法,接受檔案路徑。以下示範如何使用 `SimpleOCR` 引擎: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** 使用絕對路徑或 `os.path.join`,可避免在不同工作目錄執行腳本時出現「找不到檔案」的狀況。 + +--- + +## Step 2: Define OCR Region of Interest + +與其讓引擎掃描整頁,我們直接告訴它 **ocr region of interest** 的精確位置。這一步是可靠抽取的關鍵,尤其當文件包含雜訊的標頭或頁腳時。 + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +為什麼是這些數字?`x` 與 `y` 為左上角的像素偏移量,`width` 與 `height` 則描述方框的尺寸。如果不確定,可在任意編輯器中開啟影像,開啟尺規並記錄座標。許多 IDE 甚至允許在游標懸停時即時顯示位置。 + +--- + +## Step 3: Extract Text from Rectangle + +ROI 設定完成後,我們請引擎 **recognize text from invoice**,但僅限於剛剛定義的矩形。此呼叫會回傳一個結果物件,通常包含原始字串、信心分數,甚至邊界框資訊。 + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +在背後,`recognize()` 會遍歷每個 ROI,裁切該區塊、執行 OCR 模型,最後將結果拼接回傳。這也是為什麼定義緊湊的 **extract text from rectangle** 區域能為批次作業節省數秒處理時間的原因。 + +--- + +## Step 4: How to Extract Amount – Clean the Output + +OCR 並非完美,常會出現多餘的空格、換行,甚至讀錯字元(例如「S」與「5」)。簡單的 `strip()` 加上一小段正規表達式,通常就能正確取得金額。 + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** 若要將金額寫入資料庫或付款閘道,必須保證格式一致。去除空白與非數字字元可防止下游錯誤。 + +--- + +## Step 5: Recognize Text from Invoice – Full Script + +將上述所有步驟整合,即得到完整可執行的腳本。將檔案存為 `extract_amount.py`,然後執行 `python extract_amount.py`。 + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### 預期輸出 + +``` +Amount: 1,245.67 +``` + +如果 ROI 對齊不正確,可能會看到類似 `Amount: 1245.6S` 的結果——注意那個多餘的「S」。請調整矩形座標後重新執行,直到輸出乾淨為止。 + +--- + +## 常見問題與邊緣案例 + +| 問題 | 發生原因 | 解決方案 | +|------|----------|----------| +| **ROI 太小** | 金額文字被裁切,導致辨識不完整。 | 將 `width`/`height` 增大約 10‑20 %,再測試。 | +| **DPI 不正確** | 低解析度掃描(≤150 dpi)降低 OCR 準確度。 | 在載入前將影像重新取樣至 300 dpi,或要求掃描器使用更高 DPI。 | +| **多種貨幣** | 正則表達式抓到第一個數字群,可能是發票編號。 | 改寫正則式,先偵測貨幣符號(`$`, `€`, `£`)再匹配數字。 | +| **發票旋轉** | OCR 引擎預設文字為直立,旋轉的頁面會失敗。 | 在加入 ROI 前先執行旋轉校正(`ocr_engine.rotate(90)`)。 | +| **背景噪點** | 陰影或印章干擾模型辨識。 | 使用簡單的閾值處理(`cv2.threshold`)或去噪濾波。 | + +提前處理這些情況,可為日後除錯省下大量時間。 + +--- + +## 實務專業小技巧 + +- **批次處理:** 迴圈遍歷發票資料夾,動態計算 ROI(例如根據模板偵測),並將結果寫入 CSV。 +- **模板匹配:** 若需支援多種發票版型,可維護一個 `template_id → ROI 座標` 的 JSON 映射,根據快速版型分類器切換 ROI。 +- **平行執行:** 使用 `concurrent.futures.ThreadPoolExecutor` 同時執行多個 OCR 實例,適合高量能的後勤管線。 +- **信心過濾:** 大多數 OCR 結果會提供信心分數。將低於門檻(例如 85 %)的結果剔除,並標記為需人工審核。 + +--- + +## 結論 + +我們已完整說明如何 **ocr region of interest**、**load image for OCR**、**extract text from rectangle**,最終 **recognize text from invoice**,解決那個經典的 **how to extract amount** 問題。此腳本簡潔卻具彈性,足以因應不同文件格式、語言與 OCR 後端。 + +掌握基礎後,可進一步擴充工作流程:加入條碼掃描、整合 PDF 解析器,或將抽取的金額推送至會計 API。只要 ROI 定義清晰,你就能持續獲得更快、更乾淨的結果。 + +若遇到任何問題,歡迎在下方留言——祝 OCR 順利! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## 接下來該學什麼? + +- [如何透過在 OCR 中準備矩形來提取圖像文字](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [使用 Aspose.OCR Detect Areas Mode 於 Java 提取圖像文字](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [使用 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/hungarian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/hungarian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..059cd68c3 --- /dev/null +++ b/ocr/hungarian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Aszinkron OCR oktató, amely bemutatja, hogyan használjuk az Aspose OCR-t + Pythonban az asyncio-val a gyors képszöveg‑kivonáshoz. Tanulja meg lépésről‑lépésre + az aszinkron OCR megvalósítását. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: hu +og_description: Az aszinkron OCR oktatóanyag lépésről lépésre bemutatja, hogyan használhatod + az Aspose OCR-t Pythonban az asyncio-val a hatékony képszöveg-kivonáshoz. +og_title: Aszinkron OCR útmutató – Python asyncio az Aspose OCR-rel +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Aszinkron OCR bemutató – Python asyncio az Aspose OCR-rel +url: /hu/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR Bemutató – Python asyncio az Aspose OCR-rel + +Valaha is elgondolkodtál, hogyan lehet optikai karakterfelismerést futtatni anélkül, hogy blokkolná az alkalmazásodat? Egy **async OCR tutorial** során pont ezt láthatod – nem blokkoló szövegkinyerést a Python `asyncio` és az Aspose OCR könyvtár segítségével. + +Ha eddig egy nehéz kép feldolgozására várva akadtál, ez az útmutató egy tiszta, aszinkron megoldást nyújt, amely a eseményciklust (event loop) zökkenőmentesen tartja. + +Az alábbi szakaszokban mindent áttekintünk, amire szükséged lesz: a könyvtár telepítése, egy aszinkron segédfüggvény felépítése, az eredmény kezelése, sőt egy gyors tipp a több kép egyidejű feldolgozásához. A végére képes leszel egy **async OCR tutorial**-t beilleszteni bármely Python projektbe, amely már használja a `asyncio`-t. + +## Amire szükséged lesz + +* Python 3.9+ (a `asyncio` API, amelyet használunk, 3.7-től stabil) +* Aktív Aspose OCR licenc vagy ingyenes próba (a könyvtár tisztán Python, nincs natív bináris) +* Egy kis képfájl (`.jpg`, `.png`, stb.), amelyet be szeretnél olvasni – tedd egy ismert mappába + +Más külső eszközre nincs szükség; minden tiszta Pythonban fut. + +## 1. lépés: Az Aspose OCR csomag telepítése + +Először is, szerezd be az Aspose OCR csomagot a PyPI-ról. Nyiss egy terminált és futtasd: + +```bash +pip install aspose-ocr +``` + +> **Pro tipp:** Ha virtuális környezetben dolgozol (erősen ajánlott), először aktiváld azt. Ez izolálja a függőségeket és elkerüli a verzióütközéseket. + +## 2. lépés: Az OCR motor aszinkron inicializálása + +Az **async OCR tutorial** szíve egy aszinkron segédfüggvény. Létrehozza az `OcrEngine` példányt, betölti a képet, majd meghívja a `recognize_async()`-t. Maga a motor szinkron, de a burkoló metódus egy awaitable-t ad vissza, ami lehetővé teszi, hogy az eseményciklus reagálók maradjon. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Miért így csináljuk:** +*Az engine létrehozása a segédfüggvényen belül biztosítja a szálbiztonságot, ha később sok OCR feladatot futtatsz párhuzamosan. Az `await` kulcsszó visszaadja az irányítást az eseményciklusnak, amíg a nehéz munka a könyvtár belső szálkészletében zajlik.* + +## 3. lépés: A segédfüggvény meghívása egy aszinkron főfüggvényből + +Most egy kis `main()` coroutine-ra van szükség, amely meghívja az `async_ocr()`-t és kiírja az eredményt. Ez tükrözi egy tipikus `asyncio` szkript belépési pontját. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Mi történik a háttérben?** +`asyncio.run()` egy új eseményciklust hoz létre, ütemezi a `main()`-t, és tisztán leállítja a ciklust, amikor a `main()` befejeződik. Ez a minta a javasolt módja az aszinkron programok indításának Python 3.7+ verziókban. + +## 4. lépés: A teljes szkript tesztelése + +Mentsd el a fenti két kódrészt egyetlen fájlba, például `async_ocr_demo.py`. Futtasd a parancssorból: + +```bash +python async_ocr_demo.py +``` + +Ha minden helyesen van beállítva, valami ilyesmit kell látnod: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +A pontos kimenet a `photo.jpg` tartalmától függ. A lényeg, hogy a szkript gyorsan befejeződik, még akkor is, ha a kép nagy, mivel az OCR munka a háttérben zajlik. + +## 5. lépés: Skálázás – Több kép egyidejű feldolgozása + +Egy gyakori követő kérdés: *„Tudok-e egy csomag fájlt OCR-ölni anélkül, hogy mindenhez új folyamatot indítanék?”* Természetesen. Mivel a segédfüggvényünk teljesen aszinkron, sok coroutine-t gyűjthetünk össze a `asyncio.gather()`-rel: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Miért működik ez:** A `asyncio.gather()` egyszerre ütemezi az összes OCR feladatot. Az alapul szolgáló Aspose OCR könyvtár továbbra is a saját szálkészletét használja, de Python szempontjából minden nem blokkoló marad, így tucatnyi képet tudsz kezelni egy szinkron hívás idejében. + +## 6. lépés: Hibák szép kezelése + +Külső fájlokkal dolgozva elkerülhetetlenül hiányzó fájlok, sérült képek vagy licencproblémák merülnek fel. Tedd az OCR hívást egy `try/except` blokkba, hogy az eseményciklus élő maradjon: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Most a `batch_ocr()` a `safe_async_ocr`-t hívhatja, biztosítva, hogy egy rossz fájl ne szakítsa meg az egész csomagot. + +## Vizuális áttekintés + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial folyamatábra, amely bemutatja az async_ocr segédfüggvényt, az eseményciklust és az Aspose OCR motort"} + +A fenti diagram a folyamatot ábrázolja: az eseményciklus → `async_ocr` → `OcrEngine` → háttérszál → eredmény vissza a ciklusba. + +## Gyakori buktatók és hogyan kerüld el őket + +| Buktató | Miért fordul elő | Javítás | +|---------|------------------|--------| +| **Blokkoló I/O a segédfüggvényen belül** | Véletlenül `open()`-t használni `await` nélkül blokkolhatja a ciklust. | Használj `aiofiles`-t a fájlolvasáshoz, vagy hagyd, hogy az `engine.load_image` kezelje (már nem blokkoló). | +| **Egyetlen `OcrEngine` újrahasználata coroutine-ok között** | A motor nem szálbiztos; a párhuzamos hívások állapotot rombolhatnak. | Hozz létre egy új motor példányt minden `async_ocr` hívásnál (ahogy a példában). | +| **Hiányzó licenc** | Az Aspose OCR futás közben licenc‑kapcsolatú kivételt dob. | Regisztráld a licencet korán (`OcrEngine.set_license("license.json")`). | +| **Nagy képek memóriahasználatot növelnek** | A könyvtár betölti a teljes képet a RAM-ba. | Méretezze le a képeket OCR előtt, ha a memória aggodalom. | + +## Összefoglalás: Mit értünk el + +Ebben a **async OCR tutorial**-ban mi: + +1. Telepítettük az Aspose OCR könyvtárat. +2. Létrehoztunk egy `async_ocr` segédfüggvényt, amely blokkolás nélkül futtatja a felismerést. +3. A segédfüggvényt egy tiszta `asyncio` belépési pontból futtattuk. +4. Bemutattuk a kötegelt feldolgozást a `asyncio.gather` segítségével. +5. Hibakezelést és legjobb gyakorlat tippeket adtunk hozzá. + +Mindez tiszta Python, így beillesztheted egy webkiszolgálóba, CLI eszközbe vagy adatfolyamba anélkül, hogy át kellene írni a meglévő aszinkron kódot. + +## Következő lépések és kapcsolódó témák + +* **Aszinkron képelőfeldolgozás** – használj `aiohttp`-t a képek egyidejű letöltéséhez OCR előtt. +* **OCR eredmények tárolása** – kombináld ezt a bemutatót egy aszinkron adatbázis driverrel, például `asyncpg`-vel a PostgreSQL-hez. +* **Teljesítményhangolás** – kísérletezz a `engine.recognize_async(max_threads=4)`-vel, ha a könyvtár ilyen opciót kínál. +* **Alternatív OCR motorok** – hasonlítsd össze az Aspose OCR-t a Tesseract aszinkron burkolóival költség‑haszon elemzés céljából. + +Nyugodtan kísérletezz: próbálj PDF-eket betáplálni, állítsd be a nyelvi beállításokat, vagy csatlakoztasd az eredményeket egy chatbothoz. A lehetőségek végtelenek, ha már van egy stabil **async OCR tutorial** alapod. + +Boldog kódolást, és legyen a szövegkinyerésed mindig gyors! + +## Mit érdemes legközelebb megtanulni? + +- [Szöveg kinyerése képből az 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/) +- [Aspose OCR Bemutató – Optikai karakterfelismerés](/ocr/english/) +- [Hogyan OCR-öljünk képszöveget nyelvvel az Aspose.OCR használatával](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/hungarian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..efd207851 --- /dev/null +++ b/ocr/hungarian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Az OCR automatikus nyelvfelismerése egyszerű. Tanulja meg, hogyan töltsön + be képet OCR-hez, engedélyezze az automatikus nyelvfelismerést, és néhány lépésben + ismerje fel a szöveget a képen. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: hu +og_description: Az OCR automatikus nyelvfelismerése egyszerű. Kövesd ezt a lépésről‑lépésre + útmutatót az automatikus nyelvfelismerés engedélyezéséhez, a képes OCR betöltéséhez + és a szöveges kép felismeréséhez. +og_title: Automatikus nyelvfelismerés OCR-rel – Teljes Python útmutató +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatikus nyelvfelismerés OCR-rel – Teljes Python útmutató +url: /hu/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatikus nyelvfelismerés OCR-rel – Teljes Python útmutató + +Elgondolkodtál már azon, hogyan lehet egy OCR motor *kitalálni* egy beolvasott dokumentum nyelvét anélkül, hogy megmondanád, mire figyeljen? Pontosan ezt teszi a **automatikus nyelvfelismerés**, és igazi játék‑váltó, ha többnyelvű PDF-ekkel, utcajelzők fényképeivel vagy bármilyen, több írásrendszert keverő képpel dolgozol. + +Ebben az útmutatóban egy gyakorlati példán keresztül mutatjuk be, hogyan **kapcsolhatod be az automatikus nyelvfelismerést**, **töltsd be a kép OCR‑t**, és **ismerd fel a szöveget a képen** egy Python‑stílusú API használatával. A végére egy önálló szkriptet kapsz, amely kiírja a felismert nyelvkódot és a kinyert szöveget – manuális nyelvi beállítások nélkül. + +## Mit fogsz megtanulni + +- Hogyan hozhatsz létre egy OCR motor példányt és kapcsolhatod be a **automatikus nyelvfelismerést**. +- A pontos lépéseket a **kép OCR betöltéséhez** a lemezről. +- Hogyan hívhatod meg a motor `recognize()` metódusát, és kaphatsz vissza egy eredményt, amely tartalmazza a nyelvkódot. +- Tippek a szélhelyzetek kezeléséhez, mint például az alacsony felbontású képek vagy a nem támogatott írásrendszerek. + +Előzetes tapasztalat a többnyelvű OCR‑rel nem szükséges; csak egy alap Python környezet és egy képfájl kell. + +--- + +## Előfeltételek + +1. Python 3.8+ telepítve (bármely friss verzió megfelelő). +2. Az OCR könyvtár, amely biztosítja az `OcrEngine`, `LanguageAutoDetectMode` stb. – ebben az útmutatóban egy hipotetikus `myocr` csomagot feltételezünk. Telepítsd a következővel: + + ```bash + pip install myocr + ``` + +3. Egy képfájl (`multilingual_sample.png`), amely legalább két különböző nyelven tartalmaz szöveget. +4. Egy kis kíváncsiság – ha még sosem foglalkoztál OCR‑rel, ne aggódj; a kód szándékosan egyszerű. + +--- + +## 1. lépés: Automatikus nyelvfelismerés engedélyezése + +Az első dolog, amit meg kell tenned, hogy elmondod a motornak, hogy *önmagától* kell kitalálnia a nyelvet. Itt jön képbe a **automatikus nyelvfelismerés** jelző. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Miért fontos ez:** +> Amikor az `AUTO_DETECT` be van állítva, a motor egy könnyű nyelvklasszifikátort futtat a képen, mielőtt a nehéz karakterfelismerés elkezdődik. Ez azt jelenti, hogy nem kell kitalálnod, hogy a szöveg angol, orosz, francia vagy bármilyen kombinációja-e. A motor automatikusan kiválasztja a legjobb nyelvi modellt a kép minden régiójára. + +--- + +## 2. lépés: Kép OCR betöltése + +Most, hogy a motor tudja, hogy automatikusan fel kell ismernie a nyelveket, adni kell neki valamit, amivel dolgozhat. A **kép OCR betöltése** lépés beolvassa a bitmapet és előkészíti a belső puffereket. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro tipp:** +> Ha a képed nagyobb, mint 300 dpi, fontold meg, hogy lecsökkented körülbelül 150‑200 dpi-re. A túl sok részlet valójában *lassíthatja* a nyelvfelismerési lépést anélkül, hogy a pontosságot javítaná. + +--- + +## 3. lépés: Szöveg felismerése képből + +A kép memóriában van és a nyelvfelismerés be van kapcsolva, a végső lépés, hogy megkérjük a motort a **szöveg felismerésére a képen**. Ez az egyetlen hívás elvégzi az összes nehéz munkát. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +A `result` egy olyan objektum, amely általában legalább két attribútumot tartalmaz: + +| Attribútum | Leírás | +|------------|--------| +| `language` | A felismert nyelv ISO‑639‑1 kódja (pl. `"en"` az angolhoz). | +| `text` | A kép egyszerű szöveges transzkripciója. | + +--- + +## 4. lépés: A felismert nyelv és a kinyert szöveg lekérése + +Most egyszerűen kiírjuk, mit talált a motor. Ez bemutatja a **detect language OCR** képességet működés közben. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Minta kimenet** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Mi van, ha a motor `None`‑t ad vissza?** +> Ez általában azt jelenti, hogy a kép túl homályos vagy a szöveg túl kicsi (< 8 pt). Próbáld növelni a kontrasztot vagy használj nagyobb felbontású forrást. + +--- + +## Teljes működő példa (Automatikus nyelvfelismerés vég‑től‑végig) + +Összeállítva minden lépést, itt egy azonnal futtatható szkript, amely lefedi a **automatikus nyelvfelismerés engedélyezését**, a **kép OCR betöltését**, a **szöveg felismerését a képen**, és a **nyelvfelismerést OCR‑rel** egy lépésben. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Mentsd el `automatic_language_detection_ocr.py` néven, cseréld le a `YOUR_DIRECTORY`‑t arra a mappára, amelyik a PNG‑det tartalmazza, majd futtasd: + +```bash +python automatic_language_detection_ocr.py +``` + +A nyelvkódot és a kinyert szöveget kell látnod, pontosan úgy, mint a fenti minta kimenetben. + +--- + +## Gyakori szélhelyzetek kezelése + +| Helyzet | Javasolt megoldás | +|---------|-------------------| +| **Nagyon alacsony felbontású kép** (100 dpi alatti) | Nagyíts fel bicubic szűrővel a betöltés előtt, vagy kérj nagyobb felbontású forrást. | +| **Vegyes írásrendszerek egy képen** (pl. angol + cirill) | A motor általában felosztja az oldalt régiókra; ha hibás felismeréseket látsz, állítsd be `engine.enable_region_split = True`. | +| **Nem támogatott nyelv** | Ellenőrizd, hogy az OCR könyvtár tartalmaz-e nyelvi csomagot az adott írásrendszerhez; előfordulhat, hogy további modelleket kell letöltened. | +| **Nagy kötegelt feldolgozás** | Inicializáld a motort egyszer, majd használd újra több `load_image` / `recognize` ciklus során, hogy elkerüld az ismételt modellbetöltést. | + +--- + +## Vizuális áttekintés + +![automatikus nyelvfelismerés példa kimenet](https://example.com/auto-lang-detect.png "automatikus nyelvfelismerés") + +*Alt szöveg:* automatikus nyelvfelismerés példa kimenet, amely a felismert nyelvkódot és a kinyert többnyelvű szöveget mutatja. + +--- + +## Következtetés + +Most már átfogóan megismertük a **automatikus nyelvfelismerést** a kezdetektől a befejezésig – a motor létrehozását, az automatikus nyelvfelismerés bekapcsolását, a kép betöltését OCR‑hez, a szöveg felismerését, és végül a felismert nyelv lekérését. Ez az end‑to‑end folyamat lehetővé teszi, hogy többnyelvű dokumentumokat dolgozz fel anélkül, hogy minden alkalommal manuálisan konfigurálnád a nyelvi modelleket. + +Ha tovább szeretnéd vinni, gondolj a következőkre: + +- **Kötegelt feldolgozás** több száz képet egy ciklussal, amely újrahasználja ugyanazt az `OcrEngine` példányt. +- **Utófeldolgozás** a kinyert szövegen helyesírás-ellenőrzővel vagy nyelvspecifikus tokenizálóval. +- **Integráció** a szkriptbe egy webszolgáltatásba, amely felhasználói feltöltéseket fogad, és JSON‑t ad vissza `language` és `text` mezőkkel. + +Nyugodtan kísérletezz különböző képformátumokkal (`.jpg`, `.tif`), és figyeld meg, hogyan változik a felismerési pontosság. Van kérdésed vagy egy makacs kép, ami nem olvasható? Hagyj kommentet alább – jó kódolást! + +## Mit érdemes még megtanulni? + +- [Hogyan OCR-elj képszöveget nyelvvel az Aspose.OCR használatával](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Képszöveg kinyerése C#‑ban nyelvválasztással az Aspose.OCR segítségével](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [szöveg felismerése képen az Aspose OCR-rel több nyelvhez](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4270cd516 --- /dev/null +++ b/ocr/hungarian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Tanulja meg, hogyan konvertálhat képeket szöveggé Pythonban egy tömeges + kép‑szöveg konverziós szkript segítségével. Percek alatt felismerheti a szkennelt + képek szövegét az Aspose.OCR használatával. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: hu +og_description: Konvertálja a képeket szöveggé Pythonban azonnal. Ez az útmutató bemutatja + a tömeges kép‑szöveg konverziót, valamint azt, hogyan ismerje fel a szöveget beolvasott + képekről az Aspose.OCR segítségével. +og_title: Képek szöveggé konvertálása Pythonban – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Képek szöveggé konvertálása Pythonban – Teljes lépésről‑lépésre útmutató +url: /hu/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Képek szöveggé konvertálása Pythonban – Teljes lépésről‑lépésre útmutató + +Gondolkodtál már azon, hogyan **convert images to text python** anélkül, hogy tucatnyi könyvtárat kellene keresgélned? Nem vagy egyedül. Legyen szó régi nyugták digitalizálásáról, beolvasott számlák adatainak kinyeréséről, vagy egy kereshető PDF-archívum felépítéséről, a képek egyszerű szövegfájlokká alakítása mindennapi feladat sok fejlesztő számára. + +Ebben a bemutatóban végigvezetünk egy **bulk image to text conversion** folyamaton, amely beolvassa a szöveget a beolvasott képekről, minden eredményt egy külön `.txt` fájlba ment, és mindezt csak néhány Python‑sorral valósítja meg. Nem kell rejtett API‑kat keresgélned – az Aspose.OCR végzi a nehéz munkát, és megmutatjuk, hogyan kell azt pontosan beállítani. + +## What You’ll Learn + +- Hogyan telepítsd és konfiguráld az Aspose.OCR for Python csomagot. +- A pontos kód, amely **convert images to text python** a `BatchOcrEngine` használatával. +- Tippek a gyakori buktatók kezelésére, mint a nem támogatott formátumok vagy sérült fájlok. +- Módszerek annak ellenőrzésére, hogy a **recognize text from scanned images** lépés valóban sikeres volt-e. + +A útmutató végére egy kész‑futásra alkalmas szkriptet kapsz, amely egyszerre több ezer képet tud feldolgozni – tökéletes bármilyen kötegelt feldolgozási szituációhoz. + +## Prerequisites + +- Python 3.8+ telepítve a gépeden. +- Egy mappa képfájlokkal (PNG, JPEG, TIFF, stb.), amelyeket szöveggé szeretnél alakítani. +- Aktív Aspose Cloud fiók vagy ingyenes próbaverziós licenc (az ingyenes szint elég a teszteléshez). + +Ha ezek megvannak, merüljünk el. + +--- + +## Step 1 – Set Up Your Python Environment + +Mielőtt bármilyen OCR‑kódot írnánk, győződj meg róla, hogy egy tiszta virtuális környezetben dolgozol. Ez elkülöníti a függőségeket és megakadályozza a verzióütközéseket. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Tartsd rendezettnek a projektkönyvtáradat – hozz létre egy `ocr_project` nevű almappát, és helyezd el benne a szkriptet. Ez később megkönnyíti az útvonalkezelést. + +## Step 2 – Install Aspose.OCR for Python + +Az Aspose.OCR egy kereskedelmi könyvtár, de egy ingyenes NuGet‑stílusú wheel‑t tartalmaz, amelyet a PyPI‑ról tölthetsz le. Futtasd a következő parancsot a aktivált virtuális környezetben: + +```bash +pip install aspose-ocr +``` + +Ha jogosultsági hibát kapsz, add hozzá a `--user` kapcsolót, vagy futtasd a parancsot `sudo`‑val (csak Linux/macOS esetén). A telepítés után valami ilyesmit kell látnod: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** A legtöbb nyílt forráskódú OCR‑eszközzel ellentétben az Aspose.OCR alapból támogatja a **bulk image to text conversion** funkciót, és széles körű képformátumot kezel extra konfiguráció nélkül. Emellett rendelkezik egy `BatchOcrEngine` osztállyal, amely a “convert images to text python” feladatot egyetlen sorba sűríti. + +## Step 3 – Convert Images to Text Python with Batch OCR + +Most jön a tutorial szíve. Az alábbiakban egy teljesen futtatható szkriptet találsz, amely: + +1. Importálja az OCR motor osztályait. +2. Példányosít egy `BatchOcrEngine`‑t. +3. A motort egy bemeneti képmappára irányítja. +4. Az eredményeket egy kimeneti mappába írja. +5. Meghívja a `recognize()` metódust, amely **recognize text from scanned images** egyesével. + +Mentsd el a következőt `batch_ocr.py` néven a projektmappádba: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### How It Works + +- **`BatchOcrEngine`** a szokásos `OcrEngine`-et csomagolja be, de mappaszintű koordinációt biztosít, ami pontosan azt a feladatot szolgálja, amikor **convert images to text python** kötegelt módon szeretnéd végrehajtani. +- Az `input_folder` tulajdonság megadja, hol keresse a forrásképeket. Automatikusan beolvassa a könyvtárat, és sorba állítja az összes támogatott fájltípust. +- Az `output_folder` határozza meg, hová kerüljenek a `.txt` fájlok. A motor az eredeti fájlnévhez igazítja a kimenetet, így a `receipt1.png` `receipt1.txt`‑vé alakul. +- A `recognize()` meghívása elindítja a belső ciklust, amely betölti a képet, futtatja az OCR‑t, és kiírja az eredményt. A metódus addig blokkol, amíg minden fájl feldolgozásra nem kerül, így egyszerűen láncolhatsz további műveleteket (pl. a kimeneti mappa zip‑elése). + +#### Expected Output + +A szkript futtatásakor: + +```bash +python batch_ocr.py +``` + +A következőt kell látnod: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Az `output_texts` mappában minden képhez egy egyszerű szövegfájl tartozik. Nyiss meg bármelyiket egy szövegszerkesztővel, és a nyers OCR‑eredményt fogod látni – általában a nyomtatott szöveg közelítő másolata. + +## Step 4 – Verify the Results and Handle Errors + +Még a legjobb OCR motorok is elakadhatnak alacsony felbontású beolvasásoknál vagy erősen ferde oldalaknál. Itt egy gyors módszer a kimenet ellenőrzésére és a hibák naplózására. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Why add this?** +- Elkapja azokat az eseteket, amikor a motor csendben üres karakterláncot ad vissza (gyakori olvashatatlan képeknél). +- Listát ad a problémás fájlokról, így manuálisan ellenőrizheted vagy újra futtathatod más beállításokkal (pl. növeld az `OcrEngine.preprocess` opciókat). + +### Edge Cases & Tweaks + +| Situation | Suggested Fix | +|-----------|----------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Step 5 – Automate the Whole Workflow (Optional) + +Ha ezt a konverziót éjszakánként szeretnéd futtatni, csomagold be a szkriptet egy egyszerű shell vagy Windows batch fájlba, és ütemezd `cron`‑nal (Linux/macOS) vagy a Feladatütemezővel (Windows). Íme egy minimális `run_ocr.sh` Unix‑szerű rendszerekhez: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Tedd futtathatóvá (`chmod +x run_ocr.sh`), és adj hozzá egy cron bejegyzést: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Ez minden nap 2 AM‑kor lefuttatja a konverziót, és a kimenetet naplózza későbbi áttekintés céljából. + +--- + +## Conclusion + +Most már van egy bevált, termelés‑kész módszered a **convert images to text python** feladatra az Aspose.OCR `BatchOcrEngine`‑jével. A szkript kezeli a **bulk image to text conversion**‑t, gondosan minden eredményt egy dedikált fájlba ír, és ellenőrzési lépéseket tartalmaz, hogy valóban **recognize text from scanned images** helyesen történjen. + +Innen tovább: + +- Kísérletezz különböző OCR beállításokkal (nyelvi csomagok, asztalra helyezés, zajcsökkentés). +- A generált szöveget irányítsd egy keresőindexbe, például Elasticsearch‑be, hogy azonnali teljes szöveges keresést biztosítson. +- Kombináld ezt a folyamatot PDF‑konverziós eszközökkel, hogy beolvasott PDF‑eket egy lépésben dolgozz fel. + +Van kérdésed, vagy hibát észleltél egy adott fájltípusnál? Írj egy megjegyzést alul, és segítünk a hibaelhárításban. Boldog kódolást, és legyenek gyorsak és hibamentesek az OCR futásaid! + +## What Should You Learn Next? + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..73e9634ec --- /dev/null +++ b/ocr/hungarian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Hozzon létre licencpéldányt Pythonban, és állítsa be egyszerűen a licenc + útvonalát. Tanulja meg, hogyan konfigurálja az Aspose OCR licencelést világos kódrészletekkel. +draft: false +keywords: +- create license instance +- configure license path +language: hu +og_description: Hozzon létre licencpéldányt Pythonban, és azonnal állítsa be a licenc + útvonalát. Kövesse ezt az útmutatót, hogy magabiztosan aktiválja az Aspose OCR-t. +og_title: Licencpéldány létrehozása Pythonban – Teljes beállítási útmutató +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Licencpéldány létrehozása Pythonban – Lépésről lépésre útmutató +url: /hu/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Licencpéldány létrehozása Pythonban – Teljes beállítási útmutató + +Szükséged van **licencpéldány létrehozására** az Aspose OCR-hez Pythonban? Jó helyen vagy. Ebben az útmutatóban megmutatjuk, hogyan **állítsd be a licenc útvonalát**, hogy az SDK megtalálja a `.lic` fájlodat. + +Ha már valaha is egy üres szkriptre bámultál, azon tűnődve, miért panaszkodik az OCR motor a nem licencelt termékre, nem vagy egyedül. A megoldás általában csak néhány sor kód – ha tudod, hová kell őket helyezni. A útmutató végére egy teljesen licencelt Aspose OCR környezetet kapsz, amely gond nélkül képes szöveget, képeket és PDF-eket felismerni. + +## Mit fogsz megtanulni + +- Hogyan **hozz létre licencpéldányt** a `asposeocr` csomag használatával. +- A helyes módja a **licenc útvonalának beállítására** fejlesztés és éles környezet esetén egyaránt. +- Gyakori buktatók (hiányzó fájl, rossz jogosultságok) és azok elkerülése. +- Egy teljes, futtatható szkript, amelyet bármely projektbe beilleszthetsz. + +Nem szükséges előzetes tapasztalat az Aspose OCR-rel, csak egy működő Python 3 telepítés és egy érvényes licencfájl. + +--- + +## 1. lépés: Az Aspose OCR Python csomag telepítése + +Mielőtt **licencpéldányt hozhatnánk létre**, a könyvtárnak jelen kell lennie. Nyiss egy terminált és futtasd: + +```bash +pip install aspose-ocr +``` + +> **Pro tipp:** Ha virtuális környezetet használsz (erősen ajánlott), először aktiváld azt. Így rendezett maradnak a függőségek, és elkerülheted a verzióütközéseket. + +## 2. lépés: A License osztály importálása + +Most, hogy az SDK elérhető, a szkript első sorának importálnia kell a `License` osztályt. Ez az objektum, amellyel **licencpéldányt hozunk létre**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Miért importáljuk azonnal? Mert a `License` objektumot **mielőtt** bármilyen OCR hívás történik, példányosítani kell; különben az SDK licenchibát dob, amint megpróbálsz egy képet feldolgozni. + +## 3. lépés: Licencpéldány létrehozása + +Itt jön a várt pillanat – ténylegesen **licencpéldányt hozunk létre**. Ez egyetlen sor, de a környező kontextus számít. + +```python +# Step 3: Create a License instance +license = License() +``` + +A `license` változó most egy olyan objektumot tartalmaz, amely a jelenlegi Python folyamat összes licencelési viselkedését irányítja. Tekintsd úgy, mint egy kapuőröt, amely azt mondja az Aspose OCR-nek: „Hé, nekem jogom van futni.” + +## 4. lépés: Licenc útvonalának beállítása + +Miután a példány készen áll, rá kell mutatnunk a `.lic` fájlra. Itt jön a **licenc útvonalának beállítása** szerepbe. Cseréld ki a helyőrzőt a licencfájl abszolút útvonalára. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Néhány fontos megjegyzés: + +1. **Nyers karakterláncok (`r"…"`)** megakadályozzák, hogy a Windows‑os visszaperjelek escape karakterként értelmeződjenek. +2. Használj **abszolút útvonalat**, hogy elkerüld a zavarokat, ha a szkript más munkakönyvtárból indul. +3. Ha relatív útvonalat részesítesz előnyben (pl. a licenc a projekttel együtt kerül csomagolásra), győződj meg róla, hogy a relatív alap a szkript helye, nem a jelenlegi parancssori könyvtár. + +### Hiányzó fájlok kezelése + +Ha az útvonal hibás vagy a fájl nem olvasható, a `set_license` kivételt dob. Tedd a hívást egy `try/except` blokkba, hogy barátságos hibaüzenetet kapj: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Ez a kódrészlet **biztonságosan beállítja a licenc útvonalát**, és pontosan megmondja, mi ment rosszul – nincs titokzatos stack trace. + +## 5. lépés: Ellenőrizd, hogy a licenc aktív-e + +Egy gyors szanitás ellenőrzés órákat takarít meg a későbbi hibakeresésben. Miután meghívtad a `set_license`-t, próbálj ki egy egyszerű OCR műveletet. Ha a licenc érvényes, az SDK a képet hibamentesen feldolgozza. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Ha a felismert szöveget kiírja, gratulálok – sikeresen **licencpéldányt hoztál létre** és **beállítottad a licenc útvonalát**. Ha licenckivételt kapsz, ellenőrizd újra az útvonalat és a fájl jogosultságait. + +## Szélsőséges esetek és legjobb gyakorlatok + +| Helyzet | Mit tegyünk | +|-----------|------------| +| **Licencfájl hálózati megosztáson él** | Csatold a megosztást egy meghajtó betűjelhez vagy használj UNC útvonalat (`\\server\share\license.lic`). Bizonyosodj meg róla, hogy a Python folyamatnak olvasási joga van. | +| **Docker konténerben futtatás** | Másold a `.lic` fájlt a képre, és hivatkozz rá egy abszolút útvonallal, például `/app/license/Aspose.OCR.Java.lic`. | +| **Több Python interpreter** (pl. conda környezetek) | Telepítsd a licencfájlt egyszer minden környezetben, vagy tarts egy központi helyet, és irányítsd minden interpretert oda. | +| **Licencfájl hiányzik futás közben** | Elegánsan térj vissza próbaverzióba (ha támogatott), vagy állj le egy egyértelmű naplóüzenettel. | + +### Gyakori buktatók + +- **Előre írt perjelek használata Windowson** – a Python elfogadja őket, de néhány régebbi SDK verzió félreértheti. Maradj a nyers karakterláncoknál vagy dupla visszaperjeleknél. +- **Elfelejtetted importálni a `License`-t** – a szkript `NameError`-rel leáll. Mindig importáld, mielőtt példányosítanád. +- **A `set_license` hívása OCR metódusok után** – az SDK az első használatkor ellenőrzi a licencet, ezért **előbb** állítsd be az útvonalat. + +## Teljesen működő példa + +Az alábbiakban egy komplett szkript látható, amely mindent összekapcsol. Mentsd el `ocr_setup.py` néven, és futtasd a parancssorból. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Várható kimenet** (érvényes kép esetén): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Ha a licencfájl nem található, egyértelmű hibaüzenetet kapsz a titokzatos „License not found” kivétel helyett. + +--- + +## Összegzés + +Most már pontosan tudod, hogyan **hozz létre licencpéldányt** Pythonban és hogyan **állítsd be a licenc útvonalát** az Aspose OCR SDK-hoz. A lépések egyszerűek: telepítsd a csomagot, importáld a `License`-t, példányosítsd, mutasd rá a `.lic` fájlra, és ellenőrizd egy kis OCR teszttel. + +Ezzel a tudással OCR képességeket ágyazhatsz be webszolgáltatásokba, asztali alkalmazásokba vagy automatizált pipeline-okba anélkül, hogy licenchibákba ütköznél. Következő lépésként érdemes megismerned a fejlett OCR beállításokat – nyelvi csomagok, képelőfeldolgozás vagy kötegelt feldolgozás – amelyek mind a most felállított szilárd alapra épülnek. + +Kérdésed van a telepítéssel, Dockerrel vagy több licenc kezelésével kapcsolatban? Írj egy megjegyzést, és jó kódolást! + +## Mit érdemes még tanulnod? + +- [Aspose OCR Bemutató – Optikai Karakterfelismerés](/ocr/english/) +- [Hogyan állíts be licencet és ellenőrizd az Aspose.OCR licencet Java-ban](/ocr/english/java/ocr-basics/set-license/) +- [Hogyan OCR-ozz képszöveget nyelvvel az Aspose.OCR használatával](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..cba958981 --- /dev/null +++ b/ocr/hungarian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: Keressenelhető PDF létrehozása beolvasott képekből Python OCR-rel. Tanulja + meg, hogyan konvertáljon beolvasott képes PDF-et, hogyan konvertáljon TIFF-et PDF-be, + és hogyan adjon hozzá OCR szövegréteget percek alatt. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: hu +og_description: Készítsen azonnal kereshető PDF-et. Ez az útmutató bemutatja, hogyan + futtathat OCR-t, konvertálhat beolvasott képes PDF-et, és adhat hozzá OCR szövegréteget + egyetlen Python szkript segítségével. +og_title: Kereshető PDF létrehozása Python segítségével – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Kereshető PDF létrehozása Python‑ban – Lépésről‑lépésre útmutató +url: /hu/python-java/general/create-searchable-pdf-with-python-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 Python‑nal – Lépésről‑lépésre útmutató + +Gondolkodtál már azon, hogyan lehet **create searchable PDF**-t létrehozni egy beolvasott oldalból anélkül, hogy tucatnyi eszközt kellene cserélgetned? Nem vagy egyedül. Sok irodai munkafolyamatban egy beolvasott TIFF vagy JPEG kerül a megosztott meghajtóra, és a következő személynek kézzel kell másolnia‑beillesztenie a szöveget – fájdalmas, hibára hajlamos és időpazarló. + +Ebben az útmutatóban egy tiszta, programozott megoldáson keresztül vezetünk végig, amely lehetővé teszi, hogy **convert scanned image PDF**, **convert TIFF to PDF**, és **add OCR text layer** egy lépésben. A végére egy kész‑használatra szánt szkriptet kapsz, amely futtatja az OCR‑t, beágyazza a rejtett szöveget, és egy kereshető PDF‑et állít elő, amelyet indexelhetsz, kereshetsz vagy magabiztosan megoszthatsz. + +## Amire szükséged lesz + +- Python 3.9+ (bármely friss verzió működik) +- `aspose-ocr` és `aspose-pdf` csomagok (telepítve a `pip install aspose-ocr aspose-pdf` paranccsal) +- Egy beolvasott képfájl (`.tif`, `.png`, `.jpg`, vagy akár egy PDF‑oldal, amely csak egy kép) +- Mérsékelt mennyiségű RAM (az OCR motor könnyű; még egy laptop is képes kezelni) + +> **Pro tipp:** Ha Windows‑t használsz, a csomagok legegyszerűbb beszerzési módja, ha a parancsot egy emelt jogosultságú PowerShell ablakban futtatod. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Most, hogy az előfeltételek rendben vannak, merüljünk el a kódban. + +## 1. lépés: OCR motor példány létrehozása – *create searchable pdf* + +Az első dolog, amit teszünk, elindítjuk az OCR motort. Gondolj rá úgy, mint egy agyra, amely minden pixelt elolvas és karakterekké alakít. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Miért fontos:** A motor egyszeri inicializálása alacsony memóriahasználatot biztosít. Ha `OcrEngine()`‑t egy ciklusban minden oldalra meghívnád, gyorsan kifogynál az erőforrásokból. + +## 2. lépés: Beolvasott kép betöltése – *convert tiff to pdf* & *convert scanned image pdf* + +Ezután irányítsd a motort arra a fájlra, amelyet feldolgozni szeretnél. Az API bármilyen raszteres képet elfogad, így egy TIFF ugyanolyan jól működik, mint egy JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Ha egy PDF‑ed csak egy beolvasott képet tartalmaz, akkor is használhatod a `load_image`‑t, mivel az Aspose automatikusan kinyeri az első oldalt. + +## 3. lépés: PDF mentési beállítások előkészítése – *add OCR text layer* + +Itt konfiguráljuk, hogyan nézzen ki a végleges PDF. A kulcsfontosságú jelző a `create_searchable_pdf`; `True`‑ra állítva a könyvtár egy láthatatlan szövegréteget ágyaz be, amely tükrözi a vizuális tartalmat. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Mit csinál a szövegréteg:** Amikor megnyitod a létrehozott fájlt az Adobe Readerben és megpróbálsz szöveget kijelölni, a rejtett karaktereket fogod látni. A keresőmotorok is indexelni tudják őket – tökéletes megfelelőség vagy archiválás esetén. + +## 4. lépés: OCR futtatása és mentés – *how to run OCR* egyetlen hívásban + +Most történik a varázslat. Egy metódushívás lefuttatja a felismerő motort és a kereshető PDF‑et a lemezre írja. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +A `recognize` metódus egy státuszobjektust ad vissza, amelyet hibák után ellenőrizhetsz, de a legtöbb egyszerű esetben a fenti egyszerű hívás elegendő. + +### Várt kimenet + +A szkript futtatása a következőt írja ki: + +``` +PDF saved as searchable PDF. +``` + +Ha megnyitod a `scanned_page_searchable.pdf` fájlt, észre fogod venni, hogy szöveget kijelölhetsz, másolhatsz‑beilleszthetsz, és még egy `Ctrl+F` keresést is futtathatsz. Ez a **create searchable pdf** munkafolyamat jellemzője. + +## Teljes működő szkript + +Az alábbiakban a teljes, futtatható szkript található. Csak cseréld ki a helyőrző útvonalakat a saját fájlhelyeidre. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Mentsd el `create_searchable_pdf.py` néven, és futtasd: + +```bash +python create_searchable_pdf.py +``` + +## Gyakori kérdések és széljegyek + +### 1️⃣ Feldolgozhatok többoldalas PDF‑eket? + +Igen. Használd a `ocr_engine.load_image("file.pdf")`‑t, majd egy ciklussal dolgozd fel az egyes oldalakat a `ocr_engine.recognize(pdf_save_options, page_number)`‑val. A könyvtár automatikusan többoldalas kereshető PDF‑et generál. + +### 2️⃣ Mi van, ha a forrásfájl egy nagy felbontású TIFF (300 dpi+)? + +A magasabb DPI jobb OCR pontosságot eredményez, de nagyobb memóriahasználatot is. Ha `MemoryError`‑t kapsz, először méretezd le a képet: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Hogyan változtathatom meg az OCR nyelvét? + +Állítsd be a `language` tulajdonságot a motoron, mielőtt betöltenéd a képet: + +```python +ocr_engine.language = "fra" # French +``` + +A támogatott nyelvkódok teljes listája az Aspose dokumentációban található. + +### 4️⃣ Mi van, ha meg kell őriznem az eredeti képminőséget? + +A `PdfSaveOptions` osztálynak van egy `compression` tulajdonsága. Állítsd `PdfCompression.None`‑ra, hogy a raszteres adatot pontosan úgy őrizd meg, ahogy volt. + +```python +pdf_save_options.compression = "None" +``` + +## Tippek a termelés‑kész telepítésekhez + +- **Kötegelt feldolgozás:** Csomagold a fő logikát egy olyan függvénybe, amely fájlútvonalak listáját fogadja. Minden sikeres vagy sikertelen műveletet naplózz CSV‑ben az audit nyomvonalakhoz. +- **Párhuzamosság:** Használd a `concurrent.futures.ThreadPoolExecutor`‑t, hogy több magon futtass OCR‑t. Csak ne feledd, hogy minden szálnak saját `OcrEngine` példányra van szüksége. +- **Biztonság:** Ha érzékeny dokumentumokat kezelsz, futtasd a szkriptet egy sandbox környezetben, és a feldolgozás után azonnal töröld a temporális fájlokat. + +## Összegzés + +Most már tudod, hogyan kell **create searchable PDF** fájlokat létrehozni beolvasott képekből egy tömör Python szkript segítségével. Az OCR motor inicializálásával, egy TIFF (vagy bármilyen raszter) betöltésével, a `PdfSaveOptions` beállításával **add OCR text layer**, és végül a `recognize` meghívásával az egész **convert scanned image pdf** és **convert TIFF to PDF** folyamat egyetlen, ismételhető parancssá válik. + +Következő lépések? Próbáld meg összekapcsolni ezt a szkriptet egy fájlfigyelővel, hogy bármely új beolvasás, amely egy mappába kerül, automatikusan kereshető legyen. Vagy kísérletezz különböző OCR nyelvekkel a többnyelvű archívumok támogatásához. A határ csak a képzeleted, ha az OCR‑t a PDF‑generálással kombinálod. + +Van még kérdésed a **how to run OCR**-rel kapcsolatban más nyelvekben vagy keretrendszerekben? Hagyj egy megjegyzést alább, és jó kódolást! + +![Diagram, amely a beolvasott képből → OCR motor → kereshető PDF (create searchable pdf) folyamatot mutatja](searchable-pdf-flow.png "Create searchable pdf folyamat diagram") + +## Mit érdemes még megtanulni? + +- [Hogyan OCR‑elj PDF-et .NET‑ben az Aspose.OCR segítségével](/ocr/english/net/text-recognition/recognize-pdf/) +- [Képek konvertálása PDF‑be C# – Többoldalas OCR eredmény mentése](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Hogyan OCR‑elj képszöveget nyelvvel az Aspose.OCR használatával](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/hungarian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e8188525f --- /dev/null +++ b/ocr/hungarian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Javítsd az OCR pontosságát Python segítségével a képek előfeldolgozásával. + Tanuld meg, hogyan lehet szöveget kinyerni képfájlokból, PNG-ből felismerni, és + fokozni az eredményeket. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: hu +og_description: Növelje az OCR pontosságát Pythonban képfeldolgozással a szöveghez. + Kövesse ezt az útmutatót, hogy könnyedén kinyerje a szöveget képfájlokból, és felismerje + a PNG-kből a szöveget. +og_title: OCR pontosságának javítása Pythonban – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR pontosságának javítása Pythonban – Teljes lépésről‑lépésre útmutató +url: /hu/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR pontosság javítása Pythonban – Teljes lépésről‑lépésre útmutató + +Próbáltad már **javítani az OCR pontosságát**, csak hogy összezavart kimenetet kapj? Nem vagy egyedül. A legtöbb fejlesztő elakad, amikor a nyers kép zajos, ferde vagy egyszerűen alacsony kontrasztú. A jó hír? Néhány előfeldolgozási trükkel egy homályos képernyőképet tiszta, gép‑olvasható szöveggé alakíthatunk. + +Ebben a tutorialban egy valós példán keresztül mutatjuk be, hogyan **előfeldolgozzuk a képet OCR‑hez**, futtatjuk a felismerő motorját, és végül **kivonjuk a szöveget a képfájlból** – konkrétan egy PNG‑ből. A végére pontosan tudni fogod, hogyan **ismerjünk fel szöveget PNG‑ből** magasabb sikerarány mellett, és kapsz egy újrahasználható kódrészletet, amit bármely projektbe beilleszthetsz. + +## Mit fogsz megtanulni + +- Miért fontos a kép‑előfeldolgozás az OCR motorok számára +- Mely előfeldolgozási módok (denoise, deskew) adnak a legnagyobb lökést +- Hogyan konfigurálj egy `OcrEngine` példányt Pythonban +- A teljes, futtatható szkript, amely **kivonja a szöveget a képfájlból** +- Tippek a szélhelyzetek kezeléséhez, például elfordított szkennek vagy alacsony felbontású képeknek + +Nem szükséges külső könyvtár az OCR SDK‑n kívül, de Python 3.8+ és egy PNG kép szükséges, amelyet be szeretnél olvasni. + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Improve OCR accuracy workflow") + +*Alt szöveg: OCR pontosság javításának munkafolyamatai, amely bemutatja az előfeldolgozási és felismerési lépéseket.* + +## Előfeltételek + +- Python 3.8 vagy újabb telepítve +- Hozzáférés az OCR SDK‑hoz, amely biztosítja az `OcrEngine`, `OcrEngineSettings` és `ImagePreprocessMode` osztályokat (az alábbi kód egy általános API‑t használ; szükség esetén cseréld ki a saját szállítód osztályaira) +- Egy PNG kép (`input.png`) egy olyan mappában, amelyre hivatkozhatsz + +Ha virtuális környezetet használsz, aktiváld most – semmi bonyolult, csak `python -m venv venv && source venv/bin/activate`. + +--- + +## 1. lépés: OCR motor példány létrehozása – Kezdjük az OCR pontosság javítását + +Az első dolog, amire szükséged van, egy OCR motor objektum. Gondolj rá úgy, mint az agyra, amely később a pixeleket olvassa és karaktereket ad ki. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Miért fontos: motor nélkül nem tudsz semmilyen előfeldolgozást alkalmazni, és a nyers képet közvetlenül a felismerőnek adod – ami általában a legrosszabb eset a pontosság szempontjából. + +--- + +## 2. lépés: Cél PNG betöltése – A színpad felállítása a „Recognize Text from PNG” számára + +Most megmondjuk a motornak, melyik fájlon dolgozzon. A PNG veszteségmentes, ami már egy kis előnyt jelent a JPEG‑hez képest. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Ha a kép máshol van, csak módosítsd az elérési utat. A motor bármely támogatott formátumot elfogad, de a PNG gyakran megőrzi a finom részleteket, amelyek a tiszta karakterélekhez szükségesek. + +--- + +## 3. lépés: Előfeldolgozás beállítása – Preprocess Image for OCR + +Itt történik a varázslat. Létrehozunk egy beállítási objektumot, engedélyezzük a zajszűrést a foltok eltávolításához, és bekapcsoljuk a ferde szöveg automatikus kiegyenesítését. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Miért Denoise + Deskew? + +- **Denoise**: A véletlenszerű pixelzaj összezavarja a mintázat‑illesztő algoritmusokat. A zaj eltávolítása élesíti a betűket. +- **Deskew**: Már egy 2‑fokos ferdeség is drámaian csökkentheti a bizalmi pontszámokat. A deskew kiegyenesíti az alapvonalat, így a felismerő megbízhatóbban tudja párosítani a betűtípusokat. + +Kísérletezhetsz további flag‑ekkel (pl. `ImagePreprocessMode.CONTRAST_ENHANCE`), ha a képeid különösen sötétek. Az SDK dokumentációja általában felsorolja az összes elérhető módot. + +--- + +## 4. lépés: Beállítások alkalmazása a motorra – Tie Preprocessing to OCR + +Rendeld hozzá a beállítási objektumot a motorhoz, hogy a következő felismerési futtatás a most definiált transzformációkat használja. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Ha kihagyod ezt a lépést, a motor az alapértelmezett beállításokra (gyakran „nincs előfeldolgozás”) tér vissza, és **alacsonyabb OCR pontosságot** fogsz tapasztalni. + +--- + +## 5. lépés: A felismerési folyamat indítása – Extract Text from Image + +Miután mindent összekapcsoltunk, végül megkérjük a motort, hogy végezze el a feladatát. A hívás szinkron, egy eredményobjektumot ad vissza, amely a felismert szöveget tartalmazza. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +A motor a háttérben most: + +1. Betölti a PNG‑t a memóriába +2. Alkalmazza a denoise‑t és a deskew‑et a beállításaink alapján +3. Fut a neurális háló vagy a klasszikus mintázat‑illesztő +4. Az eredményt a `recognition_result`‑ba csomagolja + +--- + +## 6. lépés: A felismert szöveg kiírása – Verify the Improvement + +Nyomtassuk ki a kinyert karakterláncot. Egy valós alkalmazásban fájlba, adatbázisba vagy egy másik szolgáltatásba is továbbíthatod. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Várható kimenet + +Ha a kép a „Hello, OCR World!” mondatot tartalmazza, a következőt kell látnod: + +``` +Hello, OCR World! +``` + +Figyeld meg, hogy a szöveg tiszta – nincsenek idegen szimbólumok vagy törött karakterek. Ez a megfelelő **image preprocessing for text** eredménye. + +--- + +## Pro tippek & szélhelyzetek + +| Szituáció | Mit kell módosítani | Miért | +|-----------|---------------------|-------| +| Nagyon alacsony felbontású PNG (≤ 72 dpi) | Add hozzá az `ImagePreprocessMode.SUPER_RESOLUTION` flag‑et, ha elérhető | Az upsampling több pixelt ad a felismerőnek, így jobb eredményt érhet el | +| A szöveg > 5°‑kal elfordult | Növeld a deskew toleranciát vagy előbb manuálisan forgasd el a képet a `Pillow`‑al, mielőtt a motorhoz adnád | A szélsőséges szögek néha megkerülik az automatikus deskew‑et | +| Erős háttérminták | Engedélyezd az `ImagePreprocessMode.BACKGROUND_REMOVAL` flag‑et | Eltávolítja a nem‑szöveges zajt, amely egyébként félreolvasásra késztethet | +| Többnyelvű dokumentum | Állítsd be `ocr_engine.language = "eng+spa"` (vagy hasonló) | A motor a megfelelő karakterkészletet választja, ezáltal javítva a teljes pontosságot | + +Ne feledd, a **improve OCR accuracy** nem egy mindenki számára egyforma megoldás; a saját adatkészletedhez valószínűleg iterálni kell a előfeldolgozási flag‑eken. + +--- + +## Teljes szkript – Kész a másolásra és beillesztésre + +Az alábbiakban megtalálod a teljes, futtatható példát, amely tartalmazza a megbeszélt minden lépést. Mentsd el `improve_ocr_accuracy.py` néven, és futtasd a `python improve_ocr_accuracy.py` paranccsal. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Futtasd, figyeld a konzolt, és azonnal látnod kell a **extract text from image** eredményt. Ha a kimenet nem megfelelő, finomhangold a `preprocess_mode` flag‑eket a “Pro tippek” táblázatban leírtak szerint. + +--- + +## Összegzés + +Átmentünk egy gyakorlati recepten, amely **javítja az OCR pontosságát** Python segítségével. Létrehoztunk egy `OcrEngine`‑t, betöltöttünk egy PNG‑t, **előfeldolgoztuk a képet OCR‑hez**, és végül **szöveget ismerünk fel PNG‑ből**, így megbízhatóan **kivonjuk a szöveget a képfájlból**, még ha a forrás nem is tökéletes. + +Mi a következő lépés? Próbálj meg egy képcsomagot egy ciklusban feldolgozni, az eredményeket CSV‑be menteni, vagy kísérletezni további előfeldolgozási módokkal, például kontrasztjavítással. Ugyanez a minta PDF‑ekhez, beolvasott számlákhoz vagy kézírásos jegyzetekhez is működik – csak cseréld ki a bemenetet és állítsd be a paramétereket. + +Van kérdésed egy konkrét kép típussal kapcsolatban, vagy szeretnéd tudni, hogyan integráld ezt egy webszolgáltatásba? Írj kommentet, és együtt vizsgáljuk meg a szcenáriókat. Boldog kódolást, és legyen a OCR eredményed mindig kristálytiszta! + +## Mit érdemes még tanulni? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/hungarian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..bf186ad09 --- /dev/null +++ b/ocr/hungarian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Tanulja meg, hogyan használja az OCR érdeklődési területet a kép betöltéséhez + OCR-hez, és szöveget nyerjen ki egy téglalapból – tökéletes a számla összegének + felismeréséhez. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: hu +og_description: Mesteri OCR érdeklődési terület a kép betöltéséhez, a szöveg kinyerése + a téglalapból és a számla szövegének felismerése egyetlen oktatóanyagban. +og_title: OCR érdeklődési terület – lépésről lépésre Python útmutató +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR érdeklődési terület – Szöveg kinyerése téglalapból Pythonban +url: /hu/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR érdeklődési terület – Szöveg kinyerése téglalapból Pythonban + +Gondolkodtál már azon, hogyan **ocr region of interest** egy beolvasott számla adott részén anélkül, hogy az egész oldalt betáplálnád a motorba? Nem vagy az első, aki egy homályos nyugtán ülve azt kérdezi: „Hogyan nyerjem ki az összeget, ami valahol a jobb alsó sarokban van?” A jó hír, hogy megmondhatod az OCR könyvtárnak, pontosan hol keressen, ezzel drámaian növelve a sebességet és a pontosságot. + +Ebben az útmutatóban egy teljes, futtatható példán keresztül mutatjuk be, hogyan **load image for OCR**, hogyan definiálj egy **region of interest**, majd hogyan **extract text from rectangle**, végül hogyan **recognize text from invoice**, és válaszolj a klasszikus „hogyan nyerjük ki az összeget” kérdésre. Nincs homályos hivatkozás – csak konkrét kód, világos magyarázatok és néhány profi tipp, amiről jó lenne, ha korábban tudtad volna. + +--- + +## Mit fogsz építeni + +A tutorial végére egy apró Python szkriptet kapsz, amely: + +1. Betölti a számla képet a lemezről. +2. Megjelöli azt a téglalap alakú ROI-t, ahol a végösszeg található. +3. Az OCR‑t csak ezen a ROI‑n futtatja. +4. Kiírja a megtisztított összeg karakterláncot. + +Mindez bármelyik ROI‑t támogató OCR könyvtárral működik – itt egy fiktív, de reprezentatív `SimpleOCR` csomagot használunk, amely a Tesseract vagy EasyOCR népszerű eszközeit idézi. Nyugodtan cseréld le; a koncepciók változatlanok. + +--- + +## Előfeltételek + +- Python 3.8+ telepítve (`python --version`‑nek ≥3.8‑at kell mutatnia). +- Pip‑el telepíthető OCR csomag (pl. `pip install simpleocr`). +- Egy számla kép (PNG vagy JPEG), amely egy mappában van, ahonnan hivatkozhatsz. +- Alapvető ismeretek Python függvényekről és osztályokról (semmi bonyolult). + +Ha már megvannak ezek, nagyszerű – vágjunk bele. Ha nem, először szerezd be a képet; a további lépések függetlenek a fájl tényleges tartalmától. + +--- + +## 1. lépés: Load Image for OCR + +Az első dolog, amire bármely OCR munkafolyamatnak szüksége van, egy bitmap, amiből olvasni tud. A legtöbb könyvtár egyszerű `load_image` metódust kínál, amely egy fájl útvonalat fogad. Így néz ki a `SimpleOCR` motorunkkal: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Használj abszolút útvonalakat vagy `os.path.join`‑t, hogy elkerüld a „file not found” meglepetéseket, amikor a szkriptet más munkakönyvtárból futtatod. + +--- + +## 2. lépés: Define OCR Region of Interest + +Ahelyett, hogy a motor az egész oldalt átvizsgálná, pontosan megmondjuk, hol helyezkedik el az összeg. Ez a **ocr region of interest** lépés, és ez a kulcs a megbízható kinyeréshez, különösen, ha a dokumentum zajos fejléceket vagy lábléceket tartalmaz. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Miért ezek a számok? Az `x` és `y` pixel eltolások a bal‑felső sarokhoz képest, míg a `width` és `height` a doboz méretét írják le. Ha bizonytalan vagy, nyisd meg a képet bármely szerkesztőben, aktiváld a vonalzót, és jegyezd fel a koordinátákat. Sok IDE is lehetővé teszi, hogy a kurzor pozícióját mutassa, miközben lebegsz. + +--- + +## 3. lépés: Extract Text from Rectangle + +Most, hogy a ROI be van állítva, megkérjük a motort, hogy **recognize text from invoice**, de csak a most hozzáadott téglalapra korlátozva. A hívás egy eredményobjektust ad vissza, amely általában a nyers karakterláncot, a biztonsági pontszámokat és néha a határoló dobozokat tartalmazza. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +A háttérben a `recognize()` minden ROI‑t bejár, kivágja a szeletet, lefuttatja az OCR modellt, és összefűzi az eredményeket. Ezért egy szorosan definiált **extract text from rectangle** terület akár másodperceket is spórolhat a kötegelt feladatok feldolgozásában. + +--- + +## 4. lépés: How to Extract Amount – Clean the Output + +Az OCR nem tökéletes; gyakran kapsz felesleges szóközöket, sortöréseket vagy akár félreolvasott karaktereket (pl. „S” vs „5”). Egy gyors `strip()` és egy apró regex általában megoldja a pénzügyi értékek esetén. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Miért fontos:** Ha az összeget adatbázisba vagy fizetési átjáróba szeretnéd továbbadni, előre meghatározott formátumra van szükség. A whitespace eltávolítása és a nem numerikus karakterek szűrése megakadályozza a downstream hibákat. + +--- + +## 5. lépés: Recognize Text from Invoice – Full Script + +Mindent összevetve, itt a teljes, azonnal futtatható szkript. Mentsd el `extract_amount.py` néven, és futtasd `python extract_amount.py`‑vel. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Várható kimenet + +``` +Amount: 1,245.67 +``` + +Ha a ROI nincs megfelelően igazítva, előfordulhat, hogy `Amount: 1245.6S`‑t látsz – vegyük észre a felesleges „S” karaktert. Állítsd be a téglalap koordinátáit, és futtasd újra, amíg a kimenet tisztának tűnik. + +--- + +## Gyakori hibák és széljegyek + +| Probléma | Miért fordul elő | Javítás | +|----------|------------------|---------| +| **ROI túl kicsi** | Az összeg szövege levágódik, részleges felismeréshez vezet. | Növeld a `width`/`height` értékeket ~10‑20 %-kal, és teszteld újra. | +| **Helytelen DPI** | Alacsony felbontású szkennelés (≤150 dpi) csökkenti az OCR pontosságát. | Resample-eld a képet 300 dpi-re a betöltés előtt, vagy kérj magasabb DPI‑t a szkennertől. | +| **Több pénznem** | A regex az első numerikus csoportot veszi, ami lehet egy számlaszám. | Finomítsd a regexet, hogy a számjegyek előtt keresse a pénznem szimbólumokat (`$`, `€`, `£`). | +| **Forgatott számlák** | Az OCR motorok felálló szöveget várnak; a forgatott oldalak hibásak. | Alkalmazz forgatási korrekciót (`ocr_engine.rotate(90)`) a ROI hozzáadása előtt. | +| **Zaj a háttérben** | Árnyékok vagy bélyegek összezavarják a modellt. | Előfeldolgozás egyszerű küszöböléssel (`cv2.threshold`) vagy zajszűrő szűrővel. | + +Ezeknek a széljegyeknek a korai kezelése órákat takaríthat meg a későbbi hibakeresésben. + +--- + +## Pro tippek valós projektekhez + +- **Kötegelt feldolgozás:** Egy mappában lévő számlákon iterálj, dinamikusan számold ki a ROI‑t (pl. sablonfelismerés alapján), és az eredményeket CSV‑ben tárold. +- **Sablon egyezés:** Ha több számla elrendezést kezelsz, tarts egy JSON térképet `template_id → ROI koordináták` formátumban. Válts ROI‑t egy gyors elrendezés‑osztályozó alapján. +- **Párhuzamos végrehajtás:** Használd a `concurrent.futures.ThreadPoolExecutor`‑t, hogy több OCR példányt futtass egyszerre – nagyszerű nagy mennyiségű back‑office csővezetékekhez. +- **Biztonsági szűrés:** A legtöbb OCR eredmény tartalmaz biztonsági pontszámot. Dobd el a 85 % alatti eredményeket, és jelöld őket manuális felülvizsgálatra. + +--- + +## Összegzés + +Mindent lefedtünk, ami ahhoz kell, hogy **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, és végül **recognize text from invoice** segítségével megválaszold a klasszikus **how to extract amount** kérdést. A szkript kompakt, mégis elég rugalmas ahhoz, hogy különböző dokumentumformátumokhoz, nyelvekhez és OCR back‑ekhez igazodjon. + +Miután elsajátítottad az alapokat, gondolkodj a munkafolyamat bővítésén: adj hozzá vonalkód‑olvasást, integráld egy PDF parserrel, vagy küldd el a kinyert összeget egy könyvelő API‑nak. A lehetőségek végtelenek, és egy jól definiált ROI‑val mindig gyorsabb, tisztább eredményeket kapsz. + +Ha elakadsz, írj egy megjegyzést alul – jó OCR‑ozást! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## Mit tanulj meg legközelebb? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/indonesian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..58e9fb38f --- /dev/null +++ b/ocr/indonesian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Tutorial OCR async yang menunjukkan cara menggunakan Aspose OCR di Python + dengan asyncio untuk ekstraksi teks gambar yang cepat. Pelajari implementasi OCR + async langkah demi langkah. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: id +og_description: Tutorial OCR async memandu Anda melalui penggunaan Aspose OCR di Python + dengan asyncio untuk ekstraksi teks gambar yang efisien. +og_title: Tutorial OCR Asinkron – Python asyncio dengan Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Tutorial OCR Asinkron – Python asyncio dengan Aspose OCR +url: /id/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial OCR Asinkron – Python asyncio dengan Aspose OCR + +Pernah bertanya-tanya bagaimana cara menjalankan optical character recognition tanpa memblokir aplikasi Anda? Dalam **tutorial OCR asinkron** Anda akan melihat hal itu—ekstraksi teks non‑blocking menggunakan `asyncio` Python dan pustaka Aspose OCR. + +Jika Anda pernah terjebak menunggu gambar besar diproses, panduan ini memberikan solusi asinkron yang bersih sehingga event loop Anda tetap berjalan. + +Di bagian-bagian berikut kami akan membahas semua yang Anda perlukan: menginstal pustaka, menyiapkan helper asinkron, menangani hasil, dan bahkan tip cepat untuk menskalakan ke banyak gambar. Pada akhir tutorial Anda dapat menyisipkan **tutorial OCR asinkron** ke proyek Python apa pun yang sudah menggunakan `asyncio`. + +## Apa yang Anda Butuhkan + +Sebelum kita mulai, pastikan Anda memiliki: + +* Python 3.9+ (API `asyncio` yang kami gunakan stabil sejak 3.7) +* Lisensi Aspose OCR yang aktif atau trial gratis (pustaka ini murni Python, tanpa binary native) +* File gambar kecil (`.jpg`, `.png`, dll.) yang ingin Anda baca – simpan di folder yang diketahui + +Tidak ada alat eksternal lain yang diperlukan; semuanya berjalan di Python murni. + +## Langkah 1: Instal Paket Aspose OCR + +Hal pertama, dapatkan paket Aspose OCR dari PyPI. Buka terminal dan jalankan: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Jika Anda bekerja di dalam virtual environment (sangat disarankan), aktifkan terlebih dahulu. Ini menjaga dependensi terisolasi dan menghindari bentrok versi. + +## Langkah 2: Inisialisasi Engine OCR Secara Asinkron + +Inti dari **tutorial OCR asinkron** kami adalah fungsi helper asinkron. Fungsi ini membuat instance `OcrEngine`, memuat gambar, dan kemudian memanggil `recognize_async()`. Engine itu sendiri bersifat sinkron, tetapi metode pembungkus mengembalikan awaitable, sehingga event loop tetap responsif. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Mengapa kami melakukannya seperti ini:** +*Membuat engine di dalam helper memastikan thread‑safety jika Anda kemudian menjalankan banyak pekerjaan OCR secara paralel. Kata kunci `await` mengembalikan kontrol ke event loop sementara pekerjaan berat dilakukan di thread pool internal pustaka.* + +## Langkah 3: Jalankan Helper dari Fungsi Async Main + +Sekarang kita membutuhkan coroutine kecil `main()` yang memanggil `async_ocr()` dan mencetak hasilnya. Ini meniru titik masuk tipikal untuk skrip `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Apa yang terjadi di balik layar?** +`asyncio.run()` membuat event loop baru, menjadwalkan `main()`, dan menutup loop dengan bersih ketika `main()` selesai. Pola ini merupakan cara yang direkomendasikan untuk memulai program asinkron di Python 3.7+. + +## Langkah 4: Uji Skrip Lengkap + +Simpan dua blok kode di atas ke dalam satu file, misalnya `async_ocr_demo.py`. Jalankan dari command line: + +```bash +python async_ocr_demo.py +``` + +Jika semuanya terpasang dengan benar Anda akan melihat sesuatu seperti: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Output tepatnya akan bergantung pada konten `photo.jpg`. Intinya, skrip selesai dengan cepat, bahkan jika gambar besar, karena pekerjaan OCR terjadi di latar belakang. + +## Langkah 5: Menskalakan – Proses Banyak Gambar Secara Bersamaan + +Pertanyaan lanjutan yang umum adalah, *“Bisakah saya OCR sekumpulan file tanpa meluncurkan proses baru untuk tiap file?”* Tentu saja. Karena helper kami sepenuhnya asinkron, kita dapat mengumpulkan banyak coroutine dengan `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Mengapa ini berhasil:** `asyncio.gather()` menjadwalkan semua tugas OCR sekaligus. Pustaka Aspose OCR tetap menggunakan thread pool-nya sendiri, tetapi dari perspektif Python semuanya tetap non‑blocking, memungkinkan Anda menangani puluhan gambar dalam waktu yang sama dengan satu panggilan sinkron. + +## Langkah 6: Menangani Error dengan Elegan + +Saat bekerja dengan file eksternal, Anda pasti akan menemui file yang hilang, gambar rusak, atau masalah lisensi. Bungkus pemanggilan OCR dalam blok `try/except` agar event loop tetap hidup: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Sekarang `batch_ocr()` dapat memanggil `safe_async_ocr` sebagai gantinya, memastikan satu file buruk tidak menghentikan seluruh batch. + +## Gambaran Visual + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial flowchart showing async_ocr helper, event loop, and Aspose OCR engine"} + +Diagram di atas memvisualisasikan alur: event loop → `async_ocr` → `OcrEngine` → thread latar belakang → hasil kembali ke loop. + +## Kesalahan Umum & Cara Menghindarinya + +| Kesalahan | Mengapa Terjadi | Solusi | +|-----------|----------------|--------| +| **I/O blocking di dalam helper** | Secara tidak sengaja menggunakan `open()` tanpa `await` dapat memblokir loop. | Gunakan `aiofiles` untuk membaca file, atau biarkan `engine.load_image` menanganinya (sudah non‑blocking). | +| **Menggunakan satu `OcrEngine` untuk banyak coroutine** | Engine tidak thread‑safe; panggilan bersamaan dapat merusak state. | Buat engine baru di setiap pemanggilan `async_ocr` (seperti yang ditunjukkan). | +| **Lisensi tidak ada** | Aspose OCR melemparkan exception terkait lisensi saat runtime. | Daftarkan lisensi Anda di awal (`OcrEngine.set_license("license.json")`). | +| **Gambar besar menyebabkan lonjakan memori** | Pustaka memuat seluruh gambar ke RAM. | Turunkan resolusi gambar sebelum OCR jika memori menjadi masalah. | + +## Ringkasan: Apa yang Telah Kita Capai + +Dalam **tutorial OCR asinkron** ini kami: + +1. Menginstal pustaka Aspose OCR. +2. Membuat helper `async_ocr` yang menjalankan pengenalan tanpa memblokir. +3. Menjalankan helper dari entry point `asyncio` yang bersih. +4. Menunjukkan pemrosesan batch dengan `asyncio.gather`. +5. Menambahkan penanganan error dan tip praktik terbaik. + +Semua ini murni Python, sehingga Anda dapat menyisipkannya ke server web, alat CLI, atau pipeline data tanpa menulis ulang kode async yang sudah ada. + +## Langkah Selanjutnya & Topik Terkait + +* **Preprocessing gambar secara asinkron** – gunakan `aiohttp` untuk mengunduh gambar secara bersamaan sebelum OCR. +* **Menyimpan hasil OCR** – kombinasikan tutorial ini dengan driver database async seperti `asyncpg` untuk PostgreSQL. +* **Optimasi performa** – coba `engine.recognize_async(max_threads=4)` jika pustaka menyediakan opsi tersebut. +* **Engine OCR alternatif** – bandingkan Aspose OCR dengan wrapper async Tesseract untuk analisis biaya‑manfaat. + +Silakan bereksperimen: coba proses PDF, sesuaikan pengaturan bahasa, atau hubungkan hasilnya ke chatbot. Langit adalah batasnya setelah Anda memiliki fondasi **tutorial OCR asinkron** yang solid. + +Selamat coding, semoga ekstraksi teks Anda selalu cepat! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +- [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/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/indonesian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..30a480e07 --- /dev/null +++ b/ocr/indonesian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-05-31 +description: Deteksi bahasa otomatis dalam OCR menjadi mudah. Pelajari cara memuat + OCR gambar, mengaktifkan deteksi bahasa otomatis, dan mengenali teks gambar dalam + beberapa langkah saja. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: id +og_description: Deteksi bahasa otomatis dalam OCR menjadi mudah. Ikuti tutorial langkah + demi langkah ini untuk mengaktifkan deteksi bahasa otomatis, memuat OCR gambar, + dan mengenali teks pada gambar. +og_title: Deteksi Bahasa Otomatis dengan OCR – Panduan Python Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Deteksi Bahasa Otomatis dengan OCR – Panduan Python Lengkap +url: /id/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Deteksi Bahasa Otomatis dengan OCR – Panduan Python Lengkap + +Pernahkah Anda bertanya-tanya bagaimana cara membuat mesin OCR *menebak* bahasa dokumen yang dipindai tanpa memberi tahu apa yang harus dicari? Itulah yang dilakukan oleh **deteksi bahasa otomatis**, dan ini benar‑benar mengubah cara kerja ketika Anda berhadapan dengan PDF multibahasa, foto rambu jalan, atau gambar apa pun yang mencampur skrip. + +Dalam tutorial ini kami akan menunjukkan contoh langsung yang memperlihatkan cara **mengaktifkan deteksi bahasa otomatis**, **memuat OCR gambar**, dan **mengenali teks gambar** menggunakan API bergaya Python. Pada akhir tutorial Anda akan memiliki skrip mandiri yang mencetak kode bahasa yang terdeteksi serta teks yang diekstrak—tanpa perlu mengatur bahasa secara manual. + +## Apa yang Akan Anda Pelajari + +- Cara membuat instance mesin OCR dan mengaktifkan **deteksi bahasa otomatis**. +- Langkah‑langkah tepat untuk **memuat OCR gambar** dari disk. +- Cara memanggil metode `recognize()` mesin dan mendapatkan hasil yang mencakup kode bahasa. +- Tips menangani kasus tepi seperti gambar beresolusi rendah atau skrip yang tidak didukung. + +Tidak diperlukan pengalaman sebelumnya dengan OCR multibahasa; cukup dengan setup Python dasar dan sebuah file gambar. + +--- + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +1. Python 3.8+ terpasang (versi terbaru apa pun sudah cukup). +2. Library OCR yang menyediakan `OcrEngine`, `LanguageAutoDetectMode`, dll. – untuk panduan ini kami mengasumsikan paket hipotetik bernama `myocr`. Instal dengan: + + ```bash + pip install myocr + ``` + +3. Sebuah file gambar (`multilingual_sample.png`) yang berisi teks dalam setidaknya dua bahasa berbeda. +4. Sedikit rasa ingin tahu—jika Anda belum pernah menyentuh OCR sebelumnya, jangan khawatir; kodenya sengaja dibuat sederhana. + +--- + +## Langkah 1: Aktifkan Deteksi Bahasa Otomatis + +Hal pertama yang harus Anda lakukan adalah memberi tahu mesin bahwa ia harus *menentukan* bahasa secara mandiri. Di sinilah flag **deteksi bahasa otomatis** berperan. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Mengapa ini penting:** +> Ketika `AUTO_DETECT` diatur, mesin menjalankan klasifikasi bahasa ringan pada gambar sebelum proses pengenalan karakter yang berat dimulai. Itu berarti Anda tidak perlu menebak apakah teksnya Bahasa Inggris, Rusia, Prancis, atau kombinasi apa pun. Mesin akan secara otomatis memilih model bahasa terbaik untuk setiap wilayah gambar. + +--- + +## Langkah 2: Muat OCR Gambar + +Setelah mesin tahu bahwa ia harus mendeteksi bahasa secara otomatis, kita perlu memberinya sesuatu untuk diproses. Langkah **muat OCR gambar** membaca bitmap dan menyiapkan buffer internal. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro tip:** +> Jika gambar Anda lebih besar dari 300 dpi, pertimbangkan untuk menurunkannya menjadi sekitar 150‑200 dpi. Terlalu banyak detail justru dapat *memperlambat* tahap deteksi bahasa tanpa meningkatkan akurasi. + +--- + +## Langkah 3: Kenali Teks dari Gambar + +Dengan gambar berada di memori dan deteksi bahasa diaktifkan, langkah terakhir adalah meminta mesin untuk **mengenali teks gambar**. Panggilan tunggal ini melakukan semua pekerjaan berat. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` adalah objek yang biasanya berisi setidaknya dua atribut: + +| Atribut | Deskripsi | +|-----------|-----------| +| `language` | Kode ISO‑639‑1 bahasa yang terdeteksi (misalnya, `"en"` untuk Bahasa Inggris). | +| `text` | Transkripsi teks biasa dari gambar. | + +--- + +## Langkah 4: Ambil Bahasa yang Terdeteksi dan Teks yang Diekstrak + +Sekarang kita cukup mencetak apa yang ditemukan mesin. Ini memperlihatkan kemampuan **detect language OCR** secara langsung. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Contoh output** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Bagaimana jika mesin mengembalikan `None`?** +> Itu biasanya berarti gambar terlalu buram atau teksnya terlalu kecil (< 8 pt). Coba tingkatkan kontras atau gunakan sumber dengan resolusi lebih tinggi. + +--- + +## Contoh Lengkap yang Berfungsi (Aktifkan Deteksi Bahasa Otomatis End‑to‑End) + +Menggabungkan semuanya, berikut skrip siap‑jalankan yang mencakup **enable auto language detection**, **load image OCR**, **recognize text image**, dan **detect language OCR** dalam satu langkah. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Simpan sebagai `automatic_language_detection_ocr.py`, ganti `YOUR_DIRECTORY` dengan folder yang berisi PNG Anda, lalu jalankan: + +```bash +python automatic_language_detection_ocr.py +``` + +Anda akan melihat kode bahasa diikuti oleh teks yang diekstrak, persis seperti contoh output di atas. + +--- + +## Menangani Kasus Tepi yang Umum + +| Situasi | Solusi yang Disarankan | +|-----------|------------------------| +| **Gambar beresolusi sangat rendah** (di bawah 100 dpi) | Upscale dengan filter bikubik sebelum memuat, atau minta sumber dengan resolusi lebih tinggi. | +| **Skrip campuran dalam satu gambar** (misalnya, Inggris + Sirilik) | Mesin biasanya akan membagi halaman menjadi wilayah; jika Anda melihat deteksi yang salah, atur `engine.enable_region_split = True`. | +| **Bahasa tidak didukung** | Pastikan library OCR menyertakan paket bahasa untuk skrip yang Anda butuhkan; Anda mungkin harus mengunduh model tambahan. | +| **Pemrosesan batch besar** | Inisialisasi mesin sekali, lalu gunakan kembali untuk beberapa siklus `load_image` / `recognize` agar tidak memuat model berulang kali. | + +--- + +## Gambaran Visual + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt text:* contoh output deteksi bahasa otomatis yang menampilkan kode bahasa dan teks multibahasa yang diekstrak. + +--- + +## Kesimpulan + +Kami baru saja membahas **deteksi bahasa otomatis** dari awal hingga akhir—membuat mesin, mengaktifkan deteksi bahasa otomatis, memuat gambar untuk OCR, mengenali teks, dan akhirnya mengambil bahasa yang terdeteksi. Alur end‑to‑end ini memungkinkan Anda memproses dokumen multibahasa tanpa harus mengonfigurasi model bahasa secara manual setiap kali. + +Jika Anda siap melangkah lebih jauh, pertimbangkan: + +- **Batching** ratusan gambar dengan loop yang menggunakan kembali instance `OcrEngine` yang sama. +- **Post‑processing** teks yang diekstrak dengan pemeriksa ejaan atau tokenizer khusus bahasa. +- **Integrasi** skrip ke layanan web yang menerima unggahan pengguna dan mengembalikan JSON dengan bidang `language` dan `text`. + +Silakan bereksperimen dengan format gambar berbeda (`.jpg`, `.tif`) dan lihat bagaimana akurasi deteksi berubah. Ada pertanyaan atau gambar sulit yang menolak untuk dibaca? Tinggalkan komentar di bawah—selamat coding! + + +## Apa yang Harus Anda Pelajari Selanjutnya? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0088e0285 --- /dev/null +++ b/ocr/indonesian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Pelajari cara mengonversi gambar menjadi teks dengan Python menggunakan + skrip konversi gambar ke teks massal. Kenali teks dari gambar yang dipindai menggunakan + Aspose.OCR dalam hitungan menit. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: id +og_description: Konversi gambar ke teks python secara instan. Panduan ini menunjukkan + konversi gambar ke teks secara massal dan cara mengenali teks dari gambar yang dipindai + dengan Aspose.OCR. +og_title: Mengonversi Gambar ke Teks dengan Python – Tutorial Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Mengonversi Gambar ke Teks dengan Python – Panduan Lengkap Langkah demi Langkah +url: /id/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi Gambar ke Teks dengan Python – Panduan Lengkap Langkah‑per‑Langkah + +Pernah bertanya-tanya bagaimana cara **convert images to text python** tanpa harus mencari puluhan pustaka? Anda tidak sendirian. Baik Anda sedang mendigitalkan kwitansi lama, mengekstrak data dari faktur yang dipindai, atau membangun arsip PDF yang dapat dicari, mengubah gambar menjadi file teks biasa adalah pekerjaan harian bagi banyak pengembang. + +Dalam tutorial ini kami akan menelusuri pipeline **bulk image to text conversion** yang mengenali teks dari gambar yang dipindai, menyimpan setiap hasil sebagai file `.txt` terpisah, dan melakukannya hanya dengan beberapa baris Python. Tidak perlu mencari‑cari API yang tidak dikenal—Aspose.OCR menangani semua pekerjaan berat, dan kami akan menunjukkan cara menghubungkannya. + +## Apa yang Akan Anda Pelajari + +- Cara menginstal dan mengonfigurasi paket Aspose.OCR untuk Python. +- Kode tepat yang diperlukan untuk **convert images to text python** menggunakan `BatchOcrEngine`. +- Tips menangani jebakan umum seperti format yang tidak didukung atau file yang rusak. +- Cara memverifikasi bahwa langkah **recognize text from scanned images** memang berhasil. + +Pada akhir panduan ini Anda akan memiliki skrip siap‑jalankan yang dapat memproses ribuan gambar sekaligus—sempurna untuk skenario pemrosesan batch apa pun. + +## Prasyarat + +- Python 3.8+ terpasang di mesin Anda. +- Sebuah folder berisi file gambar (PNG, JPEG, TIFF, dll.) yang ingin Anda ubah menjadi teks. +- Akun Aspose Cloud aktif atau lisensi percobaan gratis (paket gratis sudah cukup untuk pengujian). + +Jika Anda sudah memiliki semua itu, mari kita mulai. + +--- + +## Langkah 1 – Siapkan Lingkungan Python Anda + +Sebelum menulis kode OCR apa pun, pastikan Anda bekerja di dalam lingkungan virtual yang bersih. Ini akan mengisolasi dependensi dan mencegah bentrok versi. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Jaga direktori proyek Anda tetap rapi—buat subfolder bernama `ocr_project` dan letakkan skrip di dalamnya. Ini memudahkan penanganan path di kemudian hari. + +## Langkah 2 – Instal Aspose.OCR untuk Python + +Aspose.OCR adalah pustaka komersial, tetapi disertakan dengan wheel bergaya NuGet yang dapat Anda unduh dari PyPI. Jalankan perintah berikut di dalam lingkungan virtual yang sudah diaktifkan: + +```bash +pip install aspose-ocr +``` + +Jika Anda mendapatkan error izin, tambahkan flag `--user` atau jalankan perintah dengan `sudo` (hanya untuk Linux/macOS). Setelah instalasi, Anda akan melihat sesuatu seperti: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** Tidak seperti banyak alat OCR open‑source, Aspose.OCR mendukung **bulk image to text conversion** secara langsung dan menangani berbagai format gambar tanpa konfigurasi tambahan. Ia juga menyediakan kelas `BatchOcrEngine` yang menjadikan tugas “convert images to text python” menjadi operasi satu baris. + +## Langkah 3 – Konversi Gambar ke Teks Python dengan Batch OCR + +Berikutnya adalah inti tutorial. Di bawah ini adalah skrip yang dapat dijalankan sepenuhnya: + +1. Mengimpor kelas mesin OCR. +2. Membuat instance `BatchOcrEngine`. +3. Menunjuk mesin ke folder input berisi gambar. +4. Mengarahkan mesin menulis setiap file teks yang diekstrak ke folder output. +5. Menjalankan metode `recognize()`, yang **recognize text from scanned images** satu per satu. + +Simpan kode berikut sebagai `batch_ocr.py` di dalam folder proyek Anda: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Cara Kerjanya + +- **`BatchOcrEngine`** membungkus `OcrEngine` biasa tetapi menambahkan orkestrasi tingkat folder, tepat apa yang Anda butuhkan ketika ingin **convert images to text python** secara massal. +- Properti `input_folder` memberi tahu mesin di mana mencari gambar sumber. Ia secara otomatis memindai direktori dan mengantri setiap tipe file yang didukung. +- Properti `output_folder` menentukan tempat setiap file `.txt` disimpan. Mesin meniru nama file asli, sehingga `receipt1.png` menjadi `receipt1.txt`. +- Memanggil `recognize()` memicu loop internal yang memuat tiap gambar, menjalankan OCR, dan menulis hasilnya. Metode ini akan blok hingga semua file selesai diproses, memudahkan Anda menambahkan aksi lanjutan (misalnya, meng‑zip folder output). + +#### Output yang Diharapkan + +Saat Anda menjalankan skrip: + +```bash +python batch_ocr.py +``` + +Anda akan melihat: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Di dalam `output_texts` akan terdapat file teks biasa untuk setiap gambar. Buka salah satunya dengan editor teks dan Anda akan melihat hasil OCR mentah—biasanya mendekati teks cetak asli. + +## Langkah 4 – Verifikasi Hasil dan Tangani Kesalahan + +Bahkan mesin OCR terbaik pun dapat gagal pada pemindaian beresolusi rendah atau halaman yang sangat miring. Berikut cara cepat memeriksa output dan mencatat kegagalan apa pun. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Mengapa menambahkan ini?** +- Menangkap kasus di mana mesin secara diam‑diam menghasilkan string kosong (umum pada gambar yang tidak terbaca). +- Memberikan Anda daftar file bermasalah sehingga dapat diperiksa manual atau dijalankan ulang dengan pengaturan berbeda (misalnya, meningkatkan opsi `OcrEngine.preprocess`). + +### Kasus Khusus & Penyesuaian + +| Situation | Suggested Fix | +|-----------|----------------| +| Gambar diputar 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Bahasa campuran (Inggris + Prancis) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| PDF besar diubah menjadi gambar terlebih dahulu | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Kesalahan memori pada batch sangat besar | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Langkah 5 – Otomatiskan Seluruh Alur Kerja (Opsional) + +Jika Anda perlu menjalankan konversi ini setiap malam, bungkus skrip dalam file shell atau batch Windows sederhana, dan jadwalkan dengan `cron` (Linux/macOS) atau Task Scheduler (Windows). Berikut contoh minimal `run_ocr.sh` untuk sistem berbasis Unix: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Buat file dapat dieksekusi (`chmod +x run_ocr.sh`) dan tambahkan entri cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Itu akan menjalankan konversi setiap hari pada pukul 2 AM dan mencatat semua output untuk ditinjau nanti. + +--- + +## Kesimpulan + +Anda kini memiliki metode terbukti dan siap produksi untuk **convert images to text python** menggunakan `BatchOcrEngine` dari Aspose.OCR. Skrip ini menangani **bulk image to text conversion**, menulis setiap hasil ke file terpisah dengan elegan, serta menyertakan langkah verifikasi untuk memastikan Anda benar‑benar **recognize text from scanned images** dengan tepat. + +Selanjutnya Anda dapat: + +- Bereksperimen dengan pengaturan OCR berbeda (paket bahasa, deskew, reduksi noise). +- Mengalirkan teks yang dihasilkan ke indeks pencarian seperti Elasticsearch untuk pencarian full‑text instan. +- Menggabungkan pipeline ini dengan alat konversi PDF untuk memproses PDF yang dipindai dalam satu langkah. + +Punya pertanyaan, atau menemukan kendala dengan tipe file tertentu? Tinggalkan komentar di bawah, dan mari kita selesaikan bersama. Selamat coding, semoga proses OCR Anda cepat dan bebas error! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +- [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 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/indonesian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..c314abdfb --- /dev/null +++ b/ocr/indonesian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Buat instance lisensi di Python dan konfigurasikan jalur lisensi dengan + mudah. Pelajari cara mengatur lisensi Aspose OCR dengan contoh kode yang jelas. +draft: false +keywords: +- create license instance +- configure license path +language: id +og_description: Buat instance lisensi di Python dan konfigurasikan jalur lisensi secara + instan. Ikuti tutorial ini untuk mengaktifkan Aspose OCR dengan percaya diri. +og_title: Buat instansi lisensi di Python – Panduan Pengaturan Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Buat instance lisensi di Python – Panduan Langkah demi Langkah +url: /id/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat instance lisensi di Python – Panduan Pengaturan Lengkap + +Perlu **create license instance** untuk Aspose OCR di Python? Anda berada di tempat yang tepat. Dalam tutorial ini kami juga akan menunjukkan cara **configure license path** sehingga SDK mengetahui di mana menemukan file `.lic` Anda. + +Jika Anda pernah menatap skrip kosong bertanya-tanya mengapa mesin OCR terus mengeluh tentang produk yang tidak berlisensi, Anda tidak sendirian. Solusinya biasanya hanya beberapa baris kode—setelah Anda tahu persis di mana menaruhnya. Pada akhir panduan ini Anda akan memiliki lingkungan Aspose OCR yang sepenuhnya berlisensi siap mengenali teks, gambar, dan PDF tanpa masalah. + +## Apa yang akan Anda pelajari + +- Cara **create license instance** menggunakan paket `asposeocr`. +- Cara yang tepat untuk **configure license path** baik untuk pengembangan maupun produksi. +- Kesalahan umum (file hilang, izin salah) dan cara menghindarinya. +- Skrip lengkap yang dapat dijalankan dan dapat Anda masukkan ke proyek mana pun. + +Tidak diperlukan pengalaman sebelumnya dengan Aspose OCR, hanya instalasi Python 3 yang berfungsi dan file lisensi yang valid. + +--- + +## Langkah 1: Instal Paket Aspose OCR untuk Python + +Sebelum kita dapat **create license instance**, perpustakaan itu sendiri harus ada. Buka terminal dan jalankan: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Jika Anda menggunakan lingkungan virtual (sangat disarankan), aktifkan terlebih dahulu. Ini menjaga dependensi Anda tetap rapi dan mencegah benturan versi. + +## Langkah 2: Impor Kelas License + +Sekarang SDK sudah tersedia, baris pertama skrip Anda harus mengimpor kelas `License`. Ini adalah objek yang akan kita gunakan untuk **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Mengapa mengimpornya langsung? Karena objek `License` harus diinstansiasi **sebelum** panggilan OCR apa pun; jika tidak SDK akan melempar kesalahan lisensi saat Anda mencoba memproses gambar. + +## Langkah 3: Buat Instance Lisensi + +Berikut adalah momen yang Anda tunggu—sebenarnya **create license instance**. Hanya satu baris, tetapi konteks di sekitarnya penting. + +```python +# Step 3: Create a License instance +license = License() +``` + +Variabel `license` sekarang menyimpan objek yang mengontrol semua perilaku lisensi untuk proses Python saat ini. Anggaplah sebagai penjaga gerbang yang memberi tahu Aspose OCR, “Hei, saya memiliki hak untuk menjalankan.” + +## Langkah 4: Konfigurasikan Jalur Lisensi + +Dengan instance siap, kita perlu menunjukkannya ke file `.lic` kita. Di sinilah **configure license path** berperan. Ganti placeholder dengan jalur absolut ke file lisensi Anda. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Beberapa hal yang perlu diperhatikan: + +1. **Raw strings (`r"…"`)** mencegah backslash diinterpretasikan sebagai karakter escape pada Windows. +2. Gunakan **jalur absolut** untuk menghindari kebingungan ketika skrip dijalankan dari direktori kerja yang berbeda. +3. Jika Anda lebih suka jalur relatif (misalnya saat menyertakan lisensi bersama proyek), pastikan basis relatif adalah lokasi skrip, bukan direktori shell saat ini. + +### Menangani File yang Hilang + +Jika jalur salah atau file tidak dapat dibaca, `set_license` akan menghasilkan pengecualian. Bungkus pemanggilan dalam blok `try/except` untuk memberikan pesan error yang ramah: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Potongan kode ini **configures license path** dengan aman dan memberi tahu Anda persis apa yang salah—tanpa jejak stack yang misterius. + +## Langkah 5: Verifikasi Lisensi Aktif + +Pemeriksaan cepat dapat menghemat jam debugging di kemudian hari. Setelah Anda memanggil `set_license`, coba operasi OCR sederhana. Jika lisensi valid, SDK akan memproses gambar tanpa melempar kesalahan lisensi. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Jika Anda melihat teks yang dikenali tercetak, selamat—Anda telah berhasil **create license instance** dan **configure license path**. Jika muncul pengecualian lisensi, periksa kembali jalur dan izin file. + +## Kasus Tepi & Praktik Terbaik + +| Situasi | Apa yang Harus Dilakukan | +|-----------|------------| +| **File lisensi berada di share jaringan** | Map share ke huruf drive atau gunakan jalur UNC (`\\server\share\license.lic`). Pastikan proses Python memiliki akses baca. | +| **Menjalankan di dalam container Docker** | Salin file `.lic` ke dalam image dan referensikan dengan jalur absolut seperti `/app/license/Aspose.OCR.Java.lic`. | +| **Beberapa interpreter Python** (mis. conda envs) | Instal file lisensi sekali per environment atau simpan di lokasi pusat dan arahkan setiap interpreter ke sana. | +| **File lisensi tidak ada saat runtime** | Turun secara elegan ke mode percobaan (jika didukung) atau hentikan dengan pesan log yang jelas. | + +### Kesalahan Umum + +- **Menggunakan slash maju pada Windows** – Python menerima mereka, tetapi beberapa versi lama SDK mungkin menafsirkannya secara keliru. Gunakan raw strings atau double backslashes. +- **Lupa mengimpor `License`** – Skrip akan crash dengan `NameError`. Selalu impor sebelum menginstansiasi. +- **Memanggil `set_license` setelah metode OCR** – SDK memeriksa lisensi pada penggunaan pertama, jadi set jalur **lebih dulu**. + +## Contoh Lengkap yang Berfungsi + +Berikut adalah skrip lengkap yang menggabungkan semua langkah. Simpan sebagai `ocr_setup.py` dan jalankan dari command line. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Output yang diharapkan** (asumsi gambar valid): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Jika file lisensi tidak dapat ditemukan, Anda akan melihat pesan error yang jelas alih-alih pengecualian “License not found” yang membingungkan. + +--- + +## Kesimpulan + +Anda kini tahu persis cara **create license instance** di Python dan **configure license path** untuk Aspose OCR SDK. Langkah‑langkahnya sederhana: instal paket, impor `License`, instansiasi, arahkan ke file `.lic` Anda, dan verifikasi dengan tes OCR kecil. + +Dengan pengetahuan ini Anda dapat menyematkan kemampuan OCR ke layanan web, aplikasi desktop, atau pipeline otomatis tanpa tersandung kesalahan lisensi. Selanjutnya, pertimbangkan mengeksplorasi pengaturan OCR lanjutan—paket bahasa, pra‑pemrosesan gambar, atau pemrosesan batch—yang semuanya dibangun di atas fondasi kuat yang baru saja Anda siapkan. + +Ada pertanyaan tentang deployment, Docker, atau menangani banyak lisensi? Tinggalkan komentar, dan selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +- [Tutorial Aspose OCR – Pengenalan Karakter Optik](/ocr/english/) +- [Cara Mengatur Lisensi dan Memverifikasi Lisensi Aspose.OCR di Java](/ocr/english/java/ocr-basics/set-license/) +- [Cara OCR Teks Gambar dengan Bahasa Menggunakan Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..585e0f957 --- /dev/null +++ b/ocr/indonesian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Buat PDF yang dapat dicari dari gambar hasil pemindaian menggunakan Python + OCR. Pelajari cara mengonversi PDF gambar hasil pemindaian, mengonversi TIFF ke + PDF, dan menambahkan lapisan teks OCR dalam hitungan menit. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: id +og_description: Buat PDF yang dapat dicari secara instan. Panduan ini menunjukkan + cara menjalankan OCR, mengonversi PDF gambar yang dipindai, dan menambahkan lapisan + teks OCR menggunakan satu skrip Python. +og_title: Buat PDF yang Dapat Dicari dengan Python – Tutorial Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Buat PDF yang Dapat Dicari dengan Python – Panduan Langkah demi Langkah +url: /id/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat PDF yang Dapat Dicari dengan Python – Panduan Langkah‑ demi‑Langkah + +Pernah bertanya-tanya bagaimana cara **create searchable PDF** dari halaman yang dipindai tanpa harus menggunakan puluhan alat? Anda tidak sendirian. Dalam banyak alur kerja kantor, sebuah TIFF atau JPEG yang dipindai ditempatkan di drive bersama, dan orang berikutnya harus menyalin‑tempel teks secara manual—menyakitkan, rawan kesalahan, dan membuang waktu. + +Dalam tutorial ini kami akan membahas solusi yang bersih dan programatis yang memungkinkan Anda **convert scanned image PDF**, **convert TIFF to PDF**, dan **add OCR text layer** sekaligus. Pada akhir tutorial Anda akan memiliki skrip siap‑pakai yang menjalankan OCR, menyematkan teks tersembunyi, dan menghasilkan PDF yang dapat dicari yang dapat Anda indeks, cari, atau bagikan dengan percaya diri. + +## Apa yang Anda Butuhkan + +- Python 3.9+ (versi terbaru apa pun dapat digunakan) +- `aspose-ocr` dan `aspose-pdf` packages (diinstal via `pip install aspose-ocr aspose-pdf`) +- File gambar yang dipindai (`.tif`, `.png`, `.jpg`, atau bahkan halaman PDF yang hanya berupa gambar) +- Jumlah RAM yang cukup (mesin OCR ringan; bahkan laptop dapat menangani) + +> **Pro tip:** Jika Anda menggunakan Windows, cara termudah untuk mendapatkan paket-paket tersebut adalah menjalankan perintah di jendela PowerShell yang dijalankan dengan hak istimewa. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Sekarang prasyarat sudah selesai, mari kita selami kode. + +## Langkah 1: Buat Instance OCR Engine – *create searchable pdf* + +Hal pertama yang kita lakukan adalah memulai OCR engine. Anggaplah ini sebagai otak yang akan membaca setiap piksel dan mengubahnya menjadi karakter. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Why this matters:** Menginisialisasi engine hanya sekali menjaga penggunaan memori tetap rendah. Jika Anda memanggil `OcrEngine()` di dalam loop untuk setiap halaman, Anda akan cepat kehabisan sumber daya. + +## Langkah 2: Muat Gambar yang Dipindai – *convert tiff to pdf* & *convert scanned image pdf* + +Selanjutnya, arahkan engine ke file yang ingin Anda proses. API menerima gambar raster apa pun, jadi TIFF bekerja sama baiknya dengan JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Jika Anda memiliki PDF yang hanya berisi gambar yang dipindai, Anda masih dapat menggunakan `load_image` karena Aspose akan mengekstrak halaman pertama secara otomatis. + +## Langkah 3: Siapkan PDF Save Options – *add OCR text layer* + +Di sini kami mengonfigurasi tampilan PDF akhir. Flag penting adalah `create_searchable_pdf`; mengaturnya ke `True` memberi tahu perpustakaan untuk menyematkan lapisan teks tak terlihat yang mencerminkan konten visual. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **What the text layer does:** Saat Anda membuka file hasil di Adobe Reader dan mencoba memilih teks, Anda akan melihat karakter tersembunyi. Mesin pencari juga dapat mengindeksnya—sempurna untuk kepatuhan atau pengarsipan. + +## Langkah 4: Jalankan OCR dan Simpan – *how to run OCR* dalam satu panggilan + +Sekarang keajaiban terjadi. Satu pemanggilan metode menjalankan mesin pengenalan dan menulis PDF yang dapat dicari ke disk. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Metode `recognize` mengembalikan objek status yang dapat Anda periksa untuk kesalahan, tetapi untuk kebanyakan skenario sederhana pemanggilan sederhana di atas sudah cukup. + +### Output yang Diharapkan + +Menjalankan skrip mencetak: + +``` +PDF saved as searchable PDF. +``` + +Jika Anda membuka `scanned_page_searchable.pdf` Anda akan melihat dapat memilih teks, menyalin‑tempelnya, dan bahkan menjalankan pencarian `Ctrl+F`. Itu adalah ciri khas alur kerja **create searchable pdf**. + +## Skrip Lengkap yang Berfungsi + +Berikut adalah skrip lengkap yang siap dijalankan. Cukup ganti jalur placeholder dengan lokasi file Anda yang sebenarnya. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Simpan ini sebagai `create_searchable_pdf.py` dan jalankan: + +```bash +python create_searchable_pdf.py +``` + +## Pertanyaan Umum & Kasus Tepi + +### 1️⃣ Bisakah saya memproses PDF multi‑halaman? + +Ya. Gunakan `ocr_engine.load_image("file.pdf")` lalu lakukan loop pada setiap halaman dengan `ocr_engine.recognize(pdf_save_options, page_number)`. Perpustakaan secara otomatis akan menghasilkan PDF yang dapat dicari multi‑halaman. + +### 2️⃣ Bagaimana jika file sumber saya adalah TIFF resolusi tinggi (300 dpi+)? + +DPI yang lebih tinggi menghasilkan akurasi OCR yang lebih baik tetapi juga penggunaan memori yang lebih besar. Jika Anda mengalami `MemoryError`, turunkan resolusi gambar terlebih dahulu: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Bagaimana cara mengubah bahasa OCR? + +Set properti `language` pada engine sebelum memuat gambar: + +```python +ocr_engine.language = "fra" # French +``` + +Daftar lengkap kode bahasa yang didukung terdapat di dokumentasi Aspose. + +### 4️⃣ Bagaimana jika saya perlu mempertahankan kualitas gambar asli? + +Kelas `PdfSaveOptions` memiliki properti `compression`. Atur ke `PdfCompression.None` untuk mempertahankan data raster persis seperti semula. + +```python +pdf_save_options.compression = "None" +``` + +## Tips untuk Penyebaran Siap‑Produksi + +- **Batch processing:** Bungkus logika inti dalam fungsi yang menerima daftar jalur file. Catat setiap keberhasilan/kegagalan ke CSV untuk jejak audit. +- **Parallelism:** Gunakan `concurrent.futures.ThreadPoolExecutor` untuk menjalankan OCR pada banyak core. Ingat setiap thread memerlukan instance `OcrEngine` masing‑masing. +- **Security:** Jika Anda menangani dokumen sensitif, jalankan skrip di lingkungan sandbox dan hapus file sementara segera setelah diproses. + +## Kesimpulan + +Anda sekarang tahu cara **create searchable PDF** dari gambar yang dipindai menggunakan skrip Python yang ringkas. Dengan menginisialisasi OCR engine, memuat TIFF (atau raster apa pun), mengonfigurasi `PdfSaveOptions` untuk **add OCR text layer**, dan akhirnya memanggil `recognize`, seluruh pipeline **convert scanned image pdf** dan **convert TIFF to PDF** menjadi satu perintah yang dapat diulang. + +Langkah selanjutnya? Coba sambungkan skrip ini dengan file‑watcher sehingga setiap pemindaian baru yang ditempatkan di folder secara otomatis menjadi dapat dicari. Atau bereksperimen dengan berbagai bahasa OCR untuk mendukung arsip multibahasa. Tidak ada batasan ketika Anda menggabungkan OCR dengan pembuatan PDF. + +Ada pertanyaan lebih lanjut tentang **how to run OCR** di bahasa atau kerangka kerja lain? Tinggalkan komentar di bawah, dan selamat coding! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## Apa yang Harus Anda Pelajari Selanjutnya? + +- [Cara OCR PDF di .NET dengan Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Konversi Gambar ke PDF C# – Simpan Hasil OCR Multi‑halaman](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Cara OCR Teks Gambar dengan Bahasa Menggunakan Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/indonesian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e68c897e2 --- /dev/null +++ b/ocr/indonesian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Tingkatkan akurasi OCR dengan Python melalui pra‑pemrosesan gambar untuk + OCR. Pelajari cara mengekstrak teks dari file gambar, mengenali teks dari PNG, dan + meningkatkan hasil. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: id +og_description: Tingkatkan akurasi OCR di Python dengan menerapkan pra‑pemrosesan + gambar untuk teks. Ikuti panduan ini untuk mengekstrak teks dari file gambar dan + mengenali teks dari PNG dengan mudah. +og_title: Tingkatkan Akurasi OCR di Python – Tutorial Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Tingkatkan Akurasi OCR di Python – Panduan Lengkap Langkah demi Langkah +url: /id/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-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 Langkah‑per‑Langkah + +Pernah mencoba **meningkatkan akurasi OCR** hanya untuk mendapatkan output yang berantakan? Anda tidak sendirian. Kebanyakan pengembang menemui kendala ketika gambar mentah berisik, miring, atau hanya kontras rendah. Kabar baiknya? Beberapa trik pra‑pemrosesan dapat mengubah screenshot yang buram menjadi teks bersih yang dapat dibaca mesin. + +Dalam tutorial ini kita akan melewati contoh dunia nyata yang **memproses gambar untuk OCR**, menjalankan mesin pengenalan, dan akhirnya **mengekstrak teks dari file gambar**—khususnya PNG. Pada akhir tutorial Anda akan tahu persis cara **mengenali teks dari PNG** dengan tingkat keberhasilan yang lebih tinggi, dan Anda akan memiliki potongan kode yang dapat dipakai ulang dalam proyek apa pun. + +## Apa yang Akan Anda Pelajari + +- Mengapa pra‑pemrosesan gambar penting bagi mesin OCR +- Mode pra‑pemrosesan (denoise, deskew) mana yang memberikan peningkatan terbesar +- Cara mengonfigurasi instance `OcrEngine` di Python +- Skrip lengkap yang dapat dijalankan yang **mengekstrak teks dari file gambar** +- Tips menangani kasus tepi seperti pemindaian yang diputar atau gambar beresolusi rendah + +Tidak diperlukan pustaka eksternal selain OCR SDK, tetapi Anda memerlukan Python 3.8+ dan gambar PNG yang ingin dibaca. + +--- + +![Diagram yang menunjukkan langkah‑langkah untuk meningkatkan akurasi OCR di Python](image.png "Alur kerja meningkatkan akurasi OCR") + +*Alt text: diagram alur kerja meningkatkan akurasi OCR yang menggambarkan langkah pra‑pemrosesan dan pengenalan.* + +## Prasyarat + +- Python 3.8 atau lebih baru terpasang +- Akses ke OCR SDK yang menyediakan `OcrEngine`, `OcrEngineSettings`, dan `ImagePreprocessMode` (kode di bawah menggunakan API generik; ganti dengan kelas vendor Anda jika diperlukan) +- Gambar PNG (`input.png`) yang ditempatkan di folder yang dapat Anda referensikan + +Jika Anda menggunakan lingkungan virtual, aktifkan sekarang—tidak ada yang rumit, cukup `python -m venv venv && source venv/bin/activate`. + +--- + +## Langkah 1: Buat Instance OCR Engine – Mulai Meningkatkan Akurasi OCR + +Hal pertama yang Anda butuhkan adalah objek engine OCR. Anggaplah sebagai otak yang nanti akan membaca piksel dan menghasilkan karakter. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Mengapa ini penting: tanpa engine Anda tidak dapat menerapkan pra‑pemrosesan apa pun, dan gambar mentah akan langsung diberikan ke recogniser—biasanya skenario terburuk untuk akurasi. + +--- + +## Langkah 2: Muat PNG Target – Siapkan Tahapan untuk Recognize Text from PNG + +Sekarang kita memberi tahu engine file mana yang akan diproses. PNG bersifat lossless, yang sudah memberi kita sedikit keunggulan dibanding JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Jika gambar berada di tempat lain, cukup sesuaikan jalurnya. Engine menerima format apa pun yang didukung, tetapi PNG sering mempertahankan detail halus yang diperlukan untuk tepi karakter yang tajam. + +--- + +## Langkah 3: Konfigurasikan Pra‑Pemrosesan – Preprocess Image for OCR + +Di sinilah keajaiban terjadi. Kami membuat objek pengaturan, mengaktifkan denoising untuk menghapus bintik‑bintik, dan menyalakan deskew sehingga teks yang miring menjadi lurus secara otomatis. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Mengapa Denoise + Deskew? + +- **Denoise**: Noise piksel acak membingungkan algoritma pencocokan pola. Menghilangkannya membuat huruf lebih tajam. +- **Deskew**: Bahkan kemiringan 2‑derajat pun dapat menurunkan skor kepercayaan secara drastis. Deskew menyelaraskan baseline, memungkinkan recogniser mencocokkan font dengan lebih andal. + +Anda dapat bereksperimen dengan flag tambahan (misalnya `ImagePreprocessMode.CONTRAST_ENHANCE`) jika gambar Anda sangat gelap. Dokumentasi SDK biasanya mencantumkan semua mode yang tersedia. + +--- + +## Langkah 4: Terapkan Pengaturan ke Engine – Hubungkan Pra‑Pemrosesan ke OCR + +Tetapkan objek pengaturan ke engine sehingga proses pengenalan berikutnya menggunakan transformasi yang baru saja kita definisikan. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Jika Anda melewatkan langkah ini, engine akan kembali ke defaultnya (sering “tanpa pra‑pemrosesan”), dan Anda akan melihat **akurasi OCR yang lebih rendah**. + +--- + +## Langkah 5: Jalankan Proses Pengenalan – Extract Text from Image + +Setelah semuanya terhubung, akhirnya kita meminta engine melakukan tugasnya. Panggilan ini sinkron, mengembalikan objek hasil yang berisi string yang dikenali. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Di balik layar engine kini: + +1. Memuat PNG ke memori +2. Menerapkan denoise dan deskew berdasarkan pengaturan kami +3. Menjalankan jaringan saraf atau pencocokan pola klasik +4. Mengemas output ke dalam `recognition_result` + +--- + +## Langkah 6: Tampilkan Teks yang Dikenali – Verifikasi Peningkatan + +Mari cetak string yang diekstrak. Dalam aplikasi nyata Anda mungkin menuliskannya ke file, basis data, atau mengirimnya ke layanan lain. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Output yang Diharapkan + +Jika gambar berisi kalimat “Hello, OCR World!” Anda harus melihat: + +``` +Hello, OCR World! +``` + +Perhatikan bagaimana teksnya bersih—tanpa simbol aneh atau karakter yang terputus. Itu hasil dari **pra‑pemrosesan gambar untuk teks** yang tepat. + +--- + +## Pro Tips & Kasus Tepi + +| Situasi | Apa yang Harus Disesuaikan | Mengapa | +|-----------|----------------------------|---------| +| PNG beresolusi sangat rendah (≤ 72 dpi) | Tambahkan `ImagePreprocessMode.SUPER_RESOLUTION` jika tersedia | Upsampling dapat memberi recogniser lebih banyak piksel untuk diproses | +| Teks diputar > 5° | Tingkatkan toleransi deskew atau putar secara manual dengan `Pillow` sebelum memberi ke engine | Sudut ekstrem kadang melewati deskew otomatis | +| Pola latar belakang berat | Aktifkan `ImagePreprocessMode.BACKGROUND_REMOVAL` | Menghilangkan gangguan non‑teks yang sebaliknya akan terbaca salah | +| Dokumen multibahasa | Set `ocr_engine.language = "eng+spa"` (atau serupa) | Engine memilih set karakter yang tepat, meningkatkan akurasi keseluruhan | + +Ingat, **meningkatkan akurasi OCR** bukan solusi satu‑ukuran‑untuk‑semua; Anda mungkin perlu iterasi pada flag pra‑pemrosesan untuk dataset spesifik Anda. + +--- + +## Skrip Lengkap – Siap Salin & Tempel + +Berikut contoh lengkap yang dapat dijalankan yang mencakup setiap langkah yang telah dibahas. Simpan sebagai `improve_ocr_accuracy.py` dan jalankan dengan `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Jalankan, perhatikan konsol, dan Anda akan melihat hasil **extract text from image** secara langsung. Jika output terlihat aneh, sesuaikan flag `preprocess_mode` seperti yang dijelaskan pada tabel “Pro Tips”. + +--- + +## Kesimpulan + +Kita baru saja menelusuri resep praktis untuk **meningkatkan akurasi OCR** menggunakan Python. Dengan membuat `OcrEngine`, memuat PNG, **memproses gambar untuk OCR**, dan akhirnya **mengenali teks dari PNG**, Anda dapat secara andal **mengekstrak teks dari file gambar** bahkan ketika sumbernya tidak sempurna. + +Langkah selanjutnya? Coba proses batch gambar dalam loop, simpan tiap hasil ke CSV, atau bereksperimen dengan mode pra‑pemrosesan tambahan seperti peningkatan kontras. Pola yang sama berlaku untuk PDF, kwitansi yang dipindai, atau catatan tulisan tangan—cukup ganti input dan sesuaikan pengaturannya. + +Punya pertanyaan tentang tipe gambar tertentu atau ingin tahu cara mengintegrasikan ini ke layanan web? Tinggalkan komentar, dan kami akan menjelajahi skenario tersebut bersama. Selamat coding, semoga hasil OCR Anda selalu jernih! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +- [Extract Text from Image with Aspose OCR – Panduan Langkah‑per‑Langkah](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) +- [Cara Extract Text from Image dengan Menyiapkan Rectangle di OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/indonesian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..b4b029aa7 --- /dev/null +++ b/ocr/indonesian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Pelajari cara menggunakan wilayah minat OCR untuk memuat gambar dan mengekstrak + teks dari persegi panjang, sempurna untuk mengenali jumlah pada faktur. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: id +og_description: Kuasai wilayah minat OCR untuk memuat gambar, mengekstrak teks dari + persegi panjang, dan mengenali teks dari faktur dalam satu tutorial. +og_title: OCR Region of Interest – Panduan Python Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Wilayah Minat – Ekstrak Teks dari Persegi Panjang di Python +url: /id/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Ekstrak Teks dari Persegi Panjang di Python + +Pernah bertanya-tanya bagaimana cara **ocr region of interest** pada bagian tertentu dari faktur yang dipindai tanpa harus memberi seluruh halaman ke mesin? Anda bukan orang pertama yang menatap struk buram dan berpikir, “Bagaimana cara mengekstrak jumlah yang berada di pojok kanan bawah?” Kabar baiknya, Anda dapat memberi tahu perpustakaan OCR tepat di mana harus mencari, sehingga kecepatan dan akurasi meningkat secara signifikan. + +Dalam panduan ini kami akan menelusuri contoh lengkap yang dapat dijalankan yang menunjukkan cara **load image for OCR**, mendefinisikan **region of interest**, dan kemudian **extract text from rectangle** untuk akhirnya **recognize text from invoice** serta menjawab pertanyaan klasik “bagaimana mengekstrak jumlah”. Tidak ada referensi samar—hanya kode konkret, penjelasan jelas, dan beberapa pro tip yang Anda harapkan sudah tahu sebelumnya. + +--- + +## What You’ll Build + +Pada akhir tutorial ini Anda akan memiliki skrip Python kecil yang: + +1. Memuat gambar faktur dari disk. +2. Menandai ROI persegi panjang tempat total jumlah berada. +3. Menjalankan OCR hanya di dalam ROI tersebut. +4. Mencetak string jumlah yang sudah dibersihkan. + +Semua ini bekerja dengan perpustakaan OCR apa pun yang mendukung ROI—di sini kami menggunakan paket fiktif namun representatif `SimpleOCR` yang meniru alat populer seperti Tesseract atau EasyOCR. Silakan ganti dengan yang lain; konsepnya tetap sama. + +--- + +## Prerequisites + +- Python 3.8+ terpasang (`python --version` harus menampilkan ≥3.8). +- Paket OCR yang dapat di‑install via pip (misalnya `pip install simpleocr`). +- Gambar faktur (PNG atau JPEG) yang ditempatkan di folder yang dapat Anda referensikan. +- Familiaritas dasar dengan fungsi dan kelas Python (tidak ada yang rumit). + +Jika semua sudah ada, bagus—mari kita mulai. Jika belum, ambil dulu gambarnya; langkah‑langkah selanjutnya tidak bergantung pada isi file sebenarnya. + +--- + +## Step 1: Load Image for OCR + +Hal pertama yang dibutuhkan dalam alur kerja OCR apa pun adalah bitmap untuk dibaca. Kebanyakan perpustakaan menyediakan metode sederhana `load_image` yang menerima jalur file. Berikut cara melakukannya dengan mesin `SimpleOCR` kami: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Gunakan jalur absolut atau `os.path.join` untuk menghindari kejutan “file not found” ketika menjalankan skrip dari direktori kerja yang berbeda. + +--- + +## Step 2: Define OCR Region of Interest + +Alih‑alih membiarkan mesin memindai seluruh halaman, kita memberi tahu *tepat* di mana jumlah berada. Ini adalah langkah **ocr region of interest**, dan merupakan kunci ekstraksi yang dapat diandalkan, terutama ketika dokumen mengandung header atau footer yang berisik. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Mengapa angka‑angka itu? `x` dan `y` adalah offset piksel dari sudut kiri‑atas, sementara `width` dan `height` menggambarkan ukuran kotak. Jika Anda tidak yakin, buka gambar di editor apa pun, aktifkan penggaris, dan catat koordinatnya. Banyak IDE bahkan memungkinkan Anda melihat posisi kursor saat mengarahkan mouse. + +--- + +## Step 3: Extract Text from Rectangle + +Setelah ROI ditetapkan, kita meminta mesin untuk **recognize text from invoice** namun terbatas pada persegi panjang yang baru saja ditambahkan. Pemanggilan ini mengembalikan objek hasil yang biasanya berisi string mentah, skor kepercayaan, dan kadang‑kadang kotak pembatas. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Di balik layar, `recognize()` mengiterasi setiap ROI, memotong potongan tersebut, menjalankan model OCR, dan menyatukan hasilnya. Inilah mengapa mendefinisikan wilayah **extract text from rectangle** yang ketat dapat menghemat detik pada proses batch. + +--- + +## Step 4: How to Extract Amount – Clean the Output + +OCR tidak sempurna; Anda sering mendapatkan spasi berlebih, baris baru, atau bahkan karakter yang salah dibaca (misalnya “S” vs “5”). `strip()` cepat dan regex kecil biasanya cukup untuk nilai moneter. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** Jika Anda berencana memasukkan jumlah ke basis data atau gateway pembayaran, Anda memerlukan format yang dapat diprediksi. Menghapus spasi putih dan menyaring karakter non‑numerik mencegah kesalahan di tahap selanjutnya. + +--- + +## Step 5: Recognize Text from Invoice – Full Script + +Menggabungkan semuanya, berikut skrip lengkap yang siap dijalankan. Simpan sebagai `extract_amount.py` dan jalankan `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Expected Output + +``` +Amount: 1,245.67 +``` + +Jika ROI tidak sejajar, Anda mungkin melihat sesuatu seperti `Amount: 1245.6S`—perhatikan “S” yang mengambang. Sesuaikan koordinat persegi panjang dan jalankan kembali hingga output terlihat bersih. + +--- + +## Common Pitfalls & Edge Cases + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI terlalu kecil** | Teks jumlah terpotong, menghasilkan pengenalan parsial. | Perbesar `width`/`height` sekitar 10‑20 % dan uji kembali. | +| **DPI tidak tepat** | Scan beresolusi rendah (≤150 dpi) menurunkan akurasi OCR. | Resample gambar ke 300 dpi sebelum memuat, atau minta scanner dengan DPI lebih tinggi. | +| **Beberapa mata uang** | Regex mengambil grup numerik pertama, yang mungkin adalah nomor faktur. | Perbaiki regex untuk mencari simbol mata uang (`$`, `€`, `£`) sebelum digit. | +| **Faktur terrotasi** | Mesin OCR mengasumsikan teks tegak; halaman yang diputar mengganggu pengenalan. | Terapkan koreksi rotasi (`ocr_engine.rotate(90)`) sebelum menambahkan ROI. | +| **Noise di latar belakang** | Bayangan atau stempel membingungkan model. | Pra‑proses dengan threshold sederhana (`cv2.threshold`) atau gunakan filter denoising. | + +Menangani kasus tepi ini lebih awal menghemat berjam‑jam debugging di kemudian hari. + +--- + +## Pro Tips for Real‑World Projects + +- **Batch Processing:** Loop melalui folder faktur, hitung ROI secara dinamis (misalnya berdasarkan deteksi template), dan simpan hasil ke CSV. +- **Template Matching:** Jika Anda menangani beberapa tata letak faktur, pertahankan peta JSON `template_id → ROI coordinates`. Ganti ROI berdasarkan classifier tata letak cepat. +- **Parallel Execution:** Gunakan `concurrent.futures.ThreadPoolExecutor` untuk menjalankan beberapa instance OCR secara bersamaan—ideal untuk pipeline back‑office volume tinggi. +- **Confidence Filtering:** Kebanyakan hasil OCR menyertakan skor kepercayaan. Buang hasil di bawah ambang tertentu (misalnya 85 %) dan tandai untuk peninjauan manual. + +--- + +## Conclusion + +Kami telah membahas semua yang Anda perlukan untuk **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, dan akhirnya **recognize text from invoice** guna menjawab pertanyaan klasik **how to extract amount**. Skripnya ringkas, namun cukup fleksibel untuk disesuaikan dengan format dokumen, bahasa, dan backend OCR yang berbeda. + +Setelah menguasai dasar‑dasarnya, pertimbangkan memperluas alur kerja: tambahkan pemindaian barcode, integrasikan dengan parser PDF, atau kirim jumlah yang diekstrak ke API akuntansi. Langit adalah batasnya, dan dengan ROI yang terdefinisi dengan baik Anda akan selalu mendapatkan hasil yang lebih cepat dan bersih. + +Jika Anda mengalami kendala, tinggalkan komentar di bawah—selamat OCRing! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "contoh ocr region of interest") + + +## What Should You Learn Next? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/italian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..426759b94 --- /dev/null +++ b/ocr/italian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Tutorial OCR asincrono che mostra come utilizzare Aspose OCR in Python + con asyncio per un'estrazione rapida del testo dalle immagini. Impara l'implementazione + OCR asincrona passo‑passo. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: it +og_description: Il tutorial OCR asincrono ti guida nell'utilizzo di Aspose OCR in + Python con asyncio per un'efficiente estrazione del testo dalle immagini. +og_title: Tutorial OCR asincrono – Python asyncio con Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Tutorial OCR asincrono – Python asyncio con Aspose OCR +url: /it/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial OCR asincrono – Python asyncio con Aspose OCR + +Ti sei mai chiesto come eseguire il riconoscimento ottico dei caratteri senza bloccare la tua app? In un **tutorial OCR asincrono** vedrai esattamente questo—estrazione di testo non bloccante usando `asyncio` di Python e la libreria Aspose OCR. + +Se sei rimasto bloccato ad attendere l'elaborazione di un'immagine pesante, questa guida ti offre una soluzione asincrona e pulita che mantiene il tuo event loop in funzione. + +Nelle sezioni successive copriremo tutto ciò di cui hai bisogno: installare la libreria, configurare un helper asincrono, gestire il risultato e anche un rapido suggerimento per scalare a più immagini. Alla fine potrai inserire un **tutorial OCR asincrono** in qualsiasi progetto Python che utilizza già `asyncio`. + +## Cosa ti serve + +* Python 3.9+ (l'API `asyncio` che usiamo è stabile dalla versione 3.7 in poi) +* Una licenza attiva di Aspose OCR o una prova gratuita (la libreria è pure‑Python, senza binari nativi) +* Un piccolo file immagine (`.jpg`, `.png`, ecc.) che desideri leggere – conservalo in una cartella nota + +Nessun altro strumento esterno è necessario; tutto funziona in puro Python. + +## Passo 1: Installa il pacchetto Aspose OCR + +Prima di tutto, ottieni il pacchetto Aspose OCR da PyPI. Apri un terminale ed esegui: + +```bash +pip install aspose-ocr +``` + +> **Suggerimento:** Se lavori all'interno di un ambiente virtuale (altamente consigliato), attivalo prima. Questo mantiene le dipendenze isolate ed evita conflitti di versione. + +## Passo 2: Inizializza il motore OCR in modo asincrono + +Il cuore del nostro **tutorial OCR asincrono** è una funzione helper asincrona. Crea un'istanza di `OcrEngine`, carica un'immagine e poi chiama `recognize_async()`. Il motore stesso è sincrono, ma il metodo wrapper restituisce un oggetto awaitable, consentendo al event loop di rimanere reattivo. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Perché lo facciamo in questo modo:** +*Creare il motore all'interno dell'helper garantisce la thread‑safety se in seguito esegui molti job OCR in parallelo. La keyword `await` restituisce il controllo al event loop mentre il lavoro pesante avviene nel thread pool interno della libreria.* + +## Passo 3: Utilizza l'helper da una funzione main asincrona + +Ora abbiamo bisogno di una piccola coroutine `main()` che chiama `async_ocr()` e stampa il risultato. Questo rispecchia il tipico punto di ingresso per uno script `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Cosa succede dietro le quinte?** +`asyncio.run()` crea un nuovo event loop, programma `main()` e chiude il loop in modo pulito quando `main()` termina. Questo pattern è il modo consigliato per avviare programmi asincroni in Python 3.7+. + +## Passo 4: Testa lo script completo + +Salva i due blocchi di codice sopra in un unico file, ad es. `async_ocr_demo.py`. Eseguilo dalla riga di comando: + +```bash +python async_ocr_demo.py +``` + +Se tutto è configurato correttamente dovresti vedere qualcosa del genere: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +L'output esatto dipenderà dal contenuto di `photo.jpg`. Il punto chiave è che lo script termina rapidamente, anche se l'immagine è grande, perché il lavoro OCR avviene in background. + +## Passo 5: Scalare – Processare più immagini in modo concorrente + +Una domanda comune di follow‑up è, *“Posso fare OCR su un batch di file senza avviare un nuovo processo per ciascuno?”* Assolutamente. Poiché il nostro helper è completamente asincrono, possiamo raccogliere molte coroutine con `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Perché funziona:** `asyncio.gather()` programma tutti i task OCR contemporaneamente. La libreria Aspose OCR sottostante utilizza ancora il proprio thread pool, ma dal punto di vista di Python tutto rimane non bloccante, permettendoti di gestire decine di immagini nel tempo che richiederebbe una singola chiamata sincrona. + +## Passo 6: Gestire gli errori in modo elegante + +Quando lavori con file esterni, inevitabilmente incontrerai file mancanti, immagini corrotte o problemi di licenza. Avvolgi la chiamata OCR in un blocco `try/except` per mantenere vivo il event loop: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Ora `batch_ocr()` può chiamare `safe_async_ocr` al suo posto, garantendo che un file difettoso non interrompa l'intero batch. + +## Panoramica visiva + +![Diagramma tutorial OCR asincrono](async-ocr-diagram.png){alt="Diagramma di flusso del tutorial OCR asincrono che mostra l'helper async_ocr, l'event loop e il motore Aspose OCR"} + +Il diagramma sopra visualizza il flusso: l'event loop → `async_ocr` → `OcrEngine` → thread in background → risultato restituito al loop. + +## Problemi comuni e come evitarli + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| **I/O bloccante all'interno dell'helper** | Usare accidentalmente `open()` senza `await` può bloccare il loop. | Usa `aiofiles` per la lettura dei file, o lascia che `engine.load_image` lo gestisca (è già non bloccante). | +| **Riutilizzare un singolo `OcrEngine` tra coroutine** | Il motore non è thread‑safe; le chiamate concorrenti possono corrompere lo stato. | Istanzia un nuovo motore all'interno di ogni chiamata `async_ocr` (come mostrato). | +| **Licenza mancante** | Aspose OCR genera un'eccezione legata alla licenza a runtime. | Registra la tua licenza subito (`OcrEngine.set_license("license.json")`). | +| **Immagini grandi che causano picchi di memoria** | La libreria carica l'intera immagine in RAM. | Ridimensiona le immagini prima dell'OCR se la memoria è un problema. | + +## Riepilogo: cosa abbiamo realizzato + +In questo **tutorial OCR asincrono** abbiamo: + +1. Installato la libreria Aspose OCR. +2. Creato un helper `async_ocr` che esegue il riconoscimento senza bloccare. +3. Eseguito l'helper da un punto di ingresso `asyncio` pulito. +4. Dimostrato il batch processing con `asyncio.gather`. +5. Aggiunto la gestione degli errori e consigli di best‑practice. + +Il tutto è puro Python, quindi puoi inserirlo in un server web, uno strumento da riga di comando o una pipeline di dati senza riscrivere il codice asincrono esistente. + +## Prossimi passi e argomenti correlati + +* **Pre‑elaborazione immagine asincrona** – usa `aiohttp` per scaricare le immagini in modo concorrente prima dell'OCR. +* **Salvataggio dei risultati OCR** – combina questo tutorial con un driver di database asincrono come `asyncpg` per PostgreSQL. +* **Ottimizzazione delle prestazioni** – sperimenta con `engine.recognize_async(max_threads=4)` se la libreria espone tale opzione. +* **Motori OCR alternativi** – confronta Aspose OCR con i wrapper asincroni di Tesseract per un'analisi costi‑benefici. + +Sentiti libero di sperimentare: prova a fornire PDF, regola le impostazioni della lingua o collega i risultati a un chatbot. Il cielo è il limite una volta che hai una solida base di **tutorial OCR asincrono**. + +Buon coding, e che la tua estrazione di testo sia sempre veloce! + +## Cosa dovresti imparare dopo? + +- [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/) +- [Tutorial Aspose OCR – Riconoscimento ottico dei caratteri](/ocr/english/) +- [Come fare OCR del testo di un'immagine con lingua usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/italian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..e9064d149 --- /dev/null +++ b/ocr/italian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Rilevamento automatico della lingua nell'OCR reso semplice. Scopri come + caricare l'OCR di un'immagine, abilitare il rilevamento automatico della lingua + e riconoscere il testo dell'immagine in pochi passaggi. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: it +og_description: Rilevamento automatico della lingua nell'OCR reso semplice. Segui + questo tutorial passo‑passo per abilitare il rilevamento automatico della lingua, + caricare l'OCR dell'immagine e riconoscere il testo dell'immagine. +og_title: Rilevamento automatico della lingua con OCR – Guida completa a Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Rilevamento automatico della lingua con OCR – Guida completa a Python +url: /it/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rilevamento Automatico della Lingua con OCR – Guida Completa Python + +Ti sei mai chiesto come far *indovinare* a un motore OCR la lingua di un documento scansionato senza dover specificare nulla? È esattamente quello che fa il **rilevamento automatico della lingua**, e rappresenta una vera svolta quando si lavora con PDF multilingue, foto di segnali stradali o qualsiasi immagine che mescola script diversi. + +In questo tutorial percorreremo un esempio pratico che mostra come **abilitare il rilevamento automatico della lingua**, **caricare l'OCR dell'immagine** e **riconoscere il testo dall'immagine** usando un'API in stile Python. Alla fine avrai uno script autonomo che stampa sia il codice della lingua rilevata sia il testo estratto—senza impostazioni manuali della lingua. + +## Cosa Imparerai + +- Come creare un'istanza del motore OCR e attivare **il rilevamento automatico della lingua**. +- I passaggi esatti per **caricare l'OCR dell'immagine** dal disco. +- Come chiamare il metodo `recognize()` del motore e ottenere un risultato che includa il codice della lingua. +- Suggerimenti per gestire casi particolari come immagini a bassa risoluzione o script non supportati. + +Non è necessaria alcuna esperienza pregressa con OCR multilingue; basta una configurazione base di Python e un file immagine. + +--- + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +1. Python 3.8+ installato (qualsiasi versione recente va bene). +2. La libreria OCR che fornisce `OcrEngine`, `LanguageAutoDetectMode`, ecc. – per questa guida assumiamo un pacchetto ipotetico chiamato `myocr`. Installalo con: + + ```bash + pip install myocr + ``` + +3. Un file immagine (`multilingual_sample.png`) che contenga testo in almeno due lingue diverse. +4. Un po' di curiosità—se non hai mai toccato l'OCR, non preoccuparti; il codice è deliberatamente semplice. + +--- + +## Passo 1: Abilitare il Rilevamento Automatico della Lingua + +La prima cosa da fare è dire al motore che deve *scoprire* da solo la lingua. È qui che entra in gioco il flag **automatic language detection**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Perché è importante:** +> Quando `AUTO_DETECT` è impostato, il motore esegue un classificatore di lingua leggero sull'immagine prima che parta il riconoscimento dei caratteri più pesante. Questo significa che non devi indovinare se il testo è inglese, russo, francese o una combinazione di questi. Il motore sceglierà automaticamente il modello linguistico migliore per ogni regione dell'immagine. + +--- + +## Passo 2: Caricare l'OCR dell'Immagine + +Ora che il motore sa di dover auto‑rilevare le lingue, dobbiamo fornirgli qualcosa su cui lavorare. Il passaggio **load image OCR** legge il bitmap e prepara i buffer interni. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Consiglio pratico:** +> Se la tua immagine è più grande di 300 dpi, considera di ridimensionarla a circa 150‑200 dpi. Troppi dettagli possono effettivamente *rallentare* la fase di rilevamento della lingua senza migliorare l'accuratezza. + +--- + +## Passo 3: Riconoscere il Testo dall'Immagine + +Con l'immagine in memoria e il rilevamento della lingua abilitato, l'ultimo passo è chiedere al motore di **recognize text image**. Questa singola chiamata esegue tutto il lavoro pesante. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` è un oggetto che tipicamente contiene almeno due attributi: + +| Attributo | Descrizione | +|-----------|-------------| +| `language` | Codice ISO‑639‑1 della lingua rilevata (es., `"en"` per l'inglese). | +| `text` | La trascrizione in testo semplice dell'immagine. | + +--- + +## Passo 4: Recuperare la Lingua Rilevata e il Testo Estratto + +Ora stampiamo semplicemente ciò che il motore ha scoperto. Questo dimostra la capacità **detect language OCR** in azione. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Output di esempio** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **E se il motore restituisce `None`?** +> Di solito significa che l'immagine è troppo sfocata o il testo è troppo piccolo (< 8 pt). Prova ad aumentare il contrasto o a usare una sorgente a risoluzione più alta. + +--- + +## Esempio Completo (Abilitare Rilevamento Automatico della Lingua End‑to‑End) + +Mettendo tutto insieme, ecco uno script pronto all'uso che copre **enable auto language detection**, **load image OCR**, **recognize text image** e **detect language OCR** in un unico flusso. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Salva questo file come `automatic_language_detection_ocr.py`, sostituisci `YOUR_DIRECTORY` con la cartella che contiene il tuo PNG, e avvialo: + +```bash +python automatic_language_detection_ocr.py +``` + +Dovresti vedere il codice della lingua seguito dal testo estratto, proprio come nell'output di esempio mostrato sopra. + +--- + +## Gestione dei Casi Particolari più Comuni + +| Situazione | Soluzione Consigliata | +|------------|-----------------------| +| **Immagine a risoluzione molto bassa** (meno di 100 dpi) | Upscale con filtro bicubico prima del caricamento, oppure richiedi una sorgente a risoluzione più alta. | +| **Script misti in una sola immagine** (es., inglese + cirillico) | Il motore di solito suddivide la pagina in regioni; se noti errori, imposta `engine.enable_region_split = True`. | +| **Lingua non supportata** | Verifica che la libreria OCR includa un pacchetto linguistico per lo script necessario; potresti dover scaricare modelli aggiuntivi. | +| **Elaborazione di grandi batch** | Inizializza il motore una sola volta, poi riutilizzalo per più cicli `load_image` / `recognize` per evitare il ricaricamento ripetuto dei modelli. | + +--- + +## Panoramica Visiva + +![output di esempio del rilevamento automatico della lingua](https://example.com/auto-lang-detect.png "rilevamento automatico della lingua") + +*Alt text:* output di esempio del rilevamento automatico della lingua che mostra il codice della lingua rilevata e il testo multilingue estratto. + +--- + +## Conclusione + +Abbiamo appena coperto il **rilevamento automatico della lingua** dall'inizio alla fine—creazione del motore, abilitazione del rilevamento automatico, caricamento di un'immagine per OCR, riconoscimento del testo e infine recupero della lingua rilevata. Questo flusso end‑to‑end ti permette di elaborare documenti multilingue senza configurare manualmente i modelli linguistici ogni volta. + +Se sei pronto a spingere oltre, considera: + +- **Batching** centinaia di immagini con un ciclo che riutilizza la stessa istanza di `OcrEngine`. +- **Post‑processing** del testo estratto con un correttore ortografico o un tokenizzatore specifico per la lingua. +- **Integrazione** dello script in un servizio web che accetta upload degli utenti e restituisce JSON con i campi `language` e `text`. + +Sentiti libero di sperimentare con formati immagine diversi (`.jpg`, `.tif`) e osservare come varia la precisione del rilevamento. Hai domande o un'immagine ostinata che rifiuta di essere letta? Lascia un commento qui sotto—buona programmazione! + +## Cosa Dovresti Imparare Dopo? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/italian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..20d42bcfc --- /dev/null +++ b/ocr/italian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Impara come convertire le immagini in testo con Python usando uno script + di conversione di immagini in testo in blocco. Riconosci il testo dalle immagini + scannerizzate con Aspose.OCR in pochi minuti. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: it +og_description: Converti immagini in testo con Python istantaneamente. Questa guida + mostra la conversione di immagini in testo in blocco e come riconoscere il testo + da immagini scannerizzate con Aspose.OCR. +og_title: Converti immagini in testo con Python – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Converti Immagini in Testo con Python – Guida Completa Passo‑Passo +url: /it/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converti Immagini in Testo Python – Guida Completa Passo‑Passo + +Ti sei mai chiesto come **convert images to text python** senza dover cercare decine di librerie? Non sei l'unico. Che tu stia digitalizzando vecchie ricevute, estraendo dati da fatture scannerizzate, o creando un archivio ricercabile di PDF, trasformare le immagini in file di testo semplice è un lavoro quotidiano per molti sviluppatori. + +In questo tutorial percorreremo una pipeline di **bulk image to text conversion** che riconosce il testo da immagini scannerizzate, salva ogni risultato in un file `.txt` individuale, e lo fa tutto con poche righe di Python. Niente ricerche misteriose di API poco conosciute—Aspose.OCR fa il lavoro pesante, e ti mostreremo esattamente come collegarlo. + +## Cosa Imparerai + +- Come installare e configurare il pacchetto Aspose.OCR per Python. +- Il codice esatto necessario per **convert images to text python** usando `BatchOcrEngine`. +- Suggerimenti per gestire problemi comuni come formati non supportati o file corrotti. +- Modi per verificare che il passaggio **recognize text from scanned images** sia effettivamente riuscito. + +Alla fine di questa guida avrai uno script pronto‑all'uso che può elaborare migliaia di immagini in una sola volta—perfetto per qualsiasi scenario di elaborazione batch. + +## Prerequisiti + +- Python 3.8+ installato sulla tua macchina. +- Una cartella di file immagine (PNG, JPEG, TIFF, ecc.) che vuoi trasformare in testo. +- Un account Aspose Cloud attivo o una licenza di prova gratuita (il livello gratuito è sufficiente per i test). + +Se li hai, immergiamoci. + +--- + +## Passo 1 – Configura il tuo ambiente Python + +Prima di iniziare a scrivere codice OCR, assicurati di lavorare all'interno di un ambiente virtuale pulito. Questo isola le dipendenze e previene conflitti di versione. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Consiglio Pro:** Mantieni ordinata la directory del progetto—crea una sottocartella chiamata `ocr_project` e posiziona lo script lì. Facilita la gestione dei percorsi in seguito. + +## Passo 2 – Installa Aspose.OCR per Python + +Aspose.OCR è una libreria commerciale, ma è fornita con una wheel in stile NuGet gratuita che puoi scaricare da PyPI. Esegui il comando seguente all'interno dell'ambiente virtuale attivato: + +```bash +pip install aspose-ocr +``` + +Se incontri un errore di permesso, aggiungi il flag `--user` o esegui il comando con `sudo` (solo Linux/macOS). Dopo l'installazione dovresti vedere qualcosa di simile: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Perché Aspose?** A differenza di molti strumenti OCR open‑source, Aspose.OCR supporta **bulk image to text conversion** subito pronto all'uso e gestisce un'ampia gamma di formati immagine senza configurazioni aggiuntive. Offre anche la classe `BatchOcrEngine` che rende il compito “convert images to text python” un'operazione a singola riga. + +## Passo 3 – Converti Immagini in Testo Python con Batch OCR + +Ora il cuore del tutorial. Di seguito trovi uno script completamente eseguibile che: + +1. Importa le classi del motore OCR. +2. Istanzia un `BatchOcrEngine`. +3. Indirizza il motore verso una cartella di immagini di input. +4. Fa sì che il motore scriva ogni file di testo estratto in una cartella di output. +5. Avvia il metodo `recognize()`, che **recognize text from scanned images** uno per uno. + +Salva quanto segue come `batch_ocr.py` nella tua cartella di progetto: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Come funziona + +- **`BatchOcrEngine`** avvolge il normale `OcrEngine` ma aggiunge l'orchestrazione a livello di cartella, che è esattamente ciò di cui hai bisogno quando vuoi **convert images to text python** in blocco. +- La proprietà `input_folder` indica al motore dove cercare le immagini di origine. Scansiona automaticamente la directory e accoda ogni tipo di file supportato. +- La proprietà `output_folder` determina dove finisce ogni file `.txt`. Il motore replica il nome file originale, quindi `receipt1.png` diventa `receipt1.txt`. +- Chiamare `recognize()` attiva il ciclo interno che carica ogni immagine, esegue l'OCR e scrive il risultato. Il metodo blocca l'esecuzione finché tutti i file non sono processati, facilitando il concatenamento di ulteriori azioni (es., comprimere la cartella di output). + +#### Output Atteso + +Quando esegui lo script: + +```bash +python batch_ocr.py +``` + +Dovresti vedere: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +All'interno di `output_texts` troverai un file di testo semplice per ogni immagine. Aprine uno con un editor di testo e vedrai il risultato OCR grezzo—di solito una buona approssimazione del testo stampato originale. + +## Passo 4 – Verifica i risultati e gestisci gli errori + +Anche i migliori motori OCR possono inciampare su scansioni a bassa risoluzione o pagine fortemente inclinate. Ecco un modo rapido per verificare la correttezza dell'output e registrare eventuali fallimenti. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Perché aggiungerlo?** +- Cattura i casi in cui il motore produce silenziosamente una stringa vuota (comune con immagini illeggibili). +- Fornisce un elenco di file problematici così da poterli ispezionare manualmente o rieseguire con impostazioni diverse (es., aumentare le opzioni `OcrEngine.preprocess`). + +### Casi Limite & Ottimizzazioni + +| Situazione | Correzione Suggerita | +|------------|----------------------| +| Le immagini sono ruotate di 90° | Imposta `batch_engine.ocr_engine.rotation_correction = True`. | +| Lingue miste (Inglese + Francese) | Usa `batch_engine.ocr_engine.language = "eng+fra"` prima di `recognize()`. | +| PDF di grandi dimensioni convertiti prima in immagini | Dividi i PDF in immagini a pagina singola, poi fornisci la cartella al batch engine. | +| Errori di memoria su batch molto grandi | Elabora sottocartelle più piccole in sequenza, o aumenta `batch_engine.max_memory_usage`. | + +## Passo 5 – Automatizza l'intero flusso di lavoro (Opzionale) + +Se devi eseguire questa conversione ogni notte, avvolgi lo script in una semplice shell o file batch Windows, e programmarlo con `cron` (Linux/macOS) o Task Scheduler (Windows). Ecco un `run_ocr.sh` minimale per sistemi Unix‑like: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Rendilo eseguibile (`chmod +x run_ocr.sh`) e aggiungi una voce cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Questo esegue la conversione ogni giorno alle 2 AM e registra qualsiasi output per una revisione successiva. + +--- + +## Conclusione + +Ora disponi di un metodo comprovato e pronto per la produzione per **convert images to text python** usando `BatchOcrEngine` di Aspose.OCR. Lo script gestisce **bulk image to text conversion**, scrive elegantemente ogni risultato in un file dedicato, e include passaggi di verifica per assicurarti che tu effettivamente **recognize text from scanned images** correttamente. + +Da qui potresti: + +- Sperimentare con diverse impostazioni OCR (pacchetti lingua, correzione inclinazione, riduzione rumore). +- Inoltrare il testo generato in un indice di ricerca come Elasticsearch per una ricerca full‑text istantanea. +- Combinare questa pipeline con strumenti di conversione PDF per elaborare PDF scannerizzati in un unico passaggio. + +Hai domande, o hai notato un intoppo con un tipo di file particolare? Lascia un commento qui sotto, e risolviamo insieme. Buona programmazione, e che le tue esecuzioni OCR siano veloci e prive di errori! + +## Cosa dovresti imparare dopo? + +- [Estrai Testo da Immagine con Aspose OCR – Guida Passo‑Passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Estrai Testo da Immagini Usando Operazione OCR su Cartelle](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Estrai testo immagine C# con selezione 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/italian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..3e39e3854 --- /dev/null +++ b/ocr/italian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Crea un'istanza di licenza in Python e configura facilmente il percorso + della licenza. Scopri come impostare la licenza Aspose OCR con esempi di codice + chiari. +draft: false +keywords: +- create license instance +- configure license path +language: it +og_description: Crea un'istanza di licenza in Python e configura immediatamente il + percorso della licenza. Segui questo tutorial per attivare Aspose OCR con sicurezza. +og_title: Crea un'istanza di licenza in Python – Guida completa alla configurazione +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Crea un'istanza di licenza in Python – Guida passo‑a‑passo +url: /it/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea un'istanza di licenza in Python – Guida completa di configurazione + +Devi **creare un'istanza di licenza** per Aspose OCR in Python? Sei nel posto giusto. In questo tutorial ti mostreremo anche come **configurare il percorso della licenza** affinché l'SDK sappia dove trovare il tuo file `.lic`. + +Se ti è mai capitato di fissare uno script vuoto chiedendoti perché il motore OCR continua a lamentarsi di un prodotto non licenziato, non sei solo. La soluzione è solitamente solo un paio di righe di codice—una volta che sai esattamente dove inserirle. Alla fine di questa guida avrai un ambiente Aspose OCR completamente licenziato, pronto a riconoscere testo, immagini e PDF senza intoppi. + +## Cosa imparerai + +- Come **creare un'istanza di licenza** usando il pacchetto `asposeocr`. +- Il modo corretto per **configurare il percorso della licenza** sia in sviluppo che in produzione. +- Gli errori più comuni (file mancante, permessi errati) e come evitarli. +- Uno script completo, eseguibile, che puoi inserire in qualsiasi progetto. + +Non è necessaria alcuna esperienza pregressa con Aspose OCR, basta un'installazione funzionante di Python 3 e un file di licenza valido. + +--- + +## Passo 1: Installa il pacchetto Aspose OCR per Python + +Prima di poter **creare un'istanza di licenza**, la libreria deve essere presente. Apri un terminale ed esegui: + +```bash +pip install aspose-ocr +``` + +> **Suggerimento:** Se usi un ambiente virtuale (altamente consigliato), attivalo prima. Questo mantiene ordinate le dipendenze e previene conflitti di versione. + +## Passo 2: Importa la classe License + +Ora che l'SDK è disponibile, la prima riga del tuo script deve importare la classe `License`. Questo è l'oggetto che useremo per **creare un'istanza di licenza**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Perché importarla subito? Perché l'oggetto `License` deve essere istanziato **prima** di qualsiasi chiamata OCR; altrimenti l'SDK lancerà un errore di licenza nel momento in cui proverai a processare un'immagine. + +## Passo 3: Crea l'istanza di licenza + +Ecco il momento che aspettavi: effettivamente **creare un'istanza di licenza**. È una singola riga, ma il contesto circostante è importante. + +```python +# Step 3: Create a License instance +license = License() +``` + +La variabile `license` ora contiene un oggetto che controlla tutto il comportamento di licenza per il processo Python corrente. Pensala come il guardiano che dice ad Aspose OCR: “Ehi, ho il diritto di eseguire.” + +## Passo 4: Configura il percorso della licenza + +Con l'istanza pronta, dobbiamo indicarle il nostro file `.lic`. È qui che entra in gioco **configurare il percorso della licenza**. Sostituisci il segnaposto con il percorso assoluto al tuo file di licenza. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Alcune note importanti: + +1. **Stringhe raw (`r"…"`)** evitano che le barre rovesciate vengano interpretate come caratteri di escape su Windows. +2. Usa un **percorso assoluto** per evitare confusione quando lo script viene avviato da una directory di lavoro diversa. +3. Se preferisci un percorso relativo (ad esempio quando includi la licenza nel tuo progetto), assicurati che la base relativa sia la posizione dello script, non la directory corrente della shell. + +### Gestione dei file mancanti + +Se il percorso è errato o il file non è leggibile, `set_license` solleverà un'eccezione. Avvolgi la chiamata in un blocco `try/except` per fornire un messaggio di errore amichevole: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Questo frammento **configura il percorso della licenza** in modo sicuro e ti dice esattamente cosa è andato storto—senza stack trace misteriosi. + +## Passo 5: Verifica che la licenza sia attiva + +Un rapido controllo di sanità salva ore di debug in seguito. Dopo aver chiamato `set_license`, prova un'operazione OCR semplice. Se la licenza è valida, l'SDK processerà l'immagine senza lanciare un errore di licenza. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Se vedi stampato il testo riconosciuto, congratulazioni—hai **creato un'istanza di licenza** e **configurato il percorso della licenza** con successo. Se ottieni un'eccezione di licenza, ricontrolla il percorso e i permessi del file. + +## Casi particolari e migliori pratiche + +| Situazione | Cosa fare | +|------------|-----------| +| **Il file di licenza si trova su una condivisione di rete** | Mappa la condivisione a una lettera di unità o usa un percorso UNC (`\\server\share\license.lic`). Assicurati che il processo Python abbia accesso in lettura. | +| **Esecuzione all'interno di un container Docker** | Copia il file `.lic` nell'immagine e riferiscilo con un percorso assoluto come `/app/license/Aspose.OCR.Java.lic`. | +| **Più interpreti Python** (es. ambienti conda) | Installa il file di licenza una volta per ambiente o mantieni una posizione centrale e punta ogni interprete a quella. | +| **File di licenza mancante a runtime** | Passa delicatamente a una modalità di prova (se supportata) o interrompi l'esecuzione con un messaggio di log chiaro. | + +### Errori comuni + +- **Uso di slash avanti su Windows** – Python li accetta, ma alcune versioni più vecchie dell'SDK potrebbero interpretarli male. Usa stringhe raw o doppie barre rovesciate. +- **Dimenticato di importare `License`** – Lo script andrà in crash con `NameError`. Importa sempre prima di istanziare. +- **Chiamare `set_license` dopo i metodi OCR** – L'SDK verifica la licenza al primo utilizzo, quindi imposta il percorso **prima**. + +## Esempio completo funzionante + +Di seguito trovi uno script completo che mette insieme tutti i passaggi. Salvalo come `ocr_setup.py` ed eseguilo da riga di comando. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Output previsto** (con un'immagine valida): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Se il file di licenza non viene trovato, vedrai un messaggio di errore chiaro invece di un'eccezione criptica “License not found”. + +--- + +## Conclusione + +Ora sai esattamente come **creare un'istanza di licenza** in Python e **configurare il percorso della licenza** per l'SDK Aspose OCR. I passaggi sono semplici: installa il pacchetto, importa `License`, istanziala, puntala al tuo file `.lic` e verifica con un piccolo test OCR. + +Con queste conoscenze puoi integrare le capacità OCR in servizi web, applicazioni desktop o pipeline automatizzate senza incappare in errori di licenza. Successivamente, potresti esplorare impostazioni OCR avanzate—pacchetti linguistici, pre‑elaborazione delle immagini o elaborazione batch—ognuna delle quali si basa sulla solida base appena creata. + +Hai domande su deployment, Docker o gestione di più licenze? Lascia un commento, e buona programmazione! + +## Cosa dovresti imparare dopo? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/italian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..9969ae658 --- /dev/null +++ b/ocr/italian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Crea PDF ricercabili da immagini scansionate usando Python OCR. Scopri + come convertire PDF di immagini scansionate, convertire TIFF in PDF e aggiungere + un livello di testo OCR in pochi minuti. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: it +og_description: Crea PDF ricercabili all'istante. Questa guida mostra come eseguire + l'OCR, convertire PDF di immagini scannerizzate e aggiungere un livello di testo + OCR usando un unico script Python. +og_title: Crea PDF Ricercabile con Python – Tutorial Completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Crea PDF Ricercabile con Python – Guida Passo‑Passo +url: /it/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea PDF Ricercabile con Python – Guida Passo‑Passo + +Ti sei mai chiesto come **creare PDF ricercabili** da una pagina scansionata senza dover gestire decine di strumenti? Non sei il solo. In molti flussi di lavoro d'ufficio un TIFF o JPEG scansionato finisce su un'unità condivisa, e la persona successiva deve copiare‑incollare il testo manualmente—un'operazione dolorosa, soggetta a errori e dispendiosa in termini di tempo. + +In questo tutorial percorreremo una soluzione pulita e programmatica che ti permette di **convertire PDF immagine scansionata**, **convertire TIFF in PDF**, e **aggiungere un livello di testo OCR** in un unico passaggio. Alla fine avrai uno script pronto all'uso che esegue l'OCR, incorpora il testo nascosto e genera un PDF ricercabile che puoi indicizzare, cercare o condividere con fiducia. + +## Cosa Ti Serve + +- Python 3.9+ (qualsiasi versione recente va bene) +- `aspose-ocr` e `aspose-pdf` pacchetti (installati tramite `pip install aspose-ocr aspose-pdf`) +- Un file immagine scansionato (`.tif`, `.png`, `.jpg`, o anche una pagina PDF che è solo un'immagine) +- Una quantità modesta di RAM (il motore OCR è leggero; anche un laptop lo gestisce) + +> **Suggerimento professionale:** Se sei su Windows, il modo più semplice per ottenere i pacchetti è eseguire il comando in una finestra PowerShell elevata. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Ora che i prerequisiti sono sistemati, immergiamoci nel codice. + +## Passo 1: Crea un'Istanza del Motore OCR – *create searchable pdf* + +La prima cosa che facciamo è avviare il motore OCR. Pensalo come il cervello che leggerà ogni pixel e lo trasformerà in caratteri. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Perché è importante:** Inizializzare il motore una sola volta mantiene basso l'uso della memoria. Se chiamassi `OcrEngine()` all'interno di un ciclo per ogni pagina, esauriresti rapidamente le risorse. + +## Passo 2: Carica l'Immagine Scansionata – *convert tiff to pdf* & *convert scanned image pdf* + +Successivamente, indica al motore il file che vuoi elaborare. L'API accetta qualsiasi immagine raster, quindi un TIFF funziona altrettanto bene di un JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Se per caso disponi di un PDF che contiene solo un'immagine scansionata, puoi comunque usare `load_image` perché Aspose estrarrà automaticamente la prima pagina. + +## Passo 3: Prepara le Opzioni di Salvataggio PDF – *add OCR text layer* + +Qui configuriamo l'aspetto del PDF finale. Il flag cruciale è `create_searchable_pdf`; impostarlo a `True` indica alla libreria di incorporare un livello di testo invisibile che rispecchia il contenuto visivo. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Cosa fa il livello di testo:** Quando apri il file risultante in Adobe Reader e provi a selezionare del testo, vedrai i caratteri nascosti. Anche i motori di ricerca possono indicizzarli—perfetto per conformità o archiviazione. + +## Passo 4: Esegui OCR e Salva – *how to run OCR* in a single call + +Ora avviene la magia. Una singola chiamata al metodo esegue il motore di riconoscimento e scrive il PDF ricercabile su disco. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Il metodo `recognize` restituisce un oggetto di stato che puoi ispezionare per eventuali errori, ma per la maggior parte degli scenari semplici la chiamata sopra è sufficiente. + +### Output Previsto + +Eseguendo lo script stampa: + +``` +PDF saved as searchable PDF. +``` + +Se apri `scanned_page_searchable.pdf` noterai che puoi selezionare il testo, copiarlo‑incollarlo e persino eseguire una ricerca `Ctrl+F`. Questo è il segno distintivo di un flusso di lavoro **create searchable pdf**. + +## Script Completo Funzionante + +Di seguito trovi lo script completo, pronto all'esecuzione. Sostituisci semplicemente i percorsi segnaposto con le tue posizioni di file effettive. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Salva questo file come `create_searchable_pdf.py` ed esegui: + +```bash +python create_searchable_pdf.py +``` + +## Domande Frequenti & Casi Limite + +### 1️⃣ Posso elaborare PDF multi‑pagina? + +Sì. Usa `ocr_engine.load_image("file.pdf")` e poi itera su ogni pagina con `ocr_engine.recognize(pdf_save_options, page_number)`. La libreria genererà automaticamente un PDF ricercabile multi‑pagina. + +### 2️⃣ Cosa succede se il mio file di origine è un TIFF ad alta risoluzione (300 dpi+)? + +Una DPI più alta fornisce una migliore accuratezza OCR ma richiede più memoria. Se incontri un `MemoryError`, ridimensiona prima l'immagine: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Come cambio la lingua dell'OCR? + +Imposta la proprietà `language` sul motore prima di caricare l'immagine: + +```python +ocr_engine.language = "fra" # French +``` + +Un elenco completo dei codici lingua supportati è disponibile nella documentazione di Aspose. + +### 4️⃣ Cosa fare se devo mantenere la qualità originale dell'immagine? + +La classe `PdfSaveOptions` dispone di una proprietà `compression`. Impostala a `PdfCompression.None` per preservare i dati raster esattamente com'erano. + +```python +pdf_save_options.compression = "None" +``` + +## Consigli per Distribuzioni Pronte alla Produzione + +- **Elaborazione batch:** Avvolgi la logica principale in una funzione che accetta una lista di percorsi file. Registra ogni successo/fallimento in un CSV per tracciabilità. +- **Parallelismo:** Usa `concurrent.futures.ThreadPoolExecutor` per eseguire OCR su più core. Ricorda che ogni thread necessita della propria istanza `OcrEngine`. +- **Sicurezza:** Se gestisci documenti sensibili, esegui lo script in un ambiente sandbox e elimina immediatamente i file temporanei dopo l'elaborazione. + +## Conclusione + +Ora sai come **creare PDF ricercabili** da immagini scansionate usando uno script Python conciso. Inizializzando un motore OCR, caricando un TIFF (o qualsiasi raster), configurando `PdfSaveOptions` per **add OCR text layer**, e infine chiamando `recognize`, l'intera pipeline **convert scanned image pdf** e **convert TIFF to PDF** diventa un unico comando ripetibile. + +Prossimi passi? Prova a concatenare questo script con un watcher di file in modo che ogni nuova scansione depositata in una cartella diventi automaticamente ricercabile. Oppure sperimenta con diverse lingue OCR per supportare archivi multilingue. Il cielo è il limite quando combini OCR e generazione PDF. + +Hai altre domande su **how to run OCR** in altri linguaggi o framework? Lascia un commento qui sotto, e buona programmazione! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## Cosa Dovresti Imparare Dopo? + +- [Come fare OCR di PDF in .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Converti Immagini in PDF C# – Salva Risultato OCR Multi‑pagina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Come fare OCR di Testo Immagine con Lingua usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/italian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..83723e5a8 --- /dev/null +++ b/ocr/italian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Migliora l'accuratezza OCR con Python preelaborando le immagini per l'OCR. + Scopri come estrarre testo da file immagine, riconoscere il testo da PNG e potenziare + i risultati. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: it +og_description: Migliora l'accuratezza OCR in Python applicando la preelaborazione + delle immagini per il testo. Segui questa guida per estrarre il testo dai file immagine + e riconoscere il testo da PNG senza sforzo. +og_title: Migliora l'accuratezza OCR in Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Migliora l'accuratezza OCR in Python – Guida completa passo passo +url: /it/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Migliora l'accuratezza OCR in Python – Guida completa passo‑per‑passo + +Hai mai provato a **migliorare l'accuratezza OCR** solo per ottenere output incomprensibili? Non sei l'unico. La maggior parte degli sviluppatori si scontra con il problema quando l'immagine grezza è rumorosa, inclinata o semplicemente a basso contrasto. La buona notizia? Una manciata di trucchi di pre‑elaborazione può trasformare uno screenshot sfocato in testo pulito e leggibile dalla macchina. + +In questo tutorial percorreremo un esempio reale che **preprocessa un'immagine per l'OCR**, esegue il motore di riconoscimento e infine **estrae testo da file immagine** — specificamente un PNG. Alla fine saprai esattamente come **riconoscere testo da PNG** con un tasso di successo più alto, e avrai uno snippet di codice riutilizzabile da inserire in qualsiasi progetto. + +## Cosa imparerai + +- Perché la pre‑elaborazione delle immagini è importante per i motori OCR +- Quali modalità di pre‑elaborazione (denoise, deskew) offrono il maggior miglioramento +- Come configurare un'istanza di `OcrEngine` in Python +- Lo script completo e eseguibile che **estrae testo da file immagine** +- Suggerimenti per gestire casi limite come scansioni ruotate o immagini a bassa risoluzione + +Non sono necessarie librerie esterne oltre all'OCR SDK, ma avrai bisogno di Python 3.8+ e di un'immagine PNG che desideri leggere. + +--- + +![Diagramma che mostra i passaggi per migliorare l'accuratezza OCR in Python](image.png "Flusso di lavoro per migliorare l'accuratezza OCR") + +*Testo alternativo: diagramma del flusso di lavoro per migliorare l'accuratezza OCR che illustra i passaggi di pre‑elaborazione e riconoscimento.* + +## Prerequisiti + +- Python 3.8 o versioni successive installato +- Accesso all'OCR SDK che fornisce `OcrEngine`, `OcrEngineSettings` e `ImagePreprocessMode` (il codice sotto utilizza un'API generica; sostituisci con le classi del tuo fornitore se necessario) +- Un'immagine PNG (`input.png`) posizionata in una cartella a cui puoi fare riferimento + +Se stai usando un ambiente virtuale, attivalo ora—niente di complicato, basta `python -m venv venv && source venv/bin/activate`. + +--- + +## Passo 1: Crea l'istanza del motore OCR – Inizia a migliorare l'accuratezza OCR + +La prima cosa di cui hai bisogno è un oggetto OCR engine. Pensalo come il cervello che in seguito leggerà i pixel e produrrà i caratteri. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Perché è importante: senza un motore non puoi applicare alcuna pre‑elaborazione, e l'immagine grezza verrà inviata direttamente al riconoscitore—di solito lo scenario peggiore per l'accuratezza. + +--- + +## Passo 2: Carica il PNG di destinazione – Prepara il terreno per riconoscere testo da PNG + +Ora indichiamo al motore quale file elaborare. PNG è lossless, il che ci dà già un piccolo vantaggio rispetto a JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Se l'immagine si trova altrove, basta modificare il percorso. Il motore accetta qualsiasi formato supportato, ma PNG spesso conserva i dettagli fini necessari per bordi di carattere nitidi. + +--- + +## Passo 3: Configura la pre‑elaborazione – Preprocessa l'immagine per l'OCR + +Qui avviene la magia. Creiamo un oggetto impostazioni, abilitiamo il denoise per eliminare i granelli e attiviamo il deskew così il testo inclinato viene raddrizzato automaticamente. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Perché Denoise + Deskew? + +- **Denoise**: Il rumore casuale dei pixel confonde gli algoritmi di pattern‑matching. Rimuoverlo affina le lettere. +- **Deskew**: Anche una inclinazione di 2 gradi può ridurre drasticamente i punteggi di confidenza. Deskew allinea la linea di base, permettendo al riconoscitore di abbinare i font in modo più affidabile. + +Puoi sperimentare con flag aggiuntivi (ad es., `ImagePreprocessMode.CONTRAST_ENHANCE`) se le tue immagini sono particolarmente scure. La documentazione dell'SDK solitamente elenca tutte le modalità disponibili. + +--- + +## Passo 4: Applica le impostazioni al motore – Collega la pre‑elaborazione all'OCR + +Assegna l'oggetto impostazioni al motore in modo che la prossima esecuzione di riconoscimento utilizzi le trasformazioni appena definite. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Se salti questo passo, il motore tornerà alle impostazioni predefinite (spesso “nessuna pre‑elaborazione”), e vedrai **una minore accuratezza OCR**. + +--- + +## Passo 5: Esegui il processo di riconoscimento – Estrai testo dall'immagine + +Con tutto collegato, chiediamo finalmente al motore di fare il suo lavoro. La chiamata è sincrona, restituendo un oggetto risultato che contiene la stringa riconosciuta. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Dietro le quinte il motore ora: + +1. Carica il PNG in memoria +2. Applica denoise e deskew in base alle nostre impostazioni +3. Esegue la rete neurale o il classico pattern matcher +4. Imballa l'output in `recognition_result` + +--- + +## Passo 6: Stampa il testo riconosciuto – Verifica il miglioramento + +Stampiamo la stringa estratta. In un'applicazione reale potresti scriverla su un file, su un database o passarla a un altro servizio. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Output previsto + +Se l'immagine contiene la frase “Hello, OCR World!” dovresti vedere: + +``` +Hello, OCR World! +``` + +Nota come il testo è pulito—nessun simbolo estraneo o carattere rotto. Questo è il risultato di una corretta **pre‑elaborazione dell'immagine per il testo**. + +--- + +## Consigli professionali & casi limite + +| Situazione | Cosa regolare | Perché | +|-----------|----------------|-----| +| PNG a risoluzione molto bassa (≤ 72 dpi) | Aggiungi `ImagePreprocessMode.SUPER_RESOLUTION` se disponibile | L'upsampling può fornire al riconoscitore più pixel su cui lavorare | +| Il testo è ruotato > 5° | Aumenta la tolleranza del deskew o ruota manualmente con `Pillow` prima di fornire al motore | Angoli estremi a volte bypassano il deskew automatico | +| Pattern di sfondo pesanti | Abilita `ImagePreprocessMode.BACKGROUND_REMOVAL` | Rimuove il rumore non testuale che altrimenti verrebbe letto erroneamente | +| Documento multilingue | Imposta `ocr_engine.language = "eng+spa"` (o simile) | Il motore seleziona il set di caratteri corretto, migliorando l'accuratezza complessiva | + +Ricorda, **migliorare l'accuratezza OCR** non è una soluzione unica per tutti; potresti dover iterare sulle flag di pre‑elaborazione per il tuo dataset specifico. + +--- + +## Script completo – Pronto da copiare e incollare + +Di seguito trovi l'esempio completo e eseguibile che incorpora tutti i passaggi di cui abbiamo parlato. Salvalo come `improve_ocr_accuracy.py` ed eseguilo con `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Eseguilo, osserva la console, e vedrai subito il risultato di **estrazione del testo dall'immagine**. Se l'output sembra errato, modifica le flag `preprocess_mode` come descritto nella tabella “Consigli professionali”. + +--- + +## Conclusione + +Abbiamo appena illustrato una ricetta pratica per **migliorare l'accuratezza OCR** usando Python. Creando un `OcrEngine`, caricando un PNG, **preprocessando l'immagine per l'OCR**, e infine **riconoscendo testo da PNG**, puoi affidabilmente **estrarre testo da file immagine** anche quando la sorgente non è perfetta. + +Prossimi passi? Prova a elaborare un batch di immagini in un ciclo, salva ogni risultato in un CSV, o sperimenta con modalità di pre‑elaborazione aggiuntive come il miglioramento del contrasto. Lo stesso schema funziona per PDF, ricevute scansionate o note scritte a mano—basta sostituire l'input e regolare le impostazioni. + +Hai domande su un tipo di immagine specifico o vuoi sapere come integrare questo in un servizio web? Lascia un commento e esploreremo insieme quegli scenari. Buona programmazione, e che i tuoi risultati OCR siano sempre cristallini! + +## Cosa dovresti imparare dopo? + +- [Estrai testo da immagine con Aspose OCR – Guida passo‑per‑passo](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Estrai testo da immagine – Ottimizzazione OCR con Aspose.OCR per .NET](/ocr/english/net/ocr-optimization/) +- [Come estrarre testo da immagine preparando rettangoli in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/italian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..dbe75c8ab --- /dev/null +++ b/ocr/italian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-31 +description: Scopri come utilizzare la regione di interesse OCR per caricare l'immagine + per l'OCR ed estrarre il testo da un rettangolo, perfetto per riconoscere l'importo + su una fattura. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: it +og_description: Padroneggia la regione di interesse OCR per caricare l'immagine per + l'OCR, estrarre il testo dal rettangolo e riconoscere il testo della fattura in + un unico tutorial. +og_title: OCR Regione di Interesse – Guida Python Passo‑passo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Regione di Interesse – Estrai il Testo da un Rettangolo in Python +url: /it/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Estrarre Testo da Rettangolo in Python + +Ti sei mai chiesto come **ocr region of interest** una parte specifica di una fattura scannerizzata senza fornire l'intera pagina al motore? Non sei il primo a fissare una ricevuta sfocata e a pensare: “Come estraggo l'importo che si trova da qualche parte in basso a destra?” La buona notizia è che puoi indicare alla libreria OCR esattamente dove guardare, aumentando notevolmente sia la velocità sia la precisione. + +In questa guida percorreremo un esempio completo e eseguibile che ti mostra come **load image for OCR**, definire una **region of interest**, e poi **extract text from rectangle** per infine **recognize text from invoice** e rispondere alla classica domanda “come estrarre l'importo”. Nessun riferimento vago—solo codice concreto, spiegazioni chiare e qualche consiglio professionale che avresti voluto conoscere prima. + +--- + +## Cosa Costruirai + +1. Carica un'immagine di fattura dal disco. +2. Contrassegna un ROI rettangolare dove si trova l'importo totale. +3. Esegue OCR solo all'interno di quel ROI. +4. Stampa la stringa dell'importo pulita. + +Tutto questo funziona con qualsiasi libreria OCR che supporta ROI—qui useremo un pacchetto fittizio ma rappresentativo `SimpleOCR` che imita strumenti popolari come Tesseract o EasyOCR. Sentiti libero di sostituirlo; i concetti rimangono gli stessi. + +--- + +## Prerequisiti + +- Python 3.8+ installato (`python --version` dovrebbe mostrare ≥3.8). +- Un pacchetto OCR installabile via pip (es., `pip install simpleocr`). +- Un'immagine di fattura (PNG o JPEG) collocata in una cartella a cui puoi fare riferimento. +- Familiarità di base con funzioni e classi Python (nulla di complesso). + +Se li hai già, ottimo—tuffiamoci. Altrimenti, procurati prima l'immagine; il resto dei passaggi è indipendente dal contenuto effettivo del file. + +--- + +## Passo 1: Carica Immagine per OCR + +La prima cosa di cui ha bisogno qualsiasi flusso di lavoro OCR è una bitmap da cui leggere. La maggior parte delle librerie espone un semplice metodo `load_image` che accetta un percorso file. Ecco come farlo con il nostro motore `SimpleOCR`: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Usa percorsi assoluti o `os.path.join` per evitare sorprese “file not found” quando esegui lo script da una directory di lavoro diversa. + +--- + +## Passo 2: Definisci OCR Region of Interest + +Invece di far scansionare al motore l'intera pagina, gli diciamo *esattamente* dove si trova l'importo. Questo è il passo **ocr region of interest**, ed è la chiave per un'estrazione affidabile, specialmente quando il documento contiene intestazioni o piè di pagina rumorosi. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Perché questi numeri? `x` e `y` sono offset in pixel dall'angolo in alto a sinistra, mentre `width` e `height` descrivono le dimensioni del riquadro. Se non sei sicuro, apri l'immagine in qualsiasi editor, attiva un righello e annota le coordinate. Molti IDE permettono anche di stampare la posizione del cursore al passaggio del mouse. + +--- + +## Passo 3: Estrarre Testo da Rettangolo + +Ora che il ROI è impostato, chiediamo al motore di **recognize text from invoice** ma limitato al rettangolo appena aggiunto. La chiamata restituisce un oggetto risultato che tipicamente contiene la stringa grezza, i punteggi di confidenza e talvolta i riquadri di delimitazione. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Dietro le quinte, `recognize()` itera su ogni ROI, ritaglia quella porzione, esegue il modello OCR e unisce i risultati. Ecco perché definire una regione **extract text from rectangle** stretta può risparmiare secondi sul tempo di elaborazione per lavori batch. + +--- + +## Passo 4: Come Estrarre l'Importo – Pulire l'Uscita + +L'OCR non è perfetto; spesso otterrai spazi superflui, interruzioni di riga o anche caratteri letti erroneamente (pensa a “S” vs “5”). Un rapido `strip()` e una piccola regex di solito risolvono il problema per i valori monetari. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** Se prevedi di inserire l'importo in un database o in un gateway di pagamento, ti serve un formato prevedibile. Rimuovere gli spazi bianchi e filtrare i caratteri non numerici previene errori a valle. + +--- + +## Passo 5: Recognize Text from Invoice – Script Completo + +Mettendo tutto insieme, ecco lo script completo, pronto per l'esecuzione. Salvalo come `extract_amount.py` ed esegui `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Output Atteso + +``` +Amount: 1,245.67 +``` + +Se il ROI è disallineato, potresti vedere qualcosa come `Amount: 1245.6S`—nota la “S” estranea. Regola le coordinate del rettangolo e riesegui finché l'output non appare pulito. + +--- + +## Problemi Comuni & Casi Limite + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| **ROI troppo piccolo** | Il testo dell'importo viene tagliato, portando a un riconoscimento parziale. | Espandi `width`/`height` del ~10‑20 % e ritesta. | +| **DPI errato** | Scansioni a bassa risoluzione (≤150 dpi) riducono la precisione dell'OCR. | Ricampiona l'immagine a 300 dpi prima del caricamento, o richiedi una DPI più alta allo scanner. | +| **Valute multiple** | La regex prende il primo gruppo numerico, che potrebbe essere il numero della fattura. | Raffina la regex per cercare i simboli di valuta (`$`, `€`, `£`) prima delle cifre. | +| **Fatture ruotate** | I motori OCR assumono testo verticale; le pagine ruotate interrompono il riconoscimento. | Applica una correzione di rotazione (`ocr_engine.rotate(90)`) prima di aggiungere il ROI. | +| **Rumore di sfondo** | Ombre o timbri confondono il modello. | Pre‑processa con una semplice soglia (`cv2.threshold`) o usa un filtro di denoising. | + +Affrontare questi casi limite in anticipo ti salva ore di debugging in seguito. + +--- + +## Consigli Pro per Progetti Reali + +- **Batch Processing:** Scorri una cartella di fatture, calcola il ROI dinamicamente (es., basato sul rilevamento del modello), e salva i risultati in CSV. +- **Template Matching:** Se gestisci diversi layout di fatture, mantieni una mappa JSON di `template_id → ROI coordinates`. Cambia il ROI in base a un rapido classificatore di layout. +- **Parallel Execution:** Usa `concurrent.futures.ThreadPoolExecutor` per eseguire più istanze OCR in parallelo—ideale per pipeline back‑office ad alto volume. +- **Confidence Filtering:** La maggior parte dei risultati OCR includono un punteggio di confidenza. Scarta i risultati al di sotto di una soglia (es., 85 %) e contrassegnali per revisione manuale. + +--- + +## Conclusione + +Abbiamo coperto tutto ciò di cui hai bisogno per **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, e infine **recognize text from invoice** per rispondere alla classica domanda **how to extract amount**. Lo script è compatto, ma sufficientemente flessibile da adattarsi a diversi formati di documento, lingue e back‑end OCR. + +Ora che hai padroneggiato le basi, considera di estendere il flusso di lavoro: aggiungere la scansione di codici a barre, integrare un parser PDF, o inviare l'importo estratto a un'API contabile. Il cielo è il limite, e con un ROI ben definito otterrai sempre risultati più rapidi e puliti. + +Se incontri un problema, lascia un commento qui sotto—buon OCR! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + +## Cosa Dovresti Imparare Dopo? + +- [Come Estrarre Testo da Immagine Preparando Rettangoli in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Estrarre Testo da Immagine Java con Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Estrarre Testo da Immagine – Ottimizzazione OCR con Aspose.OCR per .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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/japanese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..a160be958 --- /dev/null +++ b/ocr/japanese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-31 +description: 非同期OCRチュートリアル:PythonのasyncioでAspose OCRを使用し、画像テキストを高速に抽出する方法を紹介します。ステップバイステップで非同期OCRの実装を学びましょう。 +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: ja +og_description: 非同期OCRチュートリアルでは、Pythonのasyncioを使用してAspose OCRを活用し、効率的な画像テキスト抽出の方法を解説します。 +og_title: 非同期 OCR チュートリアル – Python asyncio と Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: 非同期 OCR チュートリアル – Python asyncio と Aspose OCR +url: /ja/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 非同期 OCR チュートリアル – Python asyncio と Aspose OCR + +アプリをブロックせずに光学文字認識(OCR)を実行する方法を考えたことはありますか? **非同期 OCR チュートリアル** では、Python の `asyncio` と Aspose OCR ライブラリを使用した、ブロックしないテキスト抽出を実際に確認できます。 + +重い画像の処理が終わるのを待ち続けている場合、このガイドはイベントループをスムーズに保つクリーンな非同期ソリューションを提供します。 + +以下のセクションでは、ライブラリのインストール、非同期ヘルパーの作成、結果の処理、さらには複数画像へのスケーリングに関する簡単なヒントまで、必要なすべてをカバーします。最後まで読めば、`asyncio` を既に使用している任意の Python プロジェクトに **非同期 OCR チュートリアル** を組み込むことができます。 + +## 必要なもの + +* Python 3.9+(使用している `asyncio` API は 3.7 以降で安定しています) +* 有効な Aspose OCR ライセンスまたは無料トライアル(ライブラリは純粋な Python で、ネイティブバイナリは不要です) +* 読み取りたい小さな画像ファイル(`.jpg`、`.png` など)を、分かりやすいフォルダーに保存しておきます + +他に外部ツールは必要ありません。すべて純粋な Python で動作します。 + +## ステップ 1: Aspose OCR パッケージのインストール + +まずはじめに、PyPI から Aspose OCR パッケージを取得します。ターミナルを開いて次のコマンドを実行してください: + +```bash +pip install aspose-ocr +``` + +> **プロのコツ:** 仮想環境内で作業している場合(強く推奨)、まずそれを有効化してください。これにより依存関係が分離され、バージョン衝突を防げます。 + +## ステップ 2: OCR エンジンを非同期に初期化する + +この **非同期 OCR チュートリアル** の中心は非同期ヘルパー関数です。`OcrEngine` のインスタンスを作成し、画像を読み込み、`recognize_async()` を呼び出します。エンジン自体は同期的ですが、ラッパーメソッドは await 可能なオブジェクトを返すため、イベントループは応答性を保ちます。 + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**このようにする理由:** +*ヘルパー内部でエンジンを作成することで、後で多数の OCR ジョブを並列に実行した場合でもスレッド安全性が確保されます。`await` キーワードは、重い処理がライブラリ内部のスレッドプールで行われている間、制御をイベントループに戻します。* + +## ステップ 3: 非同期メイン関数からヘルパーを呼び出す + +ここでは、`async_ocr()` を呼び出し結果を出力する小さな `main()` コルーチンが必要です。これは `asyncio` スクリプトの典型的なエントリーポイントに相当します。 + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**内部で何が起きているか:** +`asyncio.run()` は新しいイベントループを作成し、`main()` をスケジュールし、`main()` が終了するとループをきれいにシャットダウンします。このパターンは Python 3.7+ で非同期プログラムを開始する推奨方法です。 + +## ステップ 4: 完全なスクリプトをテストする + +上記の 2 つのコードブロックを 1 つのファイル(例: `async_ocr_demo.py`)に保存します。コマンドラインから実行してください: + +```bash +python async_ocr_demo.py +``` + +正しく設定されていれば、次のような出力が表示されます: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +正確な出力は `photo.jpg` の内容に依存します。重要なのは、画像が大きくても OCR の処理がバックグラウンドで行われるため、スクリプトが迅速に終了することです。 + +## ステップ 5: スケールアップ – 複数画像を同時に処理する + +よくある追随の質問は、*「各ファイルごとに新しいプロセスを起動せずにバッチで OCR できるか?」* です。もちろん可能です。ヘルパーが完全に非同期であるため、`asyncio.gather()` を使って多数のコルーチンをまとめられます: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**この方法が機能する理由:** `asyncio.gather()` はすべての OCR タスクを一度にスケジュールします。基盤となる Aspose OCR ライブラリは依然として独自のスレッドプールを使用しますが、Python 側から見るとすべてがノンブロッキングのままで、単一の同期呼び出しにかかる時間で数十枚の画像を処理できます。 + +## ステップ 6: エラーを優雅に処理する + +外部ファイルを扱う際には、欠損ファイルや破損画像、ライセンス問題に必ず遭遇します。OCR 呼び出しを `try/except` ブロックでラップして、イベントループが停止しないようにします: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +これで `batch_ocr()` は代わりに `safe_async_ocr` を呼び出すことができ、1 つの不良ファイルがバッチ全体を中断させないようにします。 + +## ビジュアル概要 + +![非同期 OCR チュートリアル図](async-ocr-diagram.png){alt="async_ocr ヘルパー、イベントループ、Aspose OCR エンジンを示す非同期 OCR チュートリアルのフローチャート"} + +上の図はフローを視覚化しています:イベントループ → `async_ocr` → `OcrEngine` → バックグラウンドスレッド → 結果がループに戻る。 + +## よくある落とし穴と回避方法 + +| 落とし穴 | 発生理由 | 対策 | +|---------|----------|------| +| **ヘルパー内部でのブロッキング I/O** | `await` なしで `open()` を誤って使用すると、ループがブロックされる可能性があります。 | `aiofiles` を使ってファイルを読み込むか、`engine.load_image` に任せてください(既にノンブロッキングです)。 | +| **コルーチン間で単一の `OcrEngine` を再利用する** | エンジンはスレッドセーフではなく、同時呼び出しで状態が破損する可能性があります。 | 各 `async_ocr` 呼び出し内で新しいエンジンをインスタンス化してください(上記参照)。 | +| **ライセンスがない** | Aspose OCR が実行時にライセンス関連の例外をスローします。 | 早めにライセンスを登録してください(`OcrEngine.set_license("license.json")`)。 | +| **大きな画像がメモリスパイクを引き起こす** | ライブラリが画像全体を RAM に読み込むためです。 | メモリが懸念される場合は、OCR 前に画像を縮小してください。 | + +## まとめ: 達成したこと + +この **非同期 OCR チュートリアル** では、以下を行いました: + +1. Aspose OCR ライブラリをインストールした。 +2. `async_ocr` ヘルパーを構築し、ブロックせずに認識を実行した。 +3. クリーンな `asyncio` エントリーポイントからヘルパーを実行した。 +4. `asyncio.gather` を使ったバッチ処理を実演した。 +5. エラーハンドリングとベストプラクティスのヒントを追加した。 + +これらはすべて純粋な Python で実装されているため、既存の非同期コードを書き換えることなく、Web サーバー、CLI ツール、またはデータパイプラインに組み込むことができます。 + +## 次のステップと関連トピック + +* **非同期画像前処理** – OCR 前に `aiohttp` を使用して画像を同時にダウンロードします。 +* **OCR 結果の保存** – このチュートリアルを PostgreSQL 用の非同期データベースドライバ `asyncpg` と組み合わせます。 +* **パフォーマンスチューニング** – ライブラリがそのようなオプションを提供している場合、`engine.recognize_async(max_threads=4)` を試してみてください。 +* **代替 OCR エンジン** – コスト・ベネフィット分析のために、Aspose OCR と Tesseract の非同期ラッパーを比較します。 + +自由に実験してください:PDF を入力したり、言語設定を調整したり、結果をチャットボットに連携したりできます。堅実な **非同期 OCR チュートリアル** の基盤があれば、可能性は無限です。 + +コーディングを楽しんで、テキスト抽出が常に高速でありますように! + +## 次に学ぶべきことは? + +- [Aspose OCR を使用した画像からのテキスト抽出 – ステップバイステップガイド](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR チュートリアル – 光学文字認識](/ocr/english/) +- [Aspose.OCR を使用した言語別画像テキスト OCR の方法](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/japanese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..23ed533a4 --- /dev/null +++ b/ocr/japanese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: OCRでの自動言語検出が簡単に。画像OCRの読み込み方法、自動言語検出の有効化、テキスト画像の認識を数ステップで学びましょう。 +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: ja +og_description: OCRにおける自動言語検出が簡単に。ステップバイステップのチュートリアルに従って自動言語検出を有効にし、画像OCRを読み込み、テキスト画像を認識しましょう。 +og_title: OCRによる自動言語検出 – 完全Pythonガイド +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: OCRによる自動言語検出 – 完全Pythonガイド +url: /ja/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCRによる自動言語検出 – 完全Pythonガイド + +スキャンした文書の言語を、何を探すべきか指示しなくてもOCRエンジンに*推測*させたいと思ったことはありませんか?それがまさに**自動言語検出**の役割で、マルチリンガルPDFや道路標識の写真、スクリプトが混在する画像を扱う際に大きな変化をもたらします。 + +このチュートリアルでは、PythonスタイルのAPIを使用して**自動言語検出を有効化**し、**画像OCRをロード**し、**テキスト画像を認識**するハンズオンの例を順に解説します。最後まで実行すれば、検出された言語コードと抽出されたテキストの両方を出力する単体スクリプトが手に入ります—手動で言語設定を行う必要はありません。 + +## 学習できること + +- OCRエンジンのインスタンスを作成し、**自動言語検出**を有効にする方法。 +- ディスクから**画像OCRをロード**する正確な手順。 +- エンジンの`recognize()`メソッドを呼び出し、言語コードを含む結果を取得する方法。 +- 低解像度画像やサポート外スクリプトなどのエッジケースを処理するためのヒント。 + +マルチリンガルOCRの経験は不要です;基本的なPython環境と画像ファイルがあれば始められます。 + +--- + +## 前提条件 + +始める前に、以下が揃っていることを確認してください: + +1. Python 3.8+ がインストールされていること(最近のバージョンであれば問題ありません)。 +2. `OcrEngine`、`LanguageAutoDetectMode` などを提供するOCRライブラリ – 本ガイドでは仮想パッケージ `myocr` を想定します。以下でインストールしてください: + + ```bash + pip install myocr + ``` + +3. 少なくとも2つの異なる言語が含まれる画像ファイル(`multilingual_sample.png`)。 +4. 少しの好奇心—OCRを触ったことがなくても心配無用です;コードは意図的にシンプルに作られています。 + +--- + +## ステップ1:自動言語検出を有効化 + +最初に行うべきは、エンジンに言語を自動で*判別*させることです。ここで**自動言語検出**フラグが活躍します。 + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **なぜ重要か:** +> `AUTO_DETECT` が設定されると、エンジンは重い文字認識が始まる前に画像上で軽量の言語分類器を実行します。つまり、テキストが英語、ロシア語、フランス語、あるいはそれらの組み合わせかを推測する必要はありません。エンジンは画像の各領域に最適な言語モデルを自動的に選択します。 + +--- + +## ステップ2:画像OCRをロード + +エンジンが自動言語検出を行うことを認識したので、処理対象を与える必要があります。**画像OCRをロード**ステップはビットマップを読み込み、内部バッファを準備します。 + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **プロのコツ:** +> 画像が300 dpiを超える場合は、150‑200 dpi程度にダウンサンプリングすることを検討してください。詳細が多すぎると、精度は向上せずに言語検出段階が*遅く*なることがあります。 + +--- + +## ステップ3:画像からテキストを認識 + +画像がメモリ上にあり、言語検出が有効になっている状態で、最後にエンジンに**テキスト画像を認識**させます。この一呼び出しで全ての重い処理が行われます。 + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` は通常、少なくとも2つの属性を持つオブジェクトです: + +| 属性 | 説明 | +|-----------|-------------| +| `language` | 検出された言語のISO‑639‑1コード(例:英語は`"en"`)。 | +| `text` | 画像のプレーンテキスト文字起こし。 | + +--- + +## ステップ4:検出された言語と抽出テキストを取得 + +ここではエンジンが検出した結果を単に出力します。これにより**detect language OCR**機能が実際に動作する様子が示されます。 + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**サンプル出力** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **エンジンが`None`を返した場合は?** +> 通常、画像がぼやけすぎているか、テキストが小さすぎる(< 8 pt)ことを意味します。コントラストを上げるか、より高解像度のソースを使用してみてください。 + +--- + +## 完全動作例(自動言語検出をエンドツーエンドで有効化) + +すべてをまとめた、**自動言語検出を有効化**、**画像OCRをロード**、**テキスト画像を認識**、そして**detect language OCR** を一度に実行できるスクリプトをご紹介します。 + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +`automatic_language_detection_ocr.py` として保存し、`YOUR_DIRECTORY` をPNGが格納されたフォルダーに置き換えて実行してください: + +```bash +python automatic_language_detection_ocr.py +``` + +上記サンプル出力と同様に、言語コードと抽出されたテキストが表示されるはずです。 + +--- + +## 一般的なエッジケースの対処 + +| 状況 | 推奨対策 | +|-----------|----------------| +| **Very low‑resolution image** (under 100 dpi) | ロード前にバイキュービックフィルタで拡大するか、より高解像度のソースを取得してください。 | +| **Mixed scripts in one image** (e.g., English + Cyrillic) | エンジンは通常ページを領域に分割します;誤検出が見られる場合は `engine.enable_region_split = True` を設定してください。 | +| **Unsupported language** | 必要なスクリプト用の言語パックがOCRライブラリに同梱されているか確認してください;追加モデルのダウンロードが必要になる場合があります。 | +| **Large batch processing** | エンジンを一度初期化し、複数の `load_image` / `recognize` サイクルで再利用してモデルの再ロードを防ぎます。 | + +--- + +## ビジュアル概要 + +![自動言語検出の例出力](https://example.com/auto-lang-detect.png "自動言語検出") + +*Alt text:* 検出された言語コードと抽出された多言語テキストを示す自動言語検出の例出力。 + +--- + +## 結論 + +ここまでで、**自動言語検出**の全工程—エンジンの作成、自動言語検出の有効化、OCR用画像のロード、テキストの認識、そして検出された言語の取得—を網羅しました。このエンドツーエンドのフローにより、毎回手動で言語モデルを設定することなくマルチリンガル文書を処理できます。 + +さらに踏み込む準備ができたら、以下を検討してください: + +- **バッチ処理**:同じ `OcrEngine` インスタンスを再利用するループで数百枚の画像を処理。 +- **ポストプロセッシング**:抽出テキストをスペルチェッカーや言語固有のトークナイザで処理。 +- **統合**:スクリプトをウェブサービスに組み込み、ユーザーアップロードを受け取り、`language` と `text` フィールドを持つJSONを返す。 + +さまざまな画像形式(`.jpg`、`.tif`)で実験し、検出精度の変化を確認してください。質問や読めない画像があれば、下にコメントを残してください—ハッピーコーディング! + +## 次に学ぶべきことは? + +- [Aspose.OCRを使用した言語付き画像テキストのOCR方法](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCRを使用したC#での言語選択付き画像テキスト抽出](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCRで複数言語のテキスト画像を認識](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..bbfe277e9 --- /dev/null +++ b/ocr/japanese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-31 +description: バルク画像からテキストへの変換スクリプトを使って、Pythonで画像をテキストに変換する方法を学びましょう。Aspose.OCRを利用すれば、スキャンした画像から数分でテキストを認識できます。 +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: ja +og_description: 画像を即座にPythonでテキストに変換します。このガイドでは、画像の一括テキスト変換と、Aspose.OCR を使用したスキャン画像からのテキスト認識方法を紹介します。 +og_title: 画像をテキストに変換する Python – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: 画像をテキストに変換する Python – 完全ステップバイステップガイド +url: /ja/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 画像をテキストに変換する Python – 完全ステップバイステップガイド + +何十ものライブラリを探さずに **convert images to text python** を行う方法を考えたことはありますか? あなただけではありません。古いレシートをデジタル化したり、スキャンした請求書からデータを抽出したり、PDF の検索可能なアーカイブを構築したりする場合、画像をプレーンテキストファイルに変換する作業は多くの開発者にとって日常的な課題です。 + +このチュートリアルでは、スキャン画像からテキストを認識し、各結果を個別の `.txt` ファイルとして保存し、Python の数行だけで実行できる **bulk image to text conversion** パイプラインを解説します。 obscure APIs を探す必要はありません—Aspose.OCR が重い処理を担い、設定方法を詳しく示します。 + +## 学べること + +- Aspose.OCR for Python パッケージのインストールと設定方法。 +- `BatchOcrEngine` を使用して **convert images to text python** を実行するための正確なコード。 +- サポートされていない形式や破損したファイルなど、一般的な落とし穴への対処法のヒント。 +- **recognize text from scanned images** ステップが実際に成功したかを検証する方法。 + +このガイドの最後までに、数千枚の画像を一括で処理できる実行可能なスクリプトが手に入り、あらゆるバッチ処理シナリオに最適です。 + +## 前提条件 + +- マシンに Python 3.8+ がインストールされていること。 +- テキストに変換したい画像ファイル(PNG、JPEG、TIFF など)のフォルダー。 +- 有効な Aspose Cloud アカウントまたは無料トライアルライセンス(テストには無料プランで十分)。 + +これらが揃ったら、さっそく始めましょう。 + +--- + +## ステップ 1 – Python 環境のセットアップ + +OCR コードを書く前に、クリーンな仮想環境内で作業していることを確認してください。これにより依存関係が分離され、バージョンの衝突を防げます。 + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** プロジェクトディレクトリを整理整頓しましょう—`ocr_project` というサブフォルダーを作成し、スクリプトをそこに置きます。これにより後でパス処理が楽になります。 + +## ステップ 2 – Aspose.OCR for Python のインストール + +Aspose.OCR は商用ライブラリですが、PyPI から取得できる無料の NuGet 形式の wheel が同梱されています。アクティブな仮想環境内で以下のコマンドを実行してください: + +```bash +pip install aspose-ocr +``` + +権限エラーが出た場合は `--user` フラグを付けるか、`sudo`(Linux/macOS のみ)でコマンドを実行してください。インストール後は次のような表示が出ます: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** 多くのオープンソース OCR ツールとは異なり、Aspose.OCR は **bulk image to text conversion** を標準でサポートし、追加設定なしで幅広い画像形式を処理します。また、`BatchOcrEngine` クラスを提供しており、“convert images to text python” タスクをワンラインで実行できます。 + +## ステップ 3 – Batch OCR で画像をテキストに変換する Python + +それではチュートリアルの核心です。以下は完全に実行可能なスクリプトで、次のことを行います: + +1. OCR エンジンのクラスをインポートします。 +2. `BatchOcrEngine` のインスタンスを作成します。 +3. エンジンに画像の入力フォルダーを指定します。 +4. 抽出されたテキストファイルを出力フォルダーに書き込むよう指示します。 +5. `recognize()` メソッドを呼び出し、**recognize text from scanned images** を1つずつ実行します。 + +以下の内容をプロジェクトフォルダー内に `batch_ocr.py` として保存してください: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### 動作概要 + +- **`BatchOcrEngine`** は通常の `OcrEngine` をラップし、フォルダー単位のオーケストレーションを追加します。大量に **convert images to text python** を行いたいときに最適です。 +- `input_folder` プロパティはエンジンにソース画像の場所を指示します。ディレクトリを自動的にスキャンし、サポートされているすべてのファイルタイプをキューに入れます。 +- `output_folder` プロパティは各 `.txt` ファイルの保存先を決定します。エンジンは元のファイル名をそのまま使用するため、`receipt1.png` は `receipt1.txt` になります。 +- `recognize()` を呼び出すと、各画像を読み込み OCR を実行し結果を書き込む内部ループが開始されます。すべてのファイルが処理されるまでメソッドはブロックするため、後続の処理(例:出力フォルダーを zip にする)を簡単に連結できます。 + +#### 期待される出力 + +スクリプトを実行すると: + +```bash +python batch_ocr.py +``` + +次のように表示されます: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +`output_texts` フォルダー内に、各画像に対応するプレーンテキストファイルが作成されます。テキストエディタで開くと、元の印刷テキストにかなり近い生の OCR 結果が確認できます。 + +## ステップ 4 – 結果の検証とエラー処理 + +最高の OCR エンジンでも、低解像度のスキャンや大きく歪んだページでは失敗することがあります。出力を簡易的にチェックし、失敗をログに記録する簡単な方法をご紹介します。 + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +> **Why add this?** +- エンジンが空文字列を静かに出力したケース(読めない画像でよく発生)を捕捉します。 +- 問題のあるファイルのリストを取得できるため、手動で確認したり、`OcrEngine.preprocess` オプションを変更して再実行できます。 + +### エッジケースと調整 + +| Situation | Suggested Fix | +|-----------|----------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## ステップ 5 – ワークフロー全体の自動化(オプション) + +この変換を毎晩実行したい場合は、スクリプトをシンプルなシェルまたは Windows バッチファイルでラップし、`cron`(Linux/macOS)またはタスクスケジューラ(Windows)でスケジュールします。Unix 系システム向けの最小限の `run_ocr.sh` は以下の通りです: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +実行可能にして(`chmod +x run_ocr.sh`)cron エントリを追加します: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +これにより毎日午前 2 時に変換が実行され、出力は後で確認できるようにログに残ります。 + +--- + +## 結論 + +Aspose.OCR の `BatchOcrEngine` を使用して **convert images to text python** を行う、実証済みの本番環境対応手法が手に入りました。スクリプトは **bulk image to text conversion** を処理し、各結果を個別ファイルに優雅に書き込み、**recognize text from scanned images** が正しく行われたことを検証する手順も含んでいます。 + +ここからは: + +- OCR 設定(言語パック、デスキュー、ノイズ除去)を試す。 +- 生成されたテキストを Elasticsearch などの検索インデックスに流し込み、即時全文検索を実現。 +- このパイプラインを PDF 変換ツールと組み合わせ、スキャン PDF を一括処理。 + +質問や特定のファイルタイプで問題が発生した場合は、下のコメントで教えてください。一緒にトラブルシュートしましょう。コーディングを楽しんで、OCR が高速かつエラーなしで動作しますように! + +## 次に学ぶべきこと + +- [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 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/japanese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..8355f89f5 --- /dev/null +++ b/ocr/japanese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Pythonでライセンスインスタンスを作成し、ライセンスパスを簡単に設定できます。明確なコード例でAspose OCRのライセンス設定方法を学びましょう。 +draft: false +keywords: +- create license instance +- configure license path +language: ja +og_description: Pythonでライセンスインスタンスを作成し、ライセンスパスを即座に設定します。このチュートリアルに従って、Aspose OCRを自信を持って有効化してください。 +og_title: Pythonでライセンスインスタンスを作成する – 完全セットアップガイド +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Pythonでライセンスインスタンスを作成する – ステップバイステップガイド +url: /ja/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python でライセンス インスタンスを作成 – 完全セットアップ ガイド + +Python 用 Aspose OCR の **create license instance** が必要ですか?このページが適切です。このチュートリアルでは、SDK が `.lic` ファイルの場所を認識できるように **configure license path** の方法も併せて紹介します。 + +空のスクリプトを見つめながら「なぜ OCR エンジンがライセンス未取得の製品だと文句を言うのか」悩んだことがあるなら、あなただけではありません。解決策はたいてい数行のコードだけです—正しい位置に配置すればすぐに動作します。このガイドの最後までに、テキスト、画像、PDF を問題なく認識できる完全にライセンスされた Aspose OCR 環境が手に入ります。 + +## 学べること + +- `asposeocr` パッケージを使って **create license instance** する方法 +- 開発環境・本番環境の両方で **configure license path** を正しく設定する方法 +- よくある落とし穴(ファイルが見つからない、権限が不足している)と回避策 +- 任意のプロジェクトに組み込める、完全に実行可能なスクリプト + +Aspose OCR の事前知識は不要です。Python 3 が動作する環境と有効なライセンス ファイルさえあれば始められます。 + +--- + +## Step 1: Install the Aspose OCR Python Package + +**create license instance** を行う前に、ライブラリ自体をインストールする必要があります。ターミナルを開いて次のコマンドを実行してください。 + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** 仮想環境を使用している場合(強く推奨)、まず仮想環境をアクティベートしてください。依存関係が整理され、バージョン衝突を防げます。 + +## Step 2: Import the License Class + +SDK が利用可能になったら、スクリプトの最初の行で `License` クラスをインポートします。これが **create license instance** に使用するオブジェクトです。 + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +なぜすぐにインポートする必要があるのでしょうか?`License` オブジェクトは **before** すべての OCR 呼び出しが行われる前にインスタンス化しなければなりません。そうしないと、画像処理を試みた瞬間にライセンス エラーがスローされます。 + +## Step 3: Create License Instance + +待ちに待った瞬間です—実際に **create license instance** します。たった一行ですが、前後のコンテキストが重要です。 + +```python +# Step 3: Create a License instance +license = License() +``` + +変数 `license` には、現在の Python プロセス全体のライセンス動作を制御するオブジェクトが格納されます。これは Aspose OCR に対して「実行権限があります」と伝えるゲートキーパーのようなものです。 + +## Step 4: Configure License Path + +インスタンスが用意できたら、`.lic` ファイルへのパスを設定します。ここで **configure license path** が登場します。プレースホルダーをライセンス ファイルの絶対パスに置き換えてください。 + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +留意すべき点は次のとおりです: + +1. **Raw strings (`r"…"`)** は Windows でバックスラッシュがエスケープ文字として解釈されるのを防ぎます。 +2. **絶対パス** を使用すると、スクリプトが別の作業ディレクトリから起動された場合でも混乱を防げます。 +3. 相対パスを使用したい場合(例:ライセンスをプロジェクトに同梱する場合)は、相対基準がシェルの現在ディレクトリではなくスクリプトの所在場所になるようにしてください。 + +### Handling Missing Files + +パスが間違っている、またはファイルが読み取れない場合、`set_license` は例外をスローします。`try/except` ブロックで呼び出しをラップし、分かりやすいエラーメッセージを提供しましょう。 + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +このスニペットは **configure license path** を安全に行い、何が原因で失敗したかを正確に通知します—謎のスタックトレースは表示されません。 + +## Step 5: Verify the License Is Active + +簡単な動作確認を行うことで、後々のデバッグ時間を大幅に削減できます。`set_license` を呼び出した後、シンプルな OCR 処理を試してみてください。ライセンスが有効であれば、SDK はエラーを出さずに画像を処理します。 + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +認識されたテキストが出力されれば、**create license instance** と **configure license path** が正常に完了したことになります。ライセンス例外が発生した場合は、パスとファイル権限を再確認してください。 + +## Edge Cases & Best Practices + +| Situation | What to Do | +|-----------|------------| +| **License file lives in a network share** | 共有フォルダーをドライブ文字にマップするか、UNC パス(`\\server\share\license.lic`)を使用してください。Python プロセスに読み取り権限があることを確認します。 | +| **Running inside a Docker container** | `.lic` ファイルをイメージにコピーし、`/app/license/Aspose.OCR.Java.lic` のような絶対パスで参照します。 | +| **Multiple Python interpreters** (e.g., conda envs) | 環境ごとにライセンス ファイルをインストールするか、共通の場所に置いて各インタプリタから参照させます。 | +| **License file missing at runtime** | トライアル モード(サポートされている場合)にフォールバックするか、明確なログメッセージで処理を中止します。 | + +### Common Pitfalls + +- **Using forward slashes on Windows** – Python は受け付けますが、古いバージョンの SDK が誤解釈することがあります。Raw strings か二重バックスラッシュを使用してください。 +- **Forgot to import `License`** – スクリプトは `NameError` でクラッシュします。インスタンス化の前に必ずインポートしてください。 +- **Calling `set_license` after OCR methods** – SDK は最初の使用時にライセンスをチェックするため、**first** にパスを設定してください。 + +## Full Working Example + +以下はすべてをまとめた完全なスクリプトです。`ocr_setup.py` として保存し、コマンドラインから実行してください。 + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Expected output**(有効な画像を使用した場合): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +ライセンス ファイルが見つからない場合は、暗号化された「License not found」例外ではなく、明確なエラーメッセージが表示されます。 + +--- + +## Conclusion + +Python で **create license instance** し、Aspose OCR SDK の **configure license path** を設定する方法が完全に理解できたはずです。手順はシンプル:パッケージをインストールし、`License` をインポート、インスタンス化し、`.lic` ファイルを指し示し、簡単な OCR テストで確認するだけです。 + +この知識があれば、Web サービス、デスクトップ アプリ、または自動化パイプラインに OCR 機能を組み込んでも、ライセンス エラーに悩まされることはありません。次は高度な OCR 設定(言語パック、画像前処理、バッチ処理)に挑戦してみてください。すべては今回構築した土台の上に成り立ちます。 + +デプロイ、Docker、複数ライセンスの取り扱いに関する質問があればコメントで教えてください。Happy coding! + +## What Should You Learn Next? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..1697924c6 --- /dev/null +++ b/ocr/japanese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Python OCR を使用してスキャン画像から検索可能な PDF を作成します。スキャン画像の PDF を変換し、TIFF を PDF + に変換し、数分で OCR テキストレイヤーを追加する方法を学びましょう。 +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: ja +og_description: 検索可能なPDFを即座に作成します。このガイドでは、OCRを実行し、スキャン画像PDFを変換し、単一のPythonスクリプトでOCRテキストレイヤーを追加する方法を示します。 +og_title: Pythonで検索可能なPDFを作成する – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Pythonで検索可能なPDFを作成する – ステップバイステップガイド +url: /ja/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonで検索可能なPDFを作成 – ステップバイステップガイド + +スキャンしたページから **検索可能なPDFを作成** する方法を、たくさんのツールを使い分けずに知りたくなったことはありませんか? あなただけではありません。多くのオフィスワークフローでは、スキャンしたTIFFやJPEGが共有ドライブに置かれ、次の担当者が手作業でテキストをコピー&ペーストしなければならず、面倒でエラーが起きやすく、時間が無駄になります。 + +このチュートリアルでは、**スキャン画像PDFを変換**、**TIFFをPDFに変換**、そして **OCRテキストレイヤーを追加** するクリーンでプログラム的なソリューションを順を追って解説します。最後まで実行すれば、OCRを走らせて隠しテキストを埋め込み、インデックス作成や検索、共有が自信を持ってできる検索可能なPDFを出力するスクリプトが手に入ります。 + +## 必要なもの + +- Python 3.9+(最近のバージョンならどれでも可) +- `aspose-ocr` と `aspose-pdf` パッケージ(`pip install aspose-ocr aspose-pdf` でインストール) +- スキャン画像ファイル(`.tif`、`.png`、`.jpg`、または画像だけのPDFページ) +- ほどほどのRAM(OCRエンジンは軽量で、ノートパソコンでも問題なく動作) + +> **プロのコツ:** Windows を使用している場合、管理者権限で PowerShell ウィンドウを開き、上記コマンドを実行するとパッケージ取得が最も簡単です。 + +```bash +pip install aspose-ocr aspose-pdf +``` + +前提条件が整ったので、コードに入りましょう。 + +## Step 1: OCRエンジンインスタンスの作成 – *create searchable pdf* + +最初に行うのは OCR エンジンの起動です。ピクセルを読み取り文字に変換する「脳」のようなものと考えてください。 + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **なぜ重要か:** エンジンを一度だけ初期化すればメモリ使用量が抑えられます。各ページごとに `OcrEngine()` をループ内で呼び出すと、すぐにリソースが枯渇します。 + +## Step 2: スキャン画像の読み込み – *convert tiff to pdf* & *convert scanned image pdf* + +次に、処理したいファイルをエンジンに渡します。API は任意のラスタ画像を受け付けるので、TIFF でも JPEG でも同様に扱えます。 + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +もし画像だけが埋め込まれた PDF を持っている場合でも、`load_image` を使用すれば Aspose が自動的に最初のページを抽出してくれます。 + +## Step 3: PDF保存オプションの設定 – *add OCR text layer* + +ここで最終的な PDF の見た目を構成します。重要なフラグは `create_searchable_pdf` で、`True` に設定するとライブラリは視覚コンテンツと同じ位置に見えないテキストレイヤーを埋め込みます。 + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **テキストレイヤーの働き:** 生成されたファイルを Adobe Reader で開きテキスト選択を試すと、隠れた文字が選択できるようになります。検索エンジンもインデックス化できるため、コンプライアンスやアーカイブに最適です。 + +## Step 4: OCR実行と保存 – *how to run OCR* in a single call + +いよいよ魔法の瞬間です。1 回のメソッド呼び出しで認識エンジンが走り、検索可能な PDF がディスクに書き込まれます。 + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize` メソッドはステータスオブジェクトを返し、エラーを確認できますが、ほとんどのシンプルなシナリオでは上記の呼び出しだけで十分です。 + +### 期待される出力 + +スクリプト実行時に次のように表示されます: + +``` +PDF saved as searchable PDF. +``` + +`scanned_page_searchable.pdf` を開くと、テキストが選択でき、コピー&ペーストが可能で、`Ctrl+F` 検索も動作します。これが **create searchable pdf** ワークフローの特徴です。 + +## 完全動作スクリプト + +以下が完成した、すぐに実行できるスクリプトです。プレースホルダーのパスを実際のファイル位置に置き換えてください。 + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +`create_searchable_pdf.py` として保存し、実行します: + +```bash +python create_searchable_pdf.py +``` + +## よくある質問とエッジケース + +### 1️⃣ マルチページ PDF を処理できますか? + +はい。`ocr_engine.load_image("file.pdf")` を使用し、`ocr_engine.recognize(pdf_save_options, page_number)` で各ページをループ処理します。ライブラリは自動的にマルチページの検索可能 PDF を生成します。 + +### 2️⃣ ソースファイルが高解像度 TIFF(300 dpi 以上)の場合は? + +DPI が高いほど OCR の精度は向上しますが、メモリ使用量も増えます。`MemoryError` が発生したら、まず画像をダウンサンプルしてください: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ OCR の言語を変更するには? + +画像を読み込む前にエンジンの `language` プロパティを設定します: + +```python +ocr_engine.language = "fra" # French +``` + +サポートされている言語コードの完全一覧は Aspose のドキュメントにあります。 + +### 4️⃣ 元画像の品質を保持したい場合は? + +`PdfSaveOptions` クラスの `compression` プロパティを使用します。`PdfCompression.None` に設定すると、ラスタデータが元のまま保存されます。 + +```python +pdf_save_options.compression = "None" +``` + +## 本番環境向けデプロイのヒント + +- **バッチ処理:** コアロジックをファイルパスのリストを受け取る関数でラップし、成功・失敗を CSV に記録して監査証跡を残す。 +- **並列処理:** `concurrent.futures.ThreadPoolExecutor` を使って複数コアで OCR を同時実行。ただし各スレッドは独自の `OcrEngine` インスタンスを持つ必要があります。 +- **セキュリティ:** 機密文書を扱う場合はサンドボックス環境でスクリプトを実行し、処理後は一時ファイルを即座に削除してください。 + +## 結論 + +これで、スキャン画像から **検索可能なPDF** を作成する簡潔な Python スクリプトの手順が分かりました。OCR エンジンを初期化し、TIFF(または任意のラスタ)を読み込み、`PdfSaveOptions` を **add OCR text layer** に設定し、最後に `recognize` を呼び出すだけで、**convert scanned image pdf** と **convert TIFF to PDF** のパイプラインが単一の再現可能なコマンドになります。 + +次のステップは? このスクリプトをファイルウォッチャーと組み合わせ、フォルダーに新しいスキャンがドロップされるたびに自動で検索可能にするか、あるいは異なる OCR 言語を試して多言語アーカイブに対応させるかです。OCR と PDF 生成を組み合わせれば、可能性は無限です。 + +**how to run OCR** に関して他の言語やフレームワークでの質問があれば、下のコメント欄にどうぞ。Happy coding! + +![スキャン画像 → OCRエンジン → 検索可能なPDF(create searchable pdf)のフローを示す図](searchable-pdf-flow.png "検索可能なPDFフローダイアグラム") + + +## 次に学ぶべきことは? + +- [Aspose.OCR を使用した .NET での PDF OCR 方法](/ocr/english/net/text-recognition/recognize-pdf/) +- [C# で画像を PDF に変換 – マルチページ OCR 結果の保存](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Aspose.OCR を使用した言語別画像テキスト OCR 方法](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/japanese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9c026aafc --- /dev/null +++ b/ocr/japanese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-31 +description: Pythonで画像を前処理し、OCRの精度を向上させましょう。画像ファイルからテキストを抽出する方法、PNGからテキストを認識する方法、そして結果を高めるコツを学びます。 +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: ja +og_description: テキストのために画像前処理を適用して、PythonでOCR精度を向上させましょう。このガイドに従って、画像ファイルからテキストを抽出し、PNGからのテキスト認識を簡単に行いましょう。 +og_title: PythonでOCR精度を向上させる – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: PythonでOCRの精度を向上させる – 完全ステップバイステップガイド +url: /ja/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PythonでOCR精度を向上させる – 完全ステップバイステップガイド + +OCR精度を **向上させよう** としたのに文字化けしたことはありませんか? あなただけではありません。多くの開発者が、画像がノイズだらけだったり、傾いていたり、コントラストが低すぎると壁にぶつかります。朗報です! いくつかの前処理テクニックを使えば、ぼやけたスクリーンショットでもクリーンな機械可読テキストに変えることができます。 + +このチュートリアルでは、**画像をOCR用に前処理**し、認識エンジンを実行し、最終的に **画像からテキストを抽出** する実践的な例を順を追って解説します(対象はPNG)。最後まで読めば、**PNGからテキストを認識** する方法と、成功率の高い再利用可能なコードスニペットを手に入れられます。 + +## 学べること + +- OCRエンジンにとって画像前処理が重要な理由 +- 効果が大きい前処理モード(ノイズ除去、傾き補正) +- Pythonで `OcrEngine` インスタンスを設定する方法 +- **画像からテキストを抽出** する完全実行可能スクリプト +- 回転スキャンや低解像度画像などのエッジケースへの対処法 + +OCR SDK 以外の外部ライブラリは不要ですが、Python 3.8 以上と、読み取り対象の PNG 画像が必要です。 + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Improve OCR accuracy workflow") + +*Alt text: OCR精度向上ワークフロー図(前処理と認識のステップを示す)* + +## 前提条件 + +- Python 3.8 以上がインストール済み +- `OcrEngine`、`OcrEngineSettings`、`ImagePreprocessMode` を提供する OCR SDK にアクセスできること(以下のコードは汎用 API を使用しています。必要に応じてベンダー提供のクラスに置き換えてください) +- 読み取り対象の PNG 画像(`input.png`)を参照できるフォルダーに配置してあること + +仮想環境を使用している場合は、今すぐ有効化してください。特別なことは不要で、`python -m venv venv && source venv/bin/activate` で OK です。 + +--- + +## Step 1: OCRエンジンインスタンスの作成 – OCR精度向上の第一歩 + +まず最初に必要なのは OCR エンジンオブジェクトです。ピクセルを読み取り文字に変換する「脳」のようなものです。 + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +**ポイント**: エンジンが無ければ前処理を適用できず、画像はそのまま認識器に渡されます。これは精度が最も低くなる典型的なケースです。 + +--- + +## Step 2: 対象PNGの読み込み – PNGからテキストを認識する準備 + +次にエンジンに処理対象のファイルを指定します。PNG はロスレス形式なので、JPEG に比べて若干有利です。 + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +画像が別の場所にある場合はパスを調整してください。エンジンはサポートされている形式であれば何でも受け付けますが、PNG は文字エッジの細部を保持しやすいという利点があります。 + +--- + +## Step 3: 前処理の設定 – OCR用に画像を前処理 + +ここが本番です。設定オブジェクトを作成し、ノイズ除去で斑点を除去し、傾き補正で斜め文字を自動的に水平にします。 + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### なぜ Denoise + Deskew が重要か? + +- **Denoise**: ランダムなピクセルノイズはパターンマッチングアルゴリズムを混乱させます。除去することで文字が鮮明になります。 +- **Deskew**: たった 2 度の傾きでも信頼度が大幅に低下します。傾き補正でベースラインを揃えると、認識器がフォントを正確にマッチさせやすくなります。 + +画像が特に暗い場合は `ImagePreprocessMode.CONTRAST_ENHANCE` などのフラグを追加で試すと良いでしょう。利用可能なモードは SDK のドキュメントに一覧があります。 + +--- + +## Step 4: エンジンへ設定を適用 – 前処理をOCRに紐付け + +設定オブジェクトをエンジンに割り当てることで、次回の認識実行時に先ほど定義した変換が自動的に適用されます。 + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +このステップを省略すると、エンジンはデフォルト設定(多くの場合「前処理なし」)にフォールバックし、**OCR精度が低下** します。 + +--- + +## Step 5: 認識プロセスの実行 – 画像からテキストを抽出 + +すべてが接続されたら、エンジンに仕事を依頼します。呼び出しは同期的で、認識された文字列を含む結果オブジェクトが返ります。 + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +内部ではエンジンが次の手順を実行します: + +1. PNG をメモリにロード +2. 設定に基づきノイズ除去と傾き補正を適用 +3. ニューラルネットまたは従来のパターンマッチャで認識 +4. 出力を `recognition_result` にパッケージ化 + +--- + +## Step 6: 認識結果の出力 – 改善効果を確認 + +抽出した文字列をコンソールに出力します。実際のアプリではファイルやデータベースに保存したり、別サービスに渡したりすることもあります。 + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### 期待される出力例 + +画像に「Hello, OCR World!」という文が含まれていれば、次のように表示されます: + +``` +Hello, OCR World! +``` + +テキストがきれいに出力されていることが分かりますね。余計な記号や文字化けがないのは、**テキスト用画像前処理** が正しく機能した結果です。 + +--- + +## プロ向けヒント & エッジケース + +| 状況 | 調整すべき項目 | 理由 | +|-----------|----------------|-----| +| 非常に低解像度の PNG(≤ 72 dpi) | `ImagePreprocessMode.SUPER_RESOLUTION` が利用可能なら追加 | アップサンプリングで認識器に与えるピクセル数を増やす | +| 文字が 5° 超で回転している | デスクエア許容範囲を上げるか、`Pillow` で事前に回転させる | 大きな角度は自動デスクエアが追いつかないことがある | +| 背景にパターンが多い | `ImagePreprocessMode.BACKGROUND_REMOVAL` を有効化 | テキスト以外のノイズが誤認識されるのを防止 | +| 多言語文書 | `ocr_engine.language = "eng+spa"` などに設定 | 正しい文字セットを選択することで全体的な精度が向上 | + +**OCR精度を向上させる** には一律の解決策はありません。データセットに合わせて前処理フラグを調整する必要があります。 + +--- + +## 完全スクリプト – コピー&ペーストで即利用 + +以下は本チュートリアルで説明したすべての手順を組み込んだ、実行可能なサンプルです。`improve_ocr_accuracy.py` として保存し、`python improve_ocr_accuracy.py` で実行してください。 + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +実行するとコンソールに **画像からテキストを抽出** した結果がすぐに表示されます。出力が期待と異なる場合は、上記「プロ向けヒント」表にあるように `preprocess_mode` フラグを調整してみてください。 + +--- + +## まとめ + +本稿では、Python を使って **OCR精度を向上させる** 実践的なレシピを紹介しました。`OcrEngine` を作成し、PNG を読み込み、**OCR用に画像を前処理** し、最終的に **PNGからテキストを認識** することで、元画像が完璧でなくても安定して **画像からテキストを抽出** できるようになります。 + +次のステップは? 画像のバッチ処理をループで回し、結果を CSV に保存したり、追加の前処理モード(コントラスト強調など)を試したりしてみましょう。同様の手順は PDF、スキャン領収書、手書きメモにも応用できます—入力形式を変えて設定だけ調整すれば OK です。 + +特定の画像タイプについて質問がある、あるいはウェブサービスへの組み込み方を知りたいときはコメントで教えてください。一緒にシナリオを検討します。コーディングを楽しんで、OCR の結果が常にクリアになることを願っています! + +## 次に学ぶべきこと + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/japanese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..511632e32 --- /dev/null +++ b/ocr/japanese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-31 +description: OCRの関心領域(ROI)を使用して画像を読み込み、矩形からテキストを抽出する方法を学びましょう。請求書の金額認識に最適です。 +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: ja +og_description: OCRの対象領域をマスターし、画像をOCRに読み込んで矩形からテキストを抽出し、請求書のテキストを認識する単一のチュートリアル。 +og_title: OCR関心領域 – ステップバイステップ Python ガイド +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCRの関心領域 – Pythonで矩形からテキストを抽出 +url: /ja/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR領域(Region of Interest) – Pythonで矩形からテキストを抽出 + +スキャンした請求書の特定の部分だけを **ocr region of interest** したいと思ったことはありませんか?ページ全体をエンジンに渡さずに、ぼやけたレシートを見ながら「右下にある金額をどうやって抽出すればいいんだろう?」と考えているのはあなただけではありません。朗報です。OCRライブラリに正確に「ここを見る」よう指示すれば、速度も精度も大幅に向上します。 + +このガイドでは、**load image for OCR**、**region of interest** の定義、そして **extract text from rectangle** を実演する、実行可能な完全なサンプルを順を追って解説します。最終的に **recognize text from invoice** し、古典的な「金額を抽出する方法」への答えを導き出します。曖昧な説明はありません—具体的なコード、明快な解説、そして早く知っておきたかったプロのコツを提供します。 + +--- + +## What You’ll Build + +このチュートリアルの最後までに、以下の機能を持つ小さな Python スクリプトが完成します。 + +1. ディスクから請求書画像を読み込む。 +2. 合計金額が記載されている矩形 ROI をマークする。 +3. その ROI 内だけで OCR を実行する。 +4. 整形された金額文字列を出力する。 + +これらは ROI をサポートする任意の OCR ライブラリで動作します—ここでは、Tesseract や EasyOCR などの代表的なツールを模倣した架空の `SimpleOCR` パッケージを使用します。別のライブラリに差し替えても概念は変わりません。 + +--- + +## Prerequisites + +- Python 3.8+ がインストール済み(`python --version` で ≥3.8 が表示されること)。 +- pip でインストール可能な OCR パッケージ(例:`pip install simpleocr`)。 +- 請求書画像(PNG または JPEG)を参照できるフォルダーに配置。 +- Python の関数・クラスに関する基本的な知識(特別な知識は不要)。 + +上記がすでに揃っていれば、さっそく始めましょう。まだの場合はまず画像を用意してください。残りの手順はファイル内容に依存しません。 + +--- + +## Step 1: Load Image for OCR + +OCR ワークフローの最初のステップは、読み取るビットマップを用意することです。多くのライブラリはファイルパスを受け取るシンプルな `load_image` メソッドを提供しています。以下は `SimpleOCR` エンジンでの実装例です。 + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** スクリプトを別ディレクトリから実行する際の “file not found” エラーを防ぐため、絶対パスまたは `os.path.join` を使用しましょう。 + +--- + +## Step 2: Define OCR Region of Interest + +エンジンにページ全体を走査させる代わりに、金額が存在する正確な位置を指定します。これが **ocr region of interest** のステップであり、ヘッダーやフッターがノイズになる文書でも信頼性の高い抽出を実現する鍵です。 + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +なぜその数値なのか?`x` と `y` は左上隅からのピクセルオフセット、`width` と `height` は矩形のサイズを表します。分からない場合は任意の画像エディタで定規を表示し、座標をメモしてください。多くの IDE ではカーソル位置をホバーで表示できます。 + +--- + +## Step 3: Extract Text from Rectangle + +ROI が設定できたら、エンジンに **recognize text from invoice** を依頼しますが、先ほど追加した矩形に限定します。呼び出しは通常、生文字列、信頼度スコア、場合によってはバウンディングボックスを含む結果オブジェクトを返します。 + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +内部では、`recognize()` が各 ROI を走査し、該当領域を切り取り、OCR モデルを実行し、結果を結合します。したがって、**extract text from rectangle** の領域を絞ることで、バッチ処理の時間を数秒短縮できます。 + +--- + +## Step 4: How to Extract Amount – Clean the Output + +OCR は完璧ではなく、余分な空白や改行、文字の誤認識(例: “S” と “5”)が出やすいです。`strip()` と小さな正規表現で金額形式を整えるのが一般的です。 + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** 金額をデータベースや決済ゲートウェイに渡す場合、予測可能なフォーマットが必要です。空白除去と数値以外の文字フィルタリングで下流エラーを防げます。 + +--- + +## Step 5: Recognize Text from Invoice – Full Script + +すべてをまとめた完全なスクリプトです。`extract_amount.py` として保存し、`python extract_amount.py` で実行してください。 + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Expected Output + +``` +Amount: 1,245.67 +``` + +ROI がずれていると `Amount: 1245.6S` のように余計な文字が混入します。矩形座標を調整し、出力がきれいになるまで再実行してください。 + +--- + +## Common Pitfalls & Edge Cases + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI too small** | 金額テキストが切り取られ、認識が不完全になる。 | `width`/`height` を約10‑20 % 拡大して再テスト。 | +| **Incorrect DPI** | 低解像度スキャン(≤150 dpi)で OCR 精度が低下。 | 読み込む前に画像を 300 dpi にリサンプリング、またはスキャナ設定を上げる。 | +| **Multiple currencies** | 正規表現が最初の数値グループを取得し、請求書番号になることがある。 | 通貨記号(`$`, `€`, `£`)を数字の前に探すよう正規表現を改良。 | +| **Rotated invoices** | OCR エンジンは正立テキストを前提としているため、回転ページは認識できない。 | ROI 設定前に `ocr_engine.rotate(90)` で回転補正を実施。 | +| **Noise in background** | 影やスタンプがモデルを混乱させる。 | `cv2.threshold` で閾値処理、またはデノイズフィルタを適用。 | + +これらのケースに早めに対処すれば、後々のデバッグ時間を大幅に削減できます。 + +--- + +## Pro Tips for Real‑World Projects + +- **Batch Processing:** 請求書フォルダーをループし、テンプレート検出に基づいて ROI を動的に算出、結果を CSV に保存。 +- **Template Matching:** 複数の請求書レイアウトを扱う場合、`template_id → ROI coordinates` の JSON マップを保持し、レイアウト分類器で ROI を切り替える。 +- **Parallel Execution:** `concurrent.futures.ThreadPoolExecutor` を使って OCR インスタンスを並列実行。大量のバックオフィスパイプラインに最適。 +- **Confidence Filtering:** 多くの OCR 結果は信頼度スコアを含む。閾値(例:85 %)未満は除外し、手動レビューへフラグ付け。 + +--- + +## Conclusion + +**ocr region of interest**、**load image for OCR**、**extract text from rectangle**、そして **recognize text from invoice** のすべての手順を網羅し、古典的な **how to extract amount** の疑問に答える方法を解説しました。スクリプトはコンパクトながら、さまざまな文書形式・言語・OCR バックエンドに柔軟に対応できます。 + +基本をマスターしたら、バーコードスキャンの追加、PDF パーサーとの統合、会計 API への金額送信など、ワークフローを拡張してみてください。ROI を明確に定義すれば、常に高速でクリーンな結果が得られます。 + +問題があればコメントで教えてください—Happy OCRing! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## What Should You Learn Next? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/korean/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..19bd032de --- /dev/null +++ b/ocr/korean/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: '비동기 OCR 튜토리얼: Python에서 asyncio를 사용해 Aspose OCR을 활용하여 빠른 이미지 텍스트 추출 방법을 + 보여줍니다. 단계별 비동기 OCR 구현을 배워보세요.' +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: ko +og_description: 비동기 OCR 튜토리얼은 asyncio를 사용하여 Python에서 Aspose OCR을 활용해 효율적인 이미지 텍스트 + 추출 방법을 안내합니다. +og_title: 비동기 OCR 튜토리얼 – Python asyncio와 Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: 비동기 OCR 튜토리얼 – Python asyncio와 Aspose OCR +url: /ko/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 비동기 OCR 튜토리얼 – Python asyncio와 Aspose OCR + +앱을 차단하지 않고 광학 문자 인식을 실행하는 방법이 궁금하셨나요? **비동기 OCR 튜토리얼**에서는 바로 그 방법을 확인할 수 있습니다—Python의 `asyncio`와 Aspose OCR 라이브러리를 사용한 비차단 텍스트 추출. + +무거운 이미지를 처리하기 위해 기다리는 데 지치셨다면, 이 가이드는 이벤트 루프가 원활히 동작하도록 하는 깔끔한 비동기 솔루션을 제공합니다. + +다음 섹션에서는 라이브러리 설치, 비동기 헬퍼 구성, 결과 처리, 그리고 여러 이미지로 확장하는 빠른 팁까지 필요한 모든 내용을 다룹니다. 끝까지 읽으시면 이미 `asyncio`를 사용하는 모든 Python 프로젝트에 **비동기 OCR 튜토리얼**을 바로 적용할 수 있게 됩니다. + +## 필요 사항 + +* Python 3.9+ (`asyncio` API는 3.7부터 안정적입니다) +* 활성화된 Aspose OCR 라이선스 또는 무료 체험(라이브러리는 순수 Python이며 네이티브 바이너리가 없습니다) +* 읽고자 하는 작은 이미지 파일(`.jpg`, `.png` 등) – 알려진 폴더에 보관하세요 + +다른 외부 도구는 필요하지 않으며, 모든 것이 순수 Python에서 실행됩니다. + +## 단계 1: Aspose OCR 패키지 설치 + +먼저, PyPI에서 Aspose OCR 패키지를 가져옵니다. 터미널을 열고 다음을 실행하세요: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** 가상 환경 안에서 작업하고 있다면(강력히 권장) 먼저 활성화하세요. 이렇게 하면 종속성이 격리되고 버전 충돌을 방지할 수 있습니다. + +## 단계 2: OCR 엔진을 비동기적으로 초기화 + +우리 **비동기 OCR 튜토리얼**의 핵심은 비동기 헬퍼 함수입니다. 이 함수는 `OcrEngine` 인스턴스를 생성하고 이미지를 로드한 뒤 `recognize_async()`를 호출합니다. 엔진 자체는 동기식이지만 래퍼 메서드는 awaitable을 반환하여 이벤트 루프가 응답성을 유지합니다. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**왜 이렇게 하는가:** +*헬퍼 내부에서 엔진을 생성하면 이후에 다수의 OCR 작업을 병렬로 실행할 때 스레드 안전성을 보장합니다. `await` 키워드는 무거운 작업이 라이브러리 내부 스레드 풀에서 수행되는 동안 제어를 이벤트 루프로 반환합니다.* + +## 단계 3: 비동기 메인 함수에서 헬퍼 호출 + +이제 `async_ocr()`를 호출하고 결과를 출력하는 작은 `main()` 코루틴이 필요합니다. 이는 `asyncio` 스크립트의 일반적인 진입점을 반영합니다. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**내부에서 무슨 일이 일어나고 있나요?** +`asyncio.run()`은 새로운 이벤트 루프를 생성하고 `main()`을 스케줄링한 뒤 `main()`이 끝나면 루프를 깔끔하게 종료합니다. 이 패턴은 Python 3.7+에서 비동기 프로그램을 시작하는 권장 방법입니다. + +## 단계 4: 전체 스크립트 테스트 + +위의 두 코드 블록을 하나의 파일(e.g., `async_ocr_demo.py`)에 저장합니다. 명령줄에서 실행하세요: + +```bash +python async_ocr_demo.py +``` + +설정이 올바르게 완료되었다면 다음과 같은 출력이 나타날 것입니다: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +`photo.jpg`의 내용에 따라 정확한 출력은 달라집니다. 핵심은 이미지가 크더라도 OCR 작업이 백그라운드에서 수행되므로 스크립트가 빠르게 종료된다는 점입니다. + +## 단계 5: 확장 – 여러 이미지를 동시에 처리 + +흔히 이어지는 질문은 *“각 파일마다 새 프로세스를 실행하지 않고 배치 OCR을 할 수 있나요?”* 입니다. 물론 가능합니다. 헬퍼가 완전 비동기이기 때문에 `asyncio.gather()`를 사용해 여러 코루틴을 모을 수 있습니다: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**왜 이렇게 동작하는가:** +`asyncio.gather()`는 모든 OCR 작업을 한 번에 스케줄링합니다. 기본 Aspose OCR 라이브러리는 자체 스레드 풀을 사용하지만, Python 관점에서는 모든 것이 비차단 상태를 유지하므로 단일 동기 호출에 걸리는 시간에 수십 개의 이미지를 처리할 수 있습니다. + +## 단계 6: 오류를 우아하게 처리하기 + +외부 파일을 다룰 때는 파일 누락, 손상된 이미지, 라이선스 문제 등에 직면하게 됩니다. OCR 호출을 `try/except` 블록으로 감싸 이벤트 루프가 살아 있도록 합니다: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +이제 `batch_ocr()`는 `safe_async_ocr`를 호출하도록 변경하면, 하나의 잘못된 파일 때문에 전체 배치가 중단되지 않게 됩니다. + +## 시각적 개요 + +![비동기 OCR 튜토리얼 다이어그램](async-ocr-diagram.png){alt="async_ocr 헬퍼, 이벤트 루프 및 Aspose OCR 엔진을 보여주는 비동기 OCR 튜토리얼 흐름도"} + +위 다이어그램은 흐름을 시각화합니다: 이벤트 루프 → `async_ocr` → `OcrEngine` → 백그라운드 스레드 → 결과가 루프로 반환됩니다. + +## 흔히 발생하는 실수 및 회피 방법 + +| 실수 | 발생 원인 | 해결 방법 | +|------|----------|-----------| +| **헬퍼 내부에서 차단 I/O** | `await` 없이 `open()`을 사용하면 루프가 차단될 수 있습니다. | 파일 읽기에는 `aiofiles`를 사용하거나 `engine.load_image`에 맡기세요(이미 비차단입니다). | +| **코루틴 간에 단일 `OcrEngine` 재사용** | 엔진은 스레드 안전하지 않으며, 동시에 호출하면 상태가 손상될 수 있습니다. | 각 `async_ocr` 호출 시 새 엔진을 인스턴스화하세요(예시와 같이). | +| **라이선스 누락** | Aspose OCR이 실행 시 라이선스 관련 예외를 발생시킵니다. | 초기에 라이선스를 등록하세요(`OcrEngine.set_license("license.json")`). | +| **큰 이미지로 인한 메모리 급증** | 라이브러리가 전체 이미지를 RAM에 로드합니다. | 메모리가 우려된다면 OCR 전에 이미지를 다운스케일하세요. | + +## 요약: 달성한 내용 + +이 **비동기 OCR 튜토리얼**에서 우리는: + +1. Aspose OCR 라이브러리를 설치했습니다. +2. `async_ocr` 헬퍼를 구축하여 인식 작업을 차단 없이 실행했습니다. +3. 깨끗한 `asyncio` 진입점에서 헬퍼를 실행했습니다. +4. `asyncio.gather`를 사용한 배치 처리 시연. +5. 오류 처리와 모범 사례 팁을 추가했습니다. + +이 모든 것은 순수 Python이므로 기존 비동기 코드를 다시 작성하지 않고도 웹 서버, CLI 도구 또는 데이터 파이프라인에 바로 적용할 수 있습니다. + +## 다음 단계 및 관련 주제 + +* **비동기 이미지 전처리** – OCR 전에 이미지를 동시에 다운로드하려면 `aiohttp`를 사용하세요. +* **OCR 결과 저장** – PostgreSQL용 async 데이터베이스 드라이버 `asyncpg`와 이 튜토리얼을 결합하세요. +* **성능 튜닝** – 라이브러리가 해당 옵션을 제공한다면 `engine.recognize_async(max_threads=4)`를 실험해 보세요. +* **대체 OCR 엔진** – 비용‑효과 분석을 위해 Aspose OCR을 Tesseract의 비동기 래퍼와 비교해 보세요. + +자유롭게 실험해 보세요: PDF를 입력하거나, 언어 설정을 조정하거나, 결과를 챗봇에 연결하는 등. 견고한 **비동기 OCR 튜토리얼** 기반만 있으면 가능성은 무한합니다. + +코딩을 즐기세요, 텍스트 추출이 언제나 빠르길 바랍니다! + +## 다음에 배워야 할 내용은? + +- [Aspose OCR로 이미지에서 텍스트 추출 – 단계별 가이드](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR 튜토리얼 – 광학 문자 인식](/ocr/english/) +- [Aspose.OCR을 사용한 언어별 이미지 텍스트 OCR 방법](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/korean/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..4875e0e76 --- /dev/null +++ b/ocr/korean/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: OCR에서 자동 언어 감지를 쉽게 할 수 있습니다. 이미지 OCR을 로드하고 자동 언어 감지를 활성화하며 몇 단계만으로 텍스트 + 이미지를 인식하는 방법을 배워보세요. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: ko +og_description: OCR에서 자동 언어 감지를 쉽게 구현하세요. 자동 언어 감지를 활성화하고 이미지 OCR을 로드하며 텍스트 이미지를 인식하는 + 단계별 튜토리얼을 따라보세요. +og_title: OCR을 이용한 자동 언어 감지 – 완전한 파이썬 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: OCR을 활용한 자동 언어 감지 – 파이썬 완전 가이드 +url: /ko/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR을 이용한 자동 언어 감지 – 완전한 Python 가이드 + +스캔한 문서의 언어를 직접 지정하지 않아도 OCR 엔진이 *추측*하도록 만든 적 있나요? 바로 **자동 언어 감지**가 하는 일이며, 다국어 PDF, 거리 표지판 사진, 혹은 서로 다른 스크립트가 섞인 이미지를 다룰 때 완전한 게임 체인저입니다. + +이 튜토리얼에서는 **자동 언어 감지 활성화**, **이미지 OCR 로드**, 그리고 **텍스트 이미지 인식**을 Python 스타일 API로 수행하는 실습 예제를 단계별로 안내합니다. 최종적으로 감지된 언어 코드와 추출된 텍스트를 출력하는 독립 실행형 스크립트를 얻을 수 있으며, 별도의 언어 설정이 필요 없습니다. + +## 배울 내용 + +- OCR 엔진 인스턴스를 생성하고 **자동 언어 감지**를 켜는 방법. +- 디스크에서 **이미지 OCR 로드**하는 정확한 단계. +- 엔진의 `recognize()` 메서드를 호출해 언어 코드를 포함한 결과를 받는 방법. +- 저해상도 이미지나 지원되지 않는 스크립트와 같은 엣지 케이스를 처리하는 팁. + +다국어 OCR에 대한 사전 경험이 없어도 됩니다; 기본적인 Python 환경과 이미지 파일만 있으면 됩니다. + +--- + +## 사전 요구 사항 + +시작하기 전에 다음을 확인하세요: + +1. Python 3.8+이 설치되어 있음(최근 버전이면 모두 OK). +2. `OcrEngine`, `LanguageAutoDetectMode` 등을 제공하는 OCR 라이브러리 – 여기서는 가상의 패키지 `myocr`를 가정합니다. 다음 명령으로 설치하세요: + + ```bash + pip install myocr + ``` + +3. 최소 두 개 이상의 언어가 포함된 이미지 파일(`multilingual_sample.png`). +4. 약간의 호기심 – OCR을 한 번도 다뤄본 적이 없어도 걱정 마세요; 코드는 의도적으로 간단하게 구성했습니다. + +--- + +## 단계 1: 자동 언어 감지 활성화 + +엔진에게 스스로 언어를 *판단*하도록 알려야 합니다. 바로 **자동 언어 감지** 플래그가 여기서 사용됩니다. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **왜 중요한가:** +> `AUTO_DETECT`가 설정되면 엔진은 무거운 문자 인식이 시작되기 전에 가벼운 언어 분류기를 이미지에 적용합니다. 따라서 텍스트가 영어, 러시아어, 프랑스어 혹은 그 조합인지 직접 추측할 필요가 없으며, 엔진이 이미지 각 영역에 가장 적합한 언어 모델을 자동으로 선택합니다. + +--- + +## 단계 2: 이미지 OCR 로드 + +이제 엔진이 자동 감지를 수행하도록 설정했으니, 실제 작업할 이미지를 제공해야 합니다. **이미지 OCR 로드** 단계는 비트맵을 읽고 내부 버퍼를 준비합니다. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **프로 팁:** +> 이미지 해상도가 300 dpi를 초과한다면 150‑200 dpi 정도로 다운스케일하는 것을 고려하세요. 과도한 디테일은 언어 감지 단계만 오히려 *느려지게* 할 수 있으며 정확도 향상에는 도움이 되지 않습니다. + +--- + +## 단계 3: 이미지에서 텍스트 인식 + +이미지가 메모리에 로드되고 언어 감지가 활성화된 상태에서, 마지막으로 엔진에게 **텍스트 이미지 인식**을 요청합니다. 이 한 번의 호출이 모든 무거운 작업을 수행합니다. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` 객체는 일반적으로 최소 두 개의 속성을 포함합니다: + +| 속성 | 설명 | +|-----------|-------------| +| `language` | 감지된 언어의 ISO‑639‑1 코드 (예: 영어는 `"en"`). | +| `text` | 이미지에서 추출된 순수 텍스트 문자열. | + +--- + +## 단계 4: 감지된 언어와 추출된 텍스트 가져오기 + +이제 엔진이 발견한 내용을 간단히 출력하면 됩니다. 이는 **detect language OCR** 기능이 실제로 작동하는 모습을 보여줍니다. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**샘플 출력** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **엔진이 `None`을 반환한다면?** +> 이는 보통 이미지가 너무 흐리거나 텍스트가 너무 작아(< 8 pt) 발생합니다. 대비를 높이거나 고해상도 원본을 사용해 보세요. + +--- + +## 전체 작업 예제 (자동 언어 감지 엔드‑투‑엔드 활성화) + +모든 단계를 하나로 합친, **자동 언어 감지 활성화**, **이미지 OCR 로드**, **텍스트 이미지 인식**, 그리고 **언어 감지 OCR**을 한 번에 수행하는 실행 가능한 스크립트는 다음과 같습니다. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +`automatic_language_detection_ocr.py`라는 파일명으로 저장하고, `YOUR_DIRECTORY`를 PNG 파일이 들어 있는 폴더 경로로 교체한 뒤 실행하세요: + +```bash +python automatic_language_detection_ocr.py +``` + +위와 같은 샘플 출력처럼 언어 코드와 추출된 텍스트가 순서대로 표시됩니다. + +--- + +## 일반적인 엣지 케이스 처리 + +| 상황 | 제안된 해결책 | +|-----------|----------------| +| **매우 낮은 해상도 이미지** (100 dpi 이하) | 로드하기 전에 바이큐빅 필터로 업스케일하거나, 더 높은 해상도의 원본을 요청하세요. | +| **하나의 이미지에 혼합 스크립트** (예: 영어 + 키릴 문자) | 엔진이 일반적으로 페이지를 영역별로 분할합니다; 오탐이 보이면 `engine.enable_region_split = True`로 설정하세요. | +| **지원되지 않는 언어** | OCR 라이브러리에 해당 스크립트용 언어 팩이 포함되어 있는지 확인하고, 필요 시 추가 모델을 다운로드하세요. | +| **대량 배치 처리** | 엔진을 한 번 초기화한 뒤 여러 `load_image` / `recognize` 사이클에서 재사용하여 모델 로딩을 반복하지 않도록 합니다. | + +--- + +## 시각적 개요 + +![감지된 언어 코드와 추출된 다국어 텍스트를 보여주는 자동 언어 감지 예시 출력](https://example.com/auto-lang-detect.png "자동 언어 감지") + +*Alt text:* 감지된 언어 코드와 추출된 다국어 텍스트를 보여주는 자동 언어 감지 예시 출력. + +--- + +## 결론 + +우리는 **자동 언어 감지**를 처음부터 끝까지 다뤘습니다—엔진 생성, 자동 언어 감지 활성화, 이미지 로드, 텍스트 인식, 그리고 감지된 언어 조회까지. 이 엔드‑투‑엔드 흐름을 통해 매번 언어 모델을 수동으로 설정하지 않고도 다국어 문서를 처리할 수 있습니다. + +다음 단계로 고려해볼 내용: + +- **배치 처리**: `OcrEngine` 인스턴스를 재사용해 수백 개 이미지를 루프 처리. +- **후처리**: 추출된 텍스트에 맞춤법 검사기나 언어별 토크나이저 적용. +- **통합**: 사용자가 파일을 업로드하면 `language`와 `text` 필드를 포함한 JSON을 반환하는 웹 서비스에 스크립트 연결. + +다양한 이미지 포맷(`.jpg`, `.tif`)을 실험해 보고 감지 정확도가 어떻게 변하는지 확인해 보세요. 질문이나 읽히지 않는 까다로운 이미지가 있나요? 아래 댓글에 남겨 주세요—행복한 코딩 되세요! + +## 다음에 배울 내용은? + +- [Aspose.OCR을 사용한 언어별 이미지 텍스트 OCR 방법](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR을 사용한 언어 선택 C# 이미지 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [다중 언어를 위한 Aspose OCR 이미지 텍스트 인식](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/korean/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4943f2658 --- /dev/null +++ b/ocr/korean/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-31 +description: 대량 이미지-텍스트 변환 스크립트를 사용해 파이썬으로 이미지를 텍스트로 변환하는 방법을 배우세요. Aspose.OCR을 활용하면 + 스캔한 이미지에서 텍스트를 몇 분 안에 인식할 수 있습니다. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: ko +og_description: 이미지를 파이썬으로 즉시 텍스트로 변환합니다. 이 가이드는 대량 이미지 텍스트 변환 및 Aspose.OCR을 사용한 스캔 + 이미지에서 텍스트를 인식하는 방법을 보여줍니다. +og_title: 이미지를 텍스트로 변환하는 파이썬 – 전체 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: 이미지를 텍스트로 변환하는 파이썬 – 완전한 단계별 가이드 +url: /ko/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 텍스트 변환 Python – 완전 단계별 가이드 + +수십 개의 라이브러리를 찾아다니지 않고 **convert images to text python**을(를) 어떻게 하는지 궁금했나요? 당신만 그런 것이 아닙니다. 오래된 영수증을 디지털화하거나, 스캔한 청구서에서 데이터를 추출하거나, PDF의 검색 가능한 아카이브를 구축하든, 사진을 일반 텍스트 파일로 변환하는 일은 많은 개발자에게 일상적인 작업입니다. + +이 튜토리얼에서는 스캔한 이미지에서 텍스트를 인식하고 각 결과를 개별 `.txt` 파일로 저장하며, 몇 줄의 Python 코드만으로 모든 작업을 수행하는 **bulk image to text conversion** 파이프라인을 단계별로 살펴보겠습니다. 불명확한 API를 찾아볼 필요 없이—Aspose.OCR이 핵심 작업을 수행하며, 이를 어떻게 연결하는지 정확히 보여드릴 것입니다. + +## 배울 내용 + +- Aspose.OCR for Python 패키지를 설치하고 구성하는 방법. +- `BatchOcrEngine`을 사용하여 **convert images to text python**을 수행하는 정확한 코드. +- 지원되지 않는 형식이나 손상된 파일과 같은 일반적인 함정을 처리하기 위한 팁. +- **recognize text from scanned images** 단계가 실제로 성공했는지 확인하는 방법. + +이 가이드를 마치면 한 번에 수천 개의 이미지를 처리할 수 있는 실행 준비가 된 스크립트를 얻게 됩니다—어떤 배치 처리 시나리오에도 완벽합니다. + +## 사전 요구 사항 + +- Python 3.8+이 머신에 설치되어 있어야 합니다. +- 텍스트로 변환하려는 이미지 파일(PNG, JPEG, TIFF 등) 폴더. +- 활성화된 Aspose Cloud 계정 또는 무료 체험 라이선스(테스트에는 무료 티어면 충분합니다). + +위 조건을 갖추셨다면, 시작해봅시다. + +--- + +## Step 1 – Python 환경 설정 + +OCR 코드를 작성하기 전에, 깨끗한 가상 환경 안에서 작업하고 있는지 확인하세요. 이렇게 하면 종속성을 격리하고 버전 충돌을 방지할 수 있습니다. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** 프로젝트 디렉터리를 깔끔하게 유지하세요—`ocr_project`라는 하위 폴더를 만들고 스크립트를 그 안에 두세요. 이렇게 하면 나중에 경로 처리가 매우 쉬워집니다. + +## Step 2 – Aspose.OCR for Python 설치 + +Aspose.OCR은 상용 라이브러리이지만, PyPI에서 가져올 수 있는 무료 NuGet 스타일 휠을 제공합니다. 활성화된 가상 환경에서 다음 명령을 실행하세요: + +```bash +pip install aspose-ocr +``` + +권한 오류가 발생하면 `--user` 플래그를 추가하거나 `sudo`(Linux/macOS 전용)로 명령을 실행하세요. 설치 후에는 다음과 같은 메시지가 표시됩니다: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** 많은 오픈소스 OCR 도구와 달리, Aspose.OCR은 **bulk image to text conversion**을 기본적으로 지원하며 추가 설정 없이 다양한 이미지 형식을 처리합니다. 또한 `BatchOcrEngine` 클래스를 제공하여 “convert images to text python” 작업을 한 줄로 수행할 수 있게 합니다. + +## Step 3 – Batch OCR을 사용한 이미지에서 텍스트 변환 Python + +이제 튜토리얼의 핵심 부분입니다. 아래는 완전 실행 가능한 스크립트로, 다음을 수행합니다: + +1. OCR 엔진 클래스를 가져옵니다. +2. `BatchOcrEngine`을 인스턴스화합니다. +3. 엔진에 이미지 입력 폴더를 지정합니다. +4. 엔진이 추출된 텍스트 파일을 출력 폴더에 저장하도록 지정합니다. +5. `recognize()` 메서드를 호출하여 **recognize text from scanned images**을 하나씩 수행합니다. + +다음 코드를 프로젝트 폴더에 `batch_ocr.py`라는 이름으로 저장하세요: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### 작동 원리 + +- **`BatchOcrEngine`**는 일반 `OcrEngine`을 래핑하지만 폴더 수준의 오케스트레이션을 추가합니다. 이는 대량으로 **convert images to text python**을 수행하려는 경우 정확히 필요한 기능입니다. +- `input_folder` 속성은 엔진에게 소스 이미지를 찾을 위치를 알려줍니다. 디렉터리를 자동으로 스캔하고 지원되는 모든 파일 유형을 큐에 넣습니다. +- `output_folder` 속성은 각 `.txt` 파일이 저장될 위치를 결정합니다. 엔진은 원본 파일 이름을 그대로 복제하므로 `receipt1.png`는 `receipt1.txt`가 됩니다. +- `recognize()`를 호출하면 각 이미지를 로드하고 OCR을 실행한 뒤 결과를 기록하는 내부 루프가 시작됩니다. 이 메서드는 모든 파일이 처리될 때까지 차단되므로, 출력 폴더를 압축하는 등 추가 작업을 연쇄하기 쉽습니다. + +#### 예상 출력 + +스크립트를 실행하면: + +```bash +python batch_ocr.py +``` + +다음과 같은 출력이 표시됩니다: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +`output_texts` 폴더 안에는 각 이미지에 대한 일반 텍스트 파일이 들어 있습니다. 텍스트 편집기로 열어보면 원본 인쇄 텍스트와 거의 일치하는 원시 OCR 결과를 확인할 수 있습니다. + +## Step 4 – 결과 검증 및 오류 처리 + +최고의 OCR 엔진이라도 저해상도 스캔이나 심하게 기울어진 페이지에서는 오류가 발생할 수 있습니다. 출력 결과를 간단히 검증하고 실패를 기록하는 방법을 소개합니다. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Why add this?** +- 엔진이 읽을 수 없는 이미지에서 빈 문자열을 조용히 반환하는 경우를 포착합니다(일반적). +- 문제 파일 목록을 제공하여 수동으로 검사하거나 다른 설정(예: `OcrEngine.preprocess` 옵션 증가)으로 다시 실행할 수 있게 합니다. + +### 엣지 케이스 및 조정 + +| 상황 | 권장 해결책 | +|-----------|----------------| +| 이미지가 90° 회전됨 | `batch_engine.ocr_engine.rotation_correction = True` 설정 | +| 혼합 언어(영어 + 프랑스어) | `recognize()` 전에 `batch_engine.ocr_engine.language = "eng+fra"` 사용 | +| 큰 PDF를 먼저 이미지로 변환 | PDF를 페이지별 이미지로 분할한 뒤 폴더를 배치 엔진에 전달 | +| 매우 큰 배치에서 메모리 오류 | 작은 하위 폴더를 순차적으로 처리하거나 `batch_engine.max_memory_usage` 증가 | + +## Step 5 – 전체 워크플로 자동화 (옵션) + +이 변환을 매일 밤 실행해야 한다면, 스크립트를 간단한 셸 스크립트나 Windows 배치 파일로 감싸고 `cron`(Linux/macOS) 또는 작업 스케줄러(Windows)로 예약하세요. 아래는 Unix 계열 시스템용 최소 `run_ocr.sh` 예시입니다: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +실행 가능하도록 만들고(`chmod +x run_ocr.sh`) cron 항목을 추가하세요: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +이렇게 하면 매일 새벽 2시에 변환이 실행되고, 출력이 로그에 기록되어 나중에 검토할 수 있습니다. + +--- + +## 결론 + +이제 Aspose.OCR의 `BatchOcrEngine`을 사용하여 **convert images to text python**을 수행하는 검증된 프로덕션 준비 방법을 갖추었습니다. 스크립트는 **bulk image to text conversion**을 처리하고, 각 결과를 전용 파일에 깔끔하게 저장하며, 실제로 **recognize text from scanned images**가 올바르게 수행됐는지 확인하는 검증 단계도 포함합니다. + +이제 다음과 같은 작업을 시도해 볼 수 있습니다: + +- 다양한 OCR 설정(언어 팩, 디스키유, 노이즈 감소) 실험하기. +- 생성된 텍스트를 Elasticsearch와 같은 검색 인덱스로 파이프하여 즉시 전체 텍스트 검색 구현. +- 이 파이프라인을 PDF 변환 도구와 결합하여 스캔된 PDF를 한 번에 처리하기. + +질문이 있거나 특정 파일 유형에서 문제가 발생했나요? 아래에 댓글을 남겨 주세요. 함께 문제를 해결해 봅시다. 즐거운 코딩 되시고, OCR 실행이 빠르고 오류 없이 진행되길 바랍니다! + +## 다음에 배울 내용은? + +- [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을 사용한 언어 선택이 가능한 이미지 텍스트 추출 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/korean/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..5cf7427e6 --- /dev/null +++ b/ocr/korean/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Python에서 라이선스 인스턴스를 생성하고 라이선스 경로를 쉽게 구성합니다. 명확한 코드 예제로 Aspose OCR 라이선스 + 설정 방법을 배워보세요. +draft: false +keywords: +- create license instance +- configure license path +language: ko +og_description: Python에서 라이선스 인스턴스를 생성하고 라이선스 경로를 즉시 설정합니다. 이 튜토리얼을 따라 Aspose OCR을 + 자신 있게 활성화하세요. +og_title: Python에서 라이선스 인스턴스 만들기 – 완전 설정 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Python에서 라이선스 인스턴스 생성 – 단계별 가이드 +url: /ko/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 라이선스 인스턴스 생성 – 전체 설정 가이드 + +Python에서 Aspose OCR용 **create license instance**가 필요하신가요? 올바른 위치에 오셨습니다. 이 튜토리얼에서는 SDK가 `.lic` 파일을 찾을 수 있도록 **configure license path**를 설정하는 방법도 보여드립니다. + +빈 스크립트를 보며 OCR 엔진이 라이선스가 없는 제품이라고 계속 불평하는 이유를 궁금해 본 적이 있다면, 혼자가 아닙니다. 해결 방법은 보통 몇 줄의 코드일 뿐이며, 정확히 어디에 넣어야 하는지만 알면 됩니다. 이 가이드를 끝까지 따라오시면 텍스트, 이미지, PDF를 문제없이 인식할 수 있는 완전 라이선스가 적용된 Aspose OCR 환경을 갖추게 됩니다. + +## What You’ll Learn + +- `asposeocr` 패키지를 사용해 **create license instance**하는 방법. +- 개발 및 프로덕션 환경 모두에서 **configure license path**를 올바르게 설정하는 방법. +- 흔히 발생하는 문제(파일 누락, 권한 오류)와 회피 방법. +- 어떤 프로젝트에든 바로 넣어 사용할 수 있는 완전 실행 가능한 스크립트. + +Aspose OCR에 대한 사전 경험은 필요 없으며, Python 3이 설치되어 있고 유효한 라이선스 파일만 있으면 됩니다. + +--- + +## Step 1: Install the Aspose OCR Python Package + +**create license instance**를 만들기 전에 라이브러리가 존재해야 합니다. 터미널을 열고 다음을 실행하세요: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** 가상 환경을 사용하고 있다면(강력히 권장) 먼저 활성화하세요. 이렇게 하면 종속성을 깔끔하게 관리하고 버전 충돌을 방지할 수 있습니다. + +## Step 2: Import the License Class + +SDK가 준비되었으니, 스크립트의 가장 첫 줄에서 `License` 클래스를 import 해야 합니다. 이것이 **create license instance**에 사용할 객체입니다. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +왜 바로 import해야 할까요? `License` 객체는 OCR 호출 **이전**에 인스턴스화되어야 하기 때문입니다; 그렇지 않으면 이미지 처리 시점에 라이선스 오류가 발생합니다. + +## Step 3: Create License Instance + +기다리던 순간—실제로 **create license instance**합니다. 한 줄이지만 주변 컨텍스트가 중요합니다. + +```python +# Step 3: Create a License instance +license = License() +``` + +이제 변수 `license`는 현재 Python 프로세스의 모든 라이선스 동작을 제어하는 객체를 담고 있습니다. Aspose OCR에 “내게 실행 권한이 있다”고 알려주는 문지기 역할이라고 생각하면 됩니다. + +## Step 4: Configure License Path + +인스턴스가 준비되었으니, `.lic` 파일을 가리키도록 설정해야 합니다. 여기서 **configure license path**가 필요합니다. 플레이스홀더를 라이선스 파일의 절대 경로로 교체하세요. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +주의할 점 몇 가지: + +1. **Raw strings (`r"…"`)** 은 Windows에서 역슬래시가 이스케이프 문자로 해석되는 것을 방지합니다. +2. **절대 경로**를 사용하면 스크립트가 다른 작업 디렉터리에서 실행될 때 혼동을 피할 수 있습니다. +3. 상대 경로를 사용하고 싶다면(예: 라이선스를 프로젝트와 함께 배포할 경우) 기준이 현재 셸 디렉터리가 아니라 스크립트 위치임을 확인하세요. + +### Handling Missing Files + +경로가 잘못되었거나 파일을 읽을 수 없으면 `set_license`가 예외를 발생시킵니다. `try/except` 블록으로 감싸 친절한 오류 메시지를 제공하세요: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +이 스니펫은 **configure license path**를 안전하게 수행하고, 무엇이 잘못됐는지 정확히 알려줍니다—불명확한 스택 트레이스는 없습니다. + +## Step 5: Verify the License Is Active + +간단한 검증을 하면 나중에 디버깅 시간을 크게 절약할 수 있습니다. `set_license`를 호출한 뒤 간단한 OCR 작업을 시도해 보세요. 라이선스가 유효하면 SDK가 라이선스 오류 없이 이미지를 처리합니다. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +인식된 텍스트가 출력되면 축하합니다—**create license instance**와 **configure license path**를 성공적으로 수행한 것입니다. 라이선스 예외가 발생하면 경로와 파일 권한을 다시 확인하세요. + +## Edge Cases & Best Practices + +| Situation | What to Do | +|-----------|------------| +| **라이선스 파일이 네트워크 공유에 존재함** | 공유를 드라이브 문자에 매핑하거나 UNC 경로(`\\server\share\license.lic`)를 사용하세요. Python 프로세스에 읽기 권한이 있는지 확인합니다. | +| **Docker 컨테이너 내부에서 실행** | `.lic` 파일을 이미지에 복사하고 `/app/license/Aspose.OCR.Java.lic`와 같은 절대 경로로 참조하세요. | +| **여러 Python 인터프리터** (예: conda env) | 환경당 한 번씩 라이선스 파일을 설치하거나 중앙 위치에 두고 각 인터프리터가 해당 위치를 가리키게 하세요. | +| **런타임에 라이선스 파일이 없음** | 지원되는 경우 트라이얼 모드로 부드럽게 전환하거나 명확한 로그 메시지를 남기고 중단합니다. | + +### Common Pitfalls + +- **Windows에서 슬래시(`/`) 사용** – Python은 받아들이지만 SDK 구버전에서는 오해할 수 있습니다. Raw string이나 이중 역슬래시를 사용하세요. +- **`License` import 누락** – 스크립트가 `NameError`로 충돌합니다. 인스턴스화 전에 반드시 import하세요. +- **OCR 메서드 호출 후 `set_license` 실행** – SDK는 첫 사용 시 라이선스를 검사하므로 경로를 **먼저** 설정해야 합니다. + +## Full Working Example + +아래는 모든 단계를 하나로 묶은 완전한 스크립트입니다. `ocr_setup.py`라는 파일명으로 저장하고 명령줄에서 실행하세요. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Expected output** (유효한 이미지가 있다고 가정): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +라이선스 파일을 찾을 수 없으면 “License not found”와 같은 모호한 예외 대신 명확한 오류 메시지가 표시됩니다. + +--- + +## Conclusion + +이제 Python에서 **create license instance**하고 Aspose OCR SDK에 대해 **configure license path**하는 정확한 방법을 알게 되었습니다. 단계는 간단합니다: 패키지 설치, `License` import, 인스턴스화, `.lic` 파일 지정, 작은 OCR 테스트로 검증. + +이 지식을 바탕으로 웹 서비스, 데스크톱 앱, 자동 파이프라인 등에 OCR 기능을 손쉽게 삽입할 수 있습니다. 다음으로는 고급 OCR 설정—언어 팩, 이미지 전처리, 배치 처리 등을 탐색해 보세요. 모두 지금 설정한 탄탄한 기반 위에 구축됩니다. + +배포, Docker, 다중 라이선스 처리 등에 대한 질문이 있나요? 댓글로 알려 주세요. 즐거운 코딩 되세요! + +## What Should You Learn Next? + +- [Aspose OCR 튜토리얼 – 광학 문자 인식](/ocr/english/) +- [Java에서 Aspose.OCR 라이선스 설정 및 확인 방법](/ocr/english/java/ocr-basics/set-license/) +- [Aspose.OCR을 사용한 언어별 이미지 텍스트 OCR 방법](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/korean/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..6358eac46 --- /dev/null +++ b/ocr/korean/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Python OCR을 사용하여 스캔된 이미지에서 검색 가능한 PDF를 만들기. 스캔된 이미지 PDF 변환, TIFF를 PDF로 + 변환, 그리고 몇 분 안에 OCR 텍스트 레이어를 추가하는 방법을 배우세요. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: ko +og_description: 즉시 검색 가능한 PDF를 만들 수 있습니다. 이 가이드는 OCR을 실행하고, 스캔된 이미지 PDF를 변환하며, 단일 + 파이썬 스크립트를 사용해 OCR 텍스트 레이어를 추가하는 방법을 보여줍니다. +og_title: Python으로 검색 가능한 PDF 만들기 – 완전 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Python으로 검색 가능한 PDF 만들기 – 단계별 가이드 +url: /ko/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python으로 검색 가능한 PDF 만들기 – 단계별 가이드 + +스캔한 페이지에서 **검색 가능한 PDF**를 만들기 위해 수많은 도구를 뒤섞어 쓰는 것이 궁금했던 적 있나요? 당신만 그런 것이 아닙니다. 많은 사무 환경에서 스캔한 TIFF나 JPEG 파일이 공유 드라이브에 올라가고, 다음 사용자는 텍스트를 직접 복사‑붙여넣기 해야 합니다—불편하고 오류가 발생하기 쉬우며 시간도 많이 소요됩니다. + +이 튜토리얼에서는 **스캔 이미지 PDF 변환**, **TIFF를 PDF로 변환**, 그리고 **OCR 텍스트 레이어 추가**를 한 번에 수행할 수 있는 깔끔하고 프로그래밍적인 솔루션을 단계별로 살펴보겠습니다. 최종적으로 OCR을 실행하고 숨겨진 텍스트를 삽입한 뒤, 인덱싱·검색·공유가 가능한 검색 가능한 PDF를 출력하는 사용 가능한 스크립트를 얻게 됩니다. + +## 필요 사항 + +- Python 3.9+ (최근 버전이면 모두 사용 가능) +- `aspose-ocr` 및 `aspose-pdf` 패키지 (`pip install aspose-ocr aspose-pdf` 로 설치) +- 스캔 이미지 파일 (`.tif`, `.png`, `.jpg` 또는 이미지만 포함된 PDF 페이지) +- 적당한 양의 RAM (OCR 엔진은 가볍고 노트북에서도 충분히 처리 가능) + +> **Pro tip:** Windows 환경이라면 관리자 권한으로 PowerShell을 실행한 뒤 위 명령을 실행하는 것이 가장 간편합니다. + +```bash +pip install aspose-ocr aspose-pdf +``` + +이제 사전 준비가 끝났으니 코드로 들어가 보겠습니다. + +## 1단계: OCR 엔진 인스턴스 생성 – *create searchable pdf* + +먼저 OCR 엔진을 시작합니다. 모든 픽셀을 읽어 문자로 변환하는 두뇌와 같은 역할을 합니다. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **왜 중요한가:** 엔진을 한 번만 초기화하면 메모리 사용량을 낮게 유지할 수 있습니다. 페이지마다 `OcrEngine()`을 호출하면 금방 자원이 부족해집니다. + +## 2단계: 스캔 이미지 로드 – *convert tiff to pdf* & *convert scanned image pdf* + +다음으로 처리할 파일을 엔진에 지정합니다. API는 모든 래스터 이미지를 지원하므로 TIFF도 JPEG와 동일하게 사용할 수 있습니다. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +PDF에 스캔 이미지만 포함되어 있는 경우에도 `load_image`를 사용하면 Aspose가 첫 페이지를 자동으로 추출합니다. + +## 3단계: PDF 저장 옵션 준비 – *add OCR text layer* + +여기서는 최종 PDF의 형태를 설정합니다. 핵심 플래그는 `create_searchable_pdf`이며, 이를 `True`로 설정하면 라이브러리가 시각적 내용과 일치하는 보이지 않는 텍스트 레이어를 삽입합니다. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **텍스트 레이어가 하는 일:** 결과 파일을 Adobe Reader에서 열어 텍스트를 선택하면 숨겨진 문자를 볼 수 있습니다. 검색 엔진도 이를 색인화하므로 컴플라이언스·아카이빙에 최적입니다. + +## 4단계: OCR 실행 및 저장 – *how to run OCR* in a single call + +이제 마법이 일어납니다. 한 번의 메서드 호출로 인식 엔진을 실행하고 검색 가능한 PDF를 디스크에 기록합니다. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize` 메서드는 상태 객체를 반환해 오류를 확인할 수 있지만, 대부분의 간단한 시나리오에서는 위 호출만으로 충분합니다. + +### 예상 출력 + +스크립트를 실행하면 다음과 같이 출력됩니다: + +``` +PDF saved as searchable PDF. +``` + +`scanned_page_searchable.pdf`를 열면 텍스트를 선택·복사‑붙여넣기 할 수 있고, `Ctrl+F` 검색도 작동합니다. 이것이 **create searchable pdf** 워크플로우의 핵심입니다. + +## 전체 작업 스크립트 + +아래는 완전한 실행 가능한 스크립트입니다. 자리표시자 경로를 실제 파일 위치로 바꾸기만 하면 됩니다. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +`create_searchable_pdf.py`라는 이름으로 저장하고 실행합니다: + +```bash +python create_searchable_pdf.py +``` + +## 흔히 묻는 질문 & 예외 상황 + +### 1️⃣ 다중 페이지 PDF를 처리할 수 있나요? + +네. `ocr_engine.load_image("file.pdf")`를 사용한 뒤 `ocr_engine.recognize(pdf_save_options, page_number)`를 페이지마다 호출하면 됩니다. 라이브러리가 자동으로 다중 페이지 검색 가능한 PDF를 생성합니다. + +### 2️⃣ 소스 파일이 고해상도 TIFF(300 dpi 이상)인 경우는? + +해상도가 높을수록 OCR 정확도가 향상되지만 메모리 사용량도 커집니다. `MemoryError`가 발생하면 먼저 이미지를 다운스케일하세요: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ OCR 언어를 어떻게 변경하나요? + +이미지를 로드하기 전에 엔진의 `language` 속성을 설정하면 됩니다: + +```python +ocr_engine.language = "fra" # French +``` + +지원되는 언어 코드는 Aspose 문서에 전체 목록이 제공됩니다. + +### 4️⃣ 원본 이미지 품질을 유지해야 할 경우는? + +`PdfSaveOptions` 클래스의 `compression` 속성을 `PdfCompression.None`으로 설정하면 래스터 데이터를 그대로 보존합니다. + +```python +pdf_save_options.compression = "None" +``` + +## 프로덕션 환경 배포 팁 + +- **배치 처리:** 핵심 로직을 파일 경로 리스트를 받는 함수로 감싸고, 성공·실패를 CSV에 기록해 감사 로그를 남깁니다. +- **병렬 처리:** `concurrent.futures.ThreadPoolExecutor`를 사용해 여러 코어에서 OCR을 동시에 실행합니다. 단, 각 스레드마다 별도의 `OcrEngine` 인스턴스가 필요합니다. +- **보안:** 민감한 문서를 다룰 경우 스크립트를 샌드박스 환경에서 실행하고, 처리 후 임시 파일을 즉시 삭제하세요. + +## 결론 + +이제 Python 스크립트를 사용해 스캔 이미지에서 **검색 가능한 PDF** 파일을 만드는 방법을 알게 되었습니다. OCR 엔진을 초기화하고, TIFF(또는 기타 래스터)를 로드한 뒤, `PdfSaveOptions`를 **OCR 텍스트 레이어 추가**하도록 설정하고, 마지막으로 `recognize`를 호출하면 **스캔 이미지 PDF 변환** 및 **TIFF를 PDF로 변환** 파이프라인이 단일 명령으로 완성됩니다. + +다음 단계는? 파일 감시 프로그램과 연동해 새 스캔이 폴더에 들어올 때마다 자동으로 검색 가능한 PDF로 변환해 보세요. 혹은 다양한 OCR 언어를 적용해 다국어 아카이브를 지원하는 실험도 가능합니다. OCR과 PDF 생성이 결합되면 가능성은 무한합니다. + +다른 언어나 프레임워크에서 **how to run OCR**에 대한 질문이 있나요? 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +![스캔 이미지 → OCR 엔진 → 검색 가능한 PDF 흐름 (create searchable pdf)](searchable-pdf-flow.png "검색 가능한 pdf 흐름도") + + +## 다음에 배울 내용은? + +- [Aspose.OCR을 사용한 .NET에서 PDF OCR 처리 방법](/ocr/english/net/text-recognition/recognize-pdf/) +- [C#으로 이미지들을 PDF로 변환 – 다중 페이지 OCR 결과 저장](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Aspose.OCR을 사용해 언어별 이미지 텍스트 OCR 처리 방법](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/korean/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4cd83fa2a --- /dev/null +++ b/ocr/korean/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-31 +description: Python으로 OCR을 위한 이미지 전처리를 통해 OCR 정확도를 향상시키세요. 이미지 파일에서 텍스트를 추출하고, PNG에서 + 텍스트를 인식하며, 결과를 높이는 방법을 배워보세요. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: ko +og_description: Python에서 이미지 전처리를 적용해 OCR 정확도를 향상시키세요. 이 가이드를 따라 이미지 파일에서 텍스트를 추출하고 + PNG에서 텍스트를 손쉽게 인식하세요. +og_title: Python에서 OCR 정확도 향상 – 전체 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python에서 OCR 정확도 향상 – 완전한 단계별 가이드 +url: /ko/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 OCR 정확도 향상 – 완전 단계별 가이드 + +OCR 정확도를 **향상**하려고 시도했지만 엉망진창인 결과만 나왔나요? 당신만 그런 것이 아닙니다. 대부분의 개발자는 원본 이미지가 노이즈가 많거나, 기울어졌거나, 단순히 대비가 낮을 때 벽에 부딪힙니다. 좋은 소식은? 몇 가지 전처리 트릭만으로 흐릿한 스크린샷을 깔끔하고 기계가 읽을 수 있는 텍스트로 바꿀 수 있다는 것입니다. + +이 튜토리얼에서는 **OCR을 위한 이미지 전처리**를 수행하고, 인식 엔진을 실행한 뒤, **이미지에서 텍스트를 추출**하는 실제 예제를 단계별로 살펴봅니다—특히 PNG 파일을 대상으로 합니다. 끝까지 진행하면 **PNG에서 텍스트를 인식**하는 방법을 정확히 알게 되고, 어떤 프로젝트에든 바로 넣어 사용할 수 있는 재사용 가능한 코드 스니펫을 얻게 됩니다. + +## 배울 내용 + +- 왜 이미지 전처리가 OCR 엔진에 중요한가 +- 어떤 전처리 모드(노이즈 제거, 기울기 보정)가 가장 큰 효과를 주는가 +- `OcrEngine` 인스턴스를 Python에서 구성하는 방법 +- 이미지 파일에서 텍스트를 **추출**하는 완전하고 실행 가능한 스크립트 +- 회전된 스캔이나 저해상도 사진과 같은 엣지 케이스를 처리하기 위한 팁 + +외부 라이브러리는 OCR SDK 외에 필요하지 않지만, Python 3.8+와 읽고자 하는 PNG 이미지가 필요합니다. + +--- + +![Python에서 OCR 정확도 향상 단계](image.png "OCR 정확도 향상 워크플로우") + +*Alt text: 전처리 및 인식 단계를 보여주는 OCR 정확도 향상 워크플로우 다이어그램.* + +## 사전 요구 사항 + +- Python 3.8 이상이 설치되어 있어야 합니다 +- `OcrEngine`, `OcrEngineSettings`, `ImagePreprocessMode`를 제공하는 OCR SDK에 접근할 수 있어야 합니다 (아래 코드는 일반 API를 사용합니다; 필요에 따라 공급업체의 클래스로 교체하세요) +- `input.png`라는 PNG 이미지가 참조 가능한 폴더에 있어야 합니다 + +가상 환경을 사용한다면 지금 활성화하세요—특별한 설정 없이 `python -m venv venv && source venv/bin/activate`만 하면 됩니다. + +--- + +## Step 1: OCR 엔진 인스턴스 생성 – OCR 정확도 향상 시작 + +첫 번째로 필요한 것은 OCR 엔진 객체입니다. 이는 나중에 픽셀을 읽고 문자로 변환할 뇌와 같습니다. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +왜 중요한가: 엔진이 없으면 전처리를 적용할 수 없으며, 원본 이미지가 바로 인식기에 전달돼 정확도가 가장 낮은 상황이 됩니다. + +--- + +## Step 2: 대상 PNG 로드 – PNG에서 텍스트 인식 준비 + +이제 엔진에 작업할 파일을 알려줍니다. PNG는 무손실 포맷이라 JPEG보다 약간 유리합니다. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +이미지가 다른 위치에 있다면 경로만 조정하면 됩니다. 엔진은 지원되는 모든 포맷을 받아들이지만, PNG는 선명한 문자 가장자리를 보존하는 데 도움이 됩니다. + +--- + +## Step 3: 전처리 구성 – OCR을 위한 이미지 전처리 + +여기서 마법이 일어납니다. 설정 객체를 만들고, 잡티를 제거하기 위해 노이즈 제거를 활성화하고, 기울어진 텍스트를 자동으로 바로잡기 위해 기울기 보정을 켭니다. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### 왜 Denoise + Deskew인가? + +- **Denoise**: 무작위 픽셀 노이즈는 패턴 매칭 알고리즘을 혼란스럽게 합니다. 이를 제거하면 글자가 선명해집니다. +- **Deskew**: 2도 정도의 기울기만으로도 신뢰도 점수가 크게 떨어집니다. Deskew는 기준선을 정렬하여 인식기가 글꼴을 더 신뢰성 있게 매칭하도록 합니다. + +이미지가 특히 어두운 경우 `ImagePreprocessMode.CONTRAST_ENHANCE`와 같은 추가 플래그를 실험해 볼 수 있습니다. SDK 문서에 모든 사용 가능한 모드가 나와 있습니다. + +--- + +## Step 4: 설정을 엔진에 적용 – 전처리를 OCR에 연결 + +설정 객체를 엔진에 할당하면 다음 인식 실행 시 우리가 정의한 변환이 적용됩니다. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +이 단계를 건너뛰면 엔진이 기본값(대개 “전처리 없음”)으로 돌아가 **OCR 정확도 감소**를 경험하게 됩니다. + +--- + +## Step 5: 인식 프로세스 실행 – 이미지에서 텍스트 추출 + +모든 연결이 끝났으니 이제 엔진에게 작업을 수행하도록 요청합니다. 호출은 동기식이며, 인식된 문자열을 포함한 결과 객체를 반환합니다. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +엔진은 내부적으로 다음을 수행합니다: + +1. PNG를 메모리로 로드합니다 +2. 설정에 따라 노이즈 제거와 기울기 보정을 적용합니다 +3. 신경망 또는 고전적인 패턴 매처를 실행합니다 +4. 출력을 `recognition_result`에 패키징합니다 + +--- + +## Step 6: 인식된 텍스트 출력 – 향상 확인 + +추출된 문자열을 출력해 봅시다. 실제 애플리케이션에서는 파일, 데이터베이스에 저장하거나 다른 서비스에 전달할 수 있습니다. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### 예상 출력 + +``` +Hello, OCR World! +``` + +텍스트가 깔끔하게 보이죠—불필요한 기호나 깨진 문자가 없습니다. 이는 **텍스트를 위한 이미지 전처리**가 제대로 이루어진 결과입니다. + +--- + +## 전문가 팁 및 엣지 케이스 + +| 상황 | 조정 방법 | 이유 | +|-----------|----------------|-----| +| 매우 낮은 해상도 PNG (≤ 72 dpi) | 가능하면 `ImagePreprocessMode.SUPER_RESOLUTION` 추가 | 업샘플링은 인식기에 더 많은 픽셀을 제공하여 인식률을 높일 수 있습니다 | +| 텍스트가 5° 이상 회전 | deskew 허용치를 늘리거나 엔진에 전달하기 전에 `Pillow`로 수동 회전 | 극단적인 각도는 자동 deskew를 우회할 수 있습니다 | +| 배경 패턴이 복잡 | `ImagePreprocessMode.BACKGROUND_REMOVAL` 활성화 | 텍스트가 아닌 잡동사니를 제거하여 오인식을 방지합니다 | +| 다국어 문서 | `ocr_engine.language = "eng+spa"` (또는 유사하게) 설정 | 엔진이 올바른 문자 집합을 선택해 전체 정확도를 향상시킵니다 | + +**OCR 정확도 향상**은 일괄적인 해결책이 없으며, 데이터셋에 맞는 전처리 플래그를 반복적으로 조정해야 할 수 있습니다. + +--- + +## 전체 스크립트 – 복사·붙여넣기 준비 + +아래는 논의한 모든 단계를 포함한 완전하고 실행 가능한 예제입니다. `improve_ocr_accuracy.py`라는 파일로 저장하고 `python improve_ocr_accuracy.py`로 실행하세요. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +실행하면 콘솔에 **이미지에서 텍스트 추출** 결과가 바로 표시됩니다. 출력이 기대와 다르면 “Pro Tips” 표에 설명된 대로 `preprocess_mode` 플래그를 조정해 보세요. + +--- + +## 결론 + +우리는 Python을 사용해 **OCR 정확도 향상**을 위한 실용적인 레시피를 살펴보았습니다. `OcrEngine`을 생성하고, PNG를 로드하고, **OCR을 위한 이미지 전처리**를 수행한 뒤, **PNG에서 텍스트를 인식**함으로써 원본이 완벽하지 않아도 **이미지에서 텍스트를 추출**할 수 있게 되었습니다. + +다음 단계는? 이미지들을 루프를 돌며 배치 처리하고, 각 결과를 CSV에 저장하거나, 추가 전처리 모드(예: 대비 강화)를 실험해 보세요. 동일한 패턴은 PDF, 스캔 영수증, 손글씨 메모에도 적용할 수 있습니다—입력만 교체하고 설정을 약간 조정하면 됩니다. + +특정 이미지 유형에 대한 질문이 있거나 이를 웹 서비스에 통합하는 방법을 알고 싶다면 댓글을 남겨 주세요. 함께 시나리오를 탐구해 보겠습니다. 즐거운 코딩 되시고, OCR 결과가 언제나 선명하기를 바랍니다! + +## 다음에 배울 내용은? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/korean/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..2bb0bf610 --- /dev/null +++ b/ocr/korean/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-31 +description: OCR 관심 영역을 사용하여 이미지를 로드하고 사각형에서 텍스트를 추출하는 방법을 배우세요. 청구서의 금액을 인식하는 데 완벽합니다. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: ko +og_description: OCR 영역(ROI)을 마스터하여 이미지를 로드하고, 사각형에서 텍스트를 추출하며, 청구서 텍스트를 인식하는 단일 튜토리얼. +og_title: OCR 관심 영역 – 단계별 파이썬 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR 관심 영역 – 파이썬에서 사각형으로부터 텍스트 추출 +url: /ko/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – 사각형에서 텍스트 추출 (Python) + +스캔한 청구서의 특정 부분만 OCR에 넣고 전체 페이지를 처리하지 않고도 **ocr region of interest** 하는 방법이 궁금하셨나요? 흐릿한 영수증을 보며 “오른쪽 아래에 있는 금액을 어떻게 추출하지?” 라고 고민한 적이 있다면 당신만이 아닙니다. 좋은 소식은 OCR 라이브러리에게 정확히 어디를 볼지 알려줄 수 있어 속도와 정확성을 크게 높일 수 있다는 점입니다. + +이 가이드에서는 **load image for OCR**, **region of interest** 정의, **extract text from rectangle** 수행, 그리고 최종적으로 **recognize text from invoice** 하여 고전적인 “금액을 어떻게 추출하나요?” 질문에 답하는 완전하고 실행 가능한 예제를 단계별로 살펴보겠습니다. 모호한 언급이 아니라 구체적인 코드와 명확한 설명, 그리고 미리 알면 좋을 몇 가지 팁을 제공합니다. + +--- + +## What You’ll Build + +이 튜토리얼을 마치면 다음을 수행하는 작은 Python 스크립트를 얻게 됩니다: + +1. 디스크에서 청구서 이미지를 로드합니다. +2. 총액이 위치한 사각형 ROI를 표시합니다. +3. 해당 ROI 내부에서만 OCR을 실행합니다. +4. 정제된 금액 문자열을 출력합니다. + +이 모든 과정은 ROI를 지원하는 어떤 OCR 라이브러리와도 동작합니다—여기서는 Tesseract나 EasyOCR와 같은 도구를 모방한 가상의 `SimpleOCR` 패키지를 사용합니다. 필요에 따라 교체해도 개념은 동일합니다. + +--- + +## Prerequisites + +- Python 3.8+ 설치 (`python --version` 명령으로 ≥3.8 확인). +- pip으로 설치 가능한 OCR 패키지 (예: `pip install simpleocr`). +- 청구서 이미지 (PNG 또는 JPEG) 를 참조 가능한 폴더에 배치. +- Python 함수와 클래스에 대한 기본 이해 (특별한 지식은 필요 없음). + +위 조건을 이미 갖추었다면 바로 시작하세요. 아직이라면 먼저 이미지를 준비해 두세요; 나머지 단계는 파일 내용과 무관합니다. + +--- + +## Step 1: Load Image for OCR + +OCR 워크플로우의 첫 단계는 읽을 비트맵이 필요합니다. 대부분의 라이브러리는 파일 경로를 받아들이는 간단한 `load_image` 메서드를 제공합니다. `SimpleOCR` 엔진으로는 다음과 같이 수행합니다: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** 스크립트를 다른 작업 디렉터리에서 실행할 때 “file not found” 오류를 방지하려면 절대 경로나 `os.path.join`을 사용하세요. + +--- + +## Step 2: Define OCR Region of Interest + +엔진이 전체 페이지를 스캔하도록 두는 대신, 금액이 정확히 위치한 영역을 지정합니다. 이것이 **ocr region of interest** 단계이며, 특히 문서에 잡음이 많은 헤더나 푸터가 있을 때 신뢰할 수 있는 추출을 위한 핵심입니다. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +왜 이런 숫자인가요? `x`와 `y`는 좌상단 모서리에서의 픽셀 오프셋이며, `width`와 `height`는 박스 크기를 나타냅니다. 확실하지 않다면 이미지 편집기에서 눈금자를 켜고 좌표를 확인하세요. 많은 IDE가 커서를 올릴 때 위치를 표시해 주기도 합니다. + +--- + +## Step 3: Extract Text from Rectangle + +ROI가 설정되었으니 이제 엔진에게 **recognize text from invoice** 를 요청하지만, 방금 지정한 사각형 내부에만 제한합니다. 호출 결과는 일반적으로 원시 문자열, 신뢰도 점수, 때로는 경계 상자를 포함하는 객체를 반환합니다. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +내부적으로 `recognize()` 는 각 ROI를 순회하면서 해당 영역을 잘라내고 OCR 모델을 실행한 뒤 결과를 합칩니다. 따라서 **extract text from rectangle** 영역을 꽉 맞게 정의하면 배치 작업에서 처리 시간을 몇 초 단축할 수 있습니다. + +--- + +## Step 4: How to Extract Amount – Clean the Output + +OCR은 완벽하지 않으며, 종종 불필요한 공백, 줄 바꿈, 혹은 문자 오인(예: “S”와 “5”)이 섞여 나옵니다. `strip()` 과 짧은 정규식 하나만으로도 금액 값은 대부분 정리됩니다. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** 금액을 데이터베이스나 결제 게이트웨이에 전달하려면 예측 가능한 형식이 필요합니다. 공백을 제거하고 숫자가 아닌 문자를 필터링하면 후속 오류를 방지할 수 있습니다. + +--- + +## Step 5: Recognize Text from Invoice – Full Script + +모든 것을 하나로 합치면 다음과 같은 완전한 실행 스크립트가 됩니다. `extract_amount.py` 로 저장하고 `python extract_amount.py` 로 실행하세요. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Expected Output + +``` +Amount: 1,245.67 +``` + +ROI가 잘못 정렬되면 `Amount: 1245.6S` 와 같이 “S” 같은 잡음이 보일 수 있습니다. 사각형 좌표를 조정하고 다시 실행해 출력이 깔끔해질 때까지 반복하세요. + +--- + +## Common Pitfalls & Edge Cases + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI too small** | 금액 텍스트가 잘려서 부분적으로만 인식됩니다. | `width`/`height` 를 약 10‑20 % 확대하고 재시험하세요. | +| **Incorrect DPI** | 저해상도 스캔(≤150 dpi) 은 OCR 정확도를 떨어뜨립니다. | 로드하기 전에 이미지를 300 dpi 로 재샘플링하거나 스캐너에 고해상도를 요청하세요. | +| **Multiple currencies** | 정규식이 첫 번째 숫자 그룹을 잡아 청구서 번호가 선택될 수 있습니다. | 숫자 앞에 통화 기호(`$`, `€`, `£`) 를 찾도록 정규식을 개선하세요. | +| **Rotated invoices** | OCR 엔진은 보통 수평 텍스트를 가정하므로 회전된 페이지는 인식이 깨집니다. | ROI를 추가하기 전에 `ocr_engine.rotate(90)` 로 회전 보정하세요. | +| **Noise in background** | 그림자나 도장이 모델을 혼란시킵니다. | 간단한 임계값(`cv2.threshold`) 처리나 노이즈 제거 필터를 적용하세요. | + +초기에 이러한 상황을 해결하면 나중에 디버깅에 드는 시간을 크게 절감할 수 있습니다. + +--- + +## Pro Tips for Real‑World Projects + +- **Batch Processing:** 청구서 폴더를 순회하면서 ROI를 동적으로 계산(예: 템플릿 감지 기반)하고 결과를 CSV 로 저장합니다. +- **Template Matching:** 여러 청구서 레이아웃을 다룰 경우 `template_id → ROI coordinates` 매핑을 JSON 으로 관리하고, 빠른 레이아웃 분류기로 ROI를 전환합니다. +- **Parallel Execution:** `concurrent.futures.ThreadPoolExecutor` 를 사용해 여러 OCR 인스턴스를 동시에 실행하면 대량 백오피스 파이프라인에 유리합니다. +- **Confidence Filtering:** 대부분의 OCR 결과에는 신뢰도 점수가 포함됩니다. 85 % 이하 결과는 버리고 수동 검토 대상으로 표시하세요. + +--- + +## Conclusion + +우리는 **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, 그리고 최종적으로 **recognize text from invoice** 를 통해 고전적인 **how to extract amount** 질문에 답하는 전체 흐름을 다루었습니다. 스크립트는 작지만 다양한 문서 형식, 언어, OCR 백엔드에 맞게 확장 가능하도록 설계되었습니다. + +이제 기본을 마스터했으니 워크플로우를 확장해 보세요: 바코드 스캔 추가, PDF 파서와 연동, 혹은 추출된 금액을 회계 API에 전송 등. ROI를 명확히 정의하면 언제나 더 빠르고 깨끗한 결과를 얻을 수 있습니다. + +문제가 발생하면 아래에 댓글을 남겨 주세요—즐거운 OCR 작업 되세요! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## What Should You Learn Next? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/polish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..2912fe43a --- /dev/null +++ b/ocr/polish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Asynchroniczny samouczek OCR pokazujący, jak używać Aspose OCR w Pythonie + z asyncio do szybkiego wyodrębniania tekstu z obrazów. Naucz się krok po kroku implementacji + asynchronicznego OCR. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: pl +og_description: Samouczek Async OCR prowadzi Cię krok po kroku przez użycie Aspose + OCR w Pythonie z asyncio w celu efektywnego wyodrębniania tekstu z obrazów. +og_title: Samouczek Asynchronicznego OCR – Python asyncio z Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Samouczek asynchronicznego OCR – Python asyncio z Aspose OCR +url: /pl/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Samouczek Async OCR – Python asyncio z Aspose OCR + +Zastanawiałeś się kiedyś, jak uruchomić rozpoznawanie znaków optycznych bez blokowania aplikacji? W **samouczku async OCR** zobaczysz dokładnie to — nieblokujące wyodrębnianie tekstu przy użyciu `asyncio` w Pythonie i biblioteki Aspose OCR. + +Jeśli utknąłeś czekając na przetworzenie dużego obrazu, ten przewodnik daje czyste, asynchroniczne rozwiązanie, które utrzymuje Twój pętla zdarzeń w ruchu. + +W kolejnych sekcjach omówimy wszystko, czego potrzebujesz: instalację biblioteki, przygotowanie asynchronicznego pomocnika, obsługę wyniku oraz szybki tip skalowania na wiele obrazów. Po zakończeniu będziesz mógł wstawić **samouczek async OCR** do dowolnego projektu w Pythonie, który już używa `asyncio`. + +## Czego będziesz potrzebować + +* Python 3.9+ (API `asyncio`, którego używamy, jest stabilne od wersji 3.7) +* Aktywna licencja Aspose OCR lub darmowa wersja próbna (biblioteka jest czysto‑Pythonowa, bez natywnych binarek) +* Mały plik obrazu (`.jpg`, `.png`, itp.), który chcesz odczytać – przechowaj go w znanym folderze + +Żadne inne zewnętrzne narzędzia nie są wymagane; wszystko działa w czystym Pythonie. + +## Krok 1: Zainstaluj pakiet Aspose OCR + +Na początek pobierz pakiet Aspose OCR z PyPI. Otwórz terminal i uruchom: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Jeśli pracujesz w wirtualnym środowisku (bardzo zalecane), najpierw je aktywuj. To utrzymuje zależności w izolacji i zapobiega konfliktom wersji. + +## Krok 2: Inicjalizuj silnik OCR asynchronicznie + +Serce naszego **samouczka async OCR** to asynchroniczna funkcja pomocnicza. Tworzy ona instancję `OcrEngine`, ładuje obraz i wywołuje `recognize_async()`. Sam silnik jest synchroniczny, ale metoda opakowująca zwraca obiekt awaitable, pozwalając pętli zdarzeń pozostać responsywną. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Dlaczego robimy to w ten sposób:** +*Tworzenie silnika wewnątrz funkcji pomocniczej zapewnia bezpieczeństwo wątkowe, jeśli później uruchomisz wiele zadań OCR równolegle. Słowo kluczowe `await` zwraca kontrolę pętli zdarzeń, podczas gdy ciężka praca odbywa się w wewnętrznym puli wątków biblioteki.* + +## Krok 3: Uruchom pomocnika z asynchronicznej funkcji głównej + +Teraz potrzebujemy małej korutyny `main()`, która wywołuje `async_ocr()` i wypisuje wynik. To odzwierciedla typowy punkt wejścia dla skryptu `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Co się dzieje pod maską?** +`asyncio.run()` tworzy nową pętlę zdarzeń, planuje `main()` i zamyka pętlę czysto po zakończeniu `main()`. Ten wzorzec jest zalecanym sposobem uruchamiania programów asynchronicznych w Pythonie 3.7+. + +## Krok 4: Przetestuj pełny skrypt + +Zapisz dwa powyższe bloki kodu w jednym pliku, np. `async_ocr_demo.py`. Uruchom go z wiersza poleceń: + +```bash +python async_ocr_demo.py +``` + +Jeśli wszystko jest poprawnie skonfigurowane, powinieneś zobaczyć coś podobnego do: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Dokładny wynik będzie zależał od zawartości `photo.jpg`. Kluczowe jest to, że skrypt kończy się szybko, nawet przy dużym obrazie, ponieważ praca OCR odbywa się w tle. + +## Krok 5: Skalowanie – przetwarzanie wielu obrazów jednocześnie + +Często zadawane pytanie brzmi: *„Czy mogę wykonać OCR na partii plików bez uruchamiania nowego procesu dla każdego?”* Oczywiście. Ponieważ nasz pomocnik jest w pełni asynchroniczny, możemy zebrać wiele korutyn za pomocą `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Dlaczego to działa:** `asyncio.gather()` planuje wszystkie zadania OCR jednocześnie. Podstawowa biblioteka Aspose OCR nadal używa własnej puli wątków, ale z perspektywy Pythona wszystko pozostaje nieblokujące, pozwalając obsłużyć dziesiątki obrazów w czasie, jaki zajęłoby pojedyncze synchroniczne wywołanie. + +## Krok 6: Obsługa błędów w sposób elegancki + +Podczas pracy z plikami zewnętrznymi nieuniknienie napotkasz brakujące pliki, uszkodzone obrazy lub problemy z licencją. Owiń wywołanie OCR w blok `try/except`, aby utrzymać pętlę zdarzeń przy życiu: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Teraz `batch_ocr()` może wywoływać `safe_async_ocr`, zapewniając, że jeden wadliwy plik nie przerwie całej partii. + +## Wizualny przegląd + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Diagram przepływu samouczka Async OCR pokazujący pomocnika async_ocr, pętlę zdarzeń i silnik Aspose OCR"} + +Powyższy diagram wizualizuje przepływ: pętla zdarzeń → `async_ocr` → `OcrEngine` → wątek w tle → wynik z powrotem do pętli. + +## Częste pułapki i jak ich unikać + +| Pułapka | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| **Blokujący I/O wewnątrz pomocnika** | Przypadkowe użycie `open()` bez `await` może zablokować pętlę. | Użyj `aiofiles` do odczytu plików lub pozwól, aby `engine.load_image` obsłużyło to (jest już nieblokujące). | +| **Ponowne użycie jednego `OcrEngine` w wielu korutynach** | Silnik nie jest bezpieczny wątkowo; równoczesne wywołania mogą uszkodzić stan. | Utwórz nowy silnik wewnątrz każdego wywołania `async_ocr` (jak pokazano). | +| **Brak licencji** | Aspose OCR zgłasza wyjątek związany z licencją w czasie wykonywania. | Zarejestruj licencję wcześnie (`OcrEngine.set_license("license.json")`). | +| **Duże obrazy powodujące skoki pamięci** | Biblioteka ładuje cały obraz do pamięci RAM. | Zmniejsz rozmiar obrazów przed OCR, jeśli pamięć jest problemem. | + +## Podsumowanie: Co osiągnęliśmy + +W tym **samouczku async OCR** wykonaliśmy: + +1. Zainstalowaliśmy bibliotekę Aspose OCR. +2. Zbudowaliśmy pomocnika `async_ocr`, który wykonuje rozpoznawanie bez blokowania. +3. Uruchomiliśmy pomocnika z czystym punktem wejścia `asyncio`. +4. Zademonstrowaliśmy przetwarzanie partii przy użyciu `asyncio.gather`. +5. Dodaliśmy obsługę błędów i wskazówki najlepszych praktyk. + +To wszystko jest czystym Pythonem, więc możesz wstawić to do serwera webowego, narzędzia CLI lub potoku danych bez przepisywania istniejącego kodu async. + +## Kolejne kroki i powiązane tematy + +* **Asynchroniczne przetwarzanie obrazów** – użyj `aiohttp` do równoczesnego pobierania obrazów przed OCR. +* **Przechowywanie wyników OCR** – połącz ten samouczek z asynchronicznym sterownikiem bazy danych, takim jak `asyncpg` dla PostgreSQL. +* **Dostrajanie wydajności** – eksperymentuj z `engine.recognize_async(max_threads=4)`, jeśli biblioteka udostępnia taką opcję. +* **Alternatywne silniki OCR** – porównaj Aspose OCR z asynchronicznymi wrapperami Tesseract pod kątem analizy koszt‑korzyść. + +Śmiało eksperymentuj: spróbuj podać pliki PDF, dostosować ustawienia języka lub podłączyć wyniki do chatbota. Nie ma granic, gdy masz solidną bazę **samouczka async OCR**. + +Szczęśliwego kodowania i niech Twoje wyodrębnianie tekstu będzie zawsze szybkie! + +## Co powinieneś nauczyć się dalej? + +- [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/) +- [Samouczek Aspose OCR – rozpoznawanie znaków optycznych](/ocr/english/) +- [Jak wykonać OCR tekstu obrazu z językiem przy użyciu Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/polish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..b8a0613b2 --- /dev/null +++ b/ocr/polish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-31 +description: Automatyczne wykrywanie języka w OCR stało się proste. Dowiedz się, jak + wczytać obraz do OCR, włączyć automatyczne wykrywanie języka i rozpoznać tekst na + obrazie w kilku prostych krokach. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: pl +og_description: Automatyczne wykrywanie języka w OCR jest proste. Skorzystaj z tego + krok po kroku poradnika, aby włączyć automatyczne wykrywanie języka, załadować OCR + obrazu i rozpoznać tekst na obrazie. +og_title: Automatyczne wykrywanie języka przy użyciu OCR – Kompletny przewodnik Pythona +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatyczne wykrywanie języka przy użyciu OCR – Kompletny przewodnik Pythona +url: /pl/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatyczne wykrywanie języka przy użyciu OCR – Kompletny przewodnik w Pythonie + +Zastanawiałeś się kiedyś, jak sprawić, by silnik OCR *zgadł* język zeskanowanego dokumentu, nie podając mu, czego ma szukać? To właśnie robi **automatic language detection**, i jest to prawdziwy przełom, gdy masz do czynienia z wielojęzycznymi PDF‑ami, zdjęciami znaków drogowych czy dowolnym obrazem łączącym różne skrypty. + +W tym samouczku przeprowadzimy Cię przez praktyczny przykład, który pokaże, jak **włączyć automatyczne wykrywanie języka**, **załadować obraz do OCR** i **rozpoznać tekst na obrazie** przy użyciu API w stylu Pythona. Po zakończeniu będziesz mieć samodzielny skrypt, który wypisuje zarówno wykryty kod języka, jak i wyodrębniony tekst — bez konieczności ręcznego ustawiania języka. + +## Czego się nauczysz + +- Jak utworzyć instancję silnika OCR i włączyć **automatic language detection**. +- Dokładne kroki, aby **load image OCR** z dysku. +- Jak wywołać metodę `recognize()` silnika i otrzymać wynik zawierający kod języka. +- Wskazówki dotyczące obsługi przypadków brzegowych, takich jak obrazy o niskiej rozdzielczości lub nieobsługiwane skrypty. + +Nie wymagana jest wcześniejsza znajomość wielojęzycznego OCR; wystarczy podstawowa konfiguracja Pythona i plik obrazu. + +--- + +## Wymagania wstępne + +Zanim zaczniemy, upewnij się, że masz: + +1. Zainstalowany Python 3.8+ (dowolna nowsza wersja działa). +2. Bibliotekę OCR, która udostępnia `OcrEngine`, `LanguageAutoDetectMode` itd. – w tym przewodniku zakładamy hipotetyczny pakiet o nazwie `myocr`. Zainstaluj go za pomocą: + + ```bash + pip install myocr + ``` + +3. Plik obrazu (`multilingual_sample.png`) zawierający tekst w co najmniej dwóch różnych językach. +4. Odrobinę ciekawości — jeśli nigdy nie miałeś do czynienia z OCR, nie martw się; kod jest celowo prosty. + +## Krok 1: Włącz automatyczne wykrywanie języka + +Pierwszą rzeczą, którą musisz zrobić, jest poinformowanie silnika, że ma sam *ustalić* język. To właśnie tutaj wkracza flaga **automatic language detection**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Dlaczego to ważne:** +> Gdy ustawiony jest `AUTO_DETECT`, silnik uruchamia lekki klasyfikator języka na obrazie przed rozpoczęciem ciężkiej rozpoznawania znaków. Oznacza to, że nie musisz zgadywać, czy tekst jest po angielsku, rosyjsku, francusku czy w jakiejkolwiek kombinacji. Silnik automatycznie wybierze najlepszy model językowy dla każdego regionu obrazu. + +## Krok 2: Załaduj obraz do OCR + +Teraz, gdy silnik wie, że ma automatycznie wykrywać języki, musimy dostarczyć mu coś do przetworzenia. Krok **load image OCR** odczytuje bitmapę i przygotowuje wewnętrzne bufory. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro tip:** +> Jeśli Twój obraz ma więcej niż 300 dpi, rozważ zmniejszenie go do około 150‑200 dpi. Zbyt duża ilość szczegółów może faktycznie *spowolnić* etap wykrywania języka bez poprawy dokładności. + +## Krok 3: Rozpoznaj tekst z obrazu + +Mając obraz w pamięci i włączone wykrywanie języka, ostatnim elementem jest poproszenie silnika o **recognize text image**. To pojedyncze wywołanie wykonuje całą ciężką pracę. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` jest obiektem, który zazwyczaj zawiera przynajmniej dwa atrybuty: + +| Attribute | Description | +|-----------|-------------| +| `language` | Kod ISO‑639‑1 wykrytego języka (np. `"en"` dla angielskiego). | +| `text` | Zwykły tekst transkrypcji obrazu. | + +## Krok 4: Pobierz wykryty język i wyodrębniony tekst + +Teraz po prostu wypisujemy to, co silnik wykrył. To demonstruje działanie funkcji **detect language OCR**. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Przykładowe wyjście** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Co jeśli silnik zwróci `None`?** +> Zwykle oznacza to, że obraz jest zbyt rozmyty lub tekst zbyt mały (< 8 pt). Spróbuj zwiększyć kontrast lub użyć źródła o wyższej rozdzielczości. + +## Pełny działający przykład (Włącz automatyczne wykrywanie języka od początku do końca) + +Łącząc wszystko razem, oto gotowy do uruchomienia skrypt, który obejmuje **enable auto language detection**, **load image OCR**, **recognize text image** i **detect language OCR** w jednym kroku. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Zapisz to jako `automatic_language_detection_ocr.py`, zamień `YOUR_DIRECTORY` na folder zawierający Twój plik PNG i uruchom: + +```bash +python automatic_language_detection_ocr.py +``` + +Powinieneś zobaczyć kod języka, po którym następuje wyodrębniony tekst, tak jak w przykładowym wyjściu powyżej. + +## Obsługa typowych przypadków brzegowych + +| Situation | Suggested Fix | +|-----------|----------------| +| **Bardzo niskiej rozdzielczości obraz** (poniżej 100 dpi) | Zwiększ rozdzielczość przy użyciu filtru bikubicznego przed załadowaniem lub poproś o źródło o wyższej rozdzielczości. | +| **Mieszane skrypty na jednym obrazie** (np. angielski + cyrylica) | Silnik zazwyczaj podzieli stronę na regiony; jeśli zauważysz błędne wykrycia, ustaw `engine.enable_region_split = True`. | +| **Nieobsługiwany język** | Sprawdź, czy biblioteka OCR dostarcza pakiet językowy dla potrzebnego skryptu; może być konieczne pobranie dodatkowych modeli. | +| **Przetwarzanie dużych partii** | Zainicjalizuj silnik raz, a następnie używaj go wielokrotnie w kolejnych cyklach `load_image` / `recognize`, aby uniknąć wielokrotnego ładowania modeli. | + +## Przegląd wizualny + +![przykładowy wynik automatycznego wykrywania języka](https://example.com/auto-lang-detect.png "automatyczne wykrywanie języka") + +*Alt text:* przykładowy wynik automatycznego wykrywania języka pokazujący wykryty kod języka i wyodrębniony wielojęzyczny tekst. + +## Zakończenie + +Właśnie omówiliśmy **automatic language detection** od początku do końca — tworzenie silnika, włączanie automatycznego wykrywania języka, ładowanie obrazu do OCR, rozpoznawanie tekstu i ostateczne pobieranie wykrytego języka. Ten przepływ end‑to-end pozwala przetwarzać wielojęzyczne dokumenty bez ręcznego konfigurowania modeli językowych przy każdym użyciu. + +Jeśli jesteś gotów pójść dalej, rozważ: + +- **Batching** setki obrazów w pętli, która ponownie używa tej samej instancji `OcrEngine`. +- **Post‑processing** wyodrębnionego tekstu przy użyciu korektora ortograficznego lub tokenizera specyficznego dla języka. +- **Integrating** skryptu w usługę webową, która przyjmuje przesłane przez użytkownika pliki i zwraca JSON z polami `language` i `text`. + +Śmiało eksperymentuj z różnymi formatami obrazów (`.jpg`, `.tif`) i obserwuj, jak zmienia się dokładność wykrywania. Masz pytania lub trudny obraz, którego nie da się odczytać? Dodaj komentarz poniżej — miłego kodowania! + +## Co powinieneś się nauczyć dalej? + +- [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 obrazu w C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [rozpoznaj tekst obrazu przy użyciu Aspose OCR dla wielu języków](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/polish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..537ad8f8d --- /dev/null +++ b/ocr/polish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Naucz się konwertować obrazy na tekst w Pythonie za pomocą skryptu do + masowej konwersji obrazów na tekst. Rozpoznawaj tekst ze skanowanych obrazów przy + użyciu Aspose.OCR w kilka minut. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: pl +og_description: Konwertuj obrazy na tekst w Pythonie natychmiast. Ten przewodnik pokazuje + konwersję wielu obrazów na tekst oraz jak rozpoznawać tekst ze skanowanych obrazów + przy użyciu Aspose.OCR. +og_title: Konwertuj obrazy na tekst w Pythonie – pełny poradnik +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Konwertowanie obrazów na tekst w Pythonie – Kompletny przewodnik krok po kroku +url: /pl/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertowanie obrazów na tekst w Pythonie – Kompletny przewodnik krok po kroku + +Zastanawiałeś się kiedyś, jak **convert images to text python** bez przeszukiwania dziesiątek bibliotek? Nie jesteś jedyny. Czy to digitalizujesz stare paragony, wyciągasz dane ze zeskanowanych faktur, czy tworzysz przeszukiwalny archiwum PDF‑ów, zamiana obrazów na pliki tekstowe to codzienne wyzwanie dla wielu programistów. + +W tym samouczku przeprowadzimy Cię przez pipeline **bulk image to text conversion**, który rozpoznaje tekst ze zeskanowanych obrazów, zapisuje każdy wynik jako osobny plik `.txt` i robi to wszystko w kilku linijkach Pythona. Nie musisz szukać niejasnych API — Aspose.OCR wykonuje ciężką pracę, a my pokażemy dokładnie, jak to podłączyć. + +## Co się nauczysz + +- Jak zainstalować i skonfigurować pakiet Aspose.OCR dla Pythona. +- Dokładny kod potrzebny do **convert images to text python** przy użyciu `BatchOcrEngine`. +- Wskazówki dotyczące radzenia sobie z typowymi problemami, takimi jak nieobsługiwane formaty lub uszkodzone pliki. +- Sposoby weryfikacji, że krok **recognize text from scanned images** rzeczywiście się powiódł. + +Po zakończeniu tego przewodnika będziesz mieć gotowy do uruchomienia skrypt, który może przetworzyć tysiące obrazów jednorazowo — idealny dla każdego scenariusza przetwarzania wsadowego. + +## Wymagania wstępne + +- Python 3.8+ zainstalowany na Twoim komputerze. +- Folder z plikami obrazów (PNG, JPEG, TIFF itd.), które chcesz przekształcić w tekst. +- Aktywne konto Aspose Cloud lub darmowa licencja trial (darmowy poziom wystarczy do testów). + +Jeśli masz to wszystko, zanurzmy się. + +--- + +## Krok 1 – Skonfiguruj środowisko Python + +Zanim zaczniemy pisać jakikolwiek kod OCR, upewnij się, że pracujesz w czystym środowisku wirtualnym. To izoluje zależności i zapobiega konfliktom wersji. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Utrzymuj katalog projektu w porządku — utwórz podfolder o nazwie `ocr_project` i umieść w nim skrypt. To ułatwia późniejsze zarządzanie ścieżkami. + +## Krok 2 – Zainstaluj Aspose.OCR dla Pythona + +Aspose.OCR jest biblioteką komercyjną, ale dostarcza darmowe koło w stylu NuGet, które możesz pobrać z PyPI. Uruchom następujące polecenie w aktywowanym środowisku wirtualnym: + +```bash +pip install aspose-ocr +``` + +Jeśli napotkasz błąd uprawnień, dodaj flagę `--user` lub uruchom polecenie z `sudo` (tylko Linux/macOS). Po instalacji powinieneś zobaczyć coś podobnego: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** W przeciwieństwie do wielu otwarto‑źródłowych narzędzi OCR, Aspose.OCR obsługuje **bulk image to text conversion** od razu po instalacji i radzi sobie z szeroką gamą formatów obrazów bez dodatkowej konfiguracji. Oferuje także klasę `BatchOcrEngine`, która sprawia, że zadanie „convert images to text python” staje się jednowierszową operacją. + +## Krok 3 – Konwertuj obrazy na tekst w Pythonie przy użyciu Batch OCR + +Teraz do sedna samouczka. Poniżej znajduje się w pełni uruchamialny skrypt, który: + +1. Importuje klasy silnika OCR. +2. Tworzy instancję `BatchOcrEngine`. +3. Wskazuje silnikowi folder wejściowy z obrazami. +4. Nakazuje silnikowi zapisać każdy wyodrębniony plik tekstowy w folderze wyjściowym. +5. Wywołuje metodę `recognize()`, która **recognize text from scanned images** pojedynczo. + +Zapisz poniższy kod jako `batch_ocr.py` w folderze projektu: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Jak to działa + +- **`BatchOcrEngine`** otacza standardowy `OcrEngine`, ale dodaje orkiestrację na poziomie folderu, co jest dokładnie tym, czego potrzebujesz, gdy chcesz **convert images to text python** masowo. +- Właściwość `input_folder` informuje silnik, gdzie szukać obrazów źródłowych. Automatycznie skanuje katalog i kolejkowuje każdy obsługiwany typ pliku. +- Właściwość `output_folder` określa, gdzie trafia każdy plik `.txt`. Silnik zachowuje oryginalną nazwę pliku, więc `receipt1.png` staje się `receipt1.txt`. +- Wywołanie `recognize()` uruchamia wewnętrzną pętlę, która wczytuje każdy obraz, wykonuje OCR i zapisuje wynik. Metoda blokuje działanie, dopóki wszystkie pliki nie zostaną przetworzone, co ułatwia dalsze działania (np. spakowanie folderu wyjściowego). + +#### Oczekiwany wynik + +Gdy uruchomisz skrypt: + +```bash +python batch_ocr.py +``` + +Powinieneś zobaczyć: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +W folderze `output_texts` znajdziesz plik tekstowy dla każdego obrazu. Otwórz dowolny z nich w edytorze tekstu, a zobaczysz surowy wynik OCR — zazwyczaj bliskie odzwierciedlenie oryginalnego wydrukowanego tekstu. + +## Krok 4 – Zweryfikuj wyniki i obsłuż błędy + +Nawet najlepsze silniki OCR mogą mieć problemy z niskiej rozdzielczości skanami lub mocno przechylonymi stronami. Oto szybki sposób na sprawdzenie poprawności wyników i zapisanie ewentualnych niepowodzeń. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Dlaczego to dodać?** +- Łapie przypadki, w których silnik cicho zwrócił pusty ciąg (częste przy nieczytelnych obrazach). +- Dostarcza listę problematycznych plików, abyś mógł je ręcznie sprawdzić lub ponownie uruchomić z innymi ustawieniami (np. zwiększyć opcje `OcrEngine.preprocess`). + +### Przypadki brzegowe i poprawki + +| Sytuacja | Sugerowane rozwiązanie | +|-----------|------------------------| +| Obrazy są obrócone o 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mieszane języki (angielski + francuski) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Duże pliki PDF najpierw konwertowane na obrazy | Podziel PDF‑y na obrazy jednosktronicowe, a następnie podaj folder silnikowi wsadowemu. | +| Błędy pamięci przy bardzo dużych partiach | Przetwarzaj mniejsze podfoldery kolejno lub zwiększ `batch_engine.max_memory_usage`. | + +## Krok 5 – Zautomatyzuj cały przepływ pracy (Opcjonalnie) + +Jeśli potrzebujesz uruchamiać tę konwersję co noc, opakuj skrypt w prosty plik powłoki lub wsadowy Windows i zaplanuj go przy użyciu `cron` (Linux/macOS) lub Harmonogramu zadań (Windows). Oto minimalny `run_ocr.sh` dla systemów Unix‑owych: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Uczyń go wykonywalnym (`chmod +x run_ocr.sh`) i dodaj wpis cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +To uruchamia konwersję codziennie o 2  rano i zapisuje wszelkie wyjścia do późniejszego przeglądu. + +--- + +## Podsumowanie + +Masz teraz sprawdzoną, gotową do produkcji metodę **convert images to text python** przy użyciu `BatchOcrEngine` z Aspose.OCR. Skrypt obsługuje **bulk image to text conversion**, elegancko zapisuje każdy wynik w dedykowany plik i zawiera kroki weryfikacyjne, aby upewnić się, że naprawdę **recognize text from scanned images** poprawnie. + +Od tego momentu możesz: + +- Eksperymentować z różnymi ustawieniami OCR (pakiety językowe, prostowanie, redukcja szumów). +- Przekierować wygenerowany tekst do indeksu wyszukiwania, takiego jak Elasticsearch, aby uzyskać natychmiastowe wyszukiwanie pełnotekstowe. +- Połączyć ten pipeline z narzędziami konwersji PDF, aby przetworzyć zeskanowane PDF‑y jednorazowo. + +Masz pytania lub zauważyłeś problem z konkretnym typem pliku? zostaw komentarz poniżej, a razem rozwiążemy problem. Szczęśliwego kodowania i niech Twoje uruchomienia OCR będą szybkie i wolne od błędów! + +## Co warto nauczyć się dalej? + +- [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/) +- [Wyodrębnij tekst z obrazów przy użyciu operacji OCR na folderach](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/polish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..d476dcef6 --- /dev/null +++ b/ocr/polish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Utwórz instancję licencji w Pythonie i łatwo skonfiguruj ścieżkę licencji. + Dowiedz się, jak skonfigurować licencjonowanie Aspose OCR, korzystając z przejrzystych + przykładów kodu. +draft: false +keywords: +- create license instance +- configure license path +language: pl +og_description: Utwórz instancję licencji w Pythonie i natychmiast skonfiguruj ścieżkę + licencji. Skorzystaj z tego samouczka, aby pewnie aktywować Aspose OCR. +og_title: Utwórz instancję licencji w Pythonie – Kompletny przewodnik konfiguracji +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Utwórz instancję licencji w Pythonie – Przewodnik krok po kroku +url: /pl/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz instancję licencji w Pythonie – Kompletny przewodnik konfiguracji + +Potrzebujesz **utworzyć instancję licencji** dla Aspose OCR w Pythonie? Jesteś we właściwym miejscu. W tym samouczku pokażemy również, jak **skonfigurować ścieżkę licencji**, aby SDK wiedziało, gdzie znajduje się Twój plik `.lic`. + +Jeśli kiedykolwiek patrzyłeś na pusty skrypt, zastanawiając się, dlaczego silnik OCR ciągle narzeka na nielicencjonowany produkt, nie jesteś sam. Rozwiązanie zazwyczaj wymaga zaledwie kilku linii kodu — gdy już wiesz, gdzie je umieścić. Po zakończeniu tego przewodnika będziesz mieć w pełni licencjonowane środowisko Aspose OCR gotowe do rozpoznawania tekstu, obrazów i plików PDF bez problemów. + +## Czego się nauczysz + +- Jak **utworzyć instancję licencji** przy użyciu pakietu `asposeocr`. +- Poprawny sposób **skonfigurowania ścieżki licencji** zarówno w środowisku deweloperskim, jak i produkcyjnym. +- Typowe pułapki (brak pliku, niewłaściwe uprawnienia) i jak ich unikać. +- Pełny, gotowy do uruchomienia skrypt, który możesz wkleić do dowolnego projektu. + +Nie wymagana jest wcześniejsza znajomość Aspose OCR, wystarczy działająca instalacja Python 3 oraz ważny plik licencji. + +--- + +## Krok 1: Zainstaluj pakiet Aspose OCR dla Pythona + +Zanim będziemy mogli **utworzyć instancję licencji**, biblioteka musi być zainstalowana. Otwórz terminal i uruchom: + +```bash +pip install aspose-ocr +``` + +> **Porada:** Jeśli używasz wirtualnego środowiska (bardzo zalecane), najpierw je aktywuj. Dzięki temu Twoje zależności będą uporządkowane i unikniesz konfliktów wersji. + +## Krok 2: Zaimportuj klasę License + +Teraz, gdy SDK jest dostępne, pierwsza linia Twojego skryptu powinna importować klasę `License`. To jest obiekt, którego użyjemy do **utworzenia instancji licencji**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Dlaczego od razu go importujemy? Ponieważ obiekt `License` musi być zainicjowany **przed** jakimikolwiek wywołaniami OCR; w przeciwnym razie SDK zgłosi błąd licencyjny w momencie próby przetworzenia obrazu. + +## Krok 3: Utwórz instancję licencji + +Oto moment, na który czekałeś — faktycznie **utworzyć instancję licencji**. To jedna linia, ale kontekst otaczający ma znaczenie. + +```python +# Step 3: Create a License instance +license = License() +``` + +Zmienna `license` teraz przechowuje obiekt, który kontroluje wszystkie zachowania licencyjne bieżącego procesu Pythona. Traktuj go jak strażnika, który mówi Aspose OCR: „Hej, mam prawo do uruchomienia.” + +## Krok 4: Skonfiguruj ścieżkę licencji + +Mając gotową instancję, musimy wskazać na nasz plik `.lic`. To właśnie **skonfigurowanie ścieżki licencji** wchodzi w grę. Zastąp placeholder absolutną ścieżką do swojego pliku licencji. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Kilka rzeczy do zauważenia: + +1. **Surowe łańcuchy (`r"…"`)** zapobiegają interpretacji odwrotnych ukośników jako znaków ucieczki w systemie Windows. +2. Użyj **absolutnej ścieżki**, aby uniknąć nieporozumień, gdy skrypt jest uruchamiany z innego katalogu roboczego. +3. Jeśli wolisz ścieżkę względną (np. przy dołączaniu licencji do projektu), upewnij się, że bazą względną jest lokalizacja skryptu, a nie bieżący katalog powłoki. + +### Obsługa brakujących plików + +Jeśli ścieżka jest nieprawidłowa lub plik nieczytelny, `set_license` zgłosi wyjątek. Owiń wywołanie w blok `try/except`, aby wyświetlić przyjazny komunikat o błędzie: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Ten fragment **konfiguruje ścieżkę licencji** w sposób bezpieczny i informuje dokładnie, co poszło nie tak — bez tajemniczych śladów stosu. + +## Krok 5: Zweryfikuj, że licencja jest aktywna + +Szybka kontrola poprawności oszczędza godziny debugowania później. Po wywołaniu `set_license` spróbuj prostej operacji OCR. Jeśli licencja jest ważna, SDK przetworzy obraz bez zgłaszania błędu licencyjnego. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Jeśli zobaczysz wydrukowany rozpoznany tekst, gratulacje — pomyślnie **utworzyłeś instancję licencji** i **skonfigurowałeś ścieżkę licencji**. Jeśli otrzymasz wyjątek licencyjny, sprawdź ponownie ścieżkę i uprawnienia do pliku. + +## Przypadki brzegowe i najlepsze praktyki + +| Situation | What to Do | +|-----------|------------| +| **Plik licencji znajduje się w udziale sieciowym** | Zmapuj udział do litery dysku lub użyj ścieżki UNC (`\\server\share\license.lic`). Upewnij się, że proces Pythona ma dostęp do odczytu. | +| **Uruchamianie wewnątrz kontenera Docker** | Skopiuj plik `.lic` do obrazu i odwołuj się do niego przy użyciu ścieżki absolutnej, np. `/app/license/Aspose.OCR.Java.lic`. | +| **Wiele interpreterów Pythona** (np. środowiska conda) | Zainstaluj plik licencji raz na środowisko lub przechowuj go w centralnym miejscu i wskazuj na niego każdy interpreter. | +| **Brak pliku licencji w czasie wykonywania** | Łagodnie przejdź w tryb testowy (jeśli jest wspierany) lub zakończ działanie z czytelnym komunikatem w logu. | + +### Typowe pułapki + +- **Używanie ukośników (forward slashes) w Windows** – Python je akceptuje, ale niektóre starsze wersje SDK mogą je błędnie interpretować. Trzymaj się surowych łańcuchów lub podwójnych backslashów. +- **Zapomniano zaimportować `License`** – Skrypt zakończy się błędem `NameError`. Zawsze importuj przed tworzeniem instancji. +- **Wywołanie `set_license` po metodach OCR** – SDK sprawdza licencję przy pierwszym użyciu, więc najpierw ustaw ścieżkę **pierwsza**. + +## Pełny działający przykład + +Poniżej znajduje się kompletny skrypt, który łączy wszystkie elementy. Zapisz go jako `ocr_setup.py` i uruchom z wiersza poleceń. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Oczekiwany wynik** (zakładając prawidłowy obraz): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Jeśli plik licencji nie zostanie znaleziony, zobaczysz czytelny komunikat o błędzie zamiast niejasnego wyjątku „License not found”. + +--- + +## Podsumowanie + +Teraz dokładnie wiesz, jak **utworzyć instancję licencji** w Pythonie i **skonfigurować ścieżkę licencji** dla SDK Aspose OCR. Kroki są proste: zainstaluj pakiet, zaimportuj `License`, utwórz jego instancję, wskaż na swój plik `.lic` i zweryfikuj przy pomocy małego testu OCR. + +Mając tę wiedzę, możesz osadzać możliwości OCR w usługach internetowych, aplikacjach desktopowych lub zautomatyzowanych pipeline'ach, nie napotykając błędów licencyjnych. Następnie rozważ zgłębienie zaawansowanych ustawień OCR — pakietów językowych, wstępnego przetwarzania obrazów lub przetwarzania wsadowego — które wszystkie opierają się na solidnej podstawie, którą właśnie stworzyłeś. + +Masz pytania dotyczące wdrożenia, Dockera lub obsługi wielu licencji? Zostaw komentarz i szczęśliwego kodowania! + +## Co powinieneś nauczyć się dalej? + +- [Samouczek Aspose OCR – Rozpoznawanie znaków optycznych](/ocr/english/) +- [Jak ustawić licencję i zweryfikować licencję Aspose.OCR w Javie](/ocr/english/java/ocr-basics/set-license/) +- [Jak wykonać OCR tekstu obrazu z językiem przy użyciu Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/polish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..02e8267cf --- /dev/null +++ b/ocr/polish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Utwórz przeszukiwalny PDF ze skanowanych obrazów przy użyciu OCR w Pythonie. + Dowiedz się, jak konwertować PDF ze skanowanymi obrazami, konwertować TIFF na PDF + i dodać warstwę tekstową OCR w kilka minut. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: pl +og_description: Twórz przeszukiwalne PDF natychmiast. Ten przewodnik pokazuje, jak + uruchomić OCR, konwertować zeskanowane PDF‑y obrazu i dodać warstwę tekstu OCR za + pomocą jednego skryptu Pythona. +og_title: Utwórz przeszukiwalny PDF w Pythonie – Kompletny poradnik +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Tworzenie przeszukiwalnego PDF za pomocą Pythona – Przewodnik krok po kroku +url: /pl/python-java/general/create-searchable-pdf-with-python-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 – Przewodnik krok po kroku + +Zastanawiałeś się kiedyś, jak **utworzyć przeszukiwalny PDF** ze zeskanowanej strony bez używania dziesiątek narzędzi? Nie jesteś sam. W wielu procesach biurowych zeskanowany plik TIFF lub JPEG trafia na współdzielony dysk, a kolejna osoba musi ręcznie kopiować‑wklejać tekst — bolesne, podatne na błędy i marnujące czas. + +W tym samouczku przeprowadzimy Cię przez czyste, programistyczne rozwiązanie, które pozwala **konwertować zeskanowany obraz PDF**, **konwertować TIFF do PDF** i **dodać warstwę tekstu OCR** w jednym kroku. Po zakończeniu będziesz mieć gotowy do użycia skrypt, który uruchamia OCR, osadza ukryty tekst i generuje przeszukiwalny PDF, który możesz indeksować, przeszukiwać lub udostępniać z pewnością. + +## Czego będziesz potrzebować + +- Python 3.9+ (dowolna aktualna wersja działa) +- `aspose-ocr` i `aspose-pdf` pakiety (instalowane za pomocą `pip install aspose-ocr aspose-pdf`) +- Zeskanowany plik obrazu (`.tif`, `.png`, `.jpg` lub nawet strona PDF będąca jedynie obrazem) +- Umiarkowana ilość RAM (silnik OCR jest lekki; nawet laptop sobie radzi) + +> **Wskazówka:** Jeśli używasz systemu Windows, najłatwiejszy sposób na uzyskanie pakietów to uruchomienie polecenia w podniesionym oknie PowerShell. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Teraz, gdy wymagania wstępne są załatwione, zanurzmy się w kod. + +## Krok 1: Utwórz instancję silnika OCR – *create searchable pdf* + +Pierwszą rzeczą, którą robimy, jest uruchomienie silnika OCR. Traktuj go jak mózg, który odczyta każdy piksel i przekształci go w znaki. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Dlaczego to ważne:** Inicjalizacja silnika tylko raz utrzymuje niskie zużycie pamięci. Gdybyś wywoływał `OcrEngine()` w pętli dla każdej strony, szybko wyczerpałbyś zasoby. + +## Krok 2: Załaduj zeskanowany obraz – *convert tiff to pdf* & *convert scanned image pdf* + +Następnie skieruj silnik na plik, który chcesz przetworzyć. API akceptuje dowolny obraz rastrowy, więc TIFF działa tak samo dobrze jak JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Jeśli masz PDF zawierający jedynie zeskanowany obraz, nadal możesz użyć `load_image`, ponieważ Aspose automatycznie wyodrębni pierwszą stronę. + +## Krok 3: Przygotuj opcje zapisu PDF – *add OCR text layer* + +Tutaj konfigurujemy, jak ma wyglądać końcowy PDF. Kluczową flagą jest `create_searchable_pdf`; ustawienie jej na `True` informuje bibliotekę, aby osadziła niewidoczną warstwę tekstu odzwierciedlającą zawartość wizualną. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Co robi warstwa tekstowa:** Gdy otworzysz powstały plik w Adobe Reader i spróbujesz zaznaczyć tekst, zobaczysz ukryte znaki. Wyszukiwarki również mogą je indeksować — idealne dla zgodności lub archiwizacji. + +## Krok 4: Uruchom OCR i zapisz – *how to run OCR* w jednym wywołaniu + +Teraz dzieje się magia. Jedno wywołanie metody uruchamia silnik rozpoznawania i zapisuje przeszukiwalny PDF na dysku. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Metoda `recognize` zwraca obiekt statusu, który możesz sprawdzić pod kątem błędów, ale w większości prostych scenariuszy wystarczy powyższe proste wywołanie. + +### Oczekiwany wynik + +Uruchomienie skryptu wypisuje: + +``` +PDF saved as searchable PDF. +``` + +Jeśli otworzysz `scanned_page_searchable.pdf`, zauważysz, że możesz zaznaczyć tekst, skopiować‑wkleić go i nawet wykonać wyszukiwanie `Ctrl+F`. To znak rozpoznawczy przepływu pracy **create searchable pdf**. + +## Pełny działający skrypt + +Poniżej znajduje się kompletny, gotowy do uruchomienia skrypt. Wystarczy zamienić ścieżki zastępcze na rzeczywiste lokalizacje plików. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Zapisz to jako `create_searchable_pdf.py` i uruchom: + +```bash +python create_searchable_pdf.py +``` + +## Częste pytania i przypadki brzegowe + +### 1️⃣ Czy mogę przetwarzać wielostronicowe PDFy? + +Tak. Użyj `ocr_engine.load_image("file.pdf")`, a następnie iteruj po każdej stronie za pomocą `ocr_engine.recognize(pdf_save_options, page_number)`. Biblioteka automatycznie wygeneruje wielostronicowy przeszukiwalny PDF. + +### 2️⃣ Co jeśli mój plik źródłowy to wysokiej rozdzielczości TIFF (300 dpi+)? + +Wyższe DPI zapewnia lepszą dokładność OCR, ale także większe zużycie pamięci. Jeśli napotkasz `MemoryError`, najpierw zmniejsz rozdzielczość obrazu: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Jak zmienić język OCR? + +Ustaw właściwość `language` w silniku przed załadowaniem obrazu: + +```python +ocr_engine.language = "fra" # French +``` + +Pełna lista obsługiwanych kodów językowych znajduje się w dokumentacji Aspose. + +### 4️⃣ Co jeśli muszę zachować oryginalną jakość obrazu? + +Klasa `PdfSaveOptions` posiada właściwość `compression`. Ustaw ją na `PdfCompression.None`, aby zachować dane rastrowe dokładnie tak, jak były. + +```python +pdf_save_options.compression = "None" +``` + +## Wskazówki dla wdrożeń gotowych do produkcji + +- **Przetwarzanie wsadowe:** Owiń główną logikę w funkcję przyjmującą listę ścieżek plików. Zapisuj każde powodzenie/porażkę do pliku CSV w celu audytu. +- **Równoległość:** Użyj `concurrent.futures.ThreadPoolExecutor`, aby uruchamiać OCR na wielu rdzeniach. Pamiętaj, że każdy wątek potrzebuje własnej instancji `OcrEngine`. +- **Bezpieczeństwo:** Jeśli przetwarzasz poufne dokumenty, uruchom skrypt w środowisku sandbox i usuń tymczasowe pliki natychmiast po przetworzeniu. + +## Zakończenie + +Teraz wiesz, jak **utworzyć przeszukiwalny PDF** z zeskanowanych obrazów przy użyciu zwięzłego skryptu w Pythonie. Inicjalizując silnik OCR, ładując TIFF (lub dowolny raster), konfigurując `PdfSaveOptions` do **add OCR text layer**, a na końcu wywołując `recognize`, cały pipeline **convert scanned image pdf** i **convert TIFF to PDF** staje się pojedynczym, powtarzalnym poleceniem. + +Kolejne kroki? Spróbuj połączyć ten skrypt z obserwatorem plików, aby każdy nowy skan umieszczony w folderze automatycznie stawał się przeszukiwalny. Albo eksperymentuj z różnymi językami OCR, aby obsługiwać wielojęzyczne archiwa. Nie ma ograniczeń, gdy łączysz OCR z generowaniem PDF. + +Masz więcej pytań o **how to run OCR** w innych językach lub frameworkach? zostaw komentarz poniżej i szczęśliwego kodowania! + +![Diagram pokazujący przepływ od zeskanowanego obrazu → silnika OCR → przeszukiwalnego PDF (create searchable pdf)](searchable-pdf-flow.png "Diagram przepływu tworzenia przeszukiwalnego pdf") + + +## Co powinieneś nauczyć się dalej? + +- [Jak wykonać OCR PDF w .NET z Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Konwertuj obrazy do PDF C# – Zapisz wynik OCR wielostronicowy](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Jak wykonać OCR tekstu obrazu z językiem przy użyciu Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/polish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7993b4112 --- /dev/null +++ b/ocr/polish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Popraw dokładność OCR w Pythonie, przetwarzając obrazy przed rozpoznawaniem. + Dowiedz się, jak wyodrębniać tekst z plików graficznych, rozpoznawać tekst z PNG + i zwiększać wyniki. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: pl +og_description: Popraw dokładność OCR w Pythonie, stosując wstępne przetwarzanie obrazu + dla tekstu. Skorzystaj z tego przewodnika, aby wyodrębnić tekst z plików graficznych + i bez wysiłku rozpoznać tekst z plików PNG. +og_title: Popraw dokładność OCR w Pythonie – pełny poradnik +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Popraw dokładność OCR w Pythonie – Kompletny przewodnik krok po kroku +url: /pl/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-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 krok po kroku + +Czy kiedykolwiek próbowałeś **poprawić dokładność OCR**, a otrzymałeś zniekształcony wynik? Nie jesteś sam. Większość programistów napotyka problem, gdy surowy obraz jest zaszumiony, pochyły lub po prostu ma niski kontrast. Dobra wiadomość? Kilka sztuczek wstępnego przetwarzania może zamienić rozmyty zrzut ekranu w czysty, maszynowo czytelny tekst. + +W tym samouczku przejdziemy przez rzeczywisty przykład, który **przetwarza obraz pod OCR**, uruchamia silnik rozpoznawania, a na końcu **wyodrębnia tekst z plików obrazu** — konkretnie z PNG. Po zakończeniu będziesz dokładnie wiedział, jak **rozpoznać tekst z PNG** z wyższym wskaźnikiem sukcesu i będziesz mieć gotowy fragment kodu, który możesz wkleić do dowolnego projektu. + +## Czego się nauczysz + +- Dlaczego wstępne przetwarzanie obrazu ma znaczenie dla silników OCR +- Które tryby wstępnego przetwarzania (denoise, deskew) dają największy przyrost +- Jak skonfigurować instancję `OcrEngine` w Pythonie +- Kompletny, gotowy do uruchomienia skrypt, który **wyodrębnia tekst z plików obrazu** +- Wskazówki dotyczące obsługi przypadków brzegowych, takich jak obrócone skany czy obrazy o niskiej rozdzielczości + +Nie są wymagane zewnętrzne biblioteki poza SDK OCR, ale potrzebujesz Pythona 3.8+ i obrazu PNG, który chcesz odczytać. + +--- + +![Diagram pokazujący kroki poprawy dokładności OCR w Pythonie](image.png "Workflow poprawy dokładności OCR") + +*Alt text: diagram workflowu poprawy dokładności OCR ilustrujący kroki wstępnego przetwarzania i rozpoznawania.* + +## Wymagania wstępne + +- Python 3.8 lub nowszy zainstalowany +- Dostęp do SDK OCR, które udostępnia `OcrEngine`, `OcrEngineSettings` oraz `ImagePreprocessMode` (poniższy kod używa ogólnego API; w razie potrzeby zamień na klasy swojego dostawcy) +- Obraz PNG (`input.png`) umieszczony w folderze, do którego możesz odwołać się w kodzie + +Jeśli używasz wirtualnego środowiska, aktywuj je teraz — nic skomplikowanego, po prostu `python -m venv venv && source venv/bin/activate`. + +--- + +## Krok 1: Utwórz instancję silnika OCR – Rozpocznij poprawę dokładności OCR + +Pierwszą rzeczą, której potrzebujesz, jest obiekt silnika OCR. Pomyśl o nim jak o mózgu, który później odczyta piksele i zwróci znaki. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Dlaczego to ważne: bez silnika nie możesz zastosować żadnego wstępnego przetwarzania, a surowy obraz zostanie podany bezpośrednio do rozpoznawacza — zazwyczaj najgorszy scenariusz pod względem dokładności. + +--- + +## Krok 2: Załaduj docelowy PNG – Przygotuj scenę do rozpoznania tekstu z PNG + +Teraz informujemy silnik, z którym plikiem ma pracować. PNG jest bezstratny, co już daje nam niewielką przewagę nad JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Jeśli obraz znajduje się w innym miejscu, po prostu dostosuj ścieżkę. Silnik akceptuje każdy obsługiwany format, ale PNG często zachowuje drobne szczegóły potrzebne do wyraźnych krawędzi znaków. + +--- + +## Krok 3: Skonfiguruj wstępne przetwarzanie – Preprocess Image for OCR + +Tutaj dzieje się magia. Tworzymy obiekt ustawień, włączamy odszumianie, aby usunąć plamki, i włączamy prostowanie, aby pochyły tekst został automatycznie wyrównany. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Dlaczego Denoise + Deskew? + +- **Denoise**: Losowy szum pikseli myli algorytmy dopasowujące wzorce. Usunięcie go wyostrza litery. +- **Deskew**: Nawet nachylenie o 2 stopnie może drastycznie obniżyć wyniki pewności. Prostowanie wyrównuje linię bazową, pozwalając rozpoznawaczowi lepiej dopasować czcionki. + +Możesz eksperymentować z dodatkowymi flagami (np. `ImagePreprocessMode.CONTRAST_ENHANCE`), jeśli Twoje obrazy są szczególnie ciemne. Dokumentacja SDK zazwyczaj wymienia wszystkie dostępne tryby. + +--- + +## Krok 4: Przypisz ustawienia do silnika – Połącz wstępne przetwarzanie z OCR + +Przypisz obiekt ustawień do silnika, aby kolejny przebieg rozpoznawania użył zdefiniowanych przez nas transformacji. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Jeśli pominiesz ten krok, silnik powróci do domyślnych ustawień (często „brak wstępnego przetwarzania”), a Ty zobaczysz **niższą dokładność OCR**. + +--- + +## Krok 5: Uruchom proces rozpoznawania – Extract Text from Image + +Po podłączeniu wszystkiego w końcu prosimy silnik o wykonanie zadania. Wywołanie jest synchroniczne i zwraca obiekt wyniku zawierający rozpoznany ciąg znaków. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +W tle silnik teraz: + +1. Ładuje PNG do pamięci +2. Stosuje odszumianie i prostowanie zgodnie z naszymi ustawieniami +3. Uruchamia sieć neuronową lub klasyczny dopasowywacz wzorców +4. Pakietuje wynik w `recognition_result` + +--- + +## Krok 6: Wyświetl rozpoznany tekst – Zweryfikuj poprawę + +Wypiszmy wyodrębniony ciąg. W rzeczywistej aplikacji możesz zapisać go do pliku, bazy danych lub przekazać do innej usługi. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Oczekiwany wynik + +Jeśli obraz zawiera zdanie „Hello, OCR World!”, powinieneś zobaczyć: + +``` +Hello, OCR World! +``` + +Zauważ, że tekst jest czysty — bez zbędnych znaków czy uszkodzonych liter. To rezultat prawidłowego **image preprocessing for text**. + +--- + +## Porady profesjonalne i przypadki brzegowe + +| Sytuacja | Co dostosować | Dlaczego | +|-----------|----------------|-----| +| Bardzo niska rozdzielczość PNG (≤ 72 dpi) | Dodaj `ImagePreprocessMode.SUPER_RESOLUTION`, jeśli jest dostępny | Upsampling może dać rozpoznawaczowi więcej pikseli do analizy | +| Tekst obrócony > 5° | Zwiększ tolerancję deskew lub ręcznie obróć obraz przy pomocy `Pillow` przed przekazaniem do silnika | Ekstremalne kąty czasem omijają automatyczne prostowanie | +| Intensywne wzory tła | Włącz `ImagePreprocessMode.BACKGROUND_REMOVAL` | Usuwa nie‑tekstowy szum, który mógłby zostać błędnie odczytany | +| Dokument wielojęzyczny | Ustaw `ocr_engine.language = "eng+spa"` (lub podobnie) | Silnik wybiera właściwy zestaw znaków, zwiększając ogólną dokładność | + +Pamiętaj, że **poprawa dokładności OCR** nie jest rozwiązaniem jednorazowym; może być konieczne iteracyjne dostosowywanie flag wstępnego przetwarzania dla Twojego konkretnego zestawu danych. + +--- + +## Pełny skrypt – Gotowy do skopiowania i wklejenia + +Poniżej znajduje się kompletny, gotowy do uruchomienia przykład, który zawiera wszystkie omówione kroki. Zapisz go jako `improve_ocr_accuracy.py` i uruchom poleceniem `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Uruchom go, obserwuj konsolę i od razu zobaczysz wynik **extract text from image**. Jeśli wynik wydaje się niepoprawny, dostosuj flagi `preprocess_mode` zgodnie z tabelą „Porady profesjonalne”. + +--- + +## Zakończenie + +Przeszliśmy razem praktyczny przepis na **poprawę dokładności OCR** przy użyciu Pythona. Tworząc `OcrEngine`, ładując PNG, **przetwarzając obraz pod OCR**, a na końcu **rozpoznając tekst z PNG**, możesz niezawodnie **wyodrębniać tekst z plików obrazu**, nawet gdy źródło nie jest idealne. + +Co dalej? Spróbuj przetworzyć wsadowo zestaw obrazów w pętli, zapisać każdy wynik w CSV lub poeksperymentować z dodatkowymi trybami wstępnego przetwarzania, takimi jak zwiększanie kontrastu. Ten sam schemat działa dla PDF‑ów, zeskanowanych paragonów czy odręcznych notatek — wystarczy zamienić wejście i dostosować ustawienia. + +Masz pytania dotyczące konkretnego typu obrazu lub chcesz wiedzieć, jak zintegrować to z usługą webową? Zostaw komentarz, a razem przeanalizujemy te scenariusze. Powodzenia w kodowaniu i niech Twoje wyniki OCR będą zawsze krystalicznie czyste! + +## Co warto nauczyć się dalej? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/polish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..aabd4aa56 --- /dev/null +++ b/ocr/polish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-31 +description: Poznaj, jak używać regionu zainteresowania OCR do wczytywania obrazu + i wyodrębniania tekstu z prostokąta, co jest idealne do rozpoznawania kwoty na fakturze. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: pl +og_description: Opanuj obszar zainteresowania OCR, aby wczytać obraz do OCR, wyodrębnić + tekst z prostokąta i rozpoznać tekst z faktury w jednym samouczku. +og_title: OCR – Obszar zainteresowania – Przewodnik krok po kroku w Pythonie +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Region of Interest – Wyodrębnij tekst z prostokąta w Pythonie +url: /pl/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Wyodrębnianie tekstu z prostokąta w Pythonie + +Zastanawiałeś się kiedyś, jak **ocr region of interest** konkretną część zeskanowanej faktury, nie przekazując całej strony do silnika? Nie jesteś pierwszym, który patrzy na rozmazany paragon i myśli: „Jak wyodrębnić kwotę, która znajduje się gdzieś w prawym dolnym rogu?” Dobra wiadomość jest taka, że możesz powiedzieć bibliotece OCR dokładnie, gdzie ma szukać, co znacząco zwiększa zarówno szybkość, jak i dokładność. + +W tym przewodniku przeprowadzimy Cię przez kompletny, gotowy do uruchomienia przykład, który pokaże, jak **load image for OCR**, zdefiniować **region of interest**, a następnie **extract text from rectangle**, aby w końcu **recognize text from invoice** i odpowiedzieć na klasyczne pytanie „jak wyodrębnić kwotę”. Bez niejasnych odniesień — tylko konkretny kod, jasne wyjaśnienia i kilka profesjonalnych wskazówek, które chciałbyś znać wcześniej. + +--- + +## Co zbudujesz + +Pod koniec tego samouczka będziesz mieć mały skrypt w Pythonie, który: + +1. Wczytuje obraz faktury z dysku. +2. Zaznacza prostokątny ROI, w którym znajduje się całkowita kwota. +3. Uruchamia OCR tylko w obrębie tego ROI. +4. Wyświetla oczyszczony ciąg kwoty. + +Wszystko to działa z dowolną biblioteką OCR obsługującą ROI — tutaj użyjemy fikcyjnego, ale reprezentatywnego pakietu `SimpleOCR`, który naśladuje popularne narzędzia takie jak Tesseract czy EasyOCR. Śmiało możesz go zamienić; koncepcje pozostają takie same. + +## Wymagania wstępne + +- Zainstalowany Python 3.8+ (`python --version` powinien wyświetlać ≥3.8). +- Pakiet OCR instalowalny przez pip (np. `pip install simpleocr`). +- Obraz faktury (PNG lub JPEG) umieszczony w folderze, do którego możesz odwołać się. +- Podstawowa znajomość funkcji i klas w Pythonie (nic skomplikowanego). + +Jeśli już je masz, świetnie — zanurzmy się. Jeśli nie, najpierw zdobądź obraz; pozostałe kroki są niezależne od rzeczywistej zawartości pliku. + +## Krok 1: Wczytaj obraz do OCR + +Pierwszą rzeczą, której potrzebuje każdy przepływ pracy OCR, jest bitmapa do odczytu. Większość bibliotek udostępnia prostą metodę `load_image`, przyjmującą ścieżkę do pliku. Oto jak to zrobić z naszym silnikiem `SimpleOCR`: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Używaj ścieżek bezwzględnych lub `os.path.join`, aby uniknąć niespodzianek „plik nie znaleziony” podczas uruchamiania skryptu z innego katalogu roboczego. + +## Krok 2: Zdefiniuj OCR Region of Interest + +Zamiast pozwalać silnikowi skanować całą stronę, mówimy mu *dokładnie*, gdzie znajduje się kwota. To jest krok **ocr region of interest** i jest kluczem do niezawodnego wyodrębniania, szczególnie gdy dokument zawiera zaszumione nagłówki lub stopki. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Dlaczego te liczby? `x` i `y` to przesunięcia w pikselach od lewego górnego rogu, natomiast `width` i `height` opisują rozmiar prostokąta. Jeśli nie jesteś pewien, otwórz obraz w dowolnym edytorze, włącz linijkę i zanotuj współrzędne. Wiele IDE pozwala nawet wyświetlić pozycję kursora podczas najechania. + +## Krok 3: Wyodrębnij tekst z prostokąta + +Teraz, gdy ROI jest ustawiony, prosimy silnik o **recognize text from invoice**, ale ograniczony do prostokąta, który właśnie dodaliśmy. Wywołanie zwraca obiekt wyniku, który zazwyczaj zawiera surowy ciąg znaków, oceny pewności i czasami ramki ograniczające. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Za kulisami, `recognize()` iteruje po każdym ROI, przycina ten fragment, uruchamia model OCR i łączy wyniki. Dlatego zdefiniowanie precyzyjnego regionu **extract text from rectangle** może zaoszczędzić sekundy czasu przetwarzania przy zadaniach wsadowych. + +## Krok 4: Jak wyodrębnić kwotę – Oczyść wynik + +OCR nie jest doskonały; często otrzymasz zbędne spacje, znaki nowej linii lub nawet błędnie odczytane znaki (np. „S” zamiast „5”). Szybkie `strip()` i małe wyrażenie regularne zazwyczaj rozwiązują problem dla wartości pieniężnych. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Dlaczego to ważne:** Jeśli planujesz wprowadzić kwotę do bazy danych lub bramki płatności, potrzebujesz przewidywalnego formatu. Usuwanie białych znaków i filtrowanie znaków nienumerycznych zapobiega błędom w dalszych etapach. + +## Krok 5: Recognize Text from Invoice – Pełny skrypt + +Łącząc wszystko razem, oto kompletny, gotowy do uruchomienia skrypt. Zapisz go jako `extract_amount.py` i uruchom `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Oczekiwany wynik + +``` +Amount: 1,245.67 +``` + +Jeśli ROI jest źle wyrównany, możesz zobaczyć coś w stylu `Amount: 1245.6S` — zauważ zbędne „S”. Dostosuj współrzędne prostokąta i uruchom ponownie, aż wynik będzie czysty. + +## Częste pułapki i przypadki brzegowe + +| Problem | Dlaczego się dzieje | Rozwiązanie | +|---------|----------------------|-------------| +| **ROI za mały** | Tekst kwoty zostaje obcięty, co prowadzi do częściowego rozpoznania. | Zwiększ `width`/`height` o ~10‑20 % i przetestuj ponownie. | +| **Nieprawidłowe DPI** | Skanowanie w niskiej rozdzielczości (≤150 dpi) obniża dokładność OCR. | Przeskaluj obraz do 300 dpi przed wczytaniem lub poproś skaner o wyższą rozdzielczość. | +| **Wiele walut** | Wyrażenie regularne wybiera pierwszą grupę liczbową, która może być numerem faktury. | Udoskonal wyrażenie regularne, aby szukało symboli walut (`$`, `€`, `£`) przed cyframi. | +| **Obrócone faktury** | Silniki OCR zakładają pionowy tekst; obrócone strony psują rozpoznawanie. | Zastosuj korekcję obrotu (`ocr_engine.rotate(90)`) przed dodaniem ROI. | +| **Szum w tle** | Cienie lub pieczęcie mylą model. | Wstępnie przetwórz obraz prostym progowaniem (`cv2.threshold`) lub użyj filtru odszumiającego. | + +Rozwiązywanie tych przypadków brzegowych już na początku zaoszczędzi Ci godziny debugowania później. + +## Porady dla projektów w rzeczywistym świecie + +- **Batch Processing:** Przetwarzaj pętlą folder z fakturami, obliczaj ROI dynamicznie (np. na podstawie wykrywania szablonu) i zapisuj wyniki w CSV. +- **Template Matching:** Jeśli obsługujesz kilka układów faktur, utrzymuj mapę JSON `template_id → ROI coordinates`. Zmieniaj ROI w oparciu o szybki klasyfikator układu. +- **Parallel Execution:** Użyj `concurrent.futures.ThreadPoolExecutor` do równoczesnego uruchamiania wielu instancji OCR — świetne dla wysokowolumenowych pipeline'ów back‑office. +- **Confidence Filtering:** Większość wyników OCR zawiera ocenę pewności. Odrzuć wyniki poniżej progu (np. 85 %) i oznacz je do ręcznej weryfikacji. + +## Zakończenie + +Omówiliśmy wszystko, co potrzebne, aby **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, a w końcu **recognize text from invoice**, aby odpowiedzieć na klasyczne pytanie **how to extract amount**. Skrypt jest zwięzły, a jednocześnie na tyle elastyczny, aby dostosować się do różnych formatów dokumentów, języków i backendów OCR. + +Teraz, gdy opanowałeś podstawy, rozważ rozszerzenie przepływu: dodaj skanowanie kodów kreskowych, zintegrować z parserem PDF lub przesłać wyodrębnioną kwotę do API księgowego. Nie ma ograniczeń, a przy dobrze zdefiniowanym ROI zawsze uzyskasz szybsze i czystsze wyniki. + +Jeśli napotkasz problem, zostaw komentarz poniżej — powodzenia w OCR! + +![przykład regionu zainteresowania OCR](https://example.com/ocr_roi_example.png "przykład regionu zainteresowania OCR") + + +## Co powinieneś nauczyć się dalej? + +- [Jak wyodrębnić tekst z obrazu, przygotowując prostokąty w OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Wyodrębnij tekst z obrazu w Java z Aspose.OCR Tryb wykrywania obszarów](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Wyodrębnij tekst 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/portuguese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/portuguese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..9c60536c5 --- /dev/null +++ b/ocr/portuguese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Tutorial de OCR assíncrono mostrando como usar o Aspose OCR em Python + com asyncio para extração rápida de texto em imagens. Aprenda a implementação de + OCR assíncrono passo a passo. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: pt +og_description: Tutorial de OCR assíncrono orienta você a usar o Aspose OCR em Python + com asyncio para extração eficiente de texto em imagens. +og_title: Tutorial de OCR Assíncrono – Python asyncio com Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Tutorial de OCR Assíncrono – Python asyncio com Aspose OCR +url: /pt/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial de OCR Assíncrono – Python asyncio com Aspose OCR + +Já se perguntou como executar reconhecimento óptico de caracteres sem bloquear sua aplicação? Em um **tutorial de OCR assíncrono** você verá exatamente isso — extração de texto sem bloqueio usando `asyncio` do Python e a biblioteca Aspose OCR. + +Se você está cansado de esperar uma imagem pesada ser processada, este guia oferece uma solução limpa e assíncrona que mantém seu loop de eventos ativo. + +Nas seções a seguir cobriremos tudo que você precisa: instalar a biblioteca, criar um helper assíncrono, tratar o resultado e até uma dica rápida para escalar para múltiplas imagens. Ao final, você poderá inserir um **tutorial de OCR assíncrono** em qualquer projeto Python que já use `asyncio`. + +## O que você precisará + +Antes de mergulharmos, certifique‑se de ter: + +* Python 3.9+ (a API `asyncio` que usamos é estável a partir da 3.7) +* Uma licença ativa do Aspose OCR ou um teste gratuito (a biblioteca é pura‑Python, sem binários nativos) +* Um pequeno arquivo de imagem (`.jpg`, `.png`, etc.) que você queira ler – mantenha‑o em uma pasta conhecida + +Nenhuma outra ferramenta externa é necessária; tudo roda em puro Python. + +## Etapa 1: Instalar o Pacote Aspose OCR + +Primeiro de tudo, obtenha o pacote Aspose OCR do PyPI. Abra um terminal e execute: + +```bash +pip install aspose-ocr +``` + +> **Dica profissional:** Se você estiver trabalhando dentro de um ambiente virtual (altamente recomendado), ative‑o primeiro. Isso mantém as dependências isoladas e evita conflitos de versão. + +## Etapa 2: Inicializar o Motor OCR de forma Assíncrona + +O coração do nosso **tutorial de OCR assíncrono** é uma função helper assíncrona. Ela cria uma instância de `OcrEngine`, carrega uma imagem e então chama `recognize_async()`. O motor em si é síncrono, mas o método wrapper devolve um awaitable, permitindo que o loop de eventos permaneça responsivo. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Por que fazemos assim:** +*Criar o motor dentro do helper garante segurança de thread caso você execute muitos trabalhos de OCR em paralelo mais tarde. A palavra‑chave `await` devolve o controle ao loop de eventos enquanto o processamento pesado ocorre no pool de threads interno da biblioteca.* + +## Etapa 3: Acionar o Helper a partir de uma Função Principal Assíncrona + +Agora precisamos de uma pequena coroutine `main()` que chama `async_ocr()` e imprime o resultado. Isso espelha o ponto de entrada típico para um script `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**O que está acontecendo nos bastidores?** +`asyncio.run()` cria um novo loop de eventos, agenda `main()` e encerra o loop de forma limpa quando `main()` termina. Esse padrão é a forma recomendada de iniciar programas assíncronos em Python 3.7+. + +## Etapa 4: Testar o Script Completo + +Salve os dois blocos de código acima em um único arquivo, por exemplo, `async_ocr_demo.py`. Execute-o a partir da linha de comando: + +```bash +python async_ocr_demo.py +``` + +Se tudo estiver configurado corretamente, você deverá ver algo como: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +A saída exata dependerá do conteúdo de `photo.jpg`. O ponto principal é que o script termina rapidamente, mesmo que a imagem seja grande, porque o trabalho de OCR acontece em segundo plano. + +## Etapa 5: Escalar – Processar Múltiplas Imagens Concorrentemente + +Uma pergunta comum de seguimento é: *“Posso fazer OCR em um lote de arquivos sem iniciar um novo processo para cada?”* Absolutamente. Como nosso helper é totalmente assíncrono, podemos agrupar muitas corrotinas com `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Por que isso funciona:** `asyncio.gather()` agenda todas as tarefas de OCR de uma vez. A biblioteca Aspose OCR subjacente ainda usa seu próprio pool de threads, mas do ponto de vista do Python tudo permanece não‑bloqueante, permitindo que você trate dezenas de imagens no tempo que levaria uma única chamada síncrona. + +## Etapa 6: Tratamento de Erros de Forma Elegante + +Ao trabalhar com arquivos externos, você inevitavelmente encontrará arquivos ausentes, imagens corrompidas ou problemas de licença. Envolva a chamada de OCR em um bloco `try/except` para manter o loop de eventos ativo: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Agora `batch_ocr()` pode chamar `safe_async_ocr` em vez disso, garantindo que um arquivo problemático não interrompa todo o lote. + +## Visão Geral Visual + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Fluxograma do tutorial de OCR assíncrono mostrando o helper async_ocr, loop de eventos e motor Aspose OCR"} + +O diagrama acima visualiza o fluxo: o loop de eventos → `async_ocr` → `OcrEngine` → thread em segundo plano → resultado de volta ao loop. + +## Armadilhas Comuns & Como Evitá‑las + +| Problema | Por que acontece | Correção | +|----------|------------------|----------| +| **I/O bloqueante dentro do helper** | Usar `open()` sem `await` pode bloquear o loop. | Use `aiofiles` para leituras de arquivos, ou deixe `engine.load_image` cuidar disso (já é não‑bloqueante). | +| **Reutilizar um único `OcrEngine` entre corrotinas** | O motor não é thread‑safe; chamadas concorrentes podem corromper o estado. | Instancie um novo motor dentro de cada chamada `async_ocr` (conforme mostrado). | +| **Licença ausente** | Aspose OCR lança exceção relacionada à licença em tempo de execução. | Registre sua licença cedo (`OcrEngine.set_license("license.json")`). | +| **Imagens grandes causando picos de memória** | A biblioteca carrega a imagem inteira na RAM. | Reduza a escala das imagens antes do OCR se a memória for um problema. | + +## Recapitulação: O que Conquistamos + +Neste **tutorial de OCR assíncrono** nós: + +1. Instalamos a biblioteca Aspose OCR. +2. Construímos um helper `async_ocr` que executa o reconhecimento sem bloquear. +3. Executamos o helper a partir de um ponto de entrada `asyncio` limpo. +4. Demonstramos processamento em lote com `asyncio.gather`. +5. Adicionamos tratamento de erros e dicas de boas práticas. + +Tudo isso é puro Python, então você pode inseri‑lo em um servidor web, uma ferramenta CLI ou um pipeline de dados sem reescrever código assíncrono existente. + +## Próximos Passos & Tópicos Relacionados + +* **Pré‑processamento de imagem assíncrono** – use `aiohttp` para baixar imagens concorrentemente antes do OCR. +* **Armazenamento dos resultados de OCR** – combine este tutorial com um driver de banco de dados assíncrono como `asyncpg` para PostgreSQL. +* **Ajuste de desempenho** – experimente `engine.recognize_async(max_threads=4)` se a biblioteca expuser essa opção. +* **Engines OCR alternativas** – compare Aspose OCR com wrappers assíncronos do Tesseract para uma análise custo‑benefício. + +Sinta‑se à vontade para experimentar: tente processar PDFs, ajuste as configurações de idioma ou conecte os resultados a um chatbot. O céu é o limite assim que você tem uma base sólida de **tutorial de OCR assíncrono**. + +Happy coding, and may your text extraction be ever swift! + +## O que Você Deve Aprender a Seguir? + +- [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/) +- [Tutorial Aspose OCR – Reconhecimento Óptico de Caracteres](/ocr/english/) +- [Como Fazer OCR de Texto em Imagem com Idioma Usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/portuguese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..9e5b2c0bc --- /dev/null +++ b/ocr/portuguese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Detecção automática de idioma em OCR facilitada. Aprenda como carregar + OCR de imagem, habilitar a detecção automática de idioma e reconhecer texto em imagem + em apenas alguns passos. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: pt +og_description: Detecção automática de idioma em OCR facilitada. Siga este tutorial + passo a passo para habilitar a detecção automática de idioma, carregar OCR de imagem + e reconhecer texto em imagens. +og_title: Detecção automática de idioma com OCR – Guia completo de Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Detecção automática de idioma com OCR – Guia completo de Python +url: /pt/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Detecção Automática de Idioma com OCR – Guia Completo em Python + +Já se perguntou como fazer um motor OCR *adivinhar* o idioma de um documento escaneado sem precisar dizer a ele o que procurar? É exatamente isso que a **detecção automática de idioma** faz, e é uma mudança total de jogo quando você lida com PDFs multilíngues, fotos de placas de rua ou qualquer imagem que mistura scripts. + +Neste tutorial vamos percorrer um exemplo prático que mostra como **ativar a detecção automática de idioma**, **carregar OCR de imagem** e **reconhecer texto da imagem** usando uma API estilo Python. Ao final, você terá um script autônomo que imprime tanto o código do idioma detectado quanto o texto extraído — sem necessidade de configurar idiomas manualmente. + +## O que você aprenderá + +- Como criar uma instância do motor OCR e ativar a **detecção automática de idioma**. +- Os passos exatos para **carregar OCR de imagem** a partir do disco. +- Como chamar o método `recognize()` do motor e obter um resultado que inclui o código do idioma. +- Dicas para lidar com casos extremos, como imagens de baixa resolução ou scripts não suportados. + +Não é necessária experiência prévia com OCR multilíngue; basta uma configuração básica de Python e um arquivo de imagem. + +--- + +## Pré‑requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +1. Python 3.8+ instalado (qualquer versão recente funciona). +2. A biblioteca OCR que fornece `OcrEngine`, `LanguageAutoDetectMode`, etc. – para este guia assumiremos um pacote hipotético chamado `myocr`. Instale‑o com: + + ```bash + pip install myocr + ``` + +3. Um arquivo de imagem (`multilingual_sample.png`) que contém texto em pelo menos dois idiomas diferentes. +4. Um pouco de curiosidade—se você nunca trabalhou com OCR antes, não se preocupe; o código foi feito deliberadamente simples. + +--- + +## Etapa 1: Ativar a Detecção Automática de Idioma + +A primeira coisa que você precisa fazer é dizer ao motor que ele deve *descobrir* o idioma por conta própria. É aqui que a bandeira de **detecção automática de idioma** entra em ação. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Por que isso importa:** +> Quando `AUTO_DETECT` está definido, o motor executa um classificador de idioma leve na imagem antes que o reconhecimento de caracteres pesado seja iniciado. Isso significa que você não precisa adivinhar se o texto está em inglês, russo, francês ou qualquer combinação desses. O motor escolherá automaticamente o melhor modelo de idioma para cada região da imagem. + +--- + +## Etapa 2: Carregar OCR de Imagem + +Agora que o motor sabe que deve detectar idiomas automaticamente, precisamos fornecer algo para ele trabalhar. A etapa **carregar OCR de imagem** lê o bitmap e prepara buffers internos. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Dica profissional:** +> Se sua imagem for maior que 300 dpi, considere reduzi‑la para cerca de 150‑200 dpi. Muito detalhe pode, na verdade, *lentificar* a fase de detecção de idioma sem melhorar a precisão. + +--- + +## Etapa 3: Reconhecer Texto da Imagem + +Com a imagem na memória e a detecção de idioma ativada, a última etapa é solicitar ao motor que **reconheça texto da imagem**. Esta única chamada realiza todo o trabalho pesado. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` é um objeto que normalmente contém ao menos dois atributos: + +| Atributo | Descrição | +|------------|-----------| +| `language` | Código ISO‑639‑1 do idioma detectado (ex.: `"en"` para Inglês). | +| `text` | A transcrição em texto puro da imagem. | + +--- + +## Etapa 4: Recuperar o Idioma Detectado e o Texto Extraído + +Agora simplesmente imprimimos o que o motor descobriu. Isso demonstra a capacidade de **detecção de idioma OCR** em ação. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Exemplo de saída** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **E se o motor retornar `None`?** +> Isso geralmente significa que a imagem está muito borrada ou o texto é muito pequeno (< 8 pt). Tente aumentar o contraste ou usar uma fonte de resolução mais alta. + +--- + +## Exemplo Completo Funcional (Ativar Detecção Automática de Idioma de ponta a ponta) + +Juntando tudo, aqui está um script pronto‑para‑executar que cobre **ativar detecção automática de idioma**, **carregar OCR de imagem**, **reconhecer texto da imagem** e **detecção de idioma OCR** de uma só vez. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Salve este como `automatic_language_detection_ocr.py`, substitua `YOUR_DIRECTORY` pela pasta que contém seu PNG, e execute: + +```bash +python automatic_language_detection_ocr.py +``` + +Você deverá ver o código do idioma seguido do texto extraído, exatamente como o exemplo de saída acima. + +--- + +## Lidando com Casos Limítrofes Comuns + +| Situação | Correção Sugerida | +|----------|-------------------| +| **Imagem de muito baixa resolução** (menos de 100 dpi) | Aumente com um filtro bicúbico antes de carregar, ou solicite uma fonte de maior resolução. | +| **Scripts misturados em uma imagem** (ex.: Inglês + Cirílico) | O motor geralmente divide a página em regiões; se notar detecções incorretas, defina `engine.enable_region_split = True`. | +| **Idioma não suportado** | Verifique se a biblioteca OCR inclui um pacote de idioma para o script que você precisa; pode ser necessário baixar modelos adicionais. | +| **Processamento em lote grande** | Inicialize o motor uma vez, então reutilize‑o em múltiplos ciclos `load_image` / `recognize` para evitar carregamento repetido de modelos. | + +--- + +## Visão Visual + +![exemplo de saída de detecção automática de idioma](https://example.com/auto-lang-detect.png "detecção automática de idioma") + +*Texto alternativo:* exemplo de saída de detecção automática de idioma mostrando o código do idioma detectado e o texto multilíngue extraído. + +--- + +## Conclusão + +Acabamos de cobrir a **detecção automática de idioma** do início ao fim — criando o motor, ativando a detecção automática de idioma, carregando uma imagem para OCR, reconhecendo o texto e, finalmente, recuperando o idioma detectado. Esse fluxo de ponta a ponta permite processar documentos multilíngues sem precisar configurar manualmente os modelos de idioma a cada vez. + +Se você está pronto para avançar, considere: + +- **Processamento em lote** de centenas de imagens com um loop que reutiliza a mesma instância `OcrEngine`. +- **Pós‑processamento** do texto extraído com um corretor ortográfico ou tokenizador específico de idioma. +- **Integração** do script em um serviço web que aceita uploads de usuários e retorna JSON com os campos `language` e `text`. + +Sinta‑se à vontade para experimentar diferentes formatos de imagem (`.jpg`, `.tif`) e observar como a precisão da detecção varia. Tem dúvidas ou uma imagem complicada que se recusa a ser lida? Deixe um comentário abaixo — feliz codificação! + +## O que você deve aprender a seguir? + +- [Como fazer OCR de texto em imagem com idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extrair texto de imagem em C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [reconhecer texto de imagem com Aspose OCR para múltiplos idiomas](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f14399329 --- /dev/null +++ b/ocr/portuguese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Aprenda a converter imagens em texto com Python usando um script de conversão + em lote de imagens para texto. Reconheça texto em imagens escaneadas com Aspose.OCR + em minutos. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: pt +og_description: Converta imagens em texto Python instantaneamente. Este guia mostra + a conversão em lote de imagens para texto e como reconhecer texto em imagens digitalizadas + com Aspose.OCR. +og_title: Converter Imagens em Texto Python – Tutorial Completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Converter Imagens em Texto com Python – Guia Completo Passo a Passo +url: /pt/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter Imagens em Texto Python – Guia Completo Passo a Passo + +Já se perguntou como **convert images to text python** sem precisar caçar dezenas de bibliotecas? Você não está sozinho. Seja digitalizando recibos antigos, extraindo dados de faturas escaneadas ou construindo um arquivo pesquisável de PDFs, transformar imagens em arquivos de texto simples é uma tarefa diária para muitos desenvolvedores. + +Neste tutorial, percorreremos um pipeline de **bulk image to text conversion** que reconhece texto em imagens escaneadas, salva cada resultado como um arquivo `.txt` individual e faz tudo isso com apenas algumas linhas de Python. Sem precisar procurar APIs obscuras — Aspose.OCR faz o trabalho pesado, e mostraremos exatamente como configurá‑lo. + +## O que você aprenderá + +- Como instalar e configurar o pacote Aspose.OCR for Python. +- O código exato necessário para **convert images to text python** usando o `BatchOcrEngine`. +- Dicas para lidar com armadilhas comuns, como formatos não suportados ou arquivos corrompidos. +- Maneiras de verificar se a etapa **recognize text from scanned images** realmente teve sucesso. + +Ao final deste guia, você terá um script pronto‑para‑executar que pode processar milhares de imagens de uma só vez — perfeito para qualquer cenário de processamento em lote. + +## Pré‑requisitos + +- Python 3.8+ instalado na sua máquina. +- Uma pasta de arquivos de imagem (PNG, JPEG, TIFF, etc.) que você deseja transformar em texto. +- Uma conta ativa do Aspose Cloud ou uma licença de teste gratuita (o nível gratuito é suficiente para testes). + +Se você tem tudo isso, vamos mergulhar. + +--- + +## Etapa 1 – Configurar seu Ambiente Python + +Antes de começarmos a escrever qualquer código OCR, certifique‑se de que está trabalhando dentro de um ambiente virtual limpo. Isso isola as dependências e evita conflitos de versão. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Dica profissional:** Mantenha seu diretório de projeto organizado — crie uma subpasta chamada `ocr_project` e coloque o script lá. Isso facilita o manuseio de caminhos mais tarde. + +## Etapa 2 – Instalar Aspose.OCR para Python + +Aspose.OCR é uma biblioteca comercial, mas vem com um wheel estilo NuGet gratuito que você pode obter do PyPI. Execute o comando a seguir dentro do ambiente virtual ativado: + +```bash +pip install aspose-ocr +``` + +Se encontrar um erro de permissão, adicione a flag `--user` ou execute o comando com `sudo` (apenas Linux/macOS). Após a instalação, você deverá ver algo como: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Por que Aspose?** Ao contrário de muitas ferramentas OCR de código aberto, Aspose.OCR suporta **bulk image to text conversion** pronto para uso e lida com uma ampla variedade de formatos de imagem sem configuração extra. Ele também oferece a classe `BatchOcrEngine` que torna a tarefa “convert images to text python” uma operação de uma única linha. + +## Etapa 3 – Converter Imagens em Texto Python com Batch OCR + +Agora, o coração do tutorial. Abaixo está um script totalmente executável que: + +1. Importa as classes do motor OCR. +2. Instancia um `BatchOcrEngine`. +3. Aponta o motor para uma pasta de entrada contendo imagens. +4. Direciona o motor a gravar cada arquivo de texto extraído em uma pasta de saída. +5. Executa o método `recognize()`, que **recognize text from scanned images** um por um. + +Salve o seguinte como `batch_ocr.py` dentro da sua pasta de projeto: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Como funciona + +- **`BatchOcrEngine`** encapsula o `OcrEngine` regular, mas adiciona orquestração ao nível de pasta, que é exatamente o que você precisa quando deseja **convert images to text python** em lote. +- A propriedade `input_folder` indica ao motor onde procurar as imagens de origem. Ele escaneia automaticamente o diretório e enfileira todos os tipos de arquivo suportados. +- A propriedade `output_folder` determina onde cada arquivo `.txt` será salvo. O motor replica o nome original do arquivo, de modo que `receipt1.png` se torna `receipt1.txt`. +- Chamar `recognize()` dispara o loop interno que carrega cada imagem, executa o OCR e grava o resultado. O método bloqueia até que todos os arquivos sejam processados, facilitando encadear ações adicionais (por exemplo, compactar a pasta de saída). + +#### Saída esperada + +Ao executar o script: + +```bash +python batch_ocr.py +``` + +Você deverá ver: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Dentro de `output_texts` você encontrará um arquivo de texto simples para cada imagem. Abra qualquer um deles com um editor de texto e verá o resultado bruto do OCR — geralmente uma aproximação próxima do texto impresso original. + +## Etapa 4 – Verificar os Resultados e Tratar Erros + +Mesmo os melhores motores OCR podem falhar em digitalizações de baixa resolução ou páginas muito inclinadas. Aqui está uma maneira rápida de validar a saída e registrar quaisquer falhas. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Por que adicionar isso?** +- Ele captura casos em que o motor produz silenciosamente uma string vazia (comum em imagens ilegíveis). +- Ele fornece uma lista de arquivos problemáticos para que você possa inspecioná‑los manualmente ou reexecutar com configurações diferentes (por exemplo, aumentar as opções `OcrEngine.preprocess`). + +### Casos de Borda & Ajustes + +| Situação | Correção Sugerida | +|-----------|----------------| +| Imagens estão rotacionadas 90° | Defina `batch_engine.ocr_engine.rotation_correction = True`. | +| Idiomas mistos (Inglês + Francês) | Use `batch_engine.ocr_engine.language = "eng+fra"` antes de `recognize()`. | +| PDFs enormes convertidos em imagens primeiro | Divida os PDFs em imagens de página única, então alimente a pasta ao batch engine. | +| Erros de memória em lotes muito grandes | Processar subpastas menores sequencialmente, ou aumentar `batch_engine.max_memory_usage`. | + +## Etapa 5 – Automatizar todo o fluxo de trabalho (Opcional) + +Se precisar executar esta conversão diariamente, envolva o script em um simples shell ou arquivo batch do Windows, e agende‑o com `cron` (Linux/macOS) ou Task Scheduler (Windows). Aqui está um `run_ocr.sh` minimalista para sistemas tipo Unix: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Torne‑o executável (`chmod +x run_ocr.sh`) e adicione uma entrada no cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Isso executa a conversão todos os dias às 2 AM e registra qualquer saída para revisão posterior. + +--- + +## Conclusão + +Agora você tem um método comprovado e pronto para produção para **convert images to text python** usando o `BatchOcrEngine` da Aspose.OCR. O script lida com **bulk image to text conversion**, grava cada resultado em um arquivo dedicado e inclui etapas de verificação para garantir que você realmente **recognize text from scanned images** corretamente. + +A partir daqui, você pode: + +- Experimentar diferentes configurações OCR (pacotes de idioma, correção de inclinação, redução de ruído). +- Encaminhar o texto gerado para um índice de busca como Elasticsearch para pesquisa de texto completo instantânea. +- Combinar este pipeline com ferramentas de conversão de PDF para processar PDFs escaneados de uma só vez. + +Tem perguntas ou encontrou algum problema com um tipo de arquivo específico? Deixe um comentário abaixo, e vamos solucionar juntos. Boa codificação, e que suas execuções de OCR sejam rápidas e sem erros! + +## O que você deve aprender a seguir? + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..69cb3021e --- /dev/null +++ b/ocr/portuguese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Crie uma instância de licença em Python e configure o caminho da licença + facilmente. Aprenda como configurar a licença do Aspose OCR com exemplos de código + claros. +draft: false +keywords: +- create license instance +- configure license path +language: pt +og_description: Crie uma instância de licença em Python e configure o caminho da licença + instantaneamente. Siga este tutorial para ativar o Aspose OCR com confiança. +og_title: Criar instância de licença em Python – Guia completo de configuração +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Criar instância de licença em Python – Guia passo a passo +url: /pt/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crie uma instância de licença em Python – Guia de Configuração Completa + +Precisa **criar uma instância de licença** para Aspose OCR em Python? Você está no lugar certo. Neste tutorial também mostraremos como **configurar o caminho da licença** para que o SDK saiba onde encontrar seu arquivo `.lic`. + +Se você já ficou encarando um script em branco se perguntando por que o motor de OCR continua reclamando de um produto sem licença, não está sozinho. A solução geralmente são apenas algumas linhas de código—uma vez que você saiba exatamente onde colocá‑las. Ao final deste guia você terá um ambiente Aspose OCR totalmente licenciado pronto para reconhecer texto, imagens e PDFs sem problemas. + +## O que você vai aprender + +- Como **criar uma instância de licença** usando o pacote `asposeocr`. +- A forma correta de **configurar o caminho da licença** tanto para desenvolvimento quanto para produção. +- Armadilhas comuns (arquivo ausente, permissões erradas) e como evitá‑las. +- Um script completo e executável que você pode inserir em qualquer projeto. + +Nenhuma experiência prévia com Aspose OCR é necessária, apenas uma instalação funcional do Python 3 e um arquivo de licença válido. + +--- + +## Etapa 1: Instale o Pacote Python Aspose OCR + +Antes de podermos **criar a instância de licença**, a biblioteca precisa estar presente. Abra um terminal e execute: + +```bash +pip install aspose-ocr +``` + +> **Dica profissional:** Se você estiver usando um ambiente virtual (altamente recomendado), ative‑o primeiro. Isso mantém suas dependências organizadas e evita conflitos de versão. + +## Etapa 2: Importe a Classe License + +Agora que o SDK está disponível, a primeira linha do seu script deve importar a classe `License`. Este é o objeto que usaremos para **criar a instância de licença**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Por que importá‑la imediatamente? Porque o objeto `License` deve ser instanciado **antes** de qualquer chamada ao OCR; caso contrário o SDK lançará um erro de licenciamento no momento em que você tentar processar uma imagem. + +## Etapa 3: Crie a Instância de Licença + +Aqui está o momento que você esperava—realmente **criar a instância de licença**. É uma única linha, mas o contexto ao redor importa. + +```python +# Step 3: Create a License instance +license = License() +``` + +A variável `license` agora contém um objeto que controla todo o comportamento de licenciamento para o processo Python atual. Pense nele como o guardião que diz ao Aspose OCR: “Ei, eu tenho permissão para executar.” + +## Etapa 4: Configure o Caminho da Licença + +Com a instância pronta, precisamos apontá‑la para o nosso arquivo `.lic`. É aqui que **configurar o caminho da licença** entra em ação. Substitua o placeholder pelo caminho absoluto do seu arquivo de licença. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Alguns pontos a observar: + +1. **Strings brutas (`r"…"`)** evitam que as barras invertidas sejam interpretadas como caracteres de escape no Windows. +2. Use um **caminho absoluto** para evitar confusões quando o script for iniciado a partir de um diretório de trabalho diferente. +3. Se preferir um caminho relativo (por exemplo, ao empacotar a licença com seu projeto), certifique‑se de que a base relativa seja a localização do script, não o diretório atual do shell. + +### Tratamento de Arquivos Ausentes + +Se o caminho estiver errado ou o arquivo for ilegível, `set_license` lançará uma exceção. Envolva a chamada em um bloco `try/except` para exibir uma mensagem de erro amigável: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Este trecho **configura o caminho da licença** de forma segura e informa exatamente o que deu errado—sem rastros de pilha misteriosos. + +## Etapa 5: Verifique se a Licença está Ativa + +Uma verificação rápida de sanidade economiza horas de depuração depois. Depois de chamar `set_license`, tente uma operação simples de OCR. Se a licença for válida, o SDK processará a imagem sem lançar um erro de licenciamento. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Se o texto reconhecido for impresso, parabéns—você **criou a instância de licença** e **configurou o caminho da licença** com sucesso. Se receber uma exceção de licenciamento, verifique novamente o caminho e as permissões do arquivo. + +## Casos de Borda & Melhores Práticas + +| Situação | O que fazer | +|-----------|------------| +| **Arquivo de licença em um compartilhamento de rede** | Mapeie o compartilhamento para uma letra de unidade ou use um caminho UNC (`\\server\share\license.lic`). Garanta que o processo Python tenha acesso de leitura. | +| **Executando dentro de um contêiner Docker** | Copie o arquivo `.lic` para a imagem e referencie‑o com um caminho absoluto como `/app/license/Aspose.OCR.Java.lic`. | +| **Múltiplos interpretadores Python** (ex.: ambientes conda) | Instale o arquivo de licença uma vez por ambiente ou mantenha um local central e aponte cada interpretador para ele. | +| **Arquivo de licença ausente em tempo de execução** | Recorra graciosamente a um modo de avaliação (se suportado) ou interrompa com uma mensagem de log clara. | + +### Armadilhas Comuns + +- **Usar barras normais no Windows** – Python aceita, mas algumas versões mais antigas do SDK podem interpretá‑las incorretamente. Prefira strings brutas ou barras duplas invertidas. +- **Esquecer de importar `License`** – O script falhará com `NameError`. Sempre importe antes de instanciar. +- **Chamar `set_license` após métodos de OCR** – O SDK verifica a licença na primeira utilização, então defina o caminho **primeiro**. + +## Exemplo Completo em Funcionamento + +Abaixo está um script completo que une tudo. Salve como `ocr_setup.py` e execute-o a partir da linha de comando. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Saída esperada** (supondo uma imagem válida): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Se o arquivo de licença não for encontrado, você verá uma mensagem de erro clara em vez de uma exceção enigmática “License not found”. + +--- + +## Conclusão + +Agora você sabe exatamente como **criar uma instância de licença** em Python e **configurar o caminho da licença** para o SDK Aspose OCR. Os passos são simples: instalar o pacote, importar `License`, instanciá‑la, apontar para seu arquivo `.lic` e verificar com um pequeno teste de OCR. + +Com esse conhecimento, você pode incorporar recursos de OCR em serviços web, aplicativos desktop ou pipelines automatizados sem tropeçar em erros de licenciamento. Em seguida, considere explorar configurações avançadas de OCR—pacotes de idioma, pré‑processamento de imagens ou processamento em lote—cada um construído sobre a base sólida que você acabou de estabelecer. + +Tem dúvidas sobre implantação, Docker ou gerenciamento de múltiplas licenças? Deixe um comentário, e feliz codificação! + +## O que você deve aprender a seguir? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..72465ebcd --- /dev/null +++ b/ocr/portuguese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Crie PDF pesquisável a partir de imagens escaneadas usando OCR em Python. + Aprenda como converter PDF de imagem escaneada, converter TIFF para PDF e adicionar + camada de texto OCR em minutos. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: pt +og_description: Crie PDF pesquisável instantaneamente. Este guia mostra como executar + OCR, converter PDF de imagem escaneada e adicionar camada de texto OCR usando um + único script Python. +og_title: Criar PDF pesquisável com Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Criar PDF pesquisável com Python – Guia passo a passo +url: /pt/python-java/general/create-searchable-pdf-with-python-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 com Python – Guia passo a passo + +Já se perguntou como **criar PDF pesquisável** a partir de uma página escaneada sem lidar com dezenas de ferramentas? Você não está sozinho. Em muitos fluxos de trabalho de escritório, um TIFF ou JPEG escaneado chega a uma unidade compartilhada, e a pessoa seguinte precisa copiar‑colar o texto manualmente — doloroso, propenso a erros e desperdiça tempo. + +Neste tutorial vamos percorrer uma solução limpa e programática que permite **converter PDF de imagem escaneada**, **converter TIFF para PDF** e **adicionar camada de texto OCR** de uma só vez. Ao final, você terá um script pronto‑para‑usar que executa OCR, incorpora o texto oculto e gera um PDF pesquisável que pode ser indexado, buscado ou compartilhado com confiança. + +## O que você precisará + +- Python 3.9+ (qualquer versão recente funciona) +- Pacotes `aspose-ocr` e `aspose-pdf` (instalados via `pip install aspose-ocr aspose-pdf`) +- Um arquivo de imagem escaneada (`.tif`, `.png`, `.jpg` ou até mesmo uma página PDF que seja apenas uma imagem) +- Uma quantidade modesta de RAM (o motor OCR é leve; até um laptop lida com ele) + +> **Dica profissional:** Se você estiver no Windows, a maneira mais fácil de obter os pacotes é executar o comando em uma janela do PowerShell elevada. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Agora que os pré‑requisitos foram resolvidos, vamos mergulhar no código. + +## Etapa 1: Criar uma Instância do Motor OCR – *create searchable pdf* + +A primeira coisa que fazemos é iniciar o motor OCR. Pense nele como o cérebro que lerá cada pixel e o transformará em caracteres. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Por que isso importa:** Inicializar o motor apenas uma vez mantém o uso de memória baixo. Se você chamar `OcrEngine()` dentro de um loop para cada página, rapidamente ficará sem recursos. + +## Etapa 2: Carregar a Imagem Escaneada – *convert tiff to pdf* & *convert scanned image pdf* + +Em seguida, aponte o motor para o arquivo que deseja processar. A API aceita qualquer imagem raster, então um TIFF funciona tão bem quanto um JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Se você tiver um PDF que contém apenas uma imagem escaneada, ainda pode usar `load_image` porque o Aspose extrairá a primeira página automaticamente. + +## Etapa 3: Configurar Opções de Salvamento de PDF – *add OCR text layer* + +Aqui configuramos como o PDF final deve ficar. O parâmetro crucial é `create_searchable_pdf`; defini‑lo como `True` indica à biblioteca que incorpore uma camada de texto invisível que espelha o conteúdo visual. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **O que a camada de texto faz:** Quando você abre o arquivo resultante no Adobe Reader e tenta selecionar texto, verá os caracteres ocultos. Os mecanismos de busca também podem indexá‑los — perfeito para conformidade ou arquivamento. + +## Etapa 4: Executar OCR e Salvar – *how to run OCR* in a single call + +Agora a mágica acontece. Uma única chamada de método executa o motor de reconhecimento e grava o PDF pesquisável no disco. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +O método `recognize` devolve um objeto de status que você pode inspecionar para erros, mas na maioria dos cenários simples a chamada acima é suficiente. + +### Saída esperada + +Executar o script imprime: + +``` +PDF saved as searchable PDF. +``` + +Se você abrir `scanned_page_searchable.pdf` perceberá que pode selecionar texto, copiar‑colar e até executar uma busca `Ctrl+F`. Esse é o marco de um fluxo **create searchable pdf**. + +## Script completo em funcionamento + +Abaixo está o script completo, pronto‑para‑executar. Basta substituir os caminhos de placeholder pelos caminhos reais dos seus arquivos. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Salve isso como `create_searchable_pdf.py` e execute: + +```bash +python create_searchable_pdf.py +``` + +## Perguntas comuns & casos de borda + +### 1️⃣ Posso processar PDFs de múltiplas páginas? + +Sim. Use `ocr_engine.load_image("file.pdf")` e então faça um loop sobre cada página com `ocr_engine.recognize(pdf_save_options, page_number)`. A biblioteca gerará automaticamente um PDF pesquisável de várias páginas. + +### 2️⃣ E se meu arquivo de origem for um TIFF de alta resolução (300 dpi+)? + +DPI mais alto gera melhor precisão de OCR, mas também maior uso de memória. Se você encontrar um `MemoryError`, reduza a escala da imagem primeiro: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Como altero o idioma do OCR? + +Defina a propriedade `language` no motor antes de carregar a imagem: + +```python +ocr_engine.language = "fra" # French +``` + +Uma lista completa de códigos de idioma suportados está na documentação da Aspose. + +### 4️⃣ E se eu precisar manter a qualidade original da imagem? + +A classe `PdfSaveOptions` possui a propriedade `compression`. Defina‑a como `PdfCompression.None` para preservar os dados raster exatamente como estavam. + +```python +pdf_save_options.compression = "None" +``` + +## Dicas para implantações prontas para produção + +- **Processamento em lote:** Envolva a lógica principal em uma função que aceita uma lista de caminhos de arquivos. Registre cada sucesso/falha em um CSV para trilhas de auditoria. +- **Paralelismo:** Use `concurrent.futures.ThreadPoolExecutor` para executar OCR em múltiplos núcleos. Apenas lembre‑se de que cada thread precisa de sua própria instância `OcrEngine`. +- **Segurança:** Se você estiver lidando com documentos sensíveis, execute o script em um ambiente sandbox e exclua os arquivos temporários imediatamente após o processamento. + +## Conclusão + +Agora você sabe como **criar PDF pesquisável** a partir de imagens escaneadas usando um script Python conciso. Ao inicializar um motor OCR, carregar um TIFF (ou qualquer raster), configurar `PdfSaveOptions` para **add OCR text layer** e, finalmente, chamar `recognize`, todo o pipeline **convert scanned image pdf** e **convert TIFF to PDF** se torna um único comando repetível. + +Próximos passos? Experimente encadear este script com um observador de arquivos para que qualquer nova digitalização deixada em uma pasta se torne automaticamente pesquisável. Ou experimente diferentes idiomas de OCR para suportar arquivos multilíngues. O céu é o limite quando você combina OCR com geração de PDF. + +Tem mais perguntas sobre **how to run OCR** em outras linguagens ou frameworks? Deixe um comentário abaixo e feliz codificação! + +![Diagrama mostrando o fluxo de imagem escaneada → motor OCR → PDF pesquisável (create searchable pdf)](searchable-pdf-flow.png "Diagrama de fluxo criar PDF pesquisável") + + +## O que você deve aprender a seguir? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/portuguese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c1feb3445 --- /dev/null +++ b/ocr/portuguese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-31 +description: Melhore a precisão do OCR com Python ao pré‑processar imagens para OCR. + Aprenda como extrair texto de arquivos de imagem, reconhecer texto em PNG e aprimorar + os resultados. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: pt +og_description: Melhore a precisão do OCR em Python aplicando pré‑processamento de + imagens para texto. Siga este guia para extrair texto de arquivos de imagem e reconhecer + texto de PNG sem esforço. +og_title: Melhore a Precisão do OCR em Python – Tutorial Completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Melhore a Precisão do OCR em Python – Guia Completo Passo a Passo +url: /pt/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Melhorar a Precisão do OCR em Python – Guia Completo Passo a Passo + +Já tentou **melhorar a precisão do OCR** e acabou obtendo uma saída confusa? Você não está sozinho. A maioria dos desenvolvedores esbarra quando a imagem bruta está ruidosa, inclinada ou simplesmente com baixo contraste. A boa notícia? Algumas técnicas de pré‑processamento podem transformar uma captura de tela borrada em texto limpo e legível por máquina. + +Neste tutorial vamos percorrer um exemplo real que **pré‑processa uma imagem para OCR**, executa o motor de reconhecimento e, finalmente, **extrai texto de arquivos de imagem** — especificamente um PNG. Ao final, você saberá exatamente como **reconhecer texto de PNG** com uma taxa de sucesso maior e terá um trecho de código reutilizável que pode ser inserido em qualquer projeto. + +## O que você vai aprender + +- Por que o pré‑processamento de imagem importa para motores de OCR +- Quais modos de pré‑processamento (denoise, deskew) dão o maior impulso +- Como configurar uma instância `OcrEngine` em Python +- O script completo e executável que **extrai texto de arquivos de imagem** +- Dicas para lidar com casos extremos como digitalizações rotacionadas ou imagens de baixa resolução + +Nenhuma biblioteca externa além do OCR SDK é necessária, mas você precisará do Python 3.8+ e de uma imagem PNG que deseja ler. + +--- + +![Diagrama mostrando etapas para melhorar a precisão do OCR em Python](image.png "Fluxo de trabalho para melhorar a precisão do OCR") + +*Alt text: diagrama do fluxo de trabalho para melhorar a precisão do OCR ilustrando etapas de pré‑processamento e reconhecimento.* + +## Pré‑requisitos + +- Python 3.8 ou mais recente instalado +- Acesso ao OCR SDK que fornece `OcrEngine`, `OcrEngineSettings` e `ImagePreprocessMode` (o código abaixo usa uma API genérica; substitua pelas classes do seu fornecedor, se necessário) +- Uma imagem PNG (`input.png`) colocada em uma pasta que você possa referenciar + +Se estiver usando um ambiente virtual, ative‑o agora — nada complicado, apenas `python -m venv venv && source venv/bin/activate`. + +--- + +## Etapa 1: Criar a Instância do Motor OCR – Comece a Melhorar a Precisão do OCR + +A primeira coisa que você precisa é um objeto de motor OCR. Pense nele como o cérebro que mais tarde lerá os pixels e gerará caracteres. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Por que isso importa: sem um motor você não pode aplicar nenhum pré‑processamento, e a imagem bruta será enviada diretamente ao reconhecedor — geralmente o pior cenário para a precisão. + +--- + +## Etapa 2: Carregar o PNG de Destino – Prepare o Cenário para Reconhecer Texto de PNG + +Agora informamos ao motor qual arquivo ele deve processar. PNG é sem perdas, o que já nos dá uma pequena vantagem sobre JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Se a imagem estiver em outro local, basta ajustar o caminho. O motor aceita qualquer formato suportado, mas PNG costuma preservar os detalhes finos necessários para bordas de caracteres nítidas. + +--- + +## Etapa 3: Configurar o Pré‑processamento – Pré‑processar Imagem para OCR + +É aqui que a mágica acontece. Criamos um objeto de configurações, habilitamos a remoção de ruído para eliminar manchas e ativamos o deskew para que texto inclinado seja endireitado automaticamente. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Por que Denoise + Deskew? + +- **Denoise**: Ruído aleatório de pixels confunde algoritmos de correspondência de padrões. Removê‑lo aguça as letras. +- **Deskew**: Mesmo uma inclinação de 2 graus pode reduzir drasticamente as pontuações de confiança. O deskew alinha a linha de base, permitindo que o reconhecedor combine fontes de forma mais confiável. + +Você pode experimentar flags adicionais (por exemplo, `ImagePreprocessMode.CONTRAST_ENHANCE`) se suas imagens forem especialmente escuras. A documentação do SDK normalmente lista todos os modos disponíveis. + +--- + +## Etapa 4: Aplicar as Configurações ao Motor – Vincular Pré‑processamento ao OCR + +Atribua o objeto de configurações ao motor para que a próxima execução de reconhecimento use as transformações que definimos. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Se pular esta etapa, o motor voltará ao padrão (geralmente “sem pré‑processamento”), e você verá **menor precisão do OCR**. + +--- + +## Etapa 5: Executar o Processo de Reconhecimento – Extrair Texto da Imagem + +Com tudo conectado, finalmente pedimos ao motor que faça seu trabalho. A chamada é síncrona, retornando um objeto de resultado que contém a string reconhecida. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Nos bastidores, o motor agora: + +1. Carrega o PNG na memória +2. Aplica denoise e deskew com base nas nossas configurações +3. Executa a rede neural ou o matcher clássico de padrões +4. Empacota a saída em `recognition_result` + +--- + +## Etapa 6: Exibir o Texto Reconhecido – Verificar a Melhoria + +Vamos imprimir a string extraída. Em uma aplicação real você pode gravá‑la em um arquivo, em um banco de dados ou enviá‑la para outro serviço. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Saída Esperada + +Se a imagem contiver a frase “Hello, OCR World!” você deverá ver: + +``` +Hello, OCR World! +``` + +Observe como o texto está limpo — sem símbolos estranhos ou caracteres quebrados. Esse é o resultado de um **pré‑processamento de imagem adequado para texto**. + +--- + +## Dicas Pro & Casos de Borda + +| Situação | O que Ajustar | Por quê | +|-----------|----------------|-----| +| PNG de muito baixa resolução (≤ 72 dpi) | Adicionar `ImagePreprocessMode.SUPER_RESOLUTION` se disponível | O upsampling pode fornecer ao reconhecedor mais pixels para trabalhar | +| Texto rotacionado > 5° | Aumentar a tolerância do deskew ou rotacionar manualmente com `Pillow` antes de enviar ao motor | Ângulos extremos às vezes escapam do deskew automático | +| Padrões de fundo intensos | Habilitar `ImagePreprocessMode.BACKGROUND_REMOVAL` | Remove ruído não textual que seria lido incorretamente | +| Documento multilíngue | Definir `ocr_engine.language = "eng+spa"` (ou similar) | O motor escolhe o conjunto de caracteres correto, melhorando a precisão geral | + +Lembre‑se, **melhorar a precisão do OCR** não é uma solução única para todos; pode ser necessário iterar nas flags de pré‑processamento para o seu conjunto de dados específico. + +--- + +## Script Completo – Pronto para Copiar & Colar + +Abaixo está o exemplo completo e executável que incorpora cada passo que discutimos. Salve como `improve_ocr_accuracy.py` e execute com `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Execute, observe o console, e você verá o resultado de **extrair texto da imagem** imediatamente. Se a saída parecer incorreta, ajuste as flags `preprocess_mode` conforme descrito na tabela “Dicas Pro”. + +--- + +## Conclusão + +Acabamos de percorrer uma receita prática para **melhorar a precisão do OCR** usando Python. Ao criar um `OcrEngine`, carregar um PNG, **pré‑processar a imagem para OCR**, e finalmente **reconhecer texto de PNG**, você pode extrair texto de arquivos de imagem de forma confiável mesmo quando a fonte não é perfeita. + +Próximos passos? Tente processar um lote de imagens em um loop, armazenar cada resultado em um CSV, ou experimentar modos adicionais de pré‑processamento como aumento de contraste. O mesmo padrão funciona para PDFs, recibos escaneados ou notas manuscritas — basta trocar a entrada e ajustar as configurações. + +Tem perguntas sobre um tipo específico de imagem ou quer saber como integrar isso a um serviço web? Deixe um comentário, e exploraremos esses cenários juntos. Boa codificação, e que seus resultados de OCR sejam sempre cristalinos! + + +## O que você deve aprender a seguir? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/portuguese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..63571756f --- /dev/null +++ b/ocr/portuguese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Aprenda a usar a região de interesse de OCR para carregar a imagem e + extrair texto de um retângulo, perfeito para reconhecer o valor em uma fatura. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: pt +og_description: Domine a região de interesse do OCR para carregar a imagem, extrair + texto de um retângulo e reconhecer o texto de uma fatura em um único tutorial. +og_title: OCR Região de Interesse – Guia Python Passo a Passo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Região de Interesse – Extrair Texto de um Retângulo em Python +url: /pt/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Região de Interesse de OCR – Extrair Texto de um Retângulo em Python + +Já se perguntou como **ocr region of interest** uma parte específica de uma nota fiscal digitalizada sem alimentar a página inteira no motor? Você não é o primeiro a encarar um recibo borrado e pensar: “Como extrair o valor que está em algum lugar no canto inferior direito?” A boa notícia é que você pode dizer à biblioteca de OCR exatamente onde olhar, aumentando drasticamente a velocidade e a precisão. + +Neste guia vamos percorrer um exemplo completo e executável que mostra como **load image for OCR**, definir uma **region of interest**, e então **extract text from rectangle** para, finalmente, **recognize text from invoice** e responder à clássica pergunta “como extrair o valor”. Sem referências vagas — apenas código concreto, explicações claras e algumas dicas profissionais que você desejará ter conhecido antes. + +--- + +## O que Você Vai Construir + +Ao final deste tutorial você terá um pequeno script Python que: + +1. Carrega uma imagem de nota fiscal do disco. +2. Marca um ROI retangular onde o valor total está localizado. +3. Executa OCR apenas dentro desse ROI. +4. Imprime a string do valor já limpa. + +Tudo isso funciona com qualquer biblioteca de OCR que suporte ROI — aqui usaremos um pacote fictício, porém representativo, `SimpleOCR` que imita ferramentas populares como Tesseract ou EasyOCR. Sinta‑se à vontade para substituí‑lo; os conceitos permanecem os mesmos. + +--- + +## Pré‑requisitos + +- Python 3.8+ instalado (`python --version` deve mostrar ≥3.8). +- Um pacote de OCR instalável via pip (ex.: `pip install simpleocr`). +- Uma imagem de nota fiscal (PNG ou JPEG) colocada em uma pasta que você possa referenciar. +- Familiaridade básica com funções e classes Python (nada sofisticado). + +Se você já tem tudo isso, ótimo — vamos mergulhar. Caso contrário, obtenha a imagem primeiro; o resto das etapas é independente do conteúdo real do arquivo. + +--- + +## Etapa 1: Load Image for OCR + +A primeira coisa que qualquer fluxo de OCR precisa é um bitmap para ler. A maioria das bibliotecas expõe um método simples `load_image` que aceita um caminho de arquivo. Veja como fazer isso com o nosso motor `SimpleOCR`: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Use caminhos absolutos ou `os.path.join` para evitar surpresas de “arquivo não encontrado” ao executar o script a partir de um diretório de trabalho diferente. + +--- + +## Etapa 2: Definir OCR Region of Interest + +Em vez de deixar o motor escanear a página inteira, dizemos a ele *exatamente* onde o valor está. Esta é a etapa **ocr region of interest**, e é a chave para uma extração confiável, especialmente quando o documento contém cabeçalhos ou rodapés ruidosos. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Por que esses números? `x` e `y` são deslocamentos em pixels a partir do canto superior esquerdo, enquanto `width` e `height` descrevem o tamanho da caixa. Se estiver em dúvida, abra a imagem em qualquer editor, habilite uma régua e anote as coordenadas. Muitas IDEs até permitem imprimir a posição do cursor ao passar o mouse. + +--- + +## Etapa 3: Extract Text from Rectangle + +Agora que o ROI está definido, pedimos ao motor para **recognize text from invoice** limitado ao retângulo que acabamos de adicionar. A chamada retorna um objeto de resultado que normalmente contém a string bruta, pontuações de confiança e, às vezes, caixas delimitadoras. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Nos bastidores, `recognize()` itera sobre cada ROI, recorta aquela fatia, executa o modelo de OCR e junta os resultados. É por isso que definir uma região **extract text from rectangle** bem ajustada pode economizar segundos no tempo de processamento de trabalhos em lote. + +--- + +## Etapa 4: Como Extrair o Valor – Limpar a Saída + +OCR não é perfeito; você frequentemente obterá espaços extras, quebras de linha ou até caracteres lidos incorretamente (pense em “S” vs “5”). Um rápido `strip()` e uma regex pequena geralmente resolvem valores monetários. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Por que isso importa:** Se você pretende inserir o valor em um banco de dados ou em um gateway de pagamento, precisa de um formato previsível. Remover espaços em branco e filtrar caracteres não numéricos evita erros posteriores. + +--- + +## Etapa 5: Recognize Text from Invoice – Script Completo + +Juntando tudo, aqui está o script completo, pronto para ser executado. Salve como `extract_amount.py` e execute `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Saída Esperada + +``` +Amount: 1,245.67 +``` + +Se o ROI estiver desalinhado, você pode ver algo como `Amount: 1245.6S` — note o “S” solto. Ajuste as coordenadas do retângulo e execute novamente até que a saída esteja limpa. + +--- + +## Armadilhas Comuns & Casos de Borda + +| Problema | Por que Acontece | Solução | +|----------|------------------|---------| +| **ROI muito pequeno** | O texto do valor fica cortado, levando a reconhecimento parcial. | Expanda `width`/`height` em ~10‑20 % e teste novamente. | +| **DPI incorreto** | Digitalizações de baixa resolução (≤150 dpi) reduzem a precisão do OCR. | Reamostre a imagem para 300 dpi antes de carregar, ou solicite ao scanner uma DPI maior. | +| **Múltiplas moedas** | A regex captura o primeiro grupo numérico, que pode ser o número da nota. | Refine a regex para procurar símbolos de moeda (`$`, `€`, `£`) antes dos dígitos. | +| **Faturas rotacionadas** | Motores de OCR assumem texto vertical; páginas rotacionadas quebram o reconhecimento. | Aplique correção de rotação (`ocr_engine.rotate(90)`) antes de adicionar o ROI. | +| **Ruído de fundo** | Sombras ou carimbos confundem o modelo. | Pré‑processar com um simples limiar (`cv2.threshold`) ou usar um filtro de redução de ruído. | + +Abordar esses casos de borda cedo salva horas de depuração depois. + +--- + +## Dicas Profissionais para Projetos Reais + +- **Processamento em Lote:** Percorra uma pasta de faturas, calcule o ROI dinamicamente (ex.: com base em detecção de modelo) e armazene os resultados em CSV. +- **Correspondência de Modelo:** Se você lida com vários layouts de fatura, mantenha um mapa JSON de `template_id → coordenadas do ROI`. Troque o ROI com base em um classificador rápido de layout. +- **Execução Paralela:** Use `concurrent.futures.ThreadPoolExecutor` para rodar múltiplas instâncias de OCR simultaneamente — ótimo para pipelines de back‑office de alto volume. +- **Filtragem por Confiança:** A maioria dos resultados de OCR inclui uma pontuação de confiança. Descarte resultados abaixo de um limiar (ex.: 85 %) e marque‑os para revisão manual. + +--- + +## Conclusão + +Cobrimos tudo o que você precisa para **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, e finalmente **recognize text from invoice** para responder à clássica pergunta **how to extract amount**. O script é compacto, mas flexível o suficiente para se adaptar a diferentes formatos de documento, idiomas e back‑ends de OCR. + +Agora que você dominou o básico, considere estender o fluxo: adicione leitura de código de barras, integre com um parser de PDF ou envie o valor extraído para uma API contábil. O céu é o limite, e com um ROI bem definido você sempre obterá resultados mais rápidos e limpos. + +Se encontrar algum problema, deixe um comentário abaixo — boa extração de OCR! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## O que Você Deve Aprender a Seguir? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/russian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/russian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..3e53b6515 --- /dev/null +++ b/ocr/russian/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Асинхронный учебник по OCR, показывающий, как использовать Aspose OCR + в Python с asyncio для быстрого извлечения текста из изображений. Изучите пошаговую + реализацию асинхронного OCR. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: ru +og_description: Асинхронный учебник по OCR покажет, как использовать Aspose OCR в + Python с asyncio для эффективного извлечения текста из изображений. +og_title: Асинхронный OCR‑урок — Python asyncio с Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Асинхронный OCR‑урок – Python asyncio с Aspose OCR +url: /ru/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Асинхронный OCR‑урок – Python asyncio с Aspose OCR + +Задумывались когда‑нибудь, как выполнять оптическое распознавание символов, не блокируя приложение? В **асинхронном OCR‑уроке** вы увидите именно это — неблокирующее извлечение текста с помощью `asyncio` в Python и библиотеки Aspose OCR. + +Если вы устали ждать, пока будет обработано тяжёлое изображение, это руководство предлагает чистое асинхронное решение, которое держит ваш цикл событий в рабочем состоянии. + +В последующих разделах мы рассмотрим всё, что вам понадобится: установку библиотеки, создание асинхронного вспомогательного метода, обработку результата и даже быстрый совет по масштабированию на несколько изображений. К концу вы сможете внедрить **асинхронный OCR‑урок** в любой Python‑проект, уже использующий `asyncio`. + +## Что понадобится + +* Python 3.9+ (API `asyncio`, которое мы используем, стабильно с версии 3.7) +* Действующая лицензия Aspose OCR или бесплатный пробный период (библиотека написана полностью на Python, без нативных бинарных файлов) +* Небольшой файл изображения (`.jpg`, `.png` и т.п.), который вы хотите прочитать — разместите его в известной папке + +Никаких других внешних инструментов не требуется; всё работает в чистом Python. + +## Шаг 1: Установите пакет Aspose OCR + +Сначала получим пакет Aspose OCR из PyPI. Откройте терминал и выполните: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Если вы работаете внутри виртуального окружения (настоятельно рекомендуется), сначала активируйте его. Это изолирует зависимости и предотвращает конфликты версий. + +## Шаг 2: Инициализируйте OCR‑движок асинхронно + +Сердцем нашего **асинхронного OCR‑урока** является асинхронная вспомогательная функция. Она создаёт экземпляр `OcrEngine`, загружает изображение и затем вызывает `recognize_async()`. Сам движок синхронный, но обёртка возвращает awaitable, позволяя циклу событий оставаться отзывчивым. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Почему мы делаем так:** +*Создание движка внутри вспомогательной функции обеспечивает потокобезопасность, если позже вы запустите множество OCR‑задач параллельно. Ключевое слово `await` передаёт управление обратно циклу событий, пока тяжёлая работа происходит во внутреннем пуле потоков библиотеки.* + +## Шаг 3: Запустите вспомогательную функцию из асинхронной основной функции + +Теперь нам нужен небольшой корутин `main()`, который вызывает `async_ocr()` и выводит результат. Это отражает типичную точку входа для скрипта `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Что происходит под капотом?** +`asyncio.run()` создаёт новый цикл событий, планирует выполнение `main()` и корректно завершает цикл, когда `main()` заканчивает работу. Этот шаблон рекомендуется для запуска асинхронных программ в Python 3.7+. + +## Шаг 4: Протестируйте полный скрипт + +Сохраните два приведённых выше блока кода в один файл, например `async_ocr_demo.py`. Запустите его из командной строки: + +```bash +python async_ocr_demo.py +``` + +Если всё настроено правильно, вы увидите что‑то вроде: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Точный вывод будет зависеть от содержимого `photo.jpg`. Главное, что скрипт завершается быстро, даже если изображение большое, потому что работа OCR происходит в фоновом режиме. + +## Шаг 5: Масштабирование — обработка нескольких изображений одновременно + +Распространённый последующий вопрос: *«Могу ли я распознать пакет файлов без запуска нового процесса для каждого?»* Конечно. Поскольку наш вспомогательный метод полностью асинхронный, мы можем собрать множество корутин с помощью `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Почему это работает:** `asyncio.gather()` планирует все задачи OCR сразу. Подлежащая библиотека Aspose OCR всё равно использует собственный пул потоков, но с точки зрения Python всё остаётся неблокирующим, позволяя обрабатывать десятки изображений за то время, которое занял бы один синхронный вызов. + +## Шаг 6: Обработка ошибок без сбоев + +Работая с внешними файлами, вы неизбежно столкнётесь с отсутствующими файлами, повреждёнными изображениями или проблемами лицензии. Оберните вызов OCR в блок `try/except`, чтобы цикл событий оставался живым: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Теперь `batch_ocr()` может вызывать `safe_async_ocr` вместо обычного, гарантируя, что один плохой файл не прервет всю партию. + +## Визуальный обзор + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Схема потока async OCR tutorial, показывающая вспомогательную функцию async_ocr, цикл событий и движок Aspose OCR"} + +Диаграмма выше визуализирует поток: цикл событий → `async_ocr` → `OcrEngine` → фоновый поток → результат возвращается в цикл. + +## Распространённые подводные камни и как их избежать + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| **Блокирующий ввод‑вывод внутри вспомогательной функции** | Случайное использование `open()` без `await` может заблокировать цикл. | Используйте `aiofiles` для чтения файлов, либо позвольте `engine.load_image` выполнить это (он уже неблокирующий). | +| **Повторное использование одного `OcrEngine` в разных корутинах** | Движок не потокобезопасен; параллельные вызовы могут испортить состояние. | Создавайте новый движок внутри каждого вызова `async_ocr` (как показано). | +| **Отсутствующая лицензия** | Aspose OCR бросает исключение, связанное с лицензией, во время выполнения. | Зарегистрируйте лицензию заранее (`OcrEngine.set_license("license.json")`). | +| **Большие изображения вызывают всплеск памяти** | Библиотека загружает всё изображение в ОЗУ. | Снизьте разрешение изображений перед OCR, если память ограничена. | + +## Итоги: Что мы достигли + +В этом **асинхронном OCR‑уроке** мы: + +1. Установили библиотеку Aspose OCR. +2. Создали вспомогательную функцию `async_ocr`, которая выполняет распознавание без блокировки. +3. Запустили вспомогательную функцию из чистой точки входа `asyncio`. +4. Продемонстрировали пакетную обработку с помощью `asyncio.gather`. +5. Добавили обработку ошибок и рекомендации по лучшим практикам. + +Всё это написано на чистом Python, поэтому вы можете внедрить его в веб‑сервер, CLI‑утилиту или конвейер данных без переписывания существующего асинхронного кода. + +## Следующие шаги и связанные темы + +* **Асинхронная предобработка изображений** – используйте `aiohttp` для одновременной загрузки изображений перед OCR. +* **Сохранение результатов OCR** – комбинируйте этот урок с асинхронным драйвером базы данных, например `asyncpg` для PostgreSQL. +* **Тонкая настройка производительности** – поэкспериментируйте с `engine.recognize_async(max_threads=4)`, если библиотека предоставляет такую опцию. +* **Альтернативные OCR‑движки** – сравните Aspose OCR с асинхронными обёртками Tesseract для оценки стоимости и выгоды. + +Не стесняйтесь экспериментировать: пробуйте обрабатывать PDF, меняйте языковые настройки или интегрируйте результаты в чат‑бот. Возможности безграничны, как только у вас будет надёжная **асинхронная OCR‑база**. + +Счастливого кодинга, и пусть извлечение текста будет всегда быстрым! + +## Что изучать дальше? + +- [Извлечение текста из изображения с Aspose OCR – пошаговое руководство](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [Как распознать текст на изображении с учётом языка, используя Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/russian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..ef80cc646 --- /dev/null +++ b/ocr/russian/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Автоматическое определение языка в OCR стало простым. Узнайте, как загрузить + изображение для OCR, включить автоматическое определение языка и распознать текст + на изображении всего за несколько шагов. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: ru +og_description: Автоматическое определение языка в OCR стало простым. Следуйте этому + пошаговому руководству, чтобы включить автоматическое определение языка, загрузить + изображение для OCR и распознать текст на изображении. +og_title: Автоматическое определение языка с помощью OCR – Полное руководство по Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Автоматическое определение языка с помощью OCR – Полное руководство по Python +url: /ru/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Автоматическое определение языка с помощью OCR – Полное руководство на Python + +Когда‑то задумывались, как заставить OCR‑движок *угадать* язык отсканированного документа, не указывая ему, что искать? Именно это делает **автоматическое определение языка**, и это настоящий прорыв, когда вы работаете с многоязычными PDF, фотографиями уличных знаков или любыми изображениями, где смешаны разные письменности. + +В этом руководстве мы пошагово пройдем пример, показывающий, как **включить автоопределение языка**, **загрузить изображение для OCR** и **распознать текст на изображении** с помощью API в стиле Python. К концу вы получите автономный скрипт, который выводит как код обнаруженного языка, так и извлечённый текст — без необходимости вручную задавать язык. + +## Что вы узнаете + +- Как создать экземпляр OCR‑движка и включить **автоматическое определение языка**. +- Точные шаги для **загрузки изображения OCR** с диска. +- Как вызвать метод `recognize()` движка и получить результат, включающий код языка. +- Советы по обработке граничных случаев, таких как изображения низкого разрешения или неподдерживаемые письменности. + +Предыдущий опыт работы с многоязычным OCR не требуется; достаточно базовой настройки Python и файла изображения. + +--- + +## Предварительные требования + +Прежде чем начать, убедитесь, что у вас есть: + +1. Установлен Python 3.8+ (подойдёт любая современная версия). +2. Библиотека OCR, предоставляющая `OcrEngine`, `LanguageAutoDetectMode` и т.д. — в этом руководстве будем предполагать гипотетический пакет `myocr`. Установите его командой: + + ```bash + pip install myocr + ``` + +3. Файл изображения (`multilingual_sample.png`), содержащий текст минимум на двух разных языках. +4. Немного любопытства — если вы никогда не работали с OCR, не переживайте; код предельно прост. + +--- + +## Шаг 1: Включить автоматическое определение языка + +Первое, что нужно сделать, — сообщить движку, что он должен *сам* определить язык. Здесь вступает в силу флаг **автоматического определения языка**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Почему это важно:** +> Когда установлен `AUTO_DETECT`, движок запускает лёгкий классификатор языка на изображении до того, как начнётся тяжёлая часть распознавания символов. Это значит, что вам не придётся угадывать, английский это, русский, французский или их комбинация. Движок автоматически выберет лучшую языковую модель для каждой области изображения. + +--- + +## Шаг 2: Загрузить изображение для OCR + +Теперь, когда движок знает, что должен автоопределять язык, нужно предоставить ему материал для работы. Шаг **загрузки изображения OCR** читает битмап и подготавливает внутренние буферы. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Совет:** +> Если ваше изображение имеет разрешение более 300 dpi, рассмотрите возможность его уменьшения до примерно 150‑200 dpi. Слишком много деталей может *замедлить* этап определения языка без повышения точности. + +--- + +## Шаг 3: Распознать текст на изображении + +С изображением в памяти и включённым определением языка остаётся лишь попросить движок **распознать текст изображения**. Этот один вызов делает всю тяжёлую работу. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` — объект, который обычно содержит как минимум два атрибута: + +| Атрибут | Описание | +|----------|----------| +| `language` | ISO‑639‑1 код обнаруженного языка (например, `"en"` для английского). | +| `text` | Текстовая транскрипция изображения. | + +--- + +## Шаг 4: Получить обнаруженный язык и извлечённый текст + +Теперь просто выведем то, что обнаружил движок. Это демонстрирует работу **detect language OCR** в действии. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Пример вывода** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Что делать, если движок возвращает `None`?** +> Обычно это означает, что изображение слишком размыто или текст слишком мелкий (< 8 pt). Попробуйте увеличить контраст или использовать источник с более высоким разрешением. + +--- + +## Полный рабочий пример (Включение автоматического определения языка от начала до конца) + +Объединив всё вместе, получаем готовый к запуску скрипт, покрывающий **enable auto language detection**, **load image OCR**, **recognize text image** и **detect language OCR** в одном процессе. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Сохраните его как `automatic_language_detection_ocr.py`, замените `YOUR_DIRECTORY` на папку, где находится ваш PNG, и запустите: + +```bash +python automatic_language_detection_ocr.py +``` + +Вы увидите код языка, за которым следует извлечённый текст, как в примере вывода выше. + +--- + +## Обработка типовых граничных случаев + +| Ситуация | Предлагаемое решение | +|----------|----------------------| +| **Очень низкое разрешение изображения** (менее 100 dpi) | Увеличьте масштаб с помощью бикубического фильтра перед загрузкой или запросите источник с более высоким разрешением. | +| **Смешанные письменности в одном изображении** (например, английский + кириллица) | Движок обычно разбивает страницу на регионы; если замечаете ошибки, установите `engine.enable_region_split = True`. | +| **Неподдерживаемый язык** | Убедитесь, что библиотека OCR поставляется с языковым пакетом для нужной письменности; при необходимости скачайте дополнительные модели. | +| **Обработка больших пакетов** | Инициализируйте движок один раз, а затем переиспользуйте его для нескольких циклов `load_image` / `recognize`, чтобы избежать повторной загрузки моделей. | + +--- + +## Визуальный обзор + +![automatic language detection example output](https://example.com/auto-lang-detect.png "automatic language detection") + +*Alt text:* пример вывода автоматического определения языка, показывающий код обнаруженного языка и извлечённый многоязычный текст. + +--- + +## Заключение + +Мы прошли весь процесс **автоматического определения языка** от создания движка, включения автоопределения, загрузки изображения для OCR, распознавания текста и получения обнаруженного языка. Этот сквозной поток позволяет обрабатывать многоязычные документы без ручной настройки языковых моделей каждый раз. + +Если хотите пойти дальше, рассмотрите: + +- **Пакетную обработку** сотен изображений с помощью цикла, переиспользующего один экземпляр `OcrEngine`. +- **Постобработку** извлечённого текста с помощью проверяющего орфографию или языко‑специфичного токенизатора. +- **Интеграцию** скрипта в веб‑сервис, принимающий загрузки от пользователей и возвращающий JSON с полями `language` и `text`. + +Экспериментируйте с разными форматами изображений (`.jpg`, `.tif`) и наблюдайте, как меняется точность определения. Есть вопросы или «упрямое» изображение, которое отказывается читаться? Оставляйте комментарий ниже — happy coding! + +## Что изучать дальше? + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/russian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f24661b24 --- /dev/null +++ b/ocr/russian/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Узнайте, как конвертировать изображения в текст на Python с помощью скрипта + массовой конвертации изображений в текст. Распознавайте текст со сканированных изображений + с помощью Aspose.OCR за считанные минуты. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: ru +og_description: Конвертировать изображения в текст на Python мгновенно. Это руководство + показывает массовое преобразование изображений в текст и как распознавать текст + со сканированных изображений с помощью Aspose.OCR. +og_title: Конвертация изображений в текст на Python – Полный учебник +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Преобразование изображений в текст на Python – Полное пошаговое руководство +url: /ru/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Преобразование изображений в текст Python – Полное пошаговое руководство + +Когда‑то задумывались, как **convert images to text python** без бесконечного поиска библиотек? Вы не одиноки. Будь то оцифровка старых чеков, извлечение данных из отсканированных счетов‑фактур или создание поискового архива PDF‑файлов, преобразование картинок в обычный текст — ежедневная задача для многих разработчиков. + +В этом руководстве мы пройдём через конвейер **bulk image to text conversion**, который распознаёт текст со сканированных изображений, сохраняет каждый результат в отдельный файл `.txt` и делает всё это всего несколькими строками кода на Python. Никаких скрытых API — Aspose.OCR делает всю тяжёлую работу, а мы покажем, как правильно его подключить. + +## Что вы узнаете + +- Как установить и настроить пакет Aspose.OCR for Python. +- Точный код, необходимый для **convert images to text python** с использованием `BatchOcrEngine`. +- Советы по работе с распространёнными проблемами, такими как неподдерживаемые форматы или повреждённые файлы. +- Способы проверить, что шаг **recognize text from scanned images** действительно завершился успешно. + +К концу этого руководства у вас будет готовый к запуску скрипт, способный обработать тысячи изображений за один проход — идеальное решение для любого сценария пакетной обработки. + +## Предварительные требования + +- Python 3.8+ установленный на вашем компьютере. +- Папка с изображениями (PNG, JPEG, TIFF и т.д.), которые вы хотите превратить в текст. +- Активный аккаунт Aspose Cloud или бесплатная пробная лицензия (бесплатный уровень достаточен для тестов). + +Если всё это у вас есть, приступим. + +--- + +## Шаг 1 – Настройте окружение Python + +Прежде чем писать любой код OCR, убедитесь, что работаете в чистом виртуальном окружении. Это изолирует зависимости и предотвращает конфликты версий. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Держите каталог проекта аккуратным — создайте подпапку `ocr_project` и разместите скрипт там. Это упростит работу с путями позже. + +## Шаг 2 – Установите Aspose.OCR for Python + +Aspose.OCR — коммерческая библиотека, но она поставляется с бесплатным wheel‑пакетом в стиле NuGet, который можно установить из PyPI. Выполните следующую команду в активированном виртуальном окружении: + +```bash +pip install aspose-ocr +``` + +Если возникла ошибка доступа, добавьте флаг `--user` или запустите команду с `sudo` (только Linux/macOS). После установки вы должны увидеть что‑то вроде: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Почему Aspose?** В отличие от многих открытых OCR‑инструментов, Aspose.OCR поддерживает **bulk image to text conversion** «из коробки» и работает с широким спектром форматов изображений без дополнительной настройки. Кроме того, он предоставляет класс `BatchOcrEngine`, который делает задачу **convert images to text python** одно‑строчным вызовом. + +## Шаг 3 – Convert Images to Text Python с помощью Batch OCR + +Теперь к сердцу руководства. Ниже полностью рабочий скрипт, который: + +1. Импортирует классы OCR‑движка. +2. Создаёт экземпляр `BatchOcrEngine`. +3. Указывает движку входную папку с изображениями. +4. Задаёт папку вывода, куда будут записаны текстовые файлы. +5. Вызывает метод `recognize()`, который **recognize text from scanned images** по одному. + +Сохраните следующее как `batch_ocr.py` в папке проекта: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Как это работает + +- **`BatchOcrEngine`** оборачивает обычный `OcrEngine`, добавляя оркестрацию на уровне папок — именно то, что нужно для **convert images to text python** в массовом режиме. +- Свойство `input_folder` указывает движку, где искать исходные изображения. Он автоматически сканирует каталог и ставит в очередь каждый поддерживаемый тип файла. +- Свойство `output_folder` определяет, куда сохранять каждый файл `.txt`. Движок сохраняет оригинальное имя файла, так что `receipt1.png` станет `receipt1.txt`. +- Вызов `recognize()` запускает внутренний цикл, который загружает каждое изображение, выполняет OCR и записывает результат. Метод блокирует выполнение, пока не обработаются все файлы, что упрощает последующие действия (например, архивирование выходной папки). + +#### Ожидаемый вывод + +При запуске скрипта: + +```bash +python batch_ocr.py +``` + +Вы увидите: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +В папке `output_texts` появится обычный текстовый файл для каждого изображения. Откройте любой из них в текстовом редакторе — вы увидите «сырой» результат OCR, обычно близкий к оригинальному печатному тексту. + +## Шаг 4 – Проверка результатов и обработка ошибок + +Даже лучший OCR‑движок может «споткнуться» на низкокачественных сканах или сильно искажённых страницах. Ниже простой способ проверить вывод и записать любые сбои. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Зачем это нужно?** +- Выявляет случаи, когда движок молча возвращает пустую строку (часто происходит с нечитаемыми изображениями). +- Даёт список проблемных файлов, чтобы вы могли вручную проверить их или пере‑запустить с другими настройками (например, увеличить параметры `OcrEngine.preprocess`). + +### Пограничные случаи и настройки + +| Ситуация | Предлагаемое решение | +|-----------|----------------------| +| Изображения повернуты на 90° | Установите `batch_engine.ocr_engine.rotation_correction = True`. | +| Несколько языков (английский + французский) | Перед `recognize()` задайте `batch_engine.ocr_engine.language = "eng+fra"`. | +| Большие PDF‑файлы, сначала преобразованные в изображения | Разбейте PDF на одностраничные изображения, затем передайте папку в batch‑engine. | +| Ошибки памяти при очень больших пакетах | Обрабатывайте меньшие подпапки последовательно или увеличьте `batch_engine.max_memory_usage`. | + +## Шаг 5 – Автоматизация всего процесса (по желанию) + +Если требуется выполнять конвертацию каждую ночь, оберните скрипт в простой shell‑скрипт или Windows‑batch файл и запланируйте его через `cron` (Linux/macOS) или Планировщик задач (Windows). Ниже минимальный `run_ocr.sh` для Unix‑подобных систем: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Сделайте его исполняемым (`chmod +x run_ocr.sh`) и добавьте запись в cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Это будет запускать конвертацию каждый день в 2 AM и сохранять любой вывод в лог для последующего анализа. + +--- + +## Заключение + +Теперь у вас есть проверенный, готовый к продакшну способ **convert images to text python** с использованием `BatchOcrEngine` из Aspose.OCR. Скрипт осуществляет **bulk image to text conversion**, аккуратно сохраняет каждый результат в отдельный файл и включает шаги проверки, чтобы убедиться, что вы действительно **recognize text from scanned images** корректно. + +Дальше вы можете: + +- Поэкспериментировать с различными настройками OCR (языковые пакеты, исправление наклона, подавление шума). +- Передать сгенерированный текст в поисковый индекс, например Elasticsearch, для мгновенного полнотекстового поиска. +- Скомбинировать этот конвейер с инструментами конвертации PDF, чтобы обрабатывать отсканированные PDF‑файлы за один проход. + +Есть вопросы или столкнулись с проблемой конкретного типа файла? Оставьте комментарий ниже, и мы разберёмся вместе. Приятного кодинга, и пусть ваши OCR‑запуски будут быстрыми и безошибочными! + +## Что изучать дальше? + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/russian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..776fdaab1 --- /dev/null +++ b/ocr/russian/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Создайте экземпляр лицензии в Python и легко настройте путь к лицензии. + Узнайте, как настроить лицензирование Aspose OCR с понятными примерами кода. +draft: false +keywords: +- create license instance +- configure license path +language: ru +og_description: Создайте экземпляр лицензии в Python и мгновенно настройте путь к + лицензии. Следуйте этому руководству, чтобы уверенно активировать Aspose OCR. +og_title: Создание экземпляра лицензии в Python — Полное руководство по настройке +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Создание экземпляра лицензии в Python – пошаговое руководство +url: /ru/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создать экземпляр лицензии в Python – Полное руководство по настройке + +Need to **create license instance** for Aspose OCR in Python? You’re in the right spot. In this tutorial we’ll also show you how to **configure license path** so the SDK knows where to find your `.lic` file. + +Если вы когда‑нибудь смотрели на пустой скрипт, задаваясь вопросом, почему движок OCR продолжает жаловаться на отсутствие лицензии, вы не одиноки. Исправление обычно состоит всего из нескольких строк кода — как только вы знаете, куда их вставить. К концу этого руководства у вас будет полностью лицензированная среда Aspose OCR, готовая распознавать текст, изображения и PDF без проблем. + +## Что вы узнаете + +- Как **create license instance** с использованием пакета `asposeocr`. +- Правильный способ **configure license path** для разработки и продакшна. +- Распространённые подводные камни (отсутствующий файл, неправильные разрешения) и как их избежать. +- Полный, исполняемый скрипт, который можно добавить в любой проект. + +Предыдущий опыт работы с Aspose OCR не требуется, нужен лишь рабочий Python 3 и действующий файл лицензии. + +--- + +## Шаг 1: Установить пакет Aspose OCR для Python + +Прежде чем мы сможем **create license instance**, сама библиотека должна быть установлена. Откройте терминал и выполните: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Если вы используете виртуальное окружение (настоятельно рекомендуется), сначала активируйте его. Это поддерживает порядок в зависимостях и предотвращает конфликты версий. + +## Шаг 2: Импортировать класс License + +Теперь, когда SDK доступен, первая строка вашего скрипта должна импортировать класс `License`. Это объект, который мы будем использовать для **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Зачем импортировать его сразу? Потому что объект `License` должен быть создан **до** любых вызовов OCR; иначе SDK выдаст ошибку лицензирования в момент попытки обработать изображение. + +## Шаг 3: Создать экземпляр лицензии + +Вот момент, которого вы ждали — фактически **create license instance**. Это одна строка, но контекст имеет значение. + +```python +# Step 3: Create a License instance +license = License() +``` + +Переменная `license` теперь содержит объект, контролирующий все лицензирующие действия текущего процесса Python. Считайте её стражем, который говорит Aspose OCR: «Эй, у меня есть право работать». + +## Шаг 4: Настроить путь к лицензии + +С готовым экземпляром нам нужно указать ему наш файл `.lic`. Здесь и вступает в действие **configure license path**. Замените заполнитель абсолютным путём к вашему файлу лицензии. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Несколько замечаний: + +1. **Raw strings (`r"…"`)** предотвращают интерпретацию обратных слешей как управляющих символов в Windows. +2. Используйте **absolute path**, чтобы избежать путаницы, когда скрипт запускается из другой рабочей директории. +3. Если вы предпочитаете относительный путь (например, при включении лицензии в ваш проект), убедитесь, что базовый относительный путь — это расположение скрипта, а не текущая директория оболочки. + +### Обработка отсутствующих файлов + +Если путь неверен или файл недоступен для чтения, `set_license` вызовет исключение. Оберните вызов в блок `try/except`, чтобы вывести понятное сообщение об ошибке: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Этот фрагмент **configures license path** безопасно и сообщает точно, что пошло не так — без загадочных трассировок стека. + +## Шаг 5: Проверить, что лицензия активна + +Быстрая проверка спасает часы отладки позже. После вызова `set_license` попробуйте простую OCR‑операцию. Если лицензия действительна, SDK обработает изображение без ошибки лицензирования. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Если вы видите распечатанный распознанный текст, поздравляем — вы успешно **create license instance** и **configure license path**. Если возникло исключение лицензии, дважды проверьте путь и права доступа к файлу. + +## Особые случаи и лучшие практики + +| Ситуация | Что делать | +|-----------|------------| +| **License file lives in a network share** | Смонтировать общий ресурс в букву диска или использовать UNC‑путь (`\\server\share\license.lic`). Убедитесь, что процесс Python имеет права чтения. | +| **Running inside a Docker container** | Скопировать файл `.lic` в образ и ссылаться на него через абсолютный путь, например `/app/license/Aspose.OCR.Java.lic`. | +| **Multiple Python interpreters** (e.g., conda envs) | Установить файл лицензии один раз для каждой среды или хранить его в центральном месте и указывать каждому интерпретатору путь к нему. | +| **License file missing at runtime** | Корректно переключиться в режим пробной версии (если поддерживается) или завершить работу с чётким сообщением в логе. | + +### Распространённые подводные камни + +- **Using forward slashes on Windows** – Python принимает их, но некоторые старые версии SDK могут их неправильно интерпретировать. Используйте raw‑строки или двойные обратные слеши. +- **Forgot to import `License`** – Скрипт упадёт с `NameError`. Всегда импортируйте перед созданием экземпляра. +- **Calling `set_license` after OCR methods** – SDK проверяет лицензию при первом использовании, поэтому указывайте путь **сначала**. + +## Полный рабочий пример + +Ниже полный скрипт, объединяющий всё. Сохраните его как `ocr_setup.py` и запустите из командной строки. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Ожидаемый вывод** (при наличии корректного изображения): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Если файл лицензии не найден, вы увидите чёткое сообщение об ошибке вместо загадочного исключения «License not found». + +--- + +## Заключение + +Теперь вы точно знаете, как **create license instance** в Python и **configure license path** для Aspose OCR SDK. Шаги просты: установить пакет, импортировать `License`, создать его экземпляр, указать путь к вашему файлу `.lic` и проверить с помощью небольшого OCR‑теста. + +Обладая этими знаниями, вы можете внедрять возможности OCR в веб‑сервисы, настольные приложения или автоматизированные конвейеры, не сталкиваясь с ошибками лицензирования. Далее рассмотрите расширенные настройки OCR — языковые пакеты, предобработку изображений или пакетную обработку — каждая из которых опирается на прочную основу, которую вы только что создали. + +Есть вопросы по развертыванию, Docker или работе с несколькими лицензиями? Оставляйте комментарий, и удачной разработки! + +## Что стоит изучить дальше? + +- [Учебник Aspose OCR – Оптическое распознавание символов](/ocr/english/) +- [Как установить лицензию и проверить лицензию Aspose.OCR в Java](/ocr/english/java/ocr-basics/set-license/) +- [Как распознавать текст на изображении с языковой поддержкой с помощью Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/russian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..958cd8200 --- /dev/null +++ b/ocr/russian/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: Создайте PDF с возможностью поиска из отсканированных изображений с помощью + OCR на Python. Узнайте, как конвертировать PDF из отсканированных изображений, преобразовать + TIFF в PDF и добавить слой OCR‑текста за считанные минуты. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: ru +og_description: Создайте мгновенно PDF с возможностью поиска. Это руководство показывает, + как выполнить OCR, преобразовать PDF со сканированным изображением и добавить слой + текста OCR с помощью одного скрипта на Python. +og_title: Создайте поисковый PDF с помощью Python — Полный учебник +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Создание PDF с возможностью поиска с помощью Python – пошаговое руководство +url: /ru/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание поискового PDF с помощью Python – пошаговое руководство + +Задумывались ли вы когда‑нибудь, как **создать поисковый PDF** из отсканированной страницы без использования десятков инструментов? Вы не одиноки. Во многих офисных процессах отсканированный TIFF или JPEG попадает на общий диск, и следующий человек вынужден копировать‑вставлять текст вручную — болезненно, подвержено ошибкам и отнимает время. + +В этом руководстве мы пройдем чистое программное решение, которое позволяет **конвертировать PDF со сканированным изображением**, **конвертировать TIFF в PDF** и **добавить слой OCR‑текста** за один раз. К концу вы получите готовый к использованию скрипт, который запускает OCR, внедряет скрытый текст и выдаёт поисковый PDF, который можно индексировать, искать или делиться им с уверенностью. + +## Что понадобится + +- Python 3.9+ (любая современная версия подойдет) +- пакеты `aspose-ocr` и `aspose-pdf` (устанавливаются через `pip install aspose-ocr aspose-pdf`) +- отсканированный файл изображения (`.tif`, `.png`, `.jpg` или даже страница PDF, содержащая только изображение) +- умеренный объём ОЗУ (движок OCR лёгкий; даже ноутбук справится) + +> **Совет:** Если вы используете Windows, самый простой способ получить пакеты — выполнить команду в окне PowerShell с повышенными правами. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Теперь, когда предварительные требования выполнены, давайте погрузимся в код. + +## Шаг 1: Создать экземпляр OCR‑движка – *create searchable pdf* + +Первое, что мы делаем, — запускаем OCR‑движок. Считайте его мозгом, который будет читать каждый пиксель и преобразовывать его в символы. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Почему это важно:** Инициализация движка только один раз снижает использование памяти. Если вы будете вызывать `OcrEngine()` внутри цикла для каждой страницы, вы быстро исчерпаете ресурсы. + +## Шаг 2: Загрузить отсканированное изображение – *convert tiff to pdf* & *convert scanned image pdf* + +Далее указываем движку файл, который нужно обработать. API принимает любое растровое изображение, поэтому TIFF работает так же хорошо, как JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Если у вас есть PDF, содержащий только отсканированное изображение, вы всё равно можете использовать `load_image`, так как Aspose автоматически извлечёт первую страницу. + +## Шаг 3: Подготовить параметры сохранения PDF – *add OCR text layer* + +Здесь мы настраиваем, как будет выглядеть конечный PDF. Ключевой флаг — `create_searchable_pdf`; установка его в `True` сообщает библиотеке внедрить невидимый слой текста, который отражает визуальное содержимое. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Что делает слой текста:** Когда вы открываете полученный файл в Adobe Reader и пытаетесь выделить текст, вы видите скрытые символы. Поисковые системы также могут их индексировать — идеально для соответствия требованиям или архивирования. + +## Шаг 4: Запустить OCR и сохранить – *how to run OCR* в одном вызове + +Теперь происходит магия. Один вызов метода запускает движок распознавания и записывает поисковый PDF на диск. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Метод `recognize` возвращает объект статуса, который можно проверить на наличие ошибок, но для большинства простых сценариев достаточно приведённого выше простого вызова. + +### Ожидаемый вывод + +Running the script prints: + +``` +PDF saved as searchable PDF. +``` + +Если открыть `scanned_page_searchable.pdf`, вы заметите, что можно выделять текст, копировать‑вставлять его и даже выполнить поиск `Ctrl+F`. Это отличительная черта рабочего процесса **create searchable pdf**. + +## Полный рабочий скрипт + +Ниже представлен полный, готовый к запуску скрипт. Просто замените пути‑заполнители на фактические расположения ваших файлов. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Save this as `create_searchable_pdf.py` and execute: + +```bash +python create_searchable_pdf.py +``` + +## Часто задаваемые вопросы и особые случаи + +### 1️⃣ Можно ли обрабатывать многостраничные PDF? + +Да. Используйте `ocr_engine.load_image("file.pdf")`, а затем в цикле обрабатывайте каждую страницу с помощью `ocr_engine.recognize(pdf_save_options, page_number)`. Библиотека автоматически создаст многостраничный поисковый PDF. + +### 2️⃣ Что если мой исходный файл — высокоразрешающий TIFF (300 dpi+)? + +Higher DPI yields better OCR accuracy but also larger memory usage. If you hit a `MemoryError`, downscale the image first: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Как изменить язык OCR? + +Set the `language` property on the engine before loading the image: + +```python +ocr_engine.language = "fra" # French +``` + +Полный список поддерживаемых кодов языков находится в документации Aspose. + +### 4️⃣ Что если нужно сохранить оригинальное качество изображения? + +Класс `PdfSaveOptions` имеет свойство `compression`. Установите его в `PdfCompression.None`, чтобы сохранить растровые данные точно в оригинальном виде. + +```python +pdf_save_options.compression = "None" +``` + +## Советы для продакшн‑готовых развертываний + +- **Пакетная обработка:** Оберните основную логику в функцию, принимающую список путей к файлам. Записывайте каждый успех/неудачу в CSV для аудита. +- **Параллелизм:** Используйте `concurrent.futures.ThreadPoolExecutor` для запуска OCR на нескольких ядрах. Только помните, что каждый поток требует свой собственный экземпляр `OcrEngine`. +- **Безопасность:** Если вы работаете с конфиденциальными документами, запускайте скрипт в изолированной среде и сразу после обработки удаляйте временные файлы. + +## Заключение + +Теперь вы знаете, как **создавать поисковые PDF** файлы из отсканированных изображений с помощью лаконичного скрипта на Python. Инициализируя OCR‑движок, загружая TIFF (или любой растр), настраивая `PdfSaveOptions` для **добавления OCR‑слоя текста**, и, наконец, вызывая `recognize`, весь конвейер **convert scanned image pdf** и **convert TIFF to PDF** превращается в одну повторяемую команду. + +Следующие шаги? Попробуйте связать этот скрипт с наблюдателем за файлами, чтобы любой новый скан, помещённый в папку, автоматически становился поисковым. Или поэкспериментируйте с различными языками OCR для поддержки многоязычных архивов. Возможности безграничны, когда вы комбинируете OCR с генерацией PDF. + +Есть дополнительные вопросы о **how to run OCR** в других языках или фреймворках? Оставьте комментарий ниже, и удачной разработки! + +![Диаграмма, показывающая поток от отсканированного изображения → OCR‑движка → поискового PDF (create searchable pdf)](searchable-pdf-flow.png "Диаграмма потока создания поискового pdf") + +## Что стоит изучить дальше? + +- [Как выполнять OCR PDF в .NET с Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Конвертировать изображения в PDF C# – Сохранить многостраничный результат OCR](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Как выполнять OCR текста изображения с указанием языка с помощью Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/russian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ef43ffb6a --- /dev/null +++ b/ocr/russian/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Улучшите точность OCR с помощью Python, предварительно обрабатывая изображения. + Узнайте, как извлекать текст из файлов изображений, распознавать текст из PNG и + повышать результаты. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: ru +og_description: Улучшите точность OCR в Python, применяя предварительную обработку + изображений для текста. Следуйте этому руководству, чтобы извлекать текст из файлов + изображений и без усилий распознавать текст из PNG. +og_title: Улучшение точности OCR в Python – Полный учебник +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Улучшение точности OCR в Python — полное пошаговое руководство +url: /ru/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Улучшение точности OCR в Python – Полное пошаговое руководство + +Когда‑то пытались **повысить точность OCR**, а получали лишь набор бессмысленных символов? Вы не одиноки. Большинство разработчиков сталкиваются с проблемой, когда исходное изображение шумное, наклонённое или просто с низким контрастом. Хорошая новость: несколько приёмов предобработки могут превратить размытый скриншот в чистый, машинно‑читаемый текст. + +В этом руководстве мы пройдём реальный пример, который **предобрабатывает изображение для OCR**, запускает движок распознавания и, наконец, **извлекает текст из файлов‑изображений** — конкретно PNG. К концу вы точно будете знать, как **распознавать текст из PNG** с более высоким уровнем успеха, и получите переиспользуемый фрагмент кода, который можно вставить в любой проект. + +## Что вы узнаете + +- Почему предобработка изображений важна для OCR‑движков +- Какие режимы предобработки (удаление шума, исправление наклона) дают наибольший прирост +- Как настроить экземпляр `OcrEngine` в Python +- Полный, готовый к запуску скрипт, который **извлекает текст из файлов‑изображений** +- Советы по работе с краевыми случаями, такими как повернутые сканы или изображения низкого разрешения + +Никаких внешних библиотек, кроме OCR SDK, не требуется, но понадобится Python 3.8+ и PNG‑изображение, которое вы хотите прочитать. + +--- + +![Диаграмма, показывающая шаги по улучшению точности OCR в Python](image.png "Рабочий процесс улучшения точности OCR") + +*Alt text: диаграмма рабочего процесса улучшения точности OCR, иллюстрирующая шаги предобработки и распознавания.* + +## Требования + +- Установлен Python 3.8 или новее +- Доступ к OCR SDK, предоставляющему `OcrEngine`, `OcrEngineSettings` и `ImagePreprocessMode` (в примере ниже используется обобщённый API; при необходимости замените его классами вашего поставщика) +- PNG‑изображение (`input.png`) в папке, к которой вы можете обратиться + +Если вы используете виртуальное окружение, активируйте его сейчас — ничего сложного, просто `python -m venv venv && source venv/bin/activate`. + +--- + +## Шаг 1: Создание экземпляра OCR‑движка – Начало улучшения точности OCR + +Первое, что нужно — объект OCR‑движка. Считайте его мозгом, который позже будет читать пиксели и выдавать символы. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Почему это важно: без движка вы не сможете применить предобработку, и сырое изображение будет передано распознавателю напрямую — обычно худший сценарий для точности. + +--- + +## Шаг 2: Загрузка целевого PNG – Подготовка к распознаванию текста из PNG + +Теперь указываем движку, с каким файлом работать. PNG — без потерь, что уже даёт небольшое преимущество перед JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Если изображение находится в другом месте, просто поправьте путь. Движок принимает любой поддерживаемый формат, но PNG часто сохраняет тонкие детали, необходимые для чётких контуров символов. + +--- + +## Шаг 3: Настройка предобработки – Предобработка изображения для OCR + +Здесь происходит магия. Мы создаём объект настроек, включаем удаление шума, чтобы избавиться от пятен, и включаем исправление наклона, чтобы наклоненный текст автоматически выравнивался. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Почему Denoise + Deskew? + +- **Denoise**: Случайный шум пикселей сбивает с толку алгоритмы сопоставления шаблонов. Его удаление делает буквы острее. +- **Deskew**: Даже наклон в 2 градуса может резко снизить коэффициенты уверенности. Выравнивание базовой линии позволяет распознавателю надёжнее сопоставлять шрифты. + +Можно поэкспериментировать с дополнительными флагами (например, `ImagePreprocessMode.CONTRAST_ENHANCE`), если ваши изображения особенно тёмные. Документация SDK обычно перечисляет все доступные режимы. + +--- + +## Шаг 4: Применение настроек к движку – Связывание предобработки с OCR + +Назначьте объект настроек движку, чтобы следующий запуск распознавания использовал определённые нами преобразования. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Если пропустить этот шаг, движок вернётся к настройкам по умолчанию (часто «без предобработки»), и вы увидите **пониженную точность OCR**. + +--- + +## Шаг 5: Запуск процесса распознавания – Извлечение текста из изображения + +Когда всё подключено, мы наконец просим движок выполнить свою работу. Вызов синхронный, возвращает объект результата, содержащий распознанную строку. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +За кулисами движок теперь: + +1. Загружает PNG в память +2. Применяет удаление шума и исправление наклона согласно нашим настройкам +3. Запускает нейронную сеть или классический сопоставитель шаблонов +4. Упаковывает вывод в `recognition_result` + +--- + +## Шаг 6: Вывод распознанного текста – Проверка улучшения + +Выведем извлечённую строку. В реальном приложении вы, вероятно, запишете её в файл, базу данных или передадите другому сервису. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Ожидаемый вывод + +Если изображение содержит предложение «Hello, OCR World!», вы должны увидеть: + +``` +Hello, OCR World! +``` + +Обратите внимание, что текст чистый — без лишних символов или разорванных букв. Это результат правильной **предобработки изображения для текста**. + +--- + +## Профессиональные советы и краевые случаи + +| Ситуация | Что изменить | Почему | +|-----------|----------------|-----| +| Очень низкое разрешение PNG (≤ 72 dpi) | Добавить `ImagePreprocessMode.SUPER_RESOLUTION`, если доступно | Апскейлинг даёт распознавателю больше пикселей для работы | +| Текст повернут более чем на 5° | Увеличить допуск исправления наклона или вручную повернуть с помощью `Pillow` перед передачей движку | Экстремальные углы иногда обходят автоматическое исправление наклона | +| Сильные фоновые узоры | Включить `ImagePreprocessMode.BACKGROUND_REMOVAL` | Убирает не‑текстовый шум, который иначе мог бы быть ошибочно прочитан | +| Документ на нескольких языках | Установить `ocr_engine.language = "eng+spa"` (или аналог) | Движок выбирает правильный набор символов, повышая общую точность | + +Помните, **улучшение точности OCR** — не универсальное решение; возможно, придётся подбирать флаги предобработки под ваш конкретный набор данных. + +--- + +## Полный скрипт – Готов к копированию и вставке + +Ниже приведён полностью готовый к запуску пример, включающий каждый шаг, о котором мы говорили. Сохраните его как `improve_ocr_accuracy.py` и запустите командой `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Запустите, наблюдайте консоль, и вы сразу увидите результат **извлечения текста из изображения**. Если вывод выглядит странно, подправьте флаги `preprocess_mode`, как описано в таблице «Профессиональные советы». + +--- + +## Заключение + +Мы только что прошли практический рецепт **улучшения точности OCR** с помощью Python. Создав `OcrEngine`, загрузив PNG, **предобработав изображение для OCR** и, наконец, **распознав текст из PNG**, вы сможете надёжно **извлекать текст из файлов‑изображений**, даже если исходник далёк от идеала. + +Что дальше? Попробуйте обработать пакет изображений в цикле, сохранять каждый результат в CSV или поэкспериментировать с дополнительными режимами предобработки, такими как усиление контраста. Та же схема работает с PDF, сканированными чеками или рукописными заметками — просто замените входные данные и скорректируйте настройки. + +Есть вопросы о конкретном типе изображений или хотите узнать, как интегрировать это в веб‑сервис? Оставляйте комментарий, и мы разберём эти сценарии вместе. Приятного кодинга, и пусть ваши результаты OCR всегда будут кристально чистыми! + +## Что стоит изучить дальше? + +- [Извлечение текста из изображения с Aspose OCR – Пошаговое руководство](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Извлечение текста из изображения – Оптимизация OCR с Aspose.OCR для .NET](/ocr/english/net/ocr-optimization/) +- [Как извлечь текст из изображения, подготовив прямоугольники в OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/russian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..343c43c15 --- /dev/null +++ b/ocr/russian/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-31 +description: Узнайте, как использовать область интереса OCR для загрузки изображения + и извлечения текста из прямоугольника — идеально подходит для распознавания суммы + в счете. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: ru +og_description: Освойте область интереса OCR для загрузки изображения, извлечения + текста из прямоугольника и распознавания текста из счета в одном учебнике. +og_title: 'OCR: область интереса — пошаговое руководство по Python' +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR область интереса – извлечение текста из прямоугольника в Python +url: /ru/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Область интереса OCR – Извлечение текста из прямоугольника в Python + +Задумывались ли вы когда‑нибудь, как **ocr region of interest** конкретную часть отсканированного счета без подачи всей страницы в движок? Вы не первый, кто смотрит на размытый чек и думает: «Как извлечь сумму, которая где‑то в правом нижнем углу?» Хорошая новость в том, что вы можете указать библиотеке OCR, где именно искать, что значительно ускорит процесс и повысит точность. + +В этом руководстве мы пройдем полный, готовый к запуску пример, который покажет, как **load image for OCR**, определить **region of interest**, а затем **extract text from rectangle**, чтобы наконец **recognize text from invoice** и ответить на классический вопрос «how to extract amount». Никаких расплывчатых ссылок — только конкретный код, понятные объяснения и несколько профессиональных советов, о которых вы бы хотели знать раньше. + +--- + +## Что вы построите + +1. Загружает изображение счета с диска. +2. Отмечает прямоугольную ROI, где находится общая сумма. +3. Запускает OCR только внутри этой ROI. +4. Выводит очищенную строку суммы. + +Все это работает с любой библиотекой OCR, поддерживающей ROI — здесь мы используем вымышленный, но репрезентативный пакет `SimpleOCR`, имитирующий популярные инструменты, такие как Tesseract или EasyOCR. Не стесняйтесь заменить его; концепции остаются теми же. + +--- + +## Требования + +- Установлен Python 3.8+ (`python --version` должен показывать ≥3.8). +- Устанавливаемый через pip пакет OCR (например, `pip install simpleocr`). +- Изображение счета (PNG или JPEG), размещённое в папке, к которой вы можете обратиться. +- Базовое знакомство с функциями и классами Python (ничего сложного). + +Если у вас уже всё есть, отлично — давайте погрузимся. Если нет, сначала получите изображение; остальные шаги независимы от фактического содержимого файла. + +--- + +## Шаг 1: Load Image for OCR + +Первое, что требуется любой цепочке OCR, — это битмап для чтения. Большинство библиотек предоставляют простой метод `load_image`, принимающий путь к файлу. Вот как это делается с нашим движком `SimpleOCR`: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Используйте абсолютные пути или `os.path.join`, чтобы избежать неожиданностей «файл не найден» при запуске скрипта из другой рабочей директории. + +--- + +## Шаг 2: Define OCR Region of Interest + +Вместо того чтобы позволять движку сканировать всю страницу, мы указываем ему *точно*, где находится сумма. Это шаг **ocr region of interest**, и он является ключом к надёжному извлечению, особенно когда документ содержит шумные заголовки или нижние колонтитулы. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Почему именно эти числа? `x` и `y` — смещения в пикселях от верхнего‑левого угла, а `width` и `height` описывают размер коробки. Если вы не уверены, откройте изображение в любом редакторе, включите линейку и запишите координаты. Многие IDE даже позволяют выводить позицию курсора при наведении. + +--- + +## Шаг 3: Extract Text from Rectangle + +Теперь, когда ROI задан, мы просим движок **recognize text from invoice**, но ограничивая его только прямоугольником, который мы только что добавили. Вызов возвращает объект результата, который обычно содержит сырую строку, оценки уверенности и иногда ограничивающие рамки. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +За кулисами `recognize()` проходит по каждой ROI, обрезает этот фрагмент, запускает модель OCR и собирает результаты вместе. Поэтому определение точного **extract text from rectangle** региона может сэкономить секунды при обработке пакетных заданий. + +--- + +## Шаг 4: How to Extract Amount – Clean the Output + +OCR не идеален; часто появляются лишние пробелы, переводы строк или даже неверно распознанные символы (например, «S» вместо «5»). Быстрый `strip()` и небольшое регулярное выражение обычно решают задачу для денежных значений. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** Если вы планируете передавать сумму в базу данных или платёжный шлюз, нужен предсказуемый формат. Удаление пробельных символов и фильтрация нечисловых символов предотвращает ошибки на последующих этапах. + +--- + +## Шаг 5: Recognize Text from Invoice – Full Script + +Объединив всё вместе, представляем полный, готовый к запуску скрипт. Сохраните его как `extract_amount.py` и выполните `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Ожидаемый вывод + +``` +Amount: 1,245.67 +``` + +Если ROI смещён, вы можете увидеть что‑то вроде `Amount: 1245.6S` — обратите внимание на лишнее «S». Скорректируйте координаты прямоугольника и запустите снова, пока вывод не станет чистым. + +--- + +## Частые проблемы и граничные случаи + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| **ROI слишком маленькая** | Текст суммы обрезается, что приводит к частичному распознаванию. | Увеличьте `width`/`height` примерно на 10‑20 % и протестируйте снова. | +| **Неправильный DPI** | Сканы низкого разрешения (≤150 dpi) снижают точность OCR. | Пересэмплируйте изображение до 300 dpi перед загрузкой или попросите сканер использовать более высокое DPI. | +| **Несколько валют** | Регулярное выражение выбирает первую числовую группу, которая может быть номером счета. | Уточните регулярное выражение, чтобы искать символы валют (`$`, `€`, `£`) перед цифрами. | +| **Повернутые счета** | OCR‑движки предполагают вертикальный текст; повернутые страницы ломают распознавание. | Примените коррекцию вращения (`ocr_engine.rotate(90)`) перед добавлением ROI. | +| **Шум на фоне** | Тени или печати сбивают модель с толку. | Предобработайте изображение простым порогом (`cv2.threshold`) или используйте фильтр шумоподавления. | + +Решение этих граничных случаев на ранних этапах экономит часы отладки позже. + +--- + +## Профессиональные советы для реальных проектов + +- **Пакетная обработка:** Перебирайте папку со счетами, вычисляйте ROI динамически (например, на основе обнаружения шаблона) и сохраняйте результаты в CSV. +- **Сопоставление шаблонов:** Если вы работаете с несколькими макетами счетов, поддерживайте JSON‑карту `template_id → ROI coordinates`. Переключайте ROI на основе быстрого классификатора макета. +- **Параллельное выполнение:** Используйте `concurrent.futures.ThreadPoolExecutor` для одновременного запуска нескольких экземпляров OCR — отлично подходит для высокообъёмных бэк‑офисных конвейеров. +- **Фильтрация по уверенности:** Большинство результатов OCR включают оценку уверенности. Отбрасывайте результаты ниже порога (например, 85 %) и помечайте их для ручной проверки. + +--- + +## Заключение + +Мы рассмотрели всё, что нужно для **ocr region of interest**, **load image for OCR**, **extract text from rectangle** и, наконец, **recognize text from invoice**, чтобы ответить на классический вопрос **how to extract amount**. Скрипт компактен, но достаточно гибок, чтобы адаптироваться к различным форматам документов, языкам и OCR‑бэкендам. + +Теперь, когда вы освоили основы, подумайте о расширении рабочего процесса: добавить сканирование штрих‑кодов, интегрировать парсер PDF или отправлять извлечённую сумму в бухгалтерский API. Возможности безграничны, и с чётко определённой ROI вы всегда получите более быстрые и чистые результаты. + +Если возникнут сложности, оставляйте комментарий ниже — удачной OCR‑работы! + +![пример области интереса OCR](https://example.com/ocr_roi_example.png "пример области интереса OCR") + + +## Что вам стоит изучить дальше? + +- [Как извлечь текст из изображения, подготавливая прямоугольники в OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Извлечение текста из изображения Java с Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Извлечение текста из изображения – оптимизация 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/spanish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/spanish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..848fccdb7 --- /dev/null +++ b/ocr/spanish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Tutorial de OCR asíncrono que muestra cómo usar Aspose OCR en Python + con asyncio para una extracción rápida de texto de imágenes. Aprende la implementación + de OCR asíncrono paso a paso. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: es +og_description: El tutorial de OCR asíncrono te guía en el uso de Aspose OCR en Python + con asyncio para una extracción eficiente de texto en imágenes. +og_title: Tutorial de OCR asíncrono – Python asyncio con Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Tutorial de OCR asíncrono – Python asyncio con Aspose OCR +url: /es/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial de OCR Asíncrono – Python asyncio con Aspose OCR + +¿Alguna vez te has preguntado cómo ejecutar reconocimiento óptico de caracteres sin bloquear tu aplicación? En un **tutorial de OCR asíncrono** verás exactamente eso: extracción de texto sin bloqueo usando `asyncio` de Python y la biblioteca Aspose OCR. + +Si has estado esperando a que se procese una imagen pesada, esta guía te brinda una solución limpia y asíncrona que mantiene tu bucle de eventos en funcionamiento. + +En las secciones siguientes cubriremos todo lo que necesitas: instalar la biblioteca, configurar un asistente asíncrono, manejar el resultado e incluso un consejo rápido para escalar a múltiples imágenes. Al final podrás incorporar un **tutorial de OCR asíncrono** en cualquier proyecto Python que ya use `asyncio`. + +## Lo que necesitarás + +Antes de sumergirnos, asegúrate de tener: + +* Python 3.9+ (la API `asyncio` que usamos es estable desde 3.7 en adelante) +* Una licencia activa de Aspose OCR o una prueba gratuita (la biblioteca es puro‑Python, sin binarios nativos) +* Un archivo de imagen pequeño (`.jpg`, `.png`, etc.) que quieras leer – mantenlo en una carpeta conocida + +No se requieren otras herramientas externas; todo se ejecuta en puro Python. + +## Paso 1: Instalar el paquete Aspose OCR + +Lo primero, obtén el paquete Aspose OCR de PyPI. Abre una terminal y ejecuta: + +```bash +pip install aspose-ocr +``` + +> **Consejo profesional:** Si trabajas dentro de un entorno virtual (altamente recomendado), actívalo primero. Esto mantiene las dependencias aisladas y evita conflictos de versiones. + +## Paso 2: Inicializar el motor OCR de forma asíncrona + +El núcleo de nuestro **tutorial de OCR asíncrono** es una función auxiliar asíncrona. Crea una instancia de `OcrEngine`, carga una imagen y luego llama a `recognize_async()`. El motor en sí es síncrono, pero el método wrapper devuelve un awaitable, permitiendo que el bucle de eventos permanezca receptivo. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Por qué lo hacemos de esta manera:** +*Crear el motor dentro del asistente garantiza la seguridad de hilos si más adelante ejecutas muchos trabajos de OCR en paralelo. La palabra clave `await` devuelve el control al bucle de eventos mientras el trabajo pesado se realiza en el pool de hilos interno de la biblioteca.* + +## Paso 3: Ejecutar el asistente desde una función principal asíncrona + +Ahora necesitamos una pequeña corrutina `main()` que llame a `async_ocr()` e imprima el resultado. Esto refleja el punto de entrada típico para un script `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**¿Qué ocurre bajo el capó?** +`asyncio.run()` crea un nuevo bucle de eventos, programa `main()` y cierra el bucle de manera limpia cuando `main()` termina. Este patrón es la forma recomendada de iniciar programas asíncronos en Python 3.7+. + +## Paso 4: Probar el script completo + +Guarda los dos bloques de código anteriores en un solo archivo, por ejemplo, `async_ocr_demo.py`. Ejecútalo desde la línea de comandos: + +```bash +python async_ocr_demo.py +``` + +Si todo está configurado correctamente deberías ver algo como: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +El resultado exacto dependerá del contenido de `photo.jpg`. Lo importante es que el script termina rápidamente, incluso si la imagen es grande, porque el trabajo de OCR se realiza en segundo plano. + +## Paso 5: Escalar – Procesar múltiples imágenes concurrentemente + +Una pregunta frecuente de seguimiento es, *“¿Puedo hacer OCR a un lote de archivos sin lanzar un nuevo proceso para cada uno?”* Absolutamente. Como nuestro asistente es completamente asíncrono, podemos reunir muchas corrutinas con `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Por qué funciona esto:** `asyncio.gather()` programa todas las tareas de OCR a la vez. La biblioteca subyacente Aspose OCR sigue usando su propio pool de hilos, pero desde la perspectiva de Python todo permanece sin bloqueo, permitiéndote manejar decenas de imágenes en el tiempo que tomaría una única llamada síncrona. + +## Paso 6: Manejar errores de forma elegante + +Cuando trabajas con archivos externos, inevitablemente encontrarás archivos faltantes, imágenes corruptas o problemas de licencia. Envuelve la llamada OCR en un bloque `try/except` para mantener vivo el bucle de eventos: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Ahora `batch_ocr()` puede llamar a `safe_async_ocr` en su lugar, asegurando que un archivo defectuoso no abortará todo el lote. + +## Visión general visual + +![Diagrama del tutorial de OCR asíncrono](async-ocr-diagram.png){alt="Diagrama de flujo del tutorial de OCR asíncrono que muestra el asistente async_ocr, el bucle de eventos y el motor Aspose OCR"} + +El diagrama anterior visualiza el flujo: el bucle de eventos → `async_ocr` → `OcrEngine` → hilo en segundo plano → resultado de vuelta al bucle. + +## Problemas comunes y cómo evitarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| **Entrada/Salida bloqueante dentro del asistente** | Usar accidentalmente `open()` sin `await` puede bloquear el bucle. | Utiliza `aiofiles` para leer archivos, o deja que `engine.load_image` lo gestione (ya es no bloqueante). | +| **Reutilizar un solo `OcrEngine` entre corrutinas** | El motor no es seguro para hilos; las llamadas concurrentes pueden corromper el estado. | Instancia un motor nuevo dentro de cada llamada a `async_ocr` (como se muestra). | +| **Licencia faltante** | Aspose OCR lanza una excepción relacionada con la licencia en tiempo de ejecución. | Registra tu licencia temprano (`OcrEngine.set_license("license.json")`). | +| **Imágenes grandes que provocan picos de memoria** | La biblioteca carga la imagen completa en RAM. | Reduce el tamaño de las imágenes antes del OCR si la memoria es un problema. | + +## Recapitulación: Lo que logramos + +En este **tutorial de OCR asíncrono** hemos: + +1. Instalado la biblioteca Aspose OCR. +2. Construido un asistente `async_ocr` que ejecuta el reconocimiento sin bloquear. +3. Ejecutado el asistente desde un punto de entrada `asyncio` limpio. +4. Demostrado el procesamiento por lotes con `asyncio.gather`. +5. Añadido manejo de errores y consejos de mejores prácticas. + +Todo esto es puro Python, por lo que puedes incorporarlo en un servidor web, una herramienta CLI o una canalización de datos sin reescribir el código async existente. + +## Próximos pasos y temas relacionados + +* **Preprocesamiento de imágenes asíncrono** – usa `aiohttp` para descargar imágenes concurrentemente antes del OCR. +* **Almacenar resultados de OCR** – combina este tutorial con un driver de base de datos async como `asyncpg` para PostgreSQL. +* **Ajuste de rendimiento** – experimenta con `engine.recognize_async(max_threads=4)` si la biblioteca expone esa opción. +* **Motores OCR alternativos** – compara Aspose OCR con los wrappers async de Tesseract para un análisis de costo‑beneficio. + +Siéntete libre de experimentar: intenta procesar PDFs, ajustar configuraciones de idioma, o conectar los resultados a un chatbot. El cielo es el límite una vez que tengas una base sólida de **tutorial de OCR asíncrono**. + +¡Feliz codificación, y que tu extracción de texto sea siempre rápida! + +## ¿Qué deberías aprender a continuación? + +- [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/) +- [Tutorial de Aspose OCR – Reconocimiento Óptico de Caracteres](/ocr/english/) +- [Cómo hacer OCR de texto de imagen con idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/spanish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..883de2f7c --- /dev/null +++ b/ocr/spanish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Detección automática de idioma en OCR hecha fácil. Aprende cómo cargar + OCR de imagen, habilitar la detección automática de idioma y reconocer texto en + la imagen en solo unos pocos pasos. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: es +og_description: Detección automática de idioma en OCR hecha fácil. Sigue este tutorial + paso a paso para habilitar la detección automática de idioma, cargar OCR de imagen + y reconocer texto en la imagen. +og_title: Detección automática de idioma con OCR – Guía completa de Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Detección automática de idioma con OCR – Guía completa de Python +url: /es/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Detección automática de idioma con OCR – Guía completa en Python + +¿Alguna vez te has preguntado cómo hacer que un motor OCR *adivine* el idioma de un documento escaneado sin que tú le indiques qué buscar? Eso es exactamente lo que hace la **detección automática de idioma**, y es un cambio total de juego cuando trabajas con PDFs multilingües, fotos de señales de calle o cualquier imagen que mezcle escrituras. + +En este tutorial recorreremos un ejemplo práctico que muestra cómo **activar la detección automática de idioma**, **cargar OCR de imagen** y **reconocer texto de imagen** usando una API al estilo Python. Al final tendrás un script autónomo que imprime tanto el código del idioma detectado como el texto extraído — sin necesidad de configurar manualmente el idioma. + +## Lo que aprenderás + +- Cómo crear una instancia del motor OCR y activar la **detección automática de idioma**. +- Los pasos exactos para **cargar OCR de imagen** desde disco. +- Cómo llamar al método `recognize()` del motor y obtener un resultado que incluya el código del idioma. +- Consejos para manejar casos límite como imágenes de baja resolución o escrituras no soportadas. + +No se necesita experiencia previa con OCR multilingüe; solo una configuración básica de Python y un archivo de imagen. + +--- + +## Requisitos previos + +Antes de sumergirnos, asegúrate de tener: + +1. Python 3.8+ instalado (cualquier versión reciente sirve). +2. La biblioteca OCR que proporciona `OcrEngine`, `LanguageAutoDetectMode`, etc. — para esta guía asumiremos un paquete hipotético llamado `myocr`. Instálalo con: + + ```bash + pip install myocr + ``` + +3. Un archivo de imagen (`multilingual_sample.png`) que contenga texto en al menos dos idiomas diferentes. +4. Un poco de curiosidad — si nunca has tocado OCR antes, no te preocupes; el código es deliberadamente sencillo. + +--- + +## Paso 1: Activar la detección automática de idioma + +Lo primero que debes hacer es indicarle al motor que debe *descubrir* el idioma por sí mismo. Aquí es donde entra en juego la bandera de **detección automática de idioma**. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Por qué es importante:** +> Cuando `AUTO_DETECT` está activado, el motor ejecuta un clasificador de idioma ligero sobre la imagen antes de que se inicie el reconocimiento de caracteres pesado. Eso significa que no tienes que adivinar si el texto está en inglés, ruso, francés o cualquier combinación de ellos. El motor seleccionará automáticamente el modelo de idioma más adecuado para cada región de la imagen. + +--- + +## Paso 2: Cargar OCR de imagen + +Ahora que el motor sabe que debe detectar idiomas automáticamente, necesitamos darle algo sobre lo que trabajar. El paso **cargar OCR de imagen** lee el mapa de bits y prepara los búferes internos. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Consejo profesional:** +> Si tu imagen tiene más de 300 dpi, considera reducirla a alrededor de 150‑200 dpi. Demasiado detalle puede *ralentizar* la etapa de detección de idioma sin mejorar la precisión. + +--- + +## Paso 3: Reconocer texto de la imagen + +Con la imagen en memoria y la detección de idioma habilitada, la pieza final es pedir al motor que **reconozca texto de imagen**. Esta única llamada realiza todo el trabajo pesado. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` es un objeto que normalmente contiene al menos dos atributos: + +| Atributo | Descripción | +|------------|-------------| +| `language` | Código ISO‑639‑1 del idioma detectado (p. ej., `"en"` para English). | +| `text` | La transcripción en texto plano de la imagen. | + +--- + +## Paso 4: Obtener el idioma detectado y el texto extraído + +Ahora simplemente imprimimos lo que el motor descubrió. Esto demuestra la capacidad de **detectar idioma OCR** en acción. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Salida de ejemplo** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **¿Qué pasa si el motor devuelve `None`?** +> Eso suele significar que la imagen está demasiado borrosa o que el texto es demasiado pequeño (< 8 pt). Intenta aumentar el contraste o usar una fuente de mayor resolución. + +--- + +## Ejemplo completo (Activar detección automática de idioma de extremo a extremo) + +Juntando todo, aquí tienes un script listo para ejecutar que cubre **activar detección automática de idioma**, **cargar OCR de imagen**, **reconocer texto de imagen** y **detectar idioma OCR** en un solo paso. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Guarda esto como `automatic_language_detection_ocr.py`, reemplaza `YOUR_DIRECTORY` con la carpeta que contiene tu PNG y ejecuta: + +```bash +python automatic_language_detection_ocr.py +``` + +Deberías ver el código del idioma seguido del texto extraído, tal como la salida de ejemplo anterior. + +--- + +## Manejo de casos límite comunes + +| Situación | Solución sugerida | +|-----------|-------------------| +| **Imagen de muy baja resolución** (menos de 100 dpi) | Escala hacia arriba con un filtro bicúbico antes de cargar, o solicita una fuente de mayor resolución. | +| **Escrituras mixtas en una sola imagen** (p. ej., English + Cyrillic) | El motor normalmente divide la página en regiones; si notas detecciones erróneas, establece `engine.enable_region_split = True`. | +| **Idioma no soportado** | Verifica que la biblioteca OCR incluya un paquete de idioma para la escritura que necesitas; puede que debas descargar modelos adicionales. | +| **Procesamiento por lotes grande** | Inicializa el motor una sola vez y reutilízalo en múltiples ciclos `load_image` / `recognize` para evitar cargar repetidamente los modelos. | + +--- + +## Visión general visual + +![ejemplo de salida de detección automática de idioma](https://example.com/auto-lang-detect.png "detección automática de idioma") + +*Texto alternativo:* ejemplo de salida de detección automática de idioma que muestra el código del idioma detectado y el texto multilingüe extraído. + +--- + +## Conclusión + +Acabamos de cubrir **detección automática de idioma** de principio a fin: crear el motor, activar la detección automática, cargar una imagen para OCR, reconocer el texto y, finalmente, obtener el idioma detectado. Este flujo de extremo a extremo te permite procesar documentos multilingües sin configurar manualmente los modelos de idioma cada vez. + +Si estás listo para ir más allá, considera: + +- **Procesar por lotes** cientos de imágenes con un bucle que reutilice la misma instancia de `OcrEngine`. +- **Post‑procesar** el texto extraído con un corrector ortográfico o un tokenizador específico del idioma. +- **Integrar** el script en un servicio web que acepte cargas de usuarios y devuelva JSON con los campos `language` y `text`. + +¡Experimenta con diferentes formatos de imagen (`.jpg`, `.tif`) y observa cómo varía la precisión de la detección! ¿Tienes preguntas o una imagen complicada que se niega a leerse? Deja un comentario abajo — ¡feliz codificación! + +## ¿Qué deberías aprender a continuación? + +- [Cómo hacer OCR de texto en imágenes con idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extraer texto de imagen en C# con selección de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Reconocer texto de imagen con Aspose OCR para varios idiomas](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c16026867 --- /dev/null +++ b/ocr/spanish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Aprende a convertir imágenes a texto en Python con un script de conversión + masiva de imágenes a texto. Reconoce texto de imágenes escaneadas usando Aspose.OCR + en minutos. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: es +og_description: Convierte imágenes a texto con Python al instante. Esta guía muestra + la conversión masiva de imágenes a texto y cómo reconocer texto de imágenes escaneadas + con Aspose.OCR. +og_title: Convertir imágenes a texto con Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Convertir imágenes a texto con Python – Guía completa paso a paso +url: /es/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir imágenes a texto con Python – Guía completa paso a paso + +¿Alguna vez te has preguntado cómo **convertir imágenes a texto python** sin buscar entre docenas de bibliotecas? No eres el único. Ya sea que estés digitalizando recibos antiguos, extrayendo datos de facturas escaneadas, o creando un archivo searchable de PDFs, convertir imágenes en archivos de texto plano es una tarea diaria para muchos desarrolladores. + +En este tutorial recorreremos una canalización de **bulk image to text conversion** que reconoce texto de imágenes escaneadas, guarda cada resultado como un archivo `.txt` individual, y lo hace todo con solo unas pocas líneas de Python. No tendrás que buscar APIs desconocidas—Aspose.OCR hace el trabajo pesado, y te mostraremos exactamente cómo configurarlo. + +## Lo que aprenderás + +- Cómo instalar y configurar el paquete Aspose.OCR for Python. +- El código exacto necesario para **convertir imágenes a texto python** usando `BatchOcrEngine`. +- Consejos para manejar problemas comunes como formatos no compatibles o archivos corruptos. +- Formas de verificar que el paso de **recognize text from scanned images** realmente tuvo éxito. + +Al final de esta guía tendrás un script listo para ejecutar que puede procesar miles de imágenes de una sola vez—perfecto para cualquier escenario de procesamiento por lotes. + +## Requisitos previos + +- Python 3.8+ instalado en tu máquina. +- Una carpeta de archivos de imagen (PNG, JPEG, TIFF, etc.) que deseas convertir a texto. +- Una cuenta activa de Aspose Cloud o una licencia de prueba gratuita (el nivel gratuito es suficiente para pruebas). + +Si tienes todo eso, vamos a sumergirnos. + +--- + +## Paso 1 – Configura tu entorno Python + +Antes de comenzar a escribir cualquier código OCR, asegúrate de trabajar dentro de un entorno virtual limpio. Esto aísla las dependencias y evita conflictos de versiones. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Consejo profesional:** Mantén ordenado el directorio de tu proyecto—crea una subcarpeta llamada `ocr_project` y coloca el script allí. Facilita el manejo de rutas más adelante. + +## Paso 2 – Instala Aspose.OCR para Python + +Aspose.OCR es una biblioteca comercial, pero se distribuye con una rueda al estilo NuGet gratuita que puedes obtener de PyPI. Ejecuta el siguiente comando dentro del entorno virtual activado: + +```bash +pip install aspose-ocr +``` + +Si encuentras un error de permisos, agrega la bandera `--user` o ejecuta el comando con `sudo` (solo Linux/macOS). Después de la instalación deberías ver algo como: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **¿Por qué Aspose?** A diferencia de muchas herramientas OCR de código abierto, Aspose.OCR soporta **bulk image to text conversion** de forma nativa y maneja una amplia gama de formatos de imagen sin configuración adicional. También ofrece la clase `BatchOcrEngine` que convierte la tarea de “convertir imágenes a texto python” en una operación de una sola línea. + +## Paso 3 – Convertir imágenes a texto Python con Batch OCR + +Ahora llega el núcleo del tutorial. A continuación tienes un script completamente ejecutable que: + +1. Importa las clases del motor OCR. +2. Instancia un `BatchOcrEngine`. +3. Apunta el motor a una carpeta de entrada de imágenes. +4. Dirige al motor a escribir cada archivo de texto extraído en una carpeta de salida. +5. Ejecuta el método `recognize()`, que **recognize text from scanned images** una por una. + +Guarda lo siguiente como `batch_ocr.py` dentro de la carpeta de tu proyecto: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Cómo funciona + +- **`BatchOcrEngine`** envuelve al `OcrEngine` regular pero añade orquestación a nivel de carpeta, que es exactamente lo que necesitas cuando deseas **convertir imágenes a texto python** en lote. +- La propiedad `input_folder` indica al motor dónde buscar las imágenes de origen. Escanea automáticamente el directorio y encola cada tipo de archivo soportado. +- La propiedad `output_folder` determina dónde se guardará cada archivo `.txt`. El motor replica el nombre de archivo original, de modo que `receipt1.png` se convierte en `receipt1.txt`. +- Al llamar a `recognize()` se activa el bucle interno que carga cada imagen, ejecuta OCR y escribe el resultado. El método bloquea hasta que todos los archivos se procesen, facilitando encadenar acciones posteriores (p. ej., comprimir la carpeta de salida). + +#### Salida esperada + +Cuando ejecutes el script: + +```bash +python batch_ocr.py +``` + +Deberías ver: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Dentro de `output_texts` encontrarás un archivo de texto plano para cada imagen. Abre cualquiera con un editor de texto y verás el resultado OCR bruto—usualmente una aproximación cercana al texto impreso original. + +## Paso 4 – Verifica los resultados y maneja errores + +Incluso los mejores motores OCR pueden fallar con escaneos de baja resolución o páginas muy sesgadas. Aquí tienes una forma rápida de comprobar la salida y registrar cualquier fallo. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**¿Por qué añadir esto?** +- Detecta casos donde el motor produce silenciosamente una cadena vacía (común con imágenes ilegibles). +- Te brinda una lista de archivos problemáticos para que puedas inspeccionarlos manualmente o volver a ejecutar con diferentes configuraciones (p. ej., aumentar las opciones `OcrEngine.preprocess`). + +### Casos límite y ajustes + +| Situación | Solución sugerida | +|-----------|-------------------| +| Las imágenes están rotadas 90° | Establece `batch_engine.ocr_engine.rotation_correction = True`. | +| Idiomas mixtos (Inglés + Francés) | Usa `batch_engine.ocr_engine.language = "eng+fra"` antes de `recognize()`. | +| PDFs enormes convertidos a imágenes primero | Divide los PDFs en imágenes de una sola página, luego alimenta la carpeta al motor batch. | +| Errores de memoria en lotes muy grandes | Procesa subcarpetas más pequeñas secuencialmente, o incrementa `batch_engine.max_memory_usage`. | + +## Paso 5 – Automatiza todo el flujo de trabajo (Opcional) + +Si necesitas ejecutar esta conversión cada noche, envuelve el script en un simple shell o archivo batch de Windows, y prográmalo con `cron` (Linux/macOS) o el Programador de tareas (Windows). Aquí tienes un `run_ocr.sh` mínimo para sistemas tipo Unix: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Hazlo ejecutable (`chmod +x run_ocr.sh`) y añade una entrada cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Eso ejecuta la conversión todos los días a las 2 AM y registra cualquier salida para revisarla después. + +--- + +## Conclusión + +Ahora tienes un método probado y listo para producción para **convertir imágenes a texto python** usando `BatchOcrEngine` de Aspose.OCR. El script maneja **bulk image to text conversion**, escribe elegantemente cada resultado en un archivo dedicado, e incluye pasos de verificación para asegurar que realmente **recognize text from scanned images** correctamente. + +Desde aquí podrías: + +- Experimentar con diferentes configuraciones OCR (paquetes de idiomas, corrección de inclinación, reducción de ruido). +- Canalizar el texto generado a un índice de búsqueda como Elasticsearch para búsqueda de texto completo instantánea. +- Combinar esta canalización con herramientas de conversión de PDF para procesar PDFs escaneados de una sola vez. + +¿Tienes preguntas, o encontraste un problema con un tipo de archivo en particular? Deja un comentario abajo, y solucionemos juntos. ¡Feliz codificación, y que tus ejecuciones OCR sean rápidas y sin errores! + +## ¿Qué deberías aprender a continuación? + +- [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 texto de imágenes usando la operación OCR en carpetas](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..464d240d9 --- /dev/null +++ b/ocr/spanish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Crea una instancia de licencia en Python y configura la ruta de la licencia + fácilmente. Aprende cómo configurar la licencia de Aspose OCR con ejemplos de código + claros. +draft: false +keywords: +- create license instance +- configure license path +language: es +og_description: Crea una instancia de licencia en Python y configura la ruta de la + licencia al instante. Sigue este tutorial para activar Aspose OCR con confianza. +og_title: Crear instancia de licencia en Python – Guía completa de configuración +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Crear instancia de licencia en Python – Guía paso a paso +url: /es/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear instancia de licencia en Python – Guía completa de configuración + +¿Necesitas **crear una instancia de licencia** para Aspose OCR en Python? Estás en el lugar correcto. En este tutorial también te mostraremos cómo **configurar la ruta de la licencia** para que el SDK sepa dónde encontrar tu archivo `.lic`. + +Si alguna vez te has quedado mirando un script vacío preguntándote por qué el motor OCR sigue quejándose de un producto sin licencia, no estás solo. La solución suele ser solo un par de líneas de código—una vez que sabes exactamente dónde colocarlas. Al final de esta guía tendrás un entorno Aspose OCR completamente licenciado listo para reconocer texto, imágenes y PDFs sin problemas. + +## Qué aprenderás + +- Cómo **crear una instancia de licencia** usando el paquete `asposeocr`. +- La forma correcta de **configurar la ruta de la licencia** tanto para desarrollo como para producción. +- Problemas comunes (archivo faltante, permisos incorrectos) y cómo evitarlos. +- Un script completo y ejecutable que puedes incorporar a cualquier proyecto. + +No se requiere experiencia previa con Aspose OCR, solo una instalación funcional de Python 3 y un archivo de licencia válido. + +--- + +## Paso 1: Instalar el paquete Aspose OCR para Python + +Antes de que podamos **crear una instancia de licencia**, la biblioteca debe estar presente. Abre una terminal y ejecuta: + +```bash +pip install aspose-ocr +``` + +> **Consejo profesional:** Si estás usando un entorno virtual (altamente recomendado), actívalo primero. Esto mantiene tus dependencias ordenadas y evita conflictos de versiones. + +## Paso 2: Importar la clase License + +Ahora que el SDK está disponible, la primera línea de tu script debe importar la clase `License`. Este es el objeto que usaremos para **crear una instancia de licencia**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +¿Por qué importarlo de inmediato? Porque el objeto `License` debe instanciarse **antes** de cualquier llamada OCR; de lo contrario el SDK lanzará un error de licencia en el momento en que intentes procesar una imagen. + +## Paso 3: Crear instancia de licencia + +Aquí llega el momento que estabas esperando—realmente **crear una instancia de licencia**. Es una sola línea, pero el contexto que la rodea importa. + +```python +# Step 3: Create a License instance +license = License() +``` + +La variable `license` ahora contiene un objeto que controla todo el comportamiento de licenciamiento para el proceso Python actual. Piensa en él como el guardián que le dice a Aspose OCR: “Oye, tengo el derecho de ejecutarme”. + +## Paso 4: Configurar la ruta de la licencia + +Con la instancia lista, necesitamos apuntarla a nuestro archivo `.lic`. Ahí es donde entra en juego **configurar la ruta de la licencia**. Reemplaza el marcador de posición con la ruta absoluta a tu archivo de licencia. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Algunos puntos a tener en cuenta: + +1. **Cadenas crudas (`r"…"`)** evitan que las barras invertidas se interpreten como caracteres de escape en Windows. +2. Usa una **ruta absoluta** para evitar confusiones cuando el script se ejecute desde un directorio de trabajo diferente. +3. Si prefieres una ruta relativa (p. ej., al empaquetar la licencia con tu proyecto), asegúrate de que la base relativa sea la ubicación del script, no el directorio actual del shell. + +### Manejo de archivos faltantes + +Si la ruta es incorrecta o el archivo no se puede leer, `set_license` lanzará una excepción. Envuelve la llamada en un bloque `try/except` para proporcionar un mensaje de error amigable: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Este fragmento **configura la ruta de la licencia** de forma segura y te indica exactamente qué salió mal—sin rastros de pila misteriosos. + +## Paso 5: Verificar que la licencia está activa + +Una rápida comprobación de sanidad ahorra horas de depuración más adelante. Después de haber llamado a `set_license`, prueba una operación OCR simple. Si la licencia es válida, el SDK procesará la imagen sin lanzar un error de licencia. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Si ves el texto reconocido impreso, felicidades—has **creado una instancia de licencia** y **configurado la ruta de la licencia** con éxito. Si obtienes una excepción de licencia, verifica nuevamente la ruta y los permisos del archivo. + +## Casos límite y buenas prácticas + +| Situación | Qué hacer | +|-----------|------------| +| **El archivo de licencia está en un recurso de red** | Mapea el recurso a una letra de unidad o usa una ruta UNC (`\\servidor\recurso\license.lic`). Asegúrate de que el proceso Python tenga acceso de lectura. | +| **Ejecutando dentro de un contenedor Docker** | Copia el archivo `.lic` dentro de la imagen y haz referencia a él con una ruta absoluta como `/app/license/Aspose.OCR.Java.lic`. | +| **Múltiples intérpretes de Python** (p. ej., entornos conda) | Instala el archivo de licencia una vez por entorno o mantenlo en una ubicación central y apunta cada intérprete a ella. | +| **Archivo de licencia ausente en tiempo de ejecución** | Cambia a un modo de prueba (si está soportado) o aborta con un mensaje de registro claro. | + +### Errores comunes + +- **Usar barras diagonales (`/`) en Windows** – Python las acepta, pero algunas versiones antiguas del SDK pueden interpretarlas incorrectamente. Usa cadenas crudas o dobles barras invertidas. +- **Olvidar importar `License`** – El script fallará con `NameError`. Siempre importa antes de instanciar. +- **Llamar a `set_license` después de los métodos OCR** – El SDK verifica la licencia en el primer uso, así que establece la ruta **primero**. + +## Ejemplo completo y funcional + +A continuación tienes un script completo que une todo. Guárdalo como `ocr_setup.py` y ejecútalo desde la línea de comandos. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Salida esperada** (asumiendo una imagen válida): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Si el archivo de licencia no se encuentra, verás un mensaje de error claro en lugar de una excepción críptica “License not found”. + +--- + +## Conclusión + +Ahora sabes exactamente cómo **crear una instancia de licencia** en Python y **configurar la ruta de la licencia** para el SDK Aspose OCR. Los pasos son sencillos: instalar el paquete, importar `License`, instanciarlo, apuntarlo a tu archivo `.lic` y verificar con una pequeña prueba OCR. + +Con este conocimiento puedes integrar capacidades OCR en servicios web, aplicaciones de escritorio o pipelines automatizados sin tropezar con errores de licenciamiento. A continuación, considera explorar configuraciones OCR avanzadas—paquetes de idiomas, preprocesamiento de imágenes o procesamiento por lotes—cada una de las cuales se basa en la sólida base que acabas de crear. + +¿Tienes preguntas sobre despliegue, Docker o manejo de múltiples licencias? Deja un comentario, ¡y feliz codificación! + +## ¿Qué deberías aprender a continuación? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..a1ad24703 --- /dev/null +++ b/ocr/spanish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Crear PDF buscable a partir de imágenes escaneadas usando OCR de Python. + Aprende cómo convertir PDF de imágenes escaneadas, convertir TIFF a PDF y añadir + una capa de texto OCR en minutos. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: es +og_description: Crea PDF buscable al instante. Esta guía muestra cómo ejecutar OCR, + convertir PDF de imágenes escaneadas y añadir una capa de texto OCR usando un único + script de Python. +og_title: Crear PDF buscable con Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Crear PDF buscable con Python – Guía paso a paso +url: /es/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear PDF buscable con Python – Guía paso a paso + +¿Alguna vez te has preguntado cómo **crear PDF buscable** a partir de una página escaneada sin tener que usar docenas de herramientas? No estás solo. En muchos flujos de trabajo de oficina, un TIFF o JPEG escaneado llega a una unidad compartida, y la siguiente persona tiene que copiar‑pegar el texto manualmente—doloroso, propenso a errores y una pérdida de tiempo. + +En este tutorial recorreremos una solución limpia y programática que te permite **convertir PDF de imagen escaneada**, **convertir TIFF a PDF**, y **añadir capa de texto OCR** de una sola vez. Al final tendrás un script listo para usar que ejecuta OCR, inserta el texto oculto y genera un PDF buscable que puedes indexar, buscar o compartir con confianza. + +## Lo que necesitarás + +- Python 3.9+ (cualquier versión reciente funciona) +- `aspose-ocr` y `aspose-pdf` packages (instalados mediante `pip install aspose-ocr aspose-pdf`) +- Un archivo de imagen escaneada (`.tif`, `.png`, `.jpg`, o incluso una página PDF que sea solo una imagen) +- Una cantidad modesta de RAM (el motor OCR es liviano; incluso una laptop lo maneja) + +> **Consejo profesional:** Si estás en Windows, la forma más fácil de obtener los paquetes es ejecutar el comando en una ventana de PowerShell con privilegios elevados. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Ahora que los requisitos previos están listos, sumerjámonos en el código. + +## Paso 1: Crear una instancia del motor OCR – *create searchable pdf* + +Lo primero que hacemos es iniciar el motor OCR. Piensa en él como el cerebro que leerá cada píxel y lo convertirá en caracteres. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Por qué es importante:** Inicializar el motor solo una vez mantiene bajo el uso de memoria. Si llamaras a `OcrEngine()` dentro de un bucle para cada página, rápidamente te quedarías sin recursos. + +## Paso 2: Cargar la imagen escaneada – *convert tiff to pdf* & *convert scanned image pdf* + +A continuación, apunta el motor al archivo que deseas procesar. La API acepta cualquier imagen raster, por lo que un TIFF funciona tan bien como un JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Si tienes un PDF que contiene solo una imagen escaneada, aún puedes usar `load_image` porque Aspose extraerá automáticamente la primera página. + +## Paso 3: Preparar las opciones de guardado de PDF – *add OCR text layer* + +Aquí configuramos cómo debe verse el PDF final. La bandera crucial es `create_searchable_pdf`; establecerla en `True` indica a la biblioteca que inserte una capa de texto invisible que refleje el contenido visual. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Qué hace la capa de texto:** Cuando abres el archivo resultante en Adobe Reader e intentas seleccionar texto, verás los caracteres ocultos. Los motores de búsqueda también pueden indexarlos—perfecto para cumplimiento o archivado. + +## Paso 4: Ejecutar OCR y guardar – *how to run OCR* en una sola llamada + +Ahora ocurre la magia. Una única llamada al método ejecuta el motor de reconocimiento y escribe el PDF buscable en el disco. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +El método `recognize` devuelve un objeto de estado que puedes inspeccionar para detectar errores, pero para la mayoría de los escenarios simples la llamada anterior es suficiente. + +### Salida esperada + +Ejecutar el script imprime: + +``` +PDF saved as searchable PDF. +``` + +Si abres `scanned_page_searchable.pdf` notarás que puedes seleccionar texto, copiar‑pegarlo e incluso ejecutar una búsqueda `Ctrl+F`. Ese es el sello de un flujo de trabajo **create searchable pdf**. + +## Script completo y funcional + +A continuación tienes el script completo, listo para ejecutar. Simplemente reemplaza las rutas de marcador de posición con las ubicaciones reales de tus archivos. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Guarda esto como `create_searchable_pdf.py` y ejecútalo: + +```bash +python create_searchable_pdf.py +``` + +## Preguntas frecuentes y casos límite + +### 1️⃣ ¿Puedo procesar PDFs de varias páginas? + +Sí. Usa `ocr_engine.load_image("file.pdf")` y luego itera sobre cada página con `ocr_engine.recognize(pdf_save_options, page_number)`. La biblioteca generará automáticamente un PDF buscable de varias páginas. + +### 2️⃣ ¿Qué pasa si mi archivo fuente es un TIFF de alta resolución (300 dpi+)? + +Un DPI más alto brinda mejor precisión de OCR pero también mayor uso de memoria. Si encuentras un `MemoryError`, reduce la escala de la imagen primero: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ ¿Cómo cambio el idioma del OCR? + +Establece la propiedad `language` en el motor antes de cargar la imagen: + +```python +ocr_engine.language = "fra" # French +``` + +Una lista completa de los códigos de idioma compatibles está en la documentación de Aspose. + +### 4️⃣ ¿Qué pasa si necesito mantener la calidad original de la imagen? + +La clase `PdfSaveOptions` tiene una propiedad `compression`. Establécela en `PdfCompression.None` para preservar los datos raster exactamente como estaban. + +```python +pdf_save_options.compression = "None" +``` + +## Consejos para implementaciones listas para producción + +- **Procesamiento por lotes:** Envuelve la lógica central en una función que acepte una lista de rutas de archivo. Registra cada éxito/error en un CSV para auditorías. +- **Paralelismo:** Usa `concurrent.futures.ThreadPoolExecutor` para ejecutar OCR en varios núcleos. Solo recuerda que cada hilo necesita su propia instancia de `OcrEngine`. +- **Seguridad:** Si manejas documentos sensibles, ejecuta el script en un entorno aislado y elimina los archivos temporales inmediatamente después del procesamiento. + +## Conclusión + +Ahora sabes cómo **crear PDF buscables** a partir de imágenes escaneadas usando un script conciso en Python. Al inicializar un motor OCR, cargar un TIFF (o cualquier raster), configurar `PdfSaveOptions` para **add OCR text layer**, y finalmente llamar a `recognize`, todo el flujo **convert scanned image pdf** y **convert TIFF to PDF** se convierte en un único comando repetible. + +¿Próximos pasos? Intenta encadenar este script con un observador de archivos para que cualquier nuevo escaneo colocado en una carpeta se vuelva automáticamente buscable. O experimenta con diferentes idiomas de OCR para soportar archivos multilingües. El cielo es el límite cuando combinas OCR con generación de PDF. + +¿Tienes más preguntas sobre **how to run OCR** en otros lenguajes o frameworks? Deja un comentario abajo, ¡y feliz codificación! + +![Diagrama que muestra el flujo desde imagen escaneada → motor OCR → PDF buscable (create searchable pdf)](searchable-pdf-flow.png "Diagrama del flujo de crear PDF buscable") + + +## ¿Qué deberías aprender a continuación? + +- [Cómo hacer OCR de PDF en .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convertir imágenes a PDF C# – Guardar resultado OCR multipágina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Cómo hacer OCR de texto en imágenes con idioma usando Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/spanish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..de45aecb1 --- /dev/null +++ b/ocr/spanish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Mejora la precisión del OCR con Python preprocesando imágenes para OCR. + Aprende a extraer texto de archivos de imagen, reconocer texto de PNG y potenciar + los resultados. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: es +og_description: Mejora la precisión del OCR en Python aplicando preprocesamiento de + imágenes para texto. Sigue esta guía para extraer texto de archivos de imagen y + reconocer texto de PNG sin esfuerzo. +og_title: Mejora la precisión del OCR en Python – Tutorial completo +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Mejora la precisión del OCR en Python – Guía completa paso a paso +url: /es/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-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 Paso a Paso + +¿Alguna vez intentaste **mejorar la precisión del OCR** solo para obtener una salida incomprensible? No eres el único. La mayoría de los desarrolladores se topan con el problema cuando la imagen cruda es ruidosa, está sesgada o simplemente tiene bajo contraste. ¿La buena noticia? Un puñado de trucos de preprocesamiento pueden convertir una captura borrosa en texto limpio y legible por máquina. + +En este tutorial recorreremos un ejemplo del mundo real que **preprocesa una imagen para OCR**, ejecuta el motor de reconocimiento y, finalmente, **extrae texto de archivos de imagen**—específicamente un PNG. Al final sabrás exactamente cómo **reconocer texto de PNG** con una mayor tasa de éxito, y tendrás un fragmento de código reutilizable que puedes insertar en cualquier proyecto. + +## Qué Aprenderás + +- Por qué el preprocesamiento de imágenes es importante para los motores OCR +- Qué modos de preprocesamiento (denoise, deskew) aportan el mayor impulso +- Cómo configurar una instancia de `OcrEngine` en Python +- El script completo y ejecutable que **extrae texto de archivos de imagen** +- Consejos para manejar casos extremos como escaneos rotados o imágenes de baja resolución + +No se requieren bibliotecas externas más allá del OCR SDK, pero necesitarás Python 3.8+ y una imagen PNG que quieras leer. + +--- + +![Diagrama que muestra los pasos para mejorar la precisión del OCR en Python](image.png "Flujo de trabajo para mejorar la precisión del OCR") + +*Texto alternativo: diagrama del flujo de trabajo para mejorar la precisión del OCR que ilustra los pasos de preprocesamiento y reconocimiento.* + +## Requisitos Previos + +- Python 3.8 o superior instalado +- Acceso al OCR SDK que proporciona `OcrEngine`, `OcrEngineSettings` y `ImagePreprocessMode` (el código a continuación usa una API genérica; reemplázala con las clases de tu proveedor si es necesario) +- Una imagen PNG (`input.png`) ubicada en una carpeta a la que puedas hacer referencia + +Si estás usando un entorno virtual, actívalo ahora—nada complicado, solo `python -m venv venv && source venv/bin/activate`. + +--- + +## Paso 1: Crear la Instancia del Motor OCR – Comenzar a Mejorar la Precisión del OCR + +Lo primero que necesitas es un objeto motor OCR. Piensa en él como el cerebro que más tarde leerá los píxeles y generará caracteres. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Por qué es importante: sin un motor no puedes aplicar ningún preprocesamiento, y la imagen cruda se enviará directamente al reconocedor—generalmente el peor escenario para la precisión. + +--- + +## Paso 2: Cargar el PNG de Destino – Preparar el Escenario para Reconocer Texto de PNG + +Ahora indicamos al motor qué archivo debe procesar. PNG es sin pérdida, lo que ya nos brinda una pequeña ventaja sobre JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Si la imagen está en otro lugar, simplemente ajusta la ruta. El motor acepta cualquier formato compatible, pero PNG suele conservar los detalles finos necesarios para bordes de caracteres nítidos. + +--- + +## Paso 3: Configurar el Preprocesamiento – Preprocesar Imagen para OCR + +Aquí es donde ocurre la magia. Creamos un objeto de configuración, habilitamos la eliminación de ruido para borrar los puntos y activamos la corrección de sesgo para que el texto inclinado se enderece automáticamente. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### ¿Por Qué Denoise + Deskew? + +- **Denoise**: El ruido aleatorio de píxeles confunde a los algoritmos de coincidencia de patrones. Eliminarlo afila las letras. +- **Deskew**: Incluso una inclinación de 2 grados puede reducir drásticamente las puntuaciones de confianza. Deskew alinea la línea base, permitiendo que el reconocedor coincida con las fuentes de forma más fiable. + +Puedes experimentar con banderas adicionales (p. ej., `ImagePreprocessMode.CONTRAST_ENHANCE`) si tus imágenes son especialmente oscuras. La documentación del SDK suele listar todos los modos disponibles. + +--- + +## Paso 4: Aplicar la Configuración al Motor – Vincular el Preprocesamiento al OCR + +Asigna el objeto de configuración al motor para que la siguiente ejecución de reconocimiento utilice las transformaciones que acabamos de definir. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Si omites este paso, el motor volverá a su configuración predeterminada (a menudo “sin preprocesamiento”), y verás **menor precisión del OCR**. + +--- + +## Paso 5: Ejecutar el Proceso de Reconocimiento – Extraer Texto de la Imagen + +Con todo conectado, finalmente le pedimos al motor que haga su trabajo. La llamada es sincrónica, devolviendo un objeto de resultado que contiene la cadena reconocida. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Detrás de escena, el motor ahora: + +1. Carga el PNG en memoria +2. Aplica denoise y deskew según nuestra configuración +3. Ejecuta la red neuronal o el coincididor de patrones clásico +4. Empaqueta la salida en `recognition_result` + +--- + +## Paso 6: Mostrar el Texto Reconocido – Verificar la Mejora + +Imprimamos la cadena extraída. En una aplicación real podrías escribirla en un archivo, una base de datos o pasarla a otro servicio. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Salida Esperada + +Si la imagen contiene la frase “Hello, OCR World!” deberías ver: + +``` +Hello, OCR World! +``` + +Observa cómo el texto está limpio—sin símbolos extraños ni caracteres rotos. Ese es el resultado de un **preprocesamiento de imagen adecuado para texto**. + +--- + +## Consejos Profesionales y Casos Extremos + +| Situación | Qué Ajustar | Por Qué | +|-----------|-------------|---------| +| PNG de muy baja resolución (≤ 72 dpi) | Añadir `ImagePreprocessMode.SUPER_RESOLUTION` si está disponible | El upsampling puede proporcionar más píxeles al reconocedor | +| Texto rotado > 5° | Incrementar la tolerancia de deskew o rotar manualmente con `Pillow` antes de pasar al motor | Ángulos extremos a veces evaden el deskew automático | +| Patrones de fondo intensos | Habilitar `ImagePreprocessMode.BACKGROUND_REMOVAL` | Elimina el desorden no textual que de otro modo se leería incorrectamente | +| Documento multilingüe | Establecer `ocr_engine.language = "eng+spa"` (o similar) | El motor selecciona el conjunto de caracteres correcto, mejorando la precisión global | + +Recuerda, **mejorar la precisión del OCR** no es una solución única para todos; puede que necesites iterar sobre las banderas de preprocesamiento para tu conjunto de datos específico. + +--- + +## Script Completo – Listo para Copiar y Pegar + +A continuación tienes el ejemplo completo y ejecutable que incorpora cada paso que discutimos. Guárdalo como `improve_ocr_accuracy.py` y ejecútalo con `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Ejecuta el script, observa la consola y verás el resultado de **extraer texto de la imagen** de inmediato. Si la salida parece incorrecta, ajusta las banderas `preprocess_mode` como se describe en la tabla “Consejos Profesionales”. + +--- + +## Conclusión + +Acabamos de recorrer una receta práctica para **mejorar la precisión del OCR** usando Python. Al crear un `OcrEngine`, cargar un PNG, **preprocesar la imagen para OCR**, y finalmente **reconocer texto de PNG**, puedes extraer de forma fiable **texto de archivos de imagen** incluso cuando la fuente no es perfecta. + +¿Qué sigue? Prueba procesar un lote de imágenes dentro de un bucle, guarda cada resultado en un CSV, o experimenta con modos de preprocesamiento adicionales como la mejora de contraste. El mismo patrón funciona para PDFs, recibos escaneados o notas manuscritas—solo cambia la entrada y ajusta la configuración. + +¿Tienes preguntas sobre un tipo de imagen específico o quieres saber cómo integrar esto en un servicio web? Deja un comentario y exploraremos esos escenarios juntos. ¡Feliz codificación, y que tus resultados de OCR sean siempre cristalinos! + +## ¿Qué Deberías Aprender a Continuación? + +- [Extraer Texto de Imagen con Aspose OCR – Guía Paso a Paso](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extraer Texto de Imagen – Optimización OCR con Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Cómo Extraer Texto de Imagen Preparando Rectángulos en OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/spanish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..b4588763c --- /dev/null +++ b/ocr/spanish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Aprende a usar la región de interés de OCR para cargar una imagen y extraer + texto de un rectángulo, ideal para reconocer el monto en una factura. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: es +og_description: Domina la región de interés OCR para cargar la imagen, extraer texto + del rectángulo y reconocer el texto de una factura en un único tutorial. +og_title: OCR Región de Interés – Guía paso a paso en Python +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR de Región de Interés – Extraer texto de un rectángulo en Python +url: /es/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Región de Interés OCR – Extraer Texto de un Rectángulo en Python + +¿Alguna vez te has preguntado cómo **ocr region of interest** una parte específica de una factura escaneada sin alimentar toda la página al motor? No eres el primero que mira un recibo borroso y piensa: “¿Cómo extraigo el importe que está en alguna parte de la esquina inferior derecha?” La buena noticia es que puedes indicarle a la biblioteca OCR exactamente dónde buscar, lo que aumenta drásticamente la velocidad y la precisión. + +En esta guía recorreremos un ejemplo completo y ejecutable que muestra cómo **load image for OCR**, definir una **region of interest**, y luego **extract text from rectangle** para finalmente **recognize text from invoice** y responder la clásica pregunta “cómo extraer el importe”. Sin referencias vagas—solo código concreto, explicaciones claras y algunos consejos profesionales que desearías haber sabido antes. + +--- + +## Qué Construirás + +Al final de este tutorial tendrás un pequeño script en Python que: + +1. Carga una imagen de factura desde el disco. +2. Marca una ROI rectangular donde se encuentra el importe total. +3. Ejecuta OCR solo dentro de esa ROI. +4. Imprime la cadena del importe limpiada. + +Todo esto funciona con cualquier biblioteca OCR que soporte ROI—aquí usaremos un paquete ficticio pero representativo `SimpleOCR` que imita herramientas populares como Tesseract o EasyOCR. Si lo deseas, puedes cambiarlo; los conceptos siguen siendo los mismos. + +--- + +## Requisitos Previos + +- Python 3.8+ instalado (`python --version` debe mostrar ≥3.8). +- Un paquete OCR instalable con pip (p. ej., `pip install simpleocr`). +- Una imagen de factura (PNG o JPEG) colocada en una carpeta a la que puedas referenciar. +- Familiaridad básica con funciones y clases de Python (nada sofisticado). + +Si ya tienes todo eso, genial—¡vamos al grano! Si no, consigue la imagen primero; el resto de los pasos es independiente del contenido real del archivo. + +--- + +## Paso 1: Load Image for OCR + +Lo primero que necesita cualquier flujo de trabajo OCR es un mapa de bits del que leer. La mayoría de las bibliotecas exponen un método simple `load_image` que acepta una ruta de archivo. Así es como lo haces con nuestro motor `SimpleOCR`: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Usa rutas absolutas o `os.path.join` para evitar sorpresas de “archivo no encontrado” al ejecutar el script desde un directorio de trabajo diferente. + +--- + +## Paso 2: Define OCR Region of Interest + +En lugar de dejar que el motor escanee toda la página, le decimos *exactamente* dónde se encuentra el importe. Este es el paso **ocr region of interest**, y es la clave para una extracción fiable, especialmente cuando el documento contiene encabezados o pies de página ruidosos. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +¿Por qué esos números? `x` e `y` son desplazamientos en píxeles desde la esquina superior izquierda, mientras que `width` y `height` describen el tamaño del cuadro. Si no estás seguro, abre la imagen en cualquier editor, habilita una regla y anota las coordenadas. Muchos IDE incluso permiten imprimir la posición del cursor al pasar el ratón. + +--- + +## Paso 3: Extract Text from Rectangle + +Ahora que la ROI está definida, le pedimos al motor **recognize text from invoice** pero limitado al rectángulo que acabamos de añadir. La llamada devuelve un objeto de resultado que típicamente contiene la cadena cruda, puntuaciones de confianza y, a veces, cajas delimitadoras. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Detrás de escena, `recognize()` itera sobre cada ROI, recorta esa porción, ejecuta el modelo OCR y une los resultados. Por eso definir una región **extract text from rectangle** ajustada puede ahorrar segundos en el tiempo de procesamiento para trabajos por lotes. + +--- + +## Paso 4: How to Extract Amount – Clean the Output + +OCR no es perfecto; a menudo obtendrás espacios extra, saltos de línea o incluso caracteres mal leídos (p. ej., “S” vs “5”). Un rápido `strip()` y una pequeña expresión regular suelen ser suficientes para valores monetarios. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Por qué importa:** Si planeas enviar el importe a una base de datos o a una pasarela de pagos, necesitas un formato predecible. Eliminar espacios en blanco y filtrar caracteres no numéricos previene errores posteriores. + +--- + +## Paso 5: Recognize Text from Invoice – Script Completo + +Juntándolo todo, aquí tienes el script completo, listo para ejecutar. Guárdalo como `extract_amount.py` y ejecuta `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Salida Esperada + +``` +Amount: 1,245.67 +``` + +Si la ROI está desalineada, podrías ver algo como `Amount: 1245.6S`—nota la “S” extra. Ajusta las coordenadas del rectángulo y vuelve a ejecutar hasta que la salida se vea limpia. + +--- + +## Problemas Comunes & Casos Límite + +| Problema | Por Qué Ocurre | Solución | +|----------|----------------|----------| +| **ROI demasiado pequeña** | El texto del importe se corta, lo que lleva a un reconocimiento parcial. | Amplía `width`/`height` en ~10‑20 % y vuelve a probar. | +| **DPI incorrecto** | Escaneos de baja resolución (≤150 dpi) reducen la precisión del OCR. | Remuestrea la imagen a 300 dpi antes de cargarla, o solicita al escáner una DPI mayor. | +| **Múltiples monedas** | La regex captura el primer grupo numérico, que podría ser el número de factura. | Refina la regex para buscar símbolos de moneda (`$`, `€`, `£`) antes de los dígitos. | +| **Facturas rotadas** | Los motores OCR asumen texto vertical; las páginas rotadas rompen el reconocimiento. | Aplica una corrección de rotación (`ocr_engine.rotate(90)`) antes de añadir la ROI. | +| **Ruido de fondo** | Sombras o sellos confunden al modelo. | Pre‑procesa con un umbral simple (`cv2.threshold`) o usa un filtro de reducción de ruido. | + +Abordar estos casos límite temprano te ahorrará horas de depuración más adelante. + +--- + +## Consejos Profesionales para Proyectos Reales + +- **Procesamiento por Lotes:** Recorre una carpeta de facturas, calcula la ROI dinámicamente (p. ej., basándote en detección de plantillas) y guarda los resultados en CSV. +- **Coincidencia de Plantillas:** Si manejas varios diseños de factura, mantén un mapa JSON de `template_id → coordenadas ROI`. Cambia la ROI según un clasificador rápido de diseño. +- **Ejecución Paralela:** Usa `concurrent.futures.ThreadPoolExecutor` para ejecutar múltiples instancias OCR concurrentemente—ideal para pipelines de back‑office de alto volumen. +- **Filtrado por Confianza:** La mayoría de los resultados OCR incluyen una puntuación de confianza. Descarta resultados por debajo de un umbral (p. ej., 85 %) y márcalos para revisión manual. + +--- + +## Conclusión + +Hemos cubierto todo lo que necesitas para **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, y finalmente **recognize text from invoice** para responder la clásica pregunta **how to extract amount**. El script es compacto, pero lo suficientemente flexible como para adaptarse a diferentes formatos de documentos, idiomas y back‑ends OCR. + +Ahora que dominas lo básico, considera ampliar el flujo de trabajo: añadir escaneo de códigos de barras, integrar con un parser de PDF, o enviar el importe extraído a una API contable. El cielo es el límite, y con una ROI bien definida siempre obtendrás resultados más rápidos y limpios. + +Si encuentras algún problema, deja un comentario abajo—¡feliz OCR! + +![ejemplo de región de interés OCR](https://example.com/ocr_roi_example.png "ejemplo de región de interés OCR") + + +## ¿Qué Deberías Aprender Después? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/swedish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..e9fac5d26 --- /dev/null +++ b/ocr/swedish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Asynkron OCR-handledning som visar hur du använder Aspose OCR i Python + med asyncio för snabb bildtextutvinning. Lär dig steg‑för‑steg asynkron OCR-implementation. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: sv +og_description: Async OCR-handledning guidar dig genom att använda Aspose OCR i Python + med asyncio för effektiv extrahering av bildtext. +og_title: Asynkron OCR-handledning – Python asyncio med Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Asynkron OCR-handledning – Python asyncio med Aspose OCR +url: /sv/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR-handledning – Python asyncio med Aspose OCR + +Har du någonsin undrat hur man kör optisk teckenigenkänning utan att blockera din app? I en **async OCR tutorial** kommer du att se exakt det—icke‑blockerande textutvinning med Python's `asyncio` och Aspose OCR-biblioteket. + +Om du har fastnat i att vänta på att en tung bild ska bearbetas, ger den här guiden dig en ren, asynkron lösning som håller din händelseslinga igång. + +I avsnitten som följer kommer vi att gå igenom allt du behöver: installera biblioteket, koppla in en asynkron hjälpfunktion, hantera resultatet, och till och med ett snabbt tips för att skala till flera bilder. I slutet kommer du att kunna lägga in en **async OCR tutorial** i vilket Python‑projekt som helst som redan använder `asyncio`. + +## Vad du behöver + +* Python 3.9+ (API:et `asyncio` vi använder är stabilt från 3.7 och framåt) +* En aktiv Aspose OCR-licens eller en gratis provversion (biblioteket är ren‑Python, utan inhemska binärer) +* En liten bildfil (`.jpg`, `.png`, etc.) som du vill läsa – håll den i en känd mapp + +Inga andra externa verktyg krävs; allt körs i ren Python. + +## Steg 1: Installera Aspose OCR-paketet + +Först och främst, hämta Aspose OCR-paketet från PyPI. Öppna en terminal och kör: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** Om du arbetar i en virtuell miljö (starkt rekommenderat), aktivera den först. Detta håller beroenden isolerade och undviker versionskonflikter. + +## Steg 2: Initiera OCR-motorn asynkront + +Kärnan i vår **async OCR tutorial** är en asynkron hjälpfunktion. Den skapar en `OcrEngine`-instans, laddar en bild och anropar sedan `recognize_async()`. Motorn i sig är synkron, men omslagmetoden returnerar ett awaitable‑objekt, vilket låter händelseslingan förbli responsiv. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Varför vi gör så här:** +*Att skapa motorn inuti hjälpfunktionen säkerställer trådsäkerhet om du senare kör många OCR‑jobb parallellt. `await`‑nyckelordet ger tillbaka kontrollen till händelseslingan medan det tunga arbetet sker i bibliotekets interna trådpool.* + +## Steg 3: Anropa hjälpen från en asynkron huvudfunktion + +Nu behöver vi en liten `main()`‑korutin som anropar `async_ocr()` och skriver ut resultatet. Detta speglar den typiska startpunkten för ett `asyncio`‑skript. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Vad händer under huven?** +`asyncio.run()` skapar en ny händelseslinga, schemalägger `main()` och stänger ner slingan på ett rent sätt när `main()` är klar. Detta mönster är det rekommenderade sättet att starta asynkrona program i Python 3.7+. + +## Steg 4: Testa hela skriptet + +Spara de två kodblocken ovan i en enda fil, t.ex. `async_ocr_demo.py`. Kör den från kommandoraden: + +```bash +python async_ocr_demo.py +``` + +Om allt är korrekt konfigurerat bör du se något liknande: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Det exakta resultatet beror på innehållet i `photo.jpg`. Det viktiga är att skriptet avslutas snabbt, även om bilden är stor, eftersom OCR‑arbetet sker i bakgrunden. + +## Steg 5: Skala upp – Bearbeta flera bilder samtidigt + +En vanlig uppföljningsfråga är, *“Kan jag OCR:a en batch av filer utan att starta en ny process för varje?”* Absolut. Eftersom vår hjälpfunktion är helt asynkron kan vi samla många korutiner med `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Varför detta fungerar:** `asyncio.gather()` schemalägger alla OCR‑uppgifter på en gång. Det underliggande Aspose OCR‑biblioteket använder fortfarande sin egen trådpool, men ur Pythons perspektiv förblir allt icke‑blockerande, vilket låter dig hantera dussintals bilder på den tid en enda synkron anrop skulle ta. + +## Steg 6: Hantera fel på ett smidigt sätt + +När du arbetar med externa filer kommer du oundvikligen att stöta på saknade filer, korrupta bilder eller licensproblem. Omge OCR‑anropet med ett `try/except`‑block för att hålla händelseslingan vid liv: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Nu kan `batch_ocr()` anropa `safe_async_ocr` istället, vilket säkerställer att en dålig fil inte avbryter hela batchen. + +## Visuell översikt + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR-tutorial flödesschema som visar async_ocr-hjälp, händelseslinga och Aspose OCR-motor"} + +Diagrammet ovan visualiserar flödet: händelseslingan → `async_ocr` → `OcrEngine` → bakgrundstråd → resultat tillbaka till slingan. + +## Vanliga fallgropar & hur man undviker dem + +| Fallgrop | Varför det händer | Lösning | +|---------|-------------------|--------| +| **Blockerande I/O i hjälpen** | Att av misstag använda `open()` utan `await` kan blockera slingan. | Använd `aiofiles` för filinläsning, eller låt `engine.load_image` hantera det (det är redan icke‑blockerande). | +| **Återanvända en enda `OcrEngine` över korutiner** | Motorn är inte trådsäker; samtidiga anrop kan korrupta tillståndet. | Instansiera en ny motor inom varje `async_ocr`‑anrop (som visat). | +| **Saknad licens** | Aspose OCR kastar ett licensrelaterat undantag vid körning. | Registrera din licens tidigt (`OcrEngine.set_license("license.json")`). | +| **Stora bilder som orsakar minnesökningar** | Biblioteket laddar hela bilden i RAM. | Skala ner bilder innan OCR om minnet är en oro. | + +## Sammanfattning: Vad vi uppnådde + +I denna **async OCR tutorial** gjorde vi: + +1. Installerade Aspose OCR‑biblioteket. +2. Byggde en `async_ocr`‑hjälp som kör igenkänning utan att blockera. +3. Körde hjälpen från en ren `asyncio`‑startpunkt. +4. Demonstrerade batch‑bearbetning med `asyncio.gather`. +5. Lade till felhantering och bästa‑praxis‑tips. + +Allt detta är ren Python, så du kan lägga in det i en webbserver, ett CLI‑verktyg eller en datapipeline utan att skriva om befintlig asynkron kod. + +## Nästa steg & relaterade ämnen + +* **Asynkron bildförbehandling** – använd `aiohttp` för att ladda ner bilder samtidigt innan OCR. +* **Lagra OCR‑resultat** – kombinera denna handledning med en asynkron databaskörning som `asyncpg` för PostgreSQL. +* **Prestandaoptimering** – experimentera med `engine.recognize_async(max_threads=4)` om biblioteket exponerar ett sådant alternativ. +* **Alternativa OCR‑motorer** – jämför Aspose OCR med Tesseracts asynkrona omslag för en kostnads‑nyttokalkyl. + +Känn dig fri att experimentera: försök med PDF‑filer, justera språkinställningar, eller koppla resultaten till en chatbot. Himlen är gränsen när du har en solid **async OCR tutorial**‑grund. + +Lycka till med kodandet, och må din textutvinning alltid vara snabb! + +## Vad bör du lära dig härnäst? + +- [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/) +- [Aspose OCR‑handledning – optisk teckenigenkänning](/ocr/english/) +- [Hur man OCR‑ar bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/swedish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..5298b4f68 --- /dev/null +++ b/ocr/swedish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-31 +description: Automatisk språkdetektion i OCR gjort enkelt. Lär dig hur du laddar OCR + för bilder, aktiverar automatisk språkdetektion och känner igen text i bilden på + bara några steg. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: sv +og_description: Automatisk språkdetektering i OCR gjort enkelt. Följ den här steg‑för‑steg‑handledningen + för att aktivera automatisk språkdetektering, ladda bild‑OCR och känna igen text + i bilden. +og_title: Automatisk språkdetektion med OCR – Komplett Python‑guide +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Automatisk språkidentifiering med OCR – Komplett Python‑guide +url: /sv/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Automatisk språkdetektering med OCR – Komplett Python‑guide + +Har du någonsin undrat hur man får en OCR‑motor att *gissa* språket i ett skannat dokument utan att du berättar vad den ska leta efter? Det är precis vad **automatic language detection** gör, och det är en total spelväxlare när du hanterar flerspråkiga PDF‑filer, foton av gatunskyltar eller någon bild som blandar skript. + +I den här handledningen går vi igenom ett praktiskt exempel som visar dig hur du **enable auto language detection**, **load image OCR**, och **recognize text image** med ett Python‑liknande API. I slutet har du ett fristående skript som skriver ut både den upptäckta språkkoden och den extraherade texten—utan manuella språkinställningar. + +## Vad du kommer att lära dig + +- Hur man skapar en OCR‑motorinstans och slår på **automatic language detection**. +- De exakta stegen för att **load image OCR** från disk. +- Hur man anropar motorns `recognize()`‑metod och får tillbaka ett resultat som inkluderar språkkoden. +- Tips för att hantera kantfall som lågupplösta bilder eller språk som inte stöds. + +Ingen tidigare erfarenhet av flerspråkig OCR behövs; bara en grundläggande Python‑installation och en bildfil. + +--- + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +1. Python 3.8+ installerat (någon nyare version fungerar). +2. OCR‑biblioteket som tillhandahåller `OcrEngine`, `LanguageAutoDetectMode`, osv. – för den här guiden antar vi ett hypotetiskt paket som heter `myocr`. Installera det med: + + ```bash + pip install myocr + ``` + +3. En bildfil (`multilingual_sample.png`) som innehåller text på minst två olika språk. +4. Lite nyfikenhet—om du aldrig har rört OCR förut, oroa dig inte; koden är avsiktligt enkel. + +--- + +## Steg 1: Aktivera automatisk språkdetektering + +Det första du behöver göra är att tala om för motorn att den ska *ta reda på* språket på egen hand. Det är här flaggan för **automatic language detection** kommer in i bilden. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Varför detta är viktigt:** +> När `AUTO_DETECT` är satt kör motorn en lättviktig språkklassificerare på bilden innan den tunga teckenigenkänningen startar. Det betyder att du inte behöver gissa om texten är engelska, ryska, franska eller någon kombination därav. Motorn kommer automatiskt att välja den bästa språkmodellen för varje region i bilden. + +--- + +## Steg 2: Ladda bild‑OCR + +Nu när motorn vet att den ska auto‑detektera språk, måste vi ge den något att arbeta med. Steget **load image OCR** läser bitmapen och förbereder interna buffertar. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Proffstips:** +> Om din bild är större än 300 dpi, överväg att skala ner den till cirka 150‑200 dpi. För mycket detalj kan faktiskt *sakta ner* språkdetekteringssteget utan att förbättra noggrannheten. + +--- + +## Steg 3: Känn igen text från bild + +Med bilden i minnet och språkdetektering aktiverad är sista delen att be motorn att **recognize text image**. Detta enda anrop gör allt tungt arbete. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` är ett objekt som vanligtvis innehåller minst två attribut: + +| Attribut | Beskrivning | +|-----------|-------------| +| `language` | ISO‑639‑1‑kod för det upptäckta språket (t.ex. `"en"` för engelska). | +| `text` | Den rena texttranskriptionen av bilden. | + +--- + +## Steg 4: Hämta upptäckt språk och extraherad text + +Nu skriver vi helt enkelt ut vad motorn har upptäckt. Detta demonstrerar **detect language OCR**‑funktionen i praktiken. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Exempelutdata** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Vad händer om motorn returnerar `None`?** +> Det betyder vanligtvis att bilden är för suddig eller att texten är för liten (< 8 pt). Försök öka kontrasten eller använda en källa med högre upplösning. + +--- + +## Fullt fungerande exempel (Aktivera automatisk språkdetektering från början till slut) + +När vi sätter ihop allt, här är ett färdigt skript som täcker **enable auto language detection**, **load image OCR**, **recognize text image**, och **detect language OCR** i ett svep. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Spara detta som `automatic_language_detection_ocr.py`, ersätt `YOUR_DIRECTORY` med mappen som innehåller din PNG, och kör: + +```bash +python automatic_language_detection_ocr.py +``` + +Du bör se språkkoden följt av den extraherade texten, precis som i exempelutdata ovan. + +--- + +## Hantera vanliga kantfall + +| Situation | Föreslagen åtgärd | +|-----------|-------------------| +| **Mycket lågupplöst bild** (under 100 dpi) | Skala upp med ett bikubiskt filter innan inläsning, eller begär en källa med högre upplösning. | +| **Blandade skript i en bild** (t.ex. engelska + kyrilliska) | Motorn delar vanligtvis sidan i regioner; om du märker felaktiga detekteringar, sätt `engine.enable_region_split = True`. | +| **Ej stödd språk** | Verifiera att OCR‑biblioteket levereras med ett språkpaket för det skript du behöver; du kan behöva ladda ner ytterligare modeller. | +| **Storskalig batch‑behandling** | Initiera motorn en gång, återanvänd den sedan över flera `load_image` / `recognize`‑cykler för att undvika upprepad modellinläsning. | + +--- + +## Visuell översikt + +![exempel på utdata för automatisk språkdetektering](https://example.com/auto-lang-detect.png "automatisk språkdetektering") + +*Alt‑text:* exempel på utdata för automatisk språkdetektering som visar upptäckt språkkod och extraherad flerspråkig text. + +--- + +## Slutsats + +Vi har precis gått igenom **automatic language detection** från början till slut—skapa motorn, aktivera auto language detection, ladda en bild för OCR, känna igen texten och slutligen hämta det upptäckta språket. Detta end‑to‑end‑flöde låter dig bearbeta flerspråkiga dokument utan att manuellt konfigurera språkmodeller varje gång. + +Om du är redo att gå vidare, överväg: + +- **Batching** hundratals bilder med en loop som återanvänder samma `OcrEngine`‑instans. +- **Post‑processing** av den extraherade texten med en stavningskontroll eller språk‑specifik tokeniserare. +- **Integrating** skriptet i en webbtjänst som tar emot användaruppladdningar och returnerar JSON med fälten `language` och `text`. + +Känn dig fri att experimentera med olika bildformat (`.jpg`, `.tif`) och se hur detekteringsnoggrannheten förändras. Har du frågor eller en knepig bild som vägrar att läsas? Lämna en kommentar nedanför—lycka till med kodandet! + +## Vad bör du lära dig härnäst? + +- [Hur man OCR‑ar bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Känna igen bildtext med Aspose OCR för flera språk](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..221623559 --- /dev/null +++ b/ocr/swedish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Lär dig hur du konverterar bilder till text i Python med ett skript för + masskonvertering av bilder till text. Känn igen text från skannade bilder med Aspose.OCR + på några minuter. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: sv +og_description: Konvertera bilder till text med Python omedelbart. Denna guide visar + konvertering av bilder till text i bulk och hur man känner igen text från skannade + bilder med Aspose.OCR. +og_title: Konvertera bilder till text med Python – Fullständig handledning +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Konvertera bilder till text med Python – Komplett steg‑för‑steg‑guide +url: /sv/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera bilder till text med Python – Komplett steg‑för‑steg‑guide + +Har du någonsin undrat hur man **convert images to text python** utan att leta igenom dussintals bibliotek? Du är inte ensam. Oavsett om du digitaliserar gamla kvitton, extraherar data från skannade fakturor, eller bygger ett sökbart arkiv av PDF‑filer, är det en daglig rutin för många utvecklare att omvandla bilder till rena textfiler. + +I den här handledningen går vi igenom en **bulk image to text conversion**‑pipeline som känner igen text från skannade bilder, sparar varje resultat som en individuell `.txt`‑fil, och gör allt med bara några rader Python. Ingen mystisk shopping efter obskyra API:er—Aspose.OCR gör det tunga arbetet, och vi visar exakt hur du kopplar ihop det. + +## Vad du kommer att lära dig + +- Hur du installerar och konfigurerar Aspose.OCR för Python‑paketet. +- Den exakta koden som behövs för att **convert images to text python** med `BatchOcrEngine`. +- Tips för att hantera vanliga fallgropar som ej stödda format eller korrupta filer. +- Sätt att verifiera att steget **recognize text from scanned images** faktiskt lyckades. + +När du är klar med den här guiden har du ett färdigt skript som kan bearbeta tusentals bilder på en gång—perfekt för alla batch‑bearbetningsscenarier. + +## Förutsättningar + +- Python 3.8+ installerat på din maskin. +- En mapp med bildfiler (PNG, JPEG, TIFF, etc.) som du vill omvandla till text. +- Ett aktivt Aspose Cloud‑konto eller en gratis provlicens (gratisnivån räcker för testning). + +Om du har det, låt oss dyka ner. + +--- + +## Steg 1 – Ställ in din Python‑miljö + +Innan vi börjar skriva någon OCR‑kod, se till att du arbetar i en ren virtuell miljö. Detta isolerar beroenden och förhindrar versionskonflikter. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Proffstips:** Håll din projektkatalog organiserad—skapa en undermapp som heter `ocr_project` och placera skriptet där. Det gör sökvägshanteringen enkel senare. + +## Steg 2 – Installera Aspose.OCR för Python + +Aspose.OCR är ett kommersiellt bibliotek, men det levereras med ett gratis NuGet‑liknande wheel som du kan hämta från PyPI. Kör följande kommando i den aktiverade virtuella miljön: + +```bash +pip install aspose-ocr +``` + +Om du får ett behörighetsfel, lägg till flaggan `--user` eller kör kommandot med `sudo` (endast Linux/macOS). Efter installationen bör du se något liknande: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Varför Aspose?** Till skillnad från många open‑source OCR‑verktyg stödjer Aspose.OCR **bulk image to text conversion** direkt ur lådan och hanterar ett brett spektrum av bildformat utan extra konfiguration. Det erbjuder också en `BatchOcrEngine`‑klass som gör uppgiften “convert images to text python” till en en‑rad‑operation. + +## Steg 3 – Konvertera bilder till text med Python med Batch OCR + +Nu till kärnan i handledningen. Nedan är ett fullt körbart skript som: + +1. Importerar OCR‑motorklasserna. +2. Skapar en instans av `BatchOcrEngine`. +3. Pekar motorn mot en inmatningsmapp med bilder. +4. Dirigerar motorn att skriva varje extraherad textfil till en utmatningsmapp. +5. Aktiverar `recognize()`‑metoden, som **recognize text from scanned images** en efter en. + +Spara följande som `batch_ocr.py` i din projektmapp: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Så fungerar det + +- **`BatchOcrEngine`** omsluter den vanliga `OcrEngine` men lägger till mapp‑nivå orkestrering, vilket är exakt vad du behöver när du vill **convert images to text python** i bulk. +- `input_folder`‑egenskapen talar om för motorn var den ska leta efter källbilder. Den skannar automatiskt katalogen och köar varje stödd filtyp. +- `output_folder`‑egenskapen bestämmer var varje `.txt`‑fil hamnar. Motorn speglar det ursprungliga filnamnet, så `receipt1.png` blir `receipt1.txt`. +- Att anropa `recognize()` utlöser den interna loopen som laddar varje bild, kör OCR och skriver resultatet. Metoden blockerar tills varje fil är bearbetad, vilket gör det enkelt att kedja vidare åtgärder (t.ex. zippa utmatningsmappen). + +#### Förväntad output + +När du kör skriptet: + +```bash +python batch_ocr.py +``` + +Du bör se: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Inuti `output_texts` hittar du en ren‑text‑fil för varje bild. Öppna någon av dem med en textredigerare så ser du OCR‑resultatet—vanligtvis en nära approximation av den ursprungliga tryckta texten. + +## Steg 4 – Verifiera resultaten och hantera fel + +Även de bästa OCR‑motorerna kan snubbla på lågupplösta skanningar eller kraftigt skeva sidor. Här är ett snabbt sätt att kontrollera outputen och logga eventuella fel. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Varför lägga till detta?** +- Den fångar fall där motorn tyst producerade en tom sträng (vanligt med oläsliga bilder). +- Den ger dig en lista över problematiska filer så att du kan inspektera dem manuellt eller köra om med olika inställningar (t.ex. öka `OcrEngine.preprocess`‑alternativen). + +### Kantfall & justeringar + +| Situation | Föreslagen åtgärd | +|-----------|-------------------| +| Bilder är roterade 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Blandade språk (engelska + franska) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Stora PDF‑filer konverterade till bilder först | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Minnesfel vid mycket stora batcher | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Steg 5 – Automatisera hela arbetsflödet (valfritt) + +Om du behöver köra denna konvertering varje natt, paketera skriptet i ett enkelt shell‑ eller Windows‑batch‑fil, och schemalägg det med `cron` (Linux/macOS) eller Task Scheduler (Windows). Här är ett minimalt `run_ocr.sh` för Unix‑liknande system: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Gör den körbar (`chmod +x run_ocr.sh`) och lägg till ett cron‑entry: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Det kör konverteringen varje dag klockan 02:00 och loggar all output för senare granskning. + +--- + +## Slutsats + +Du har nu en beprövad, produktionsklar metod för att **convert images to text python** med Aspose.OCR:s `BatchOcrEngine`. Skriptet hanterar **bulk image to text conversion**, skriver smidigt varje resultat till en dedikerad fil, och inkluderar verifieringssteg för att säkerställa att du faktiskt **recognize text from scanned images** korrekt. + +Du kan nu: + +- Experimentera med olika OCR‑inställningar (språkpaket, deskew, brusreducering). +- Skicka den genererade texten till ett sökindex som Elasticsearch för omedelbar fulltext‑sökning. +- Kombinera denna pipeline med PDF‑konverteringsverktyg för att bearbeta skannade PDF‑filer i ett svep. + +Har du frågor, eller har du stött på ett problem med en viss filtyp? Lämna en kommentar nedan, så felsöker vi tillsammans. Lycka till med kodandet, och må dina OCR‑körningar vara snabba och felfria! + +## Vad bör du lära dig härnäst? + +- [Extrahera text från bild med Aspose OCR – Steg‑för‑steg‑guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extrahera text från bilder med OCR‑operation på mappar](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extrahera bildtext 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..ba3e66a6c --- /dev/null +++ b/ocr/swedish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Skapa licensinstans i Python och konfigurera licenssökvägen enkelt. Lär + dig hur du ställer in Aspose OCR‑licensiering med tydliga kodexempel. +draft: false +keywords: +- create license instance +- configure license path +language: sv +og_description: Skapa licensinstans i Python och konfigurera licenssökvägen omedelbart. + Följ den här handledningen för att aktivera Aspose OCR med självförtroende. +og_title: Skapa licensinstans i Python – Komplett installationsguide +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Skapa licensinstans i Python – Steg‑för‑steg‑guide +url: /sv/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa licensinstans i Python – Komplett installationsguide + +Behöver du **create license instance** för Aspose OCR i Python? Du är på rätt plats. I den här handledningen visar vi också hur du **configure license path** så att SDK vet var den ska hitta din `.lic`-fil. + +Om du någonsin har stirrat på ett tomt skript och undrat varför OCR-motorn fortsätter klaga på en olicensierad produkt, är du inte ensam. Lösningen är oftast bara ett par kodrader—när du vet exakt var du ska placera dem. I slutet av den här guiden har du en fullt licensierad Aspose OCR-miljö redo att känna igen text, bilder och PDF-filer utan problem. + +## Vad du kommer att lära dig + +- Hur du **create license instance** med paketet `asposeocr`. +- Det korrekta sättet att **configure license path** för både utveckling och produktion. +- Vanliga fallgropar (saknad fil, fel behörigheter) och hur du undviker dem. +- Ett komplett, körbart skript som du kan lägga in i vilket projekt som helst. + +Ingen tidigare erfarenhet av Aspose OCR krävs, bara en fungerande Python 3‑installation och en giltig licensfil. + +--- + +## Steg 1: Installera Aspose OCR Python‑paketet + +Innan vi kan **create license instance** måste själva biblioteket finnas. Öppna en terminal och kör: + +```bash +pip install aspose-ocr +``` + +> **Proffstips:** Om du använder en virtuell miljö (starkt rekommenderat), aktivera den först. Detta håller dina beroenden organiserade och förhindrar versionskonflikter. + +## Steg 2: Importera License‑klassen + +Nu när SDK:n är tillgänglig bör den allra första raden i ditt skript importera `License`‑klassen. Detta är objektet vi kommer att använda för att **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Varför importera den direkt? För att `License`‑objektet måste instansieras **innan** några OCR‑anrop; annars kastar SDK:n ett licensfel så snart du försöker bearbeta en bild. + +## Steg 3: Skapa licensinstans + +Här är ögonblicket du har väntat på—faktiskt **create license instance**. Det är en enda rad, men den omgivande kontexten är viktig. + +```python +# Step 3: Create a License instance +license = License() +``` + +Variabeln `license` innehåller nu ett objekt som styr all licenshantering för den aktuella Python‑processen. Tänk på det som portvakten som säger till Aspose OCR: “Hej, jag har rätt att köra.” + +## Steg 4: Konfigurera licenssökväg + +Med instansen klar måste vi peka den på vår `.lic`‑fil. Det är här **configure license path** kommer in i bilden. Ersätt platshållaren med den absoluta sökvägen till din licensfil. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Några saker att notera: + +1. **Raw strings (`r"…"`)** förhindrar att bakåtsnedstreck tolkas som escape‑tecken på Windows. +2. Använd en **absolut sökväg** för att undvika förvirring när skriptet startas från en annan arbetskatalog. +3. Om du föredrar en relativ sökväg (t.ex. när du paketerar licensen med ditt projekt), se till att den relativa basen är skriptets plats, inte den aktuella skal‑katalogen. + +### Hantera saknade filer + +Om sökvägen är fel eller filen är oläsbar, kommer `set_license` att kasta ett undantag. Omge anropet med ett `try/except`‑block för att ge ett vänligt felmeddelande: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Detta kodsnutt **configures license path** säkert och berättar exakt vad som gick fel—inga mystiska stack‑spår. + +## Steg 5: Verifiera att licensen är aktiv + +En snabb kontroll sparar timmar av felsökning senare. Efter att du har anropat `set_license`, prova en enkel OCR‑operation. Om licensen är giltig kommer SDK:n att bearbeta bilden utan att kasta ett licensfel. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Om du ser den igenkända texten skrivas ut, gratulerar—du har framgångsrikt **create license instance** och **configure license path**. Om du får ett licensundantag, dubbelkolla sökvägen och filbehörigheterna. + +## Edge Cases & bästa praxis + +| Situation | Vad man ska göra | +|-----------|-------------------| +| **Licensfilen finns på en nätverksdel** | Mappa delningen till en enhetsbokstav eller använd en UNC‑sökväg (`\\server\share\license.lic`). Säkerställ att Python‑processen har läsåtkomst. | +| **Kör i en Docker‑container** | Kopiera `.lic`‑filen till avbilden och referera den med en absolut sökväg som `/app/license/Aspose.OCR.Java.lic`. | +| **Flera Python‑tolkar** (t.ex. conda‑miljöer) | Installera licensfilen en gång per miljö eller håll den på en central plats och peka varje tolk till den. | +| **Licensfil saknas vid körning** | Falla elegant tillbaka till ett provläge (om det stöds) eller avbryt med ett tydligt loggmeddelande. | + +### Vanliga fallgropar + +- **Använda snedstreck framåt på Windows** – Python accepterar dem, men vissa äldre versioner av SDK:n kan missförstå dem. Håll dig till raw strings eller dubbla bakåtsnedstreck. +- **Glömt att importera `License`** – Skriptet kraschar med `NameError`. Importera alltid innan du instansierar. +- **Anropar `set_license` efter OCR‑metoder** – SDK:n kontrollerar licensen vid första användning, så sätt sökvägen **först**. + +## Fullt fungerande exempel + +Nedan är ett komplett skript som binder ihop allt. Spara det som `ocr_setup.py` och kör det från kommandoraden. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Förväntad output** (förutsatt en giltig bild): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Om licensfilen inte kan hittas får du ett tydligt felmeddelande istället för ett kryptiskt “License not found”-undantag. + +--- + +## Slutsats + +Du vet nu exakt hur du **create license instance** i Python och **configure license path** för Aspose OCR SDK. Stegen är enkla: installera paketet, importera `License`, instansiera det, peka på din `.lic`‑fil och verifiera med ett litet OCR‑test. + +Beväpnad med denna kunskap kan du integrera OCR‑funktioner i webb‑tjänster, skrivbordsprogram eller automatiserade pipelines utan att snubbla på licensfel. Nästa steg är att utforska avancerade OCR‑inställningar—språkpaket, bildförbehandling eller batch‑bearbetning—som alla bygger på den solida grund du just har lagt. + +Har du frågor om distribution, Docker eller hantering av flera licenser? Lägg en kommentar, och lycka till med kodningen! + +## Vad bör du lära dig härnäst? + +- [Aspose OCR‑handledning – Optisk teckenigenkänning](/ocr/english/) +- [Hur man ställer in licens och verifierar Aspose.OCR‑licens i Java](/ocr/english/java/ocr-basics/set-license/) +- [Hur man OCR‑läser bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..38e361517 --- /dev/null +++ b/ocr/swedish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-31 +description: Skapa sökbar PDF från skannade bilder med Python OCR. Lär dig hur du + konverterar skannad bild‑PDF, konverterar TIFF till PDF och lägger till ett OCR‑textlager + på några minuter. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: sv +og_description: Skapa sökbar PDF omedelbart. Den här guiden visar hur du kör OCR, + konverterar skannad bild‑PDF och lägger till ett OCR‑textlager med ett enda Python‑skript. +og_title: Skapa sökbar PDF med Python – Komplett handledning +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Skapa sökbar PDF med Python – Steg‑för‑steg‑guide +url: /sv/python-java/general/create-searchable-pdf-with-python-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 med Python – Steg‑för‑steg guide + +Har du någonsin undrat hur man **skapar sökbar PDF** från en skannad sida utan att jonglera med dussintals verktyg? Du är inte ensam. I många kontorsarbetsflöden hamnar en skannad TIFF eller JPEG på en gemensam enhet, och nästa person måste kopiera‑klistra text manuellt—smärtsamt, felbenäget och tidskrävande. + +I den här handledningen går vi igenom en ren, programmerbar lösning som låter dig **konvertera skannad bild‑PDF**, **konvertera TIFF till PDF**, och **lägga till OCR‑textlager** i ett svep. I slutet har du ett färdigt skript som kör OCR, bäddar in den dolda texten och genererar en sökbar PDF som du kan indexera, söka i eller dela med förtroende. + +## Vad du behöver + +- Python 3.9+ (någon nyare version fungerar) +- `aspose-ocr` and `aspose-pdf` packages (installerade via `pip install aspose-ocr aspose-pdf`) +- En skannad bildfil (`.tif`, `.png`, `.jpg`, eller till och med en PDF‑sida som bara är en bild) +- En måttlig mängd RAM (OCR‑motorn är lättviktig; även en laptop klarar det) + +> **Proffstips:** Om du använder Windows är det enklaste sättet att få paketen att köra kommandot i ett förhöjt PowerShell‑fönster. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Nu när förutsättningarna är avklarade, låt oss dyka ner i koden. + +## Steg 1: Skapa en OCR‑motorinstans – *create searchable pdf* + +Det första vi gör är att starta OCR‑motorn. Tänk på den som hjärnan som läser varje pixel och omvandlar den till tecken. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Varför detta är viktigt:** Att initiera motorn bara en gång håller minnesanvändningen låg. Om du skulle anropa `OcrEngine()` i en loop för varje sida, skulle du snabbt få slut på resurser. + +## Steg 2: Ladda den skannade bilden – *convert tiff to pdf* & *convert scanned image pdf* + +Nästa steg är att rikta motorn mot filen du vill bearbeta. API:et accepterar vilken rasterbild som helst, så en TIFF fungerar lika bra som en JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Om du råkar ha en PDF som bara innehåller en skannad bild, kan du fortfarande använda `load_image` eftersom Aspose automatiskt extraherar den första sidan. + +## Steg 3: Förbered PDF‑spara‑alternativ – *add OCR text layer* + +Här konfigurerar vi hur den slutgiltiga PDF‑filen ska se ut. Den avgörande flaggan är `create_searchable_pdf`; att sätta den till `True` instruerar biblioteket att bädda in ett osynligt textlager som speglar det visuella innehållet. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Vad textlagret gör:** När du öppnar den resulterande filen i Adobe Reader och försöker markera text, ser du de dolda tecknen. Sökmotorer kan också indexera dem—perfekt för efterlevnad eller arkivering. + +## Steg 4: Kör OCR och spara – *how to run OCR* i ett enda anrop + +Nu händer magin. Ett metodanrop kör igenkänningsmotorn och skriver den sökbara PDF‑filen till disk. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize`‑metoden returnerar ett statusobjekt som du kan inspektera för fel, men för de flesta enkla scenarier är det enkla anropet ovan tillräckligt. + +### Förväntad utdata + +Att köra skriptet skriver ut: + +``` +PDF saved as searchable PDF. +``` + +Om du öppnar `scanned_page_searchable.pdf` kommer du märka att du kan markera text, kopiera‑klistra den, och till och med köra en `Ctrl+F`‑sökning. Det är kännetecknet för ett **create searchable pdf**‑arbetsflöde. + +## Fullt fungerande skript + +Nedan är det kompletta, färdiga skriptet. Byt bara ut platshållar‑sökvägarna mot dina faktiska filplatser. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Spara detta som `create_searchable_pdf.py` och kör: + +```bash +python create_searchable_pdf.py +``` + +## Vanliga frågor & kantfall + +### 1️⃣ Kan jag bearbeta flersidiga PDF‑filer? + +Ja. Använd `ocr_engine.load_image("file.pdf")` och loopa sedan över varje sida med `ocr_engine.recognize(pdf_save_options, page_number)`. Biblioteket genererar automatiskt en flersidig sökbar PDF. + +### 2️⃣ Vad händer om min källfil är en högupplöst TIFF (300 dpi+)? + +Högre DPI ger bättre OCR‑noggrannhet men också större minnesanvändning. Om du får ett `MemoryError`, skala ner bilden först: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Hur ändrar jag språket för OCR? + +Ställ in `language`‑egenskapen på motorn innan du laddar bilden: + +```python +ocr_engine.language = "fra" # French +``` + +En fullständig lista över stödda språkkoder finns i Aspose‑dokumentationen. + +### 4️⃣ Vad händer om jag måste behålla den ursprungliga bildkvaliteten? + +`PdfSaveOptions`‑klassen har en `compression`‑egenskap. Sätt den till `PdfCompression.None` för att bevara rasterdata exakt som den var. + +```python +pdf_save_options.compression = "None" +``` + +## Tips för produktionsklar distribution + +- **Batch‑bearbetning:** Packa in kärnlogiken i en funktion som accepterar en lista med filsökvägar. Logga varje lyckat/misslyckat resultat till en CSV för revisionsspår. +- **Parallellism:** Använd `concurrent.futures.ThreadPoolExecutor` för att köra OCR på flera kärnor. Kom bara ihåg att varje tråd behöver sin egen `OcrEngine`‑instans. +- **Säkerhet:** Om du hanterar känsliga dokument, kör skriptet i en sandlådemiljö och radera de temporära filerna omedelbart efter bearbetning. + +## Slutsats + +Du vet nu hur man **skapar sökbar PDF**‑filer från skannade bilder med ett koncist Python‑skript. Genom att initiera en OCR‑motor, ladda en TIFF (eller någon raster), konfigurera `PdfSaveOptions` för att **lägga till OCR‑textlager**, och slutligen anropa `recognize`, blir hela **convert scanned image pdf**‑ och **convert TIFF to PDF**‑pipeline ett enda, repeterbart kommando. + +Nästa steg? Prova att kedja detta skript med en fil‑övervakare så att varje ny skanning som läggs i en mapp automatiskt blir sökbar. Eller experimentera med olika OCR‑språk för att stödja flerspråkiga arkiv. Himlen är gränsen när du kombinerar OCR med PDF‑generering. + +Har du fler frågor om **how to run OCR** i andra språk eller ramverk? Lämna en kommentar nedan, och lycka till med kodandet! + +![Diagram som visar flödet från skannad bild → OCR‑motor → sökbar PDF (create searchable pdf)](searchable-pdf-flow.png "Diagram för skapa sökbar pdf flöde") + + +## Vad bör du lära dig härnäst? + +- [Hur man OCR‑ar PDF i .NET med Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Konvertera bilder till PDF C# – Spara flersidigt OCR‑resultat](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Hur man OCR‑ar bildtext med språk med Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/swedish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..bf7f5341c --- /dev/null +++ b/ocr/swedish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Förbättra OCR‑noggrannheten med Python genom att förbehandla bilder för + OCR. Lär dig hur du extraherar text från bildfiler, känner igen text från PNG och + förbättrar resultaten. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: sv +og_description: Förbättra OCR‑noggrannheten i Python genom att tillämpa bildförbehandling + för text. Följ den här guiden för att extrahera text från bildfiler och känna igen + text från PNG utan ansträngning. +og_title: Förbättra OCR‑noggrannheten i Python – Fullständig handledning +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Förbättra OCR‑noggrannheten i Python – Komplett steg‑för‑steg‑guide +url: /sv/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-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 steg‑för‑steg‑guide + +Har du någonsin försökt **förbättra OCR‑noggrannheten** bara för att få en rörig utskrift? Du är inte ensam. De flesta utvecklare stöter på problem när den råa bilden är brusig, snedvriden eller helt enkelt har låg kontrast. Den goda nyheten? Ett fåtal förbehandlingsknep kan förvandla en suddig skärmbild till ren, maskinläsbar text. + +I den här handledningen går vi igenom ett verkligt exempel som **förbehandlar en bild för OCR**, kör igenkänningsmotorn och slutligen **extraherar text från bild**‑filer – specifikt en PNG. När du är klar vet du exakt hur du **läser text från PNG** med högre framgång, och du har ett återanvändbart kodsnutt som du kan klistra in i vilket projekt som helst. + +## Vad du kommer att lära dig + +- varför bildförbehandling är viktigt för OCR‑motorer +- vilka förbehandlingslägen (denoise, deskew) ger den största förbättringen +- hur du konfigurerar en `OcrEngine`‑instans i Python +- det kompletta, körbara skriptet som **extraherar text från bild**‑filer +- tips för att hantera kantfall som roterade skanningar eller lågupplösta bilder + +Inga externa bibliotek utöver OCR‑SDK:n behövs, men du behöver Python 3.8+ och en PNG‑bild du vill läsa. + +--- + +![Diagram som visar steg för att förbättra OCR‑noggrannhet i Python](image.png "Improve OCR accuracy workflow") + +*Alt‑text: diagram som visar arbetsflöde för att förbättra OCR‑noggrannhet och illustrerar förbehandling och igenkänningssteg.* + +## Förutsättningar + +- Python 3.8 eller nyare installerat +- Tillgång till OCR‑SDK:n som tillhandahåller `OcrEngine`, `OcrEngineSettings` och `ImagePreprocessMode` (koden nedan använder ett generiskt API; byt ut mot ditt leverantörs‑klasser om så behövs) +- En PNG‑bild (`input.png`) placerad i en mapp du kan referera till + +Om du använder ett virtuellt miljö, aktivera det nu – inget avancerat, bara `python -m venv venv && source venv/bin/activate`. + +--- + +## Steg 1: Skapa OCR‑motor‑instansen – Börja förbättra OCR‑noggrannhet + +Det första du behöver är ett OCR‑motor‑objekt. Tänk på det som hjärnan som senare läser pixlarna och spottar ut tecken. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Varför detta är viktigt: utan en motor kan du inte applicera någon förbehandling, och den råa bilden matas direkt till igenkännaren – oftast det värsta scenariot för noggrannhet. + +--- + +## Steg 2: Ladda mål‑PNG‑filen – Sätt scenen för att läsa text från PNG + +Nu talar vi om för motorn vilken fil den ska arbeta på. PNG är förlustfri, vilket redan ger oss en liten fördel jämfört med JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Om bilden finns någon annanstans, justera bara sökvägen. Motorn accepterar alla stödda format, men PNG bevarar ofta de fina detaljer som behövs för skarpa teckenkanter. + +--- + +## Steg 3: Konfigurera förbehandling – Förbehandla bild för OCR + +Här händer magin. Vi skapar ett inställningsobjekt, aktiverar brusreducering för att ta bort prickar och slår på räta upp‑funktion så att sned text automatiskt räta ut. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Varför Denoise + Deskew? + +- **Denoise**: Slumpmässigt bildbrus förvirrar mönstermatchnings‑algoritmer. Att ta bort det skärper bokstäverna. +- **Deskew**: Även en lutning på 2 grader kan kraftigt sänka förtroendesiffrorna. Deskew justerar baslinjen så att igenkännaren kan matcha typsnitt mer pålitligt. + +Du kan experimentera med ytterligare flaggor (t.ex. `ImagePreprocessMode.CONTRAST_ENHANCE`) om dina bilder är särskilt mörka. SDK‑dokumentationen listar vanligtvis alla tillgängliga lägen. + +--- + +## Steg 4: Applicera inställningarna på motorn – Koppla förbehandling till OCR + +Tilldela inställningsobjektet till motorn så att nästa igenkänningskörning använder de transformationer vi just definierat. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Om du hoppar över detta steg återgår motorn till sina standardinställningar (ofta “ingen förbehandling”), och du kommer att se **lägre OCR‑noggrannhet**. + +--- + +## Steg 5: Kör igenkänningsprocessen – Extrahera text från bild + +När allt är kopplat frågar vi äntligen motorn att göra sitt jobb. Anropet är synkront och returnerar ett resultatobjekt som innehåller den igenkända strängen. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Bakom kulisserna gör motorn nu: + +1. Laddar PNG‑filen i minnet +2. Applicerar denoise och deskew baserat på våra inställningar +3. Kör neurala nätverket eller klassisk mönstermatchning +4. Packar utdata i `recognition_result` + +--- + +## Steg 6: Skriv ut den igenkända texten – Verifiera förbättringen + +Låt oss skriva ut den extraherade strängen. I en riktig applikation kan du skriva den till en fil, en databas eller skicka den till en annan tjänst. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Förväntad utskrift + +Om bilden innehåller meningen “Hello, OCR World!” bör du se: + +``` +Hello, OCR World! +``` + +Lägg märke till hur texten är ren – inga stray‑symboler eller trasiga tecken. Det är resultatet av korrekt **bildförbehandling för text**. + +--- + +## Pro‑tips & kantfall + +| Situation | Vad som bör justeras | Varför | +|-----------|----------------------|--------| +| Mycket lågupplöst PNG (≤ 72 dpi) | Lägg till `ImagePreprocessMode.SUPER_RESOLUTION` om det finns | Uppskalning kan ge igenkännaren fler pixlar att arbeta med | +| Text är roterad > 5° | Öka deskew‑toleransen eller rotera manuellt med `Pillow` innan du matar in i motorn | Extrema vinklar kan ibland kringgå automatisk deskew | +| Tunga bakgrundsmönster | Aktivera `ImagePreprocessMode.BACKGROUND_REMOVAL` | Tar bort icke‑textuell oreda som annars kan missuppfattas | +| Flerspråkigt dokument | Sätt `ocr_engine.language = "eng+spa"` (eller liknande) | Motorn väljer rätt teckenuppsättning, vilket förbättrar den totala noggrannheten | + +Kom ihåg, **förbättra OCR‑noggrannhet** är ingen one‑size‑fits‑all‑lösning; du kan behöva iterera på förbehandlingsflaggorna för just ditt dataset. + +--- + +## Fullt skript – Klart att kopiera & klistra in + +Nedan är det kompletta, körbara exemplet som innehåller varje steg vi gått igenom. Spara det som `improve_ocr_accuracy.py` och kör med `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Kör det, håll koll på konsolen, så ser du **extrahera text från bild**‑resultatet direkt. Om utskriften ser felaktig ut, justera `preprocess_mode`‑flaggorna enligt tabellen “Pro‑tips”. + +--- + +## Slutsats + +Vi har just gått igenom ett praktiskt recept för att **förbättra OCR‑noggrannhet** med Python. Genom att skapa en `OcrEngine`, ladda en PNG, **förbehandla bilden för OCR** och slutligen **läsa text från PNG**, kan du på ett pålitligt sätt **extrahera text från bild**‑filer även när källan inte är perfekt. + +Nästa steg? Prova att bearbeta en batch av bilder i en loop, lagra varje resultat i en CSV, eller experimentera med ytterligare förbehandlingslägen som kontrastförbättring. Samma mönster fungerar för PDF‑filer, skannade kvitton eller handskrivna anteckningar – byt bara inmatning och justera inställningarna. + +Har du frågor om en specifik bildtyp eller vill veta hur du integrerar detta i en webbtjänst? Lämna en kommentar så utforskar vi de scenarierna tillsammans. Lycka till med kodandet, och må dina OCR‑resultat vara kristallklara! + +## Vad bör du lära dig härnäst? + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/swedish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..dda4870c4 --- /dev/null +++ b/ocr/swedish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Lär dig hur du använder ett intresseområde för OCR för att ladda en bild + för OCR och extrahera text från en rektangel, perfekt för att känna igen belopp + på en faktura. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: sv +og_description: Behärska OCR‑intresseområdet för att ladda bild för OCR, extrahera + text från en rektangel och känna igen text från en faktura i en enda handledning. +og_title: OCR‑intresseområde – steg‑för‑steg Python‑guide +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR-område av intresse – Extrahera text från rektangel i Python +url: /sv/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Extrahera text från rektangel i Python + +Har du någonsin funderat på hur du **ocr region of interest** en specifik del av en skannad faktura utan att mata in hela sidan i motorn? Du är inte den första som stirrar på ett suddigt kvitto och tänker: “Hur extraherar jag beloppet som ligger någonstans i nedre högra hörnet?” Den goda nyheten är att du kan tala om för OCR‑biblioteket exakt var det ska leta, vilket dramatiskt ökar både hastighet och noggrannhet. + +I den här guiden går vi igenom ett komplett, körbart exempel som visar hur du **load image for OCR**, definierar en **region of interest**, och sedan **extract text from rectangle** för att slutligen **recognize text from invoice** och svara på den klassiska frågan “hur extraherar man belopp”. Inga vaga referenser – bara konkret kod, tydliga förklaringar och några pro‑tips du önskar att du hade känt till tidigare. + +--- + +## Vad du kommer att bygga + +I slutet av den här tutorialen har du ett litet Python‑skript som: + +1. Laddar en fakturabild från disk. +2. Markerar en rektangulär ROI där totalbeloppet finns. +3. Kör OCR endast inom den ROI:n. +4. Skriver ut den rensade beloppssträngen. + +Allt detta fungerar med vilket OCR‑bibliotek som helst som stödjer ROI – här använder vi ett fiktivt men representativt `SimpleOCR`‑paket som efterliknar populära verktyg som Tesseract eller EasyOCR. Byt gärna ut det; koncepten förblir desamma. + +--- + +## Förutsättningar + +- Python 3.8+ installerat (`python --version` bör visa ≥3.8). +- Ett pip‑installabelt OCR‑paket (t.ex. `pip install simpleocr`). +- En fakturabild (PNG eller JPEG) placerad i en mapp du kan referera till. +- Grundläggande kunskap om Python‑funktioner och -klasser (inget avancerat). + +Om du redan har detta, bra – låt oss dyka ner. Om inte, hämta bilden först; resten av stegen är oberoende av själva filinnehållet. + +--- + +## Steg 1: Load Image for OCR + +Det första som någon OCR‑arbetsflöde behöver är en bitmap att läsa från. De flesta bibliotek exponerar en enkel `load_image`‑metod som accepterar en filsökväg. Så här gör du med vår `SimpleOCR`‑motor: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Använd absoluta sökvägar eller `os.path.join` för att undvika “file not found”-överraskningar när du kör skriptet från en annan arbetskatalog. + +--- + +## Steg 2: Define OCR Region of Interest + +Istället för att låta motorn skanna hela sidan, talar vi om exakt var beloppet sitter. Detta är **ocr region of interest**‑steget, och det är nyckeln till pålitlig extraktion, särskilt när dokumentet innehåller brusiga rubriker eller sidfötter. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Varför just de siffrorna? `x` och `y` är pixel‑offsets från det övre vänstra hörnet, medan `width` och `height` beskriver lådans storlek. Om du är osäker, öppna bilden i någon redigerare, aktivera en linjal och notera koordinaterna. Många IDE:er låter dig till och med skriva ut muspekarens position när du hovrar. + +--- + +## Steg 3: Extract Text from Rectangle + +Nu när ROI:n är satt ber vi motorn att **recognize text from invoice** men begränsat till den rektangel vi just lagt till. Anropet returnerar ett resultatobjekt som vanligtvis innehåller den råa strängen, förtroendesiffror och ibland avgränsningsrutor. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Bakom kulisserna itererar `recognize()` över varje ROI, beskär den delen, kör OCR‑modellen och sammanfogar resultaten. Detta är varför en väl avgränsad **extract text from rectangle**‑region kan spara sekunder på bearbetningstid för batchjobb. + +--- + +## Steg 4: How to Extract Amount – Clean the Output + +OCR är inte perfekt; du får ofta oönskade mellanslag, radbrytningar eller felaktigt lästa tecken (tänk “S” vs “5”). En snabb `strip()` och ett litet regex‑mönster löser vanligtvis problemet för monetära värden. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** Om du planerar att skicka beloppet till en databas eller en betalningsgateway behöver du ett förutsägbart format. Att ta bort whitespace och filtrera icke‑numeriska tecken förhindrar fel längre ner i kedjan. + +--- + +## Steg 5: Recognize Text from Invoice – Full Script + +Sätter vi ihop allt får du det kompletta, körklara skriptet. Spara det som `extract_amount.py` och kör `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Förväntad output + +``` +Amount: 1,245.67 +``` + +Om ROI:n är feljusterad kan du se något i stil med `Amount: 1245.6S` – notera den stray “S”. Justera rektangelkoordinaterna och kör igen tills outputen ser ren ut. + +--- + +## Vanliga fallgropar & kantfall + +| Problem | Varför det händer | Lösning | +|-------|----------------|-----| +| **ROI för liten** | Beloppstexten klipps av, vilket leder till partiell igenkänning. | Utöka `width`/`height` med ~10‑20 % och testa igen. | +| **Fel DPI** | Lågresolution‑skanningar (≤150 dpi) minskar OCR‑noggrannheten. | Resampla bilden till 300 dpi innan du laddar, eller be skannern om högre DPI. | +| **Flera valutor** | Regex fångar den första numeriska gruppen, vilket kan vara ett fakturanummer. | Förfina regex‑mönstret för att leta efter valutasymboler (`$`, `€`, `£`) före siffrorna. | +| **Rotera fakturor** | OCR‑motorer förutsätter upprätt text; roterade sidor bryter igenkänning. | Applicera en rotationskorrigering (`ocr_engine.rotate(90)`) innan du lägger till ROI. | +| **Bakgrundsbrus** | Skuggor eller stämplar förvirrar modellen. | Förbehandla med ett enkelt tröskelvärde (`cv2.threshold`) eller använd ett brusreduceringsfilter. | + +Att ta itu med dessa kantfall tidigt sparar dig timmar av felsökning senare. + +--- + +## Pro‑tips för verkliga projekt + +- **Batch‑behandling:** Loopa över en mapp med fakturor, beräkna ROI dynamiskt (t.ex. baserat på mall‑detektion), och lagra resultat i CSV. +- **Mall‑matchning:** Om du hanterar flera fakturamallar, håll en JSON‑karta över `template_id → ROI‑koordinater`. Byt ROI baserat på en snabb layout‑klassificerare. +- **Parallell körning:** Använd `concurrent.futures.ThreadPoolExecutor` för att köra flera OCR‑instanser samtidigt – perfekt för högvolym‑backoffice‑pipelines. +- **Förtroendefiltrering:** De flesta OCR‑resultat innehåller en confidence‑score. Kasta bort resultat under en tröskel (t.ex. 85 %) och flagga dem för manuell granskning. + +--- + +## Slutsats + +Vi har gått igenom allt du behöver för att **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, och slutligen **recognize text from invoice** för att svara på den klassiska frågan **how to extract amount**. Skriptet är kompakt, men ändå tillräckligt flexibelt för att anpassas till olika dokumentformat, språk och OCR‑bakgrunder. + +Nu när du behärskar grunderna, fundera på att utöka arbetsflödet: lägg till streckkodsskanning, integrera med en PDF‑parser, eller skicka det extraherade beloppet till ett bokförings‑API. Himlen är gränsen, och med en väl definierad ROI får du alltid snabbare, renare resultat. + +Om du stöter på problem, lämna en kommentar nedan – lycka till med OCR‑andet! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## Vad bör du lära dig härnäst? + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/thai/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..07c99c074 --- /dev/null +++ b/ocr/thai/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: บทเรียน OCR แบบอะซิงโครนัสแสดงวิธีใช้ Aspose OCR ใน Python พร้อม asyncio + เพื่อการสกัดข้อความจากภาพอย่างรวดเร็ว เรียนรู้การทำ OCR แบบอะซิงโครนัสขั้นตอนต่อขั้นตอน +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: th +og_description: บทแนะนำ Async OCR จะพาคุณผ่านการใช้ Aspose OCR ใน Python พร้อม asyncio + เพื่อการสกัดข้อความจากภาพอย่างมีประสิทธิภาพ +og_title: บทเรียน OCR แบบอะซิงค์ – Python asyncio กับ Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: บทเรียน OCR แบบอะซิงค์ – Python asyncio กับ Aspose OCR +url: /th/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR Tutorial – Python asyncio กับ Aspose OCR + +เคยสงสัยไหมว่าจะแสดงการรู้จำอักขระด้วยแสง (OCR) อย่างไรโดยไม่บล็อกแอปของคุณ? ใน **async OCR tutorial** คุณจะได้เห็นตรงนั้น—การสกัดข้อความแบบไม่บล็อกโดยใช้ `asyncio` ของ Python และไลบรารี Aspose OCR + +หากคุณเคยต้องรอการประมวลผลภาพขนาดใหญ่ คำแนะนำนี้จะให้วิธีแก้ที่สะอาดและแบบอะซิงโครนัสที่ทำให้ event loop ของคุณทำงานต่อเนื่อง + +ในส่วนต่อไปนี้ เราจะครอบคลุมทุกอย่างที่คุณต้องการ: การติดตั้งไลบรารี, การเชื่อมต่อฟังก์ชันช่วยเหลือแบบอะซิงโครนัส, การจัดการผลลัพธ์, และแม้แต่เคล็ดลับสั้น ๆ สำหรับการขยายไปยังหลายภาพ. เมื่อจบคุณจะสามารถใส่ **async OCR tutorial** ลงในโปรเจกต์ Python ใด ๆ ที่ใช้ `asyncio` อยู่แล้ว + +## สิ่งที่คุณต้องการ + +* Python 3.9+ (API `asyncio` ที่เราใช้มีความเสถียรตั้งแต่เวอร์ชัน 3.7 ขึ้นไป) +* ใบอนุญาต Aspose OCR ที่ใช้งานได้หรือเวอร์ชันทดลองฟรี (ไลบรารีเป็น pure‑Python, ไม่มีไบนารีเนทีฟ) +* ไฟล์รูปขนาดเล็ก (`.jpg`, `.png`, เป็นต้น) ที่คุณต้องการอ่าน – เก็บไว้ในโฟลเดอร์ที่รู้จัก + +ไม่ต้องใช้เครื่องมือภายนอกอื่น ๆ; ทุกอย่างทำงานใน pure Python. + +## ขั้นตอนที่ 1: ติดตั้งแพคเกจ Aspose OCR + +เริ่มต้นด้วยการดึงแพคเกจ Aspose OCR จาก PyPI. เปิดเทอร์มินัลและรัน: + +```bash +pip install aspose-ocr +``` + +> **Pro tip:** หากคุณทำงานภายใน virtual environment (แนะนำอย่างยิ่ง), ให้เปิดใช้งานมันก่อน. สิ่งนี้ทำให้การพึ่งพาแยกจากกันและหลีกเลี่ยงการชนกันของเวอร์ชัน. + +## ขั้นตอนที่ 2: เริ่มต้น OCR Engine แบบอะซิงโครนัส + +หัวใจของ **async OCR tutorial** ของเราคือฟังก์ชันช่วยเหลือแบบอะซิงโครนัส. มันสร้างอินสแตนซ์ `OcrEngine`, โหลดภาพ, แล้วเรียก `recognize_async()`. เองเอนจินเป็น synchronous, แต่เมธอด wrapper จะคืนค่าเป็น awaitable, ทำให้ event loop ตอบสนองได้. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**ทำไมเราถึงทำแบบนี้:** +*การสร้าง engine ภายใน helper ทำให้มั่นใจในความปลอดภัยของเธรด หากคุณรันงาน OCR จำนวนมากพร้อมกันในภายหลัง. คำสั่ง `await` ส่งการควบคุมกลับไปยัง event loop ขณะที่การทำงานหนักเกิดขึ้นใน thread pool ภายในของไลบรารี.* + +## ขั้นตอนที่ 3: เรียกใช้ Helper จากฟังก์ชัน Async Main + +ตอนนี้เราต้องการ coroutine `main()` ขนาดเล็กที่เรียก `async_ocr()` และพิมพ์ผลลัพธ์. สิ่งนี้สะท้อนจุดเริ่มต้นทั่วไปของสคริปต์ `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**อะไรที่เกิดขึ้นเบื้องหลัง?** +`asyncio.run()` สร้าง event loop ใหม่, กำหนด `main()`, และปิดลูปอย่างเรียบร้อยเมื่อ `main()` เสร็จ. รูปแบบนี้เป็นวิธีที่แนะนำให้เริ่มโปรแกรมแบบอะซิงโครนัสใน Python 3.7+. + +## ขั้นตอนที่ 4: ทดสอบสคริปต์เต็ม + +บันทึกโค้ดสองบล็อกข้างบนลงในไฟล์เดียว, เช่น `async_ocr_demo.py`. รันจากบรรทัดคำสั่ง: + +```bash +python async_ocr_demo.py +``` + +หากทุกอย่างตั้งค่าอย่างถูกต้อง คุณควรเห็นผลลัพธ์ประมาณนี้: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +ผลลัพธ์ที่แน่นอนจะขึ้นอยู่กับเนื้อหาใน `photo.jpg`. จุดสำคัญคือสคริปต์จะจบอย่างรวดเร็ว แม้ภาพจะใหญ่, เนื่องจากงาน OCR ทำงานในพื้นหลัง. + +## ขั้นตอนที่ 5: ขยายขนาด – ประมวลผลหลายภาพพร้อมกัน + +คำถามที่พบบ่อยต่อเนื่องคือ, *“ฉันสามารถ OCR กลุ่มไฟล์ได้โดยไม่ต้องเปิดโปรเซสใหม่สำหรับแต่ละไฟล์ไหม?”* แน่นอน. เนื่องจาก helper ของเราทำงานแบบอะซิงโครนัสเต็มรูปแบบ, เราสามารถรวบรวม coroutine หลาย ๆ ตัวด้วย `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**ทำไมวิธีนี้ถึงได้ผล:** `asyncio.gather()` กำหนดงาน OCR ทั้งหมดพร้อมกัน. ไลบรารี Aspose OCR ภายในยังคงใช้ thread pool ของมันเอง, แต่จากมุมมองของ Python ทุกอย่างยังคงไม่บล็อก, ทำให้คุณจัดการหลายสิบภาพในเวลาที่การเรียกแบบ synchronous เดียวจะใช้. + +## ขั้นตอนที่ 6: จัดการข้อผิดพลาดอย่างราบรื่น + +เมื่อคุณทำงานกับไฟล์ภายนอก, คุณจะเจอไฟล์หาย, ภาพเสีย, หรือปัญหาใบอนุญาต. ห่อการเรียก OCR ด้วยบล็อก `try/except` เพื่อให้ event loop ทำงานต่อ: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +ตอนนี้ `batch_ocr()` สามารถเรียก `safe_async_ocr` แทน, ทำให้ไฟล์ที่มีปัญหาเดียวไม่ทำให้แบชทั้งหมดหยุดทำงาน. + +## ภาพรวมเชิงภาพ + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="แผนผังการสอน Async OCR แสดง async_ocr helper, event loop, และ Aspose OCR engine"} + +แผนภาพด้านบนแสดงภาพรวมของกระบวนการ: event loop → `async_ocr` → `OcrEngine` → background thread → ผลลัพธ์กลับสู่ลูป. + +## ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Blocking I/O ภายใน helper** | โดยบังเอิญใช้ `open()` โดยไม่มี `await` ทำให้ลูปถูกบล็อก. | ใช้ `aiofiles` สำหรับการอ่านไฟล์, หรือให้ `engine.load_image` จัดการ (มันเป็น non‑blocking อยู่แล้ว). | +| **การใช้ `OcrEngine` ตัวเดียวซ้ำกันในหลาย coroutine** | Engine ไม่ปลอดภัยต่อเธรด; การเรียกพร้อมกันอาจทำให้สถานะเสียหาย. | สร้าง engine ใหม่ภายในแต่ละการเรียก `async_ocr` (ตามที่แสดง). | +| **ไม่มีใบอนุญาต** | Aspose OCR จะโยนข้อยกเว้นที่เกี่ยวกับใบอนุญาตในขณะรัน. | ลงทะเบียนใบอนุญาตของคุณตั้งแต่ต้น (`OcrEngine.set_license("license.json")`). | +| **ภาพขนาดใหญ่ทำให้ใช้หน่วยความจำสูง** | ไลบรารีโหลดภาพทั้งหมดเข้าสู่ RAM. | ลดขนาดภาพก่อน OCR หากเป็นกังวลเรื่องหน่วยความจำ. | + +## สรุป: สิ่งที่เราบรรลุ + +ใน **async OCR tutorial** นี้ เรา: + +1. ติดตั้งไลบรารี Aspose OCR. +2. สร้าง helper `async_ocr` ที่ทำการรู้จำโดยไม่บล็อก. +3. เรียกใช้ helper จากจุดเริ่มต้น `asyncio` ที่สะอาด. +4. สาธิตการประมวลผลแบบแบชด้วย `asyncio.gather`. +5. เพิ่มการจัดการข้อผิดพลาดและเคล็ดลับแนวปฏิบัติที่ดีที่สุด. + +ทั้งหมดนี้เป็น pure Python, ดังนั้นคุณสามารถนำไปใส่ในเว็บเซิร์ฟเวอร์, เครื่องมือ CLI, หรือ data‑pipeline ได้โดยไม่ต้องเขียนโค้ด async ที่มีอยู่ใหม่. + +## ขั้นตอนต่อไป & หัวข้อที่เกี่ยวข้อง + +* **การเตรียมภาพแบบอะซิงโครนัส** – ใช้ `aiohttp` เพื่อดาวน์โหลดภาพพร้อมกันก่อน OCR. +* **การจัดเก็บผลลัพธ์ OCR** – ผสานการสอนนี้กับไดรเวอร์ฐานข้อมูลแบบ async เช่น `asyncpg` สำหรับ PostgreSQL. +* **การปรับประสิทธิภาพ** – ทดลองใช้ `engine.recognize_async(max_threads=4)` หากไลบรารีมีตัวเลือกนี้. +* **OCR engine ทางเลือก** – เปรียบเทียบ Aspose OCR กับ async wrapper ของ Tesseract เพื่อการวิเคราะห์ต้นทุน‑ประโยชน์. + +อย่าลังเลที่จะทดลอง: ลองป้อน PDF, ปรับการตั้งค่าภาษา, หรือเชื่อมผลลัพธ์เข้ากับ chatbot. ไม่มีขีดจำกัดเมื่อคุณมีพื้นฐาน **async OCR tutorial** ที่มั่นคง. + +ขอให้เขียนโค้ดอย่างสนุกสนาน, และขอให้การสกัดข้อความของคุณเร็วเสมอ! + +## คุณควรเรียนรู้อะไรต่อไป? + +- [สกัดข้อความจากภาพด้วย Aspose OCR – คู่มือขั้นตอนโดยขั้นตอน](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Aspose OCR Tutorial – การรู้จำอักขระด้วยแสง](/ocr/english/) +- [วิธี OCR ข้อความในภาพด้วยภาษาโดยใช้ Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/thai/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..b1549ee3f --- /dev/null +++ b/ocr/thai/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: การตรวจจับภาษาที่อัตโนมัติใน OCR ทำได้ง่ายขึ้น เรียนรู้วิธีโหลด OCR ของรูปภาพ + เปิดใช้งานการตรวจจับภาษาที่อัตโนมัติ และจดจำข้อความในรูปภาพได้เพียงไม่กี่ขั้นตอน. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: th +og_description: การตรวจจับภาษาที่อัตโนมัติใน OCR ทำได้ง่ายตามขั้นตอนนี้ ติดตามบทเรียนแบบทีละขั้นตอนเพื่อเปิดใช้งานการตรวจจับภาษาอัตโนมัติ + โหลด OCR ของรูปภาพ และจดจำข้อความในรูปภาพ. +og_title: การตรวจจับภาษาด้วย OCR อัตโนมัติ – คู่มือ Python ฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: การตรวจจับภาษาที่อัตโนมัติด้วย OCR – คู่มือ Python ฉบับสมบูรณ์ +url: /th/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# การตรวจจับภาษาที่อัตโนมัติด้วย OCR – คู่มือ Python ฉบับสมบูรณ์ + +เคยสงสัยไหมว่าเราจะทำให้เครื่อง OCR *ทาย* ภาษาของเอกสารสแกนโดยที่คุณไม่ต้องบอกมันว่าจะมองหาอะไร? นั่นแหละคือสิ่งที่ **automatic language detection** ทำ และมันเป็นการเปลี่ยนเกมอย่างเต็มที่เมื่อคุณต้องจัดการกับ PDF หลายภาษา, ภาพถ่ายของป้ายถนน, หรือภาพใด ๆ ที่ผสมสคริปต์หลายแบบ + +ในบทเรียนนี้เราจะเดินผ่านตัวอย่างเชิงปฏิบัติที่แสดงให้คุณเห็นวิธี **เปิดใช้งานการตรวจจับภาษาที่อัตโนมัติ**, **โหลด OCR ของภาพ**, และ **recognize text image** ด้วย API แบบ Python สไตล์เดียวกัน เมื่อเสร็จคุณจะได้สคริปต์ที่ทำงานอิสระซึ่งพิมพ์ทั้งรหัสภาษาที่ตรวจพบและข้อความที่สกัดออกมา—ไม่ต้องตั้งค่าภาษาเองเลย + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีสร้างอินสแตนซ์ของ OCR engine และเปิด **automatic language detection** +- ขั้นตอนที่แน่นอนในการ **load image OCR** จากดิสก์ +- วิธีเรียกเมธอด `recognize()` ของ engine และรับผลลัพธ์ที่รวมรหัสภาษาไว้ด้วย +- เคล็ดลับในการจัดการกับกรณีขอบเช่นภาพความละเอียดต่ำหรือสคริปต์ที่ไม่รองรับ + +ไม่จำเป็นต้องมีประสบการณ์กับ OCR หลายภาษา; เพียงแค่การตั้งค่า Python เบื้องต้นและไฟล์ภาพหนึ่งไฟล์ + +--- + +## ข้อกำหนดเบื้องต้น + +ก่อนที่เราจะเริ่ม, ตรวจสอบให้แน่ใจว่าคุณมี: + +1. Python 3.8+ ติดตั้งอยู่ (เวอร์ชันล่าสุดก็ใช้ได้) +2. ไลบรารี OCR ที่ให้ `OcrEngine`, `LanguageAutoDetectMode` ฯลฯ – สำหรับคู่มือนี้เราจะสมมติว่าใช้แพคเกจชื่อ `myocr`. ติดตั้งด้วย: + + ```bash + pip install myocr + ``` + +3. ไฟล์ภาพ (`multilingual_sample.png`) ที่มีข้อความอย่างน้อยสองภาษาแตกต่างกัน +4. ความอยากรู้อยากเห็นเล็กน้อย—หากคุณยังไม่เคยสัมผัส OCR มาก่อน, ไม่ต้องกังวล; โค้ดถูกออกแบบให้เข้าใจง่าย + +--- + +## ขั้นตอนที่ 1: เปิดใช้งาน Automatic Language Detection + +สิ่งแรกที่คุณต้องทำคือบอก engine ว่ามันควร *หาภาษา* ด้วยตนเอง นี่คือที่ที่ **automatic language detection** ทำงาน + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **ทำไมจึงสำคัญ:** +> เมื่อกำหนด `AUTO_DETECT` ไว้, engine จะรันตัวจำแนกภาษาขนาดเล็กบนภาพก่อนที่การจดจำอักขระแบบหนักจะเริ่มทำงาน ซึ่งหมายความว่าคุณไม่ต้องเดาว่าข้อความเป็นอังกฤษ, รัสเซีย, ฝรั่งเศส หรือการผสมใด ๆ engine จะเลือกโมเดลภาษาที่เหมาะสมที่สุดโดยอัตโนมัติสำหรับแต่ละส่วนของภาพ + +--- + +## ขั้นตอนที่ 2: Load Image OCR + +ตอนนี้ engine รู้แล้วว่าต้อง auto‑detect ภาษา, เราต้องให้มันมีอะไรให้ทำงานด้วย ขั้นตอน **load image OCR** จะอ่านบิตแมพและเตรียมบัฟเฟอร์ภายใน + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **เคล็ดลับ:** +> หากภาพของคุณมีความละเอียดมากกว่า 300 dpi, ควรลดขนาดลงประมาณ 150‑200 dpi. รายละเอียดมากเกินไปอาจทำให้ขั้นตอนการตรวจจับภาษาช้าลงโดยไม่เพิ่มความแม่นยำ + +--- + +## ขั้นตอนที่ 3: Recognize Text from Image + +เมื่อภาพอยู่ในหน่วยความจำและเปิดการตรวจจับภาษาแล้ว, ขั้นตอนสุดท้ายคือให้ engine **recognize text image** การเรียกครั้งเดียวนี้ทำงานหนักทั้งหมด + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` เป็นอ็อบเจ็กต์ที่โดยทั่วไปจะมีอย่างน้อยสองแอตทริบิวต์: + +| Attribute | Description | +|-----------|-------------| +| `language` | รหัส ISO‑639‑1 ของภาษาที่ตรวจพบ (เช่น `"en"` สำหรับ English) | +| `text` | การถอดข้อความเป็น plain‑text จากภาพ | + +--- + +## ขั้นตอนที่ 4: ดึงภาษาที่ตรวจพบและข้อความที่สกัดออกมา + +ต่อไปเราจะพิมพ์ผลลัพธ์ที่ engine ค้นพบ ซึ่งแสดงความสามารถ **detect language OCR** อย่างเต็มรูปแบบ + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**ผลลัพธ์ตัวอย่าง** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **ถ้า engine คืนค่า `None` แล้วทำอย่างไร?** +> ปกติหมายความว่าภาพเบลอเกินไปหรือข้อความเล็กเกินไป (< 8 pt). ลองเพิ่มคอนทราสต์หรือใช้แหล่งที่มาที่ความละเอียดสูงกว่า + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ (Enable Auto Language Detection End‑to‑End) + +รวมทุกอย่างเข้าด้วยกัน, นี่คือสคริปต์พร้อมรันที่ครอบคลุม **enable auto language detection**, **load image OCR**, **recognize text image**, และ **detect language OCR** ในขั้นตอนเดียว + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +บันทึกไฟล์นี้เป็น `automatic_language_detection_ocr.py`, แทนที่ `YOUR_DIRECTORY` ด้วยโฟลเดอร์ที่เก็บ PNG ของคุณ, แล้วรัน: + +```bash +python automatic_language_detection_ocr.py +``` + +คุณควรเห็นรหัสภาษาแล้วตามด้วยข้อความที่สกัดออกมา, เหมือนกับผลลัพธ์ตัวอย่างด้านบน + +--- + +## การจัดการกับกรณีขอบที่พบบ่อย + +| Situation | Suggested Fix | +|-----------|----------------| +| **Very low‑resolution image** (under 100 dpi) | ขยายภาพด้วยฟิลเตอร์ bicubic ก่อนโหลด, หรือขอแหล่งที่มาที่ความละเอียดสูงกว่า | +| **Mixed scripts in one image** (e.g., English + Cyrillic) | Engine มักจะแบ่งหน้าเป็นโซน; หากพบการตรวจจับผิดพลาด, ตั้งค่า `engine.enable_region_split = True` | +| **Unsupported language** | ตรวจสอบว่าไลบรารี OCR มีแพ็คเกจภาษาสำหรับสคริปต์ที่ต้องการหรือไม่; อาจต้องดาวน์โหลดโมเดลเพิ่มเติม | +| **Large batch processing** | เริ่มต้น engine ครั้งเดียวแล้วใช้ซ้ำสำหรับหลาย `load_image` / `recognize` เพื่อลดการโหลดโมเดลซ้ำ | + +--- + +## ภาพรวมเชิงภาพ + +![การตรวจจับภาษาที่อัตโนมัติ ตัวอย่างผลลัพธ์](https://example.com/auto-lang-detect.png "การตรวจจับภาษาที่อัตโนมัติ") + +*Alt text:* ตัวอย่างผลลัพธ์การตรวจจับภาษาที่อัตโนมัติแสดงรหัสภาษาที่ตรวจพบและข้อความหลายภาษาที่สกัดออกมา + +--- + +## สรุป + +เราได้ครอบคลุม **automatic language detection** ตั้งแต่การสร้าง engine, เปิดการตรวจจับอัตโนมัติ, โหลดภาพสำหรับ OCR, จดจำข้อความ, และดึงภาษาที่ตรวจพบ ขั้นตอนแบบ end‑to‑end นี้ทำให้คุณประมวลผลเอกสารหลายภาษาโดยไม่ต้องตั้งค่าโมเดลภาษาด้วยตนเองทุกครั้ง + +หากคุณพร้อมจะต่อยอด, พิจารณา: + +- **Batching** รูปภาพหลายร้อยรูปด้วยลูปที่ใช้ `OcrEngine` อินสแตนซ์เดียวกัน +- **Post‑processing** ข้อความที่สกัดด้วย spell‑checker หรือ tokenizer เฉพาะภาษา +- **Integrating** สคริปต์เข้าเป็นเว็บเซอร์วิสที่รับอัปโหลดจากผู้ใช้และคืนค่า JSON ที่มีฟิลด์ `language` และ `text` + +ลองใช้รูปแบบไฟล์ต่าง ๆ (`.jpg`, `.tif`) แล้วสังเกตว่าความแม่นยำของการตรวจจับเปลี่ยนแปลงอย่างไร หากมีคำถามหรือภาพที่อ่านยาก, แสดงความคิดเห็นด้านล่าง—ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อไป + +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/thai/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..83ae0f69a --- /dev/null +++ b/ocr/thai/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-31 +description: เรียนรู้วิธีแปลงรูปภาพเป็นข้อความด้วย Python ด้วยสคริปต์การแปลงรูปภาพเป็นข้อความแบบกลุ่ม + จดจำข้อความจากรูปภาพที่สแกนโดยใช้ Aspose.OCR ภายในไม่กี่นาที. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: th +og_description: แปลงรูปภาพเป็นข้อความด้วย Python อย่างรวดเร็ว คู่มือนี้แสดงการแปลงรูปภาพเป็นข้อความเป็นกลุ่มและวิธีการจดจำข้อความจากภาพสแกนด้วย + Aspose.OCR. +og_title: แปลงรูปภาพเป็นข้อความด้วย Python – บทเรียนเต็ม +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: แปลงรูปภาพเป็นข้อความด้วย Python – คู่มือแบบครบถ้วนขั้นตอนต่อขั้นตอน +url: /th/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลงรูปภาพเป็นข้อความด้วย Python – คู่มือขั้นตอนเต็ม + +เคยสงสัยไหมว่า **convert images to text python** ทำได้อย่างไรโดยไม่ต้องค้นหาหลายสิบไลบรารี? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะกำลังดิจิไทซ์ใบเสร็จเก่า ดึงข้อมูลจากใบแจ้งหนี้ที่สแกนไว้ หรือสร้างคลัง PDF ที่สามารถค้นหาได้ การแปลงรูปภาพเป็นไฟล์ข้อความธรรมดาเป็นงานประจำวันของนักพัฒนาหลายคน + +ในบทเรียนนี้เราจะพาคุณผ่าน **pipeline การแปลง bulk image to text** ที่จดจำข้อความจากภาพสแกน บันทึกผลลัพธ์แต่ละไฟล์เป็นไฟล์ `.txt` แยกกัน และทำทั้งหมดด้วยเพียงไม่กี่บรรทัดของ Python ไม่ต้องหาตัว API ที่ซับซ้อน—Aspose.OCR ทำงานหนักให้คุณและเราจะแสดงวิธีเชื่อมต่อมันอย่างละเอียด + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีติดตั้งและกำหนดค่าแพ็กเกจ Aspose.OCR สำหรับ Python +- โค้ดที่จำเป็นต้องใช้เพื่อ **convert images to text python** ด้วย `BatchOcrEngine` +- เคล็ดลับการจัดการกับปัญหาทั่วไป เช่น ฟอร์แมตที่ไม่รองรับหรือไฟล์เสีย +- วิธีตรวจสอบว่า **recognize text from scanned images** ทำงานสำเร็จจริงหรือไม่ + +เมื่อจบคู่มือนี้คุณจะมีสคริปต์พร้อมรันที่สามารถประมวลผลรูปภาพหลายพันรูปในครั้งเดียว—เหมาะสำหรับสถานการณ์การประมวลผลแบบแบตช์ใด ๆ + +## ข้อกำหนดเบื้องต้น + +- Python 3.8+ ติดตั้งบนเครื่องของคุณ +- โฟลเดอร์ที่มีไฟล์รูปภาพ (PNG, JPEG, TIFF ฯลฯ) ที่ต้องการแปลงเป็นข้อความ +- บัญชี Aspose Cloud ที่ใช้งานได้หรือไลเซนส์ทดลองฟรี (ระดับฟรีเพียงพอสำหรับการทดสอบ) + +ถ้าคุณมีทั้งหมดนี้แล้ว ไปต่อกันเลย + +--- + +## ขั้นตอนที่ 1 – ตั้งค่าสภาพแวดล้อม Python ของคุณ + +ก่อนที่เราจะเริ่มเขียนโค้ด OCR ใด ๆ ให้แน่ใจว่าคุณทำงานอยู่ใน virtual environment ที่สะอาด การทำเช่นนี้จะทำให้การจัดการ dependencies แยกจากระบบหลักและป้องกันการชนกันของเวอร์ชัน + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **เคล็ดลับ:** รักษาโครงสร้างโฟลเดอร์โปรเจกต์ให้เป็นระเบียบ—สร้างโฟลเดอร์ย่อยชื่อ `ocr_project` แล้ววางสคริปต์ไว้ที่นั่น จะทำให้การจัดการ path ง่ายขึ้นในภายหลัง + +## ขั้นตอนที่ 2 – ติดตั้ง Aspose.OCR สำหรับ Python + +Aspose.OCR เป็นไลบรารีเชิงพาณิชย์ แต่มี wheel แบบ NuGet‑style ที่ฟรีและสามารถดึงจาก PyPI ได้ รันคำสั่งต่อไปนี้ภายใน virtual environment ที่เปิดใช้งานแล้ว: + +```bash +pip install aspose-ocr +``` + +หากเจอข้อผิดพลาดเรื่องสิทธิ์ ให้เพิ่ม flag `--user` หรือรันคำสั่งด้วย `sudo` (สำหรับ Linux/macOS เท่านั้น) หลังการติดตั้งคุณควรเห็นข้อความประมาณนี้: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **ทำไมต้องเลือก Aspose?** แตกต่างจากเครื่องมือ OCR แบบโอเพนซอร์สหลายตัว Aspose.OCR รองรับ **bulk image to text conversion** ตั้งแต่แรกและจัดการกับรูปแบบภาพหลากหลายโดยไม่ต้องตั้งค่าเพิ่มเติม อีกทั้งยังมีคลาส `BatchOcrEngine` ที่ทำให้การทำ **convert images to text python** เป็นการดำเนินการหนึ่งบรรทัด + +## ขั้นตอนที่ 3 – แปลงรูปภาพเป็นข้อความด้วย Batch OCR + +นี่คือหัวใจของบทเรียน สคริปต์ต่อไปนี้สามารถรันได้ทันทีและทำสิ่งต่อไปนี้: + +1. นำเข้าคลาสของ OCR engine +2. สร้างอินสแตนซ์ของ `BatchOcrEngine` +3. ชี้ engine ไปยังโฟลเดอร์รูปภาพต้นทาง +4. กำหนดให้ engine เขียนไฟล์ข้อความที่สกัดออกมาแต่ละไฟล์ลงในโฟลเดอร์ผลลัพธ์ +5. เรียกเมธอด `recognize()` ซึ่ง **recognize text from scanned images** ทีละไฟล์ + +บันทึกโค้ดต่อไปนี้เป็น `batch_ocr.py` ภายในโฟลเดอร์โปรเจกต์ของคุณ: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### วิธีการทำงาน + +- **`BatchOcrEngine`** ทำหน้าที่ห่อ `OcrEngine` ปกติแต่เพิ่มการประสานงานระดับโฟลเดอร์ ซึ่งเหมาะอย่างยิ่งเมื่อคุณต้องการ **convert images to text python** เป็นชุดใหญ่ +- คุณสมบัติ `input_folder` บอก engine ว่าจะค้นหารูปภาพต้นทางจากที่ใด มันจะสแกนไดเรกทอรีโดยอัตโนมัติและจัดคิวไฟล์ที่รองรับทั้งหมด +- คุณสมบัติ `output_folder` กำหนดตำแหน่งที่ไฟล์ `.txt` แต่ละไฟล์จะถูกบันทึก Engine จะคัดลอกชื่อไฟล์เดิม เช่น `receipt1.png` จะกลายเป็น `receipt1.txt` +- การเรียก `recognize()` จะเปิดลูปภายในที่โหลดแต่ละรูปภาพ, รัน OCR, แล้วเขียนผลลัพธ์ เมธอดนี้จะบล็อกจนกว่าทุกไฟล์จะประมวลผลเสร็จ ทำให้คุณสามารถต่อขั้นตอนต่อไปได้ง่าย (เช่น zip โฟลเดอร์ผลลัพธ์) + +#### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณรันสคริปต์: + +```bash +python batch_ocr.py +``` + +คุณควรเห็น: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +ในโฟลเดอร์ `output_texts` จะมีไฟล์ข้อความธรรมดาสำหรับทุกภาพ เปิดไฟล์ใดไฟล์หนึ่งด้วยโปรแกรมแก้ไขข้อความแล้วคุณจะเห็นผล OCR ดิบ—โดยทั่วไปจะเป็นการประมาณที่ใกล้เคียงกับข้อความพิมพ์ต้นฉบับ + +## ขั้นตอนที่ 4 – ตรวจสอบผลลัพธ์และจัดการข้อผิดพลาด + +แม้ OCR engine ที่ดีที่สุดก็อาจพลาดเมื่อสแกนความละเอียดต่ำหรือหน้าเอกสารเอียงมาก นี่คือวิธีตรวจสอบความถูกต้องของผลลัพธ์อย่างรวดเร็วและบันทึกไฟล์ที่ล้มเหลว + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**ทำไมต้องเพิ่มส่วนนี้?** +- มันจับกรณีที่ engine ผลิตสตริงว่างเปล่าโดยเงียบ (เป็นปัญหาที่พบบ่อยกับภาพที่อ่านไม่ออก) +- มันให้รายการไฟล์ที่มีปัญหาเพื่อให้คุณตรวจสอบด้วยตนเองหรือรันใหม่ด้วยการตั้งค่าอื่น (เช่น เพิ่มตัวเลือก `OcrEngine.preprocess`) + +### กรณีขอบและการปรับแต่ง + +| สถานการณ์ | วิธีแก้แนะนำ | +|-----------|----------------| +| รูปภาพหมุน 90° | ตั้งค่า `batch_engine.ocr_engine.rotation_correction = True` | +| หลายภาษา (อังกฤษ + ฝรั่งเศส) | ใช้ `batch_engine.ocr_engine.language = "eng+fra"` ก่อนเรียก `recognize()` | +| PDF ขนาดใหญ่แปลงเป็นรูปภาพก่อน | แบ่ง PDF เป็นรูปภาพหน้าเดียวแล้วใส่โฟลเดอร์ให้ batch engine | +| ข้อผิดพลาดเรื่องหน่วยความจำในแบตช์ขนาดใหญ่ | ประมวลผลโฟลเดอร์ย่อยขนาดเล็กเป็นลำดับ หรือเพิ่มค่า `batch_engine.max_memory_usage` | + +## ขั้นตอนที่ 5 – ทำอัตโนมัติทั้งหมด (ทางเลือก) + +หากคุณต้องการให้การแปลงนี้ทำงานทุกคืน ให้ห่อสคริปต์ด้วยไฟล์เชลล์หรือ batch file ง่าย ๆ แล้วตั้งเวลาให้ทำงานด้วย `cron` (Linux/macOS) หรือ Task Scheduler (Windows) ตัวอย่าง `run_ocr.sh` สำหรับระบบยูนิกซ์: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +ทำให้ไฟล์เป็น executable (`chmod +x run_ocr.sh`) แล้วเพิ่ม entry ใน cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +สคริปต์นี้จะรันการแปลงทุกวันตอน 2 AM และบันทึกผลลัพธ์ไว้ตรวจสอบภายหลัง + +--- + +## สรุป + +คุณมีวิธีที่พิสูจน์แล้วและพร้อมใช้งานในระดับ production เพื่อ **convert images to text python** ด้วย `BatchOcrEngine` ของ Aspose.OCR สคริปต์นี้จัดการ **bulk image to text conversion** อย่างราบรื่น เขียนผลลัพธ์แต่ละไฟล์แยกกัน และรวมขั้นตอนการตรวจสอบเพื่อให้แน่ใจว่าคุณ **recognize text from scanned images** อย่างถูกต้อง + +จากจุดนี้คุณอาจ: + +- ทดลองตั้งค่า OCR ต่าง ๆ (แพ็คเกจภาษา, deskew, ลดสัญญาณรบกวน) +- ส่งข้อความที่สร้างขึ้นไปยังดัชนีการค้นหาอย่าง Elasticsearch เพื่อการค้นหาเต็มข้อความทันที +- ผสาน pipeline นี้กับเครื่องมือแปลง PDF เพื่อประมวลผล PDF สแกนทั้งหมดในขั้นตอนเดียว + +มีคำถามหรือเจอปัญหาไฟล์ประเภทใดประเภทหนึ่ง? แสดงความคิดเห็นด้านล่าง แล้วเราจะช่วยกันแก้ไข Happy coding, ขอให้การรัน OCR ของคุณเร็วและปราศจากข้อผิดพลาด! + +## สิ่งที่คุณควรเรียนต่อไป + +- [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 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/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/thai/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..c51287cce --- /dev/null +++ b/ocr/thai/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: สร้างอินสแตนซ์ไลเซนส์ใน Python และกำหนดเส้นทางไลเซนส์ได้อย่างง่ายดาย + เรียนรู้วิธีตั้งค่าไลเซนส์ Aspose OCR พร้อมตัวอย่างโค้ดที่ชัดเจน +draft: false +keywords: +- create license instance +- configure license path +language: th +og_description: สร้างอินสแตนซ์ไลเซนส์ใน Python และกำหนดเส้นทางไลเซนส์ทันที ตามบทเรียนนี้เพื่อเปิดใช้งาน + Aspose OCR อย่างมั่นใจ. +og_title: สร้างอินสแตนซ์ไลเซนส์ใน Python – คู่มือการตั้งค่าแบบครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: สร้างอินสแตนซ์ใบอนุญาตใน Python – คู่มือแบบทีละขั้นตอน +url: /th/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างอินสแตนซ์ใบอนุญาตใน Python – คู่มือการตั้งค่าเต็ม + +ต้องการ **create license instance** สำหรับ Aspose OCR ใน Python หรือไม่? คุณมาถูกที่แล้ว ในบทแนะนำนี้เราจะสาธิตวิธี **configure license path** เพื่อให้ SDK รู้ว่าจะหาไฟล์ `.lic` ของคุณได้จากที่ไหน + +หากคุณเคยมองสคริปต์เปล่า ๆ แล้วสงสัยว่าทำไมเครื่องมือ OCR ถึงบ่นเรื่องผลิตภัณฑ์ที่ไม่มีใบอนุญาต คุณไม่ได้เป็นคนเดียว วิธีแก้มักเป็นเพียงไม่กี่บรรทัดของโค้ด—เมื่อคุณรู้ว่าต้องวางไว้ที่ไหน ตอนจบของคู่มือนี้คุณจะมีสภาพแวดล้อม Aspose OCR ที่ได้รับใบอนุญาตเต็มรูปแบบพร้อมรับรู้ข้อความ รูปภาพ และ PDF อย่างไม่มีปัญหา + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธี **create license instance** ด้วยแพ็กเกจ `asposeocr` +- วิธีที่ถูกต้องในการ **configure license path** สำหรับการพัฒนาและการผลิต +- ข้อผิดพลาดทั่วไป (ไฟล์หาย, สิทธิ์ไม่ถูกต้อง) และวิธีหลีกเลี่ยง +- สคริปต์ที่สมบูรณ์และรันได้ที่คุณสามารถใส่ลงในโปรเจกต์ใดก็ได้ + +ไม่จำเป็นต้องมีประสบการณ์กับ Aspose OCR มาก่อน เพียงแค่มีการติดตั้ง Python 3 ที่ทำงานได้และไฟล์ใบอนุญาตที่ถูกต้อง + +--- + +## ขั้นตอนที่ 1: ติดตั้งแพ็กเกจ Aspose OCR สำหรับ Python + +ก่อนที่เราจะ **create license instance** ไลบรารีต้องถูกติดตั้งก่อน เปิดเทอร์มินัลและรัน: + +```bash +pip install aspose-ocr +``` + +> **เคล็ดลับ:** หากคุณใช้ virtual environment (แนะนำอย่างยิ่ง) ให้เปิดใช้งานก่อน สิ่งนี้จะทำให้การจัดการ dependencies ของคุณเป็นระเบียบและป้องกันการชนกันของเวอร์ชัน + +## ขั้นตอนที่ 2: นำเข้า License Class + +เมื่อ SDK พร้อมใช้งานแล้ว บรรทัดแรกของสคริปต์ควรนำเข้า class `License` นี่คืออ็อบเจกต์ที่เราจะใช้เพื่อ **create license instance**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +ทำไมต้องนำเข้าเลย? เพราะอ็อบเจกต์ `License` ต้องถูกสร้าง **ก่อน** การเรียกใช้ OCR ใด ๆ; มิฉะนั้น SDK จะโยนข้อผิดพลาดเรื่องใบอนุญาตทันทีที่คุณพยายามประมวลผลภาพ + +## ขั้นตอนที่ 3: สร้าง License Instance + +นี่คือช่วงเวลาที่คุณรอคอย—จริง ๆ แล้ว **create license instance** เพียงบรรทัดเดียว แต่บริบทโดยรอบมีความสำคัญ + +```python +# Step 3: Create a License instance +license = License() +``` + +ตัวแปร `license` ตอนนี้ถืออ็อบเจกต์ที่ควบคุมพฤติกรรมการให้ใบอนุญาตทั้งหมดสำหรับกระบวนการ Python ปัจจุบัน คิดว่าเป็นผู้คุมประตูที่บอก Aspose OCR ว่า “เฮ้ ฉันมีสิทธิ์รันแล้ว” + +## ขั้นตอนที่ 4: ตั้งค่า License Path + +เมื่ออินสแตนซ์พร้อมแล้ว เราต้องชี้ไปที่ไฟล์ `.lic` ของเรา นั่นคือจุดที่ **configure license path** เข้ามามีบทบาท แทนที่ placeholder ด้วยพาธแบบ absolute ไปยังไฟล์ใบอนุญาตของคุณ + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +สิ่งที่ควรทราบ: + +1. **Raw strings (`r"…"`)** ป้องกันไม่ให้ backslash ถูกตีความเป็นอักขระ escape บน Windows +2. ใช้ **absolute path** เพื่อหลีกเลี่ยงความสับสนเมื่อสคริปต์ถูกเรียกจากไดเรกทอรีทำงานอื่น +3. หากคุณต้องการใช้ relative path (เช่นเมื่อรวมใบอนุญาตกับโปรเจกต์) ให้แน่ใจว่าฐาน relative คือที่ตั้งของสคริปต์ ไม่ใช่ไดเรกทอรีของเชลล์ปัจจุบัน + +### การจัดการไฟล์ที่หายไป + +หากพาธผิดหรือไฟล์ไม่สามารถอ่านได้ `set_license` จะโยนข้อยกเว้น ให้ห่อการเรียกในบล็อก `try/except` เพื่อแสดงข้อความข้อผิดพลาดที่เป็นมิตร: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +โค้ดส่วนนี้ **configures license path** อย่างปลอดภัยและบอกคุณว่าผิดพลาดตรงไหน—ไม่มี stack trace ที่ลึกลับ + +## ขั้นตอนที่ 5: ตรวจสอบว่า License ทำงานอยู่ + +การตรวจสอบอย่างรวดเร็วช่วยประหยัดเวลาการดีบักหลายชั่วโมง หลังจากที่คุณเรียก `set_license` แล้ว ลองทำ OCR อย่างง่าย หากใบอนุญาตถูกต้อง SDK จะประมวลผลภาพโดยไม่โยนข้อผิดพลาดเรื่องใบอนุญาต + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +หากคุณเห็นข้อความที่รับรู้พิมพ์ออกมา ยินดีด้วย—คุณได้ **create license instance** และ **configure license path** สำเร็จแล้ว หากเกิดข้อยกเว้นเรื่องใบอนุญาต ให้ตรวจสอบพาธและสิทธิ์ไฟล์อีกครั้ง + +## กรณีขอบและแนวทางปฏิบัติที่ดีที่สุด + +| Situation | What to Do | +|-----------|------------| +| **License file lives in a network share** | เชื่อมต่อแชร์ไปยังไดรฟ์อักษรหรือใช้ UNC path (`\\server\share\license.lic`). ตรวจสอบให้กระบวนการ Python มีสิทธิ์อ่าน | +| **Running inside a Docker container** | คัดลอกไฟล์ `.lic` เข้าไปในอิมเมจและอ้างอิงด้วยพาธ absolute เช่น `/app/license/Aspose.OCR.Java.lic`. | +| **Multiple Python interpreters** (e.g., conda envs) | ติดตั้งไฟล์ใบอนุญาตหนึ่งครั้งต่อ environment หรือเก็บไว้ในตำแหน่งศูนย์กลางและชี้แต่ละ interpreter ไปยังไฟล์นั้น | +| **License file missing at runtime** | ทำ fallback อย่างสุภาพไปยังโหมด trial (หากรองรับ) หรือหยุดทำงานพร้อมข้อความบันทึกที่ชัดเจน | + +### ข้อผิดพลาดทั่วไป + +- **Using forward slashes on Windows** – Python ยอมรับ แต่บางเวอร์ชันเก่าของ SDK อาจตีความผิด ใช้ raw strings หรือ double backslashes +- **Forgot to import `License`** – สคริปต์จะพังด้วย `NameError`. ควรนำเข้าก่อนสร้างอินสแตนซ์เสมอ +- **Calling `set_license` after OCR methods** – SDK ตรวจสอบใบอนุญาตเมื่อใช้งานครั้งแรก ดังนั้นตั้งพาธ **ก่อน** + +## ตัวอย่างการทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์สมบูรณ์ที่เชื่อมทุกส่วนเข้าด้วยกัน บันทึกเป็น `ocr_setup.py` แล้วรันจากบรรทัดคำสั่ง + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Expected output** (assuming a valid image): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +หากไฟล์ใบอนุญาตไม่พบ คุณจะเห็นข้อความข้อผิดพลาดที่ชัดเจนแทนข้อยกเว้น “License not found” ที่ไม่เข้าใจ + +## สรุป + +คุณตอนนี้รู้วิธี **create license instance** ใน Python และ **configure license path** สำหรับ Aspose OCR SDK อย่างแม่นยำ ขั้นตอนง่าย ๆ: ติดตั้งแพ็กเกจ, นำเข้า `License`, สร้างอินสแตนซ์, ชี้ไปที่ไฟล์ `.lic` ของคุณ, และตรวจสอบด้วยการทดสอบ OCR เล็ก ๆ + +ด้วยความรู้นี้คุณสามารถฝังความสามารถ OCR ลงในเว็บเซอร์วิส, แอปเดสก์ท็อป, หรือไพป์ไลน์อัตโนมัติโดยไม่ต้องกังวลเรื่องข้อผิดพลาดใบอนุญาต ต่อไปลองสำรวจการตั้งค่า OCR ขั้นสูง—แพ็คเกจภาษา, การเตรียมภาพ, หรือการประมวลผลเป็นชุด—ซึ่งทั้งหมดอาศัยพื้นฐานที่คุณตั้งค่าไว้แล้ว + +มีคำถามเกี่ยวกับการปรับใช้, Docker, หรือการจัดการหลายใบอนุญาต? แสดงความคิดเห็นได้เลย, ขอให้โค้ดสนุก! + +## สิ่งที่คุณควรเรียนต่อไป? + +- [บทแนะนำ Aspose OCR – การจดจำอักขระด้วยแสง](/ocr/english/) +- [วิธีตั้งค่า License และตรวจสอบ Aspose.OCR License ใน Java](/ocr/english/java/ocr-basics/set-license/) +- [วิธี OCR ข้อความในรูปภาพด้วยภาษาโดยใช้ Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/thai/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..7ef426c8a --- /dev/null +++ b/ocr/thai/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: สร้าง PDF ที่สามารถค้นหาได้จากภาพสแกนโดยใช้ Python OCR. เรียนรู้วิธีแปลง + PDF จากภาพสแกน, แปลง TIFF เป็น PDF, และเพิ่มชั้นข้อความ OCR ในไม่กี่นาที. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: th +og_description: สร้าง PDF ที่ค้นหาได้ทันที คู่มือนี้แสดงวิธีการทำ OCR, แปลง PDF ที่เป็นภาพสแกน, + และเพิ่มชั้นข้อความ OCR ด้วยสคริปต์ Python เพียงไฟล์เดียว. +og_title: สร้าง PDF ที่ค้นหาได้ด้วย Python – บทเรียนเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: สร้าง PDF ที่ค้นหาได้ด้วย Python – คู่มือขั้นตอนโดยละเอียด +url: /th/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง PDF ที่สามารถค้นหาได้ด้วย Python – คู่มือขั้นตอนโดยละเอียด + +เคยสงสัยไหมว่าจะ **สร้าง PDF ที่สามารถค้นหาได้** จากหน้าที่สแกนโดยไม่ต้องใช้เครื่องมือหลายสิบอย่าง? คุณไม่ได้เป็นคนเดียว ในหลายกระบวนการทำงานของสำนักงาน ไฟล์ TIFF หรือ JPEG ที่สแกนแล้วจะถูกวางไว้บนไดรฟ์ร่วมกัน และคนถัดไปต้องคัดลอก‑วางข้อความด้วยตนเอง – ทำให้เจ็บปวด มีโอกาสผิดพลาด และเสียเวลา + +ในบทเรียนนี้เราจะพาไปผ่านวิธีแก้ปัญหาแบบโปรแกรมที่สะอาดตา ซึ่งทำให้คุณ **แปลง PDF ที่เป็นภาพสแกน**, **แปลง TIFF เป็น PDF**, และ **เพิ่มชั้นข้อความ OCR** ได้ในขั้นตอนเดียว เมื่อเสร็จแล้วคุณจะได้สคริปต์พร้อมใช้ที่ทำ OCR ฝังข้อความที่ซ่อนอยู่ และสร้าง PDF ที่สามารถค้นหาได้ซึ่งคุณสามารถทำดัชนี ค้นหา หรือแชร์ได้อย่างมั่นใจ + +## สิ่งที่คุณต้องมี + +- Python 3.9+ (เวอร์ชันล่าสุดใดก็ได้) +- แพคเกจ `aspose-ocr` และ `aspose-pdf` (ติดตั้งด้วย `pip install aspose-ocr aspose-pdf`) +- ไฟล์ภาพสแกน (`.tif`, `.png`, `.jpg` หรือแม้แต่ PDF หน้าเดียวที่เป็นภาพ) +- RAM ปริมาณปานกลาง (เอนจิน OCR มีน้ำหนักเบา; แม้แล็ปท็อปก็จัดการได้) + +> **เคล็ดลับมืออาชีพ:** หากคุณใช้ Windows วิธีที่ง่ายที่สุดในการรับแพคเกจคือรันคำสั่งใน PowerShell ที่เปิดด้วยสิทธิ์ผู้ดูแลระบบ + +```bash +pip install aspose-ocr aspose-pdf +``` + +เมื่อเงื่อนไขเบื้องต้นเรียบร้อยแล้ว ไปดูกันที่โค้ดกันเลย + +## ขั้นตอนที่ 1: สร้างอินสแตนซ์ของ OCR Engine – *create searchable pdf* + +สิ่งแรกที่เราทำคือเปิดใช้งาน OCR engine คิดว่าเป็นสมองที่อ่านพิกเซลทุกจุดและแปลงเป็นอักขระ + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **ทำไมจึงสำคัญ:** การเริ่มต้นเอนจินเพียงครั้งเดียวช่วยลดการใช้หน่วยความจำ หากคุณเรียก `OcrEngine()` ภายในลูปสำหรับแต่ละหน้า คุณจะใช้ทรัพยากรหมดเร็วเกินไป + +## ขั้นตอนที่ 2: โหลดภาพสแกน – *convert tiff to pdf* & *convert scanned image pdf* + +ต่อไปให้ชี้เอนจินไปที่ไฟล์ที่ต้องการประมวลผล API รองรับภาพแรสเตอร์ใดก็ได้ ดังนั้น TIFF จึงทำงานได้เท่า JPEG + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +หากคุณมี PDF ที่มีเพียงภาพสแกนอยู่ คุณยังสามารถใช้ `load_image` ได้ เพราะ Aspose จะดึงหน้าที่แรกออกมาโดยอัตโนมัติ + +## ขั้นตอนที่ 3: เตรียมตัวเลือกการบันทึก PDF – *add OCR text layer* + +ที่นี่เราตั้งค่าการแสดงผลของ PDF ขั้นสุดท้าย ธงสำคัญคือ `create_searchable_pdf`; ตั้งค่าเป็น `True` จะบอกไลบรารีให้ฝังชั้นข้อความที่มองไม่เห็นซึ่งสอดคล้องกับเนื้อหาภาพ + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **ชั้นข้อความทำอะไร:** เมื่อคุณเปิดไฟล์ที่ได้ใน Adobe Reader แล้วพยายามเลือกข้อความ คุณจะเห็นอักขระที่ซ่อนอยู่ เครื่องมือค้นหาก็สามารถทำดัชนีได้เช่นกัน – เหมาะสำหรับการปฏิบัติตามกฎระเบียบหรือการเก็บถาวร + +## ขั้นตอนที่ 4: รัน OCR และบันทึก – *how to run OCR* ในคำสั่งเดียว + +ตอนนี้จุดมหัศจรรย์เกิดขึ้น การเรียกเมธอดเดียวจะรันเอนจินการจดจำและเขียน PDF ที่สามารถค้นหาได้ลงดิสก์ + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +เมธอด `recognize` จะคืนค่าออบเจ็กต์สถานะที่คุณสามารถตรวจสอบข้อผิดพลาดได้ แต่สำหรับสถานการณ์ที่ตรงไปตรงมาส่วนใหญ่ การเรียกแบบง่ายข้างต้นก็เพียงพอ + +### ผลลัพธ์ที่คาดหวัง + +การรันสคริปต์จะแสดงผล: + +``` +PDF saved as searchable PDF. +``` + +หากคุณเปิด `scanned_page_searchable.pdf` คุณจะสังเกตว่าเลือกข้อความได้ คัดลอก‑วางได้ และแม้กระทั่งใช้ `Ctrl+F` ค้นหาได้ นี่คือสัญลักษณ์ของกระบวนการ **create searchable pdf** + +## สคริปต์ทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์ที่พร้อมรัน เพียงแทนที่พาธตัวอย่างด้วยตำแหน่งไฟล์ของคุณเอง + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +บันทึกไฟล์นี้เป็น `create_searchable_pdf.py` แล้วรัน: + +```bash +python create_searchable_pdf.py +``` + +## คำถามที่พบบ่อย & กรณีขอบ + +### 1️⃣ ฉันสามารถประมวลผล PDF หลายหน้าได้หรือไม่? + +ได้ ใช้ `ocr_engine.load_image("file.pdf")` แล้ววนลูปแต่ละหน้าโดยใช้ `ocr_engine.recognize(pdf_save_options, page_number)` ไลบรารีจะสร้าง PDF ที่สามารถค้นหาได้หลายหน้าโดยอัตโนมัติ + +### 2️⃣ ถ้าไฟล์ต้นฉบับของฉันเป็น TIFF ความละเอียดสูง (300 dpi+) จะทำอย่างไร? + +DPI ที่สูงขึ้นให้ความแม่นยำ OCR ดียิ่งขึ้นแต่ใช้หน่วยความจำมากขึ้น หากเจอ `MemoryError` ให้ลดขนาดภาพก่อน: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ ฉันจะเปลี่ยนภาษาของ OCR ได้อย่างไร? + +ตั้งค่าคุณสมบัติ `language` ของเอนจินก่อนโหลดภาพ: + +```python +ocr_engine.language = "fra" # French +``` + +รายการรหัสภาษาที่รองรับทั้งหมดอยู่ในเอกสารของ Aspose + +### 4️⃣ ถ้าฉันต้องการรักษาคุณภาพภาพต้นฉบับไว้? + +คลาส `PdfSaveOptions` มีคุณสมบัติ `compression` ตั้งค่าเป็น `PdfCompression.None` เพื่อเก็บข้อมูลแรสเตอร์ไว้ตามเดิม + +```python +pdf_save_options.compression = "None" +``` + +## เคล็ดลับสำหรับการปรับใช้ในระดับ Production + +- **การประมวลผลเป็นชุด:** ห่อโลจิกหลักในฟังก์ชันที่รับรายการพาธไฟล์ บันทึกผลสำเร็จ/ความล้มเหลวแต่ละรายการลง CSV เพื่อใช้เป็นบันทึกตรวจสอบ +- **การทำงานแบบขนาน:** ใช้ `concurrent.futures.ThreadPoolExecutor` เพื่อรัน OCR บนหลายคอร์ จำไว้ว่าทุกเธรดต้องมีอินสแตนซ์ `OcrEngine` ของตนเอง +- **ความปลอดภัย:** หากจัดการกับเอกสารที่เป็นความลับ ให้รันสคริปต์ในสภาพแวดล้อมแซนด์บ็อกซ์และลบไฟล์ชั่วคราวทันทีหลังการประมวลผล + +## สรุป + +คุณได้เรียนรู้วิธี **สร้าง PDF ที่สามารถค้นหาได้** จากภาพสแกนด้วยสคริปต์ Python สั้น ๆ ด้วยการเริ่มต้น OCR engine, โหลด TIFF (หรือแรสเตอร์ใดก็ได้), ตั้งค่า `PdfSaveOptions` เพื่อ **add OCR text layer**, แล้วเรียก `recognize` ทั้งหมดทำให้กระบวนการ **convert scanned image pdf** และ **convert TIFF to PDF** กลายเป็นคำสั่งเดียวที่ทำซ้ำได้ + +ขั้นตอนต่อไป? ลองเชื่อมสคริปต์นี้กับตัวตรวจจับไฟล์เพื่อให้ทุกการสแกนใหม่ที่วางลงในโฟลเดอร์กลายเป็นไฟล์ที่สามารถค้นหาได้โดยอัตโนมัติ หรือทดลองใช้ภาษาต่าง ๆ ของ OCR เพื่อรองรับคลังข้อมูลหลายภาษา ความเป็นไปได้ไม่มีที่สิ้นสุดเมื่อคุณผสาน OCR กับการสร้าง PDF + +มีคำถามเพิ่มเติมเกี่ยวกับ **how to run OCR** ในภาษา หรือเฟรมเวิร์กอื่น ๆ หรือไม่? แสดงความคิดเห็นด้านล่าง แล้วขอให้เขียนโค้ดอย่างสนุกสนาน! + +![Diagram showing the flow from scanned image → OCR engine → searchable PDF (create searchable pdf)](searchable-pdf-flow.png "ไดอะแกรมการไหลของการสร้าง PDF ที่สามารถค้นหาได้") + +## คุณควรเรียนรู้อะไรต่อไป? + +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Convert Images to PDF C# – Save Multipage OCR Result](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/thai/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..b8cb80e6b --- /dev/null +++ b/ocr/thai/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-31 +description: ปรับปรุงความแม่นยำของ OCR ด้วย Python โดยการทำการประมวลผลล่วงหน้าภาพสำหรับ + OCR เรียนรู้วิธีดึงข้อความจากไฟล์ภาพ, จำแนกข้อความจาก PNG, และเพิ่มผลลัพธ์. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: th +og_description: ปรับปรุงความแม่นยำของ OCR ใน Python ด้วยการทำการประมวลผลภาพล่วงหน้าสำหรับข้อความ + ทำตามคู่มือนี้เพื่อดึงข้อความจากไฟล์ภาพและจดจำข้อความจาก PNG อย่างง่ายดาย +og_title: ปรับปรุงความแม่นยำของ OCR ใน Python – บทเรียนเต็ม +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: เพิ่มความแม่นยำของ OCR ใน Python – คู่มือขั้นตอนเต็ม +url: /th/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ปรับปรุงความแม่นยำของ OCR ใน Python – คู่มือขั้นตอนเต็ม + +เคยพยายาม **ปรับปรุงความแม่นยำของ OCR** แล้วได้ผลลัพธ์เป็นข้อความที่อ่านไม่ออกหรือเปล่า? คุณไม่ได้เป็นคนเดียวที่เจอปัญหานี้ นักพัฒนาส่วนใหญ่มักเจออุปสรรคเมื่อภาพดิบมีสัญญาณรบกวน, เอียง, หรือมีคอนทราสต์ต่ำ ข่าวดีคือ มีเทคนิคการเตรียมภาพหลายอย่างที่สามารถเปลี่ยนภาพสกรีนช็อตที่เบลอให้กลายเป็นข้อความที่เครื่องอ่านได้อย่างชัดเจน + +ในบทเรียนนี้เราจะเดินผ่านตัวอย่างจริงที่ **เตรียมภาพสำหรับ OCR**, เรียกใช้เครื่องมือจดจำ, และสุดท้าย **ดึงข้อความจากไฟล์ภาพ** — โดยเฉพาะไฟล์ PNG. เมื่อจบคุณจะรู้วิธี **จดจำข้อความจาก PNG** ด้วยอัตราความสำเร็จที่สูงขึ้น, และจะได้โค้ดส่วนนำกลับไปใช้ในโปรเจกต์ใดก็ได้ + +## สิ่งที่คุณจะได้เรียน + +- ทำไมการเตรียมภาพจึงสำคัญต่อเครื่องมือ OCR +- โหมดการเตรียมภาพ (denoise, deskew) ที่ให้ผลลัพธ์ดีที่สุด +- วิธีตั้งค่าอินสแตนซ์ `OcrEngine` ใน Python +- สคริปต์เต็มที่สามารถรันได้ซึ่ง **ดึงข้อความจากไฟล์ภาพ** +- เคล็ดลับการจัดการกรณีพิเศษ เช่น การสแกนที่หมุนหรือภาพความละเอียดต่ำ + +ไม่ต้องใช้ไลบรารีภายนอกนอกจาก OCR SDK, แต่คุณต้องมี Python 3.8+ และไฟล์ PNG ที่ต้องการอ่าน + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Improve OCR accuracy workflow") + +*ข้อความแทน: แผนผังขั้นตอนการปรับปรุงความแม่นยำของ OCR ใน Python แสดงการเตรียมภาพและขั้นตอนการจดจำ* + +## ข้อกำหนดเบื้องต้น + +- ติดตั้ง Python 3.8 หรือใหม่กว่า +- มีการเข้าถึง OCR SDK ที่ให้ `OcrEngine`, `OcrEngineSettings`, และ `ImagePreprocessMode` (โค้ดด้านล่างใช้ API ทั่วไป; แทนที่ด้วยคลาสของผู้ขายของคุณหากจำเป็น) +- มีไฟล์ PNG (`input.png`) อยู่ในโฟลเดอร์ที่คุณอ้างอิงได้ + +หากคุณใช้ virtual environment, ให้เปิดใช้งานตอนนี้ — ไม่ต้องทำอะไรซับซ้อน, เพียง `python -m venv venv && source venv/bin/activate`. + +--- + +## ขั้นตอนที่ 1: สร้างอินสแตนซ์ OCR Engine – เริ่มปรับปรุงความแม่นยำของ OCR + +สิ่งแรกที่คุณต้องมีคืออ็อบเจกต์ OCR engine. คิดว่าเป็นสมองที่ต่อมาจะอ่านพิกเซลและแปลงเป็นอักขระ + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +ทำไมต้องทำเช่นนี้: หากไม่มี engine คุณไม่สามารถทำการเตรียมภาพได้, และภาพดิบจะถูกส่งตรงไปยัง recogniser — ซึ่งมักเป็นสถานการณ์ที่ทำให้ความแม่นยำแย่ที่สุด + +--- + +## ขั้นตอนที่ 2: โหลดไฟล์ PNG ที่ต้องการ – ตั้งค่าพื้นฐานสำหรับ Recognize Text from PNG + +ต่อไปเราบอก engine ว่าไฟล์ใดจะทำงาน PNG มีลักษณะ lossless ซึ่งให้ความได้เปรียบเล็กน้อยเหนือ JPEG + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +หากภาพอยู่ที่อื่น, เพียงปรับเส้นทางให้ตรง. Engine รองรับฟอร์แมตที่สนับสนุนทั้งหมด, แต่ PNG มักเก็บรายละเอียดที่จำเป็นสำหรับขอบอักษรคมชัด + +--- + +## ขั้นตอนที่ 3: ตั้งค่าการเตรียมภาพ – Preprocess Image for OCR + +นี่คือจุดที่เวทมนตร์เกิดขึ้น. เราจะสร้างอ็อบเจกต์ settings, เปิดใช้งาน denoising เพื่อลบจุดรบกวน, และเปิด deskew เพื่อให้ข้อความที่เอียงตรงอัตโนมัติ + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### ทำไมต้อง Denoise + Deskew? + +- **Denoise**: สัญญาณรบกวนแบบสุ่มทำให้ algorithm การจับคู่รูปแบบสับสน. การลบสัญญาณรบกวนทำให้ตัวอักษรคมชัดขึ้น +- **Deskew**: การเอียงเพียง 2° ก็อาจทำให้คะแนนความเชื่อมั่นลดลงอย่างมาก. Deskew ปรับเส้นฐานให้ตรง, ทำให้ recogniser จับคู่ฟอนต์ได้แม่นยำกว่า + +คุณสามารถทดลองใช้ flag เพิ่มเติม (เช่น `ImagePreprocessMode.CONTRAST_ENHANCE`) หากภาพของคุณมืดมาก. เอกสาร SDK จะระบุโหมดที่ใช้ได้ทั้งหมด + +--- + +## ขั้นตอนที่ 4: นำ Settings ไปใช้กับ Engine – Tie Preprocessing to OCR + +กำหนดอ็อบเจกต์ settings ให้กับ engine เพื่อให้การรันครั้งต่อไปใช้การแปลงที่เรากำหนดไว้ + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +หากข้ามขั้นตอนนี้, engine จะกลับไปใช้ค่าเริ่มต้น (มักเป็น “ไม่มีการเตรียมภาพ”), และคุณจะเห็น **ความแม่นยำของ OCR ลดลง**. + +--- + +## ขั้นตอนที่ 5: รันกระบวนการจดจำ – Extract Text from Image + +เมื่อทุกอย่างเชื่อมต่อแล้ว, เราจะสั่งให้ engine ทำหน้าที่ของมัน. การเรียกนี้เป็นแบบ synchronous, จะคืนค่าเป็นอ็อบเจกต์ผลลัพธ์ที่บรรจุสตริงที่จดจำได้ + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +เบื้องหลัง engine จะทำขั้นตอนต่อไปนี้: + +1. โหลด PNG เข้าหน่วยความจำ +2. ใช้ denoise และ deskew ตาม settings ของเรา +3. รัน neural‑network หรือ classic pattern matcher +4. แพ็คผลลัพธ์เป็น `recognition_result` + +--- + +## ขั้นตอนที่ 6: แสดงข้อความที่จดจำได้ – Verify the Improvement + +พิมพ์สตริงที่ดึงออกมา. ในแอปพลิเคชันจริงคุณอาจบันทึกลงไฟล์, ฐานข้อมูล, หรือส่งต่อให้บริการอื่น + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### ผลลัพธ์ที่คาดหวัง + +หากภาพมีประโยค “Hello, OCR World!” คุณควรเห็น: + +``` +Hello, OCR World! +``` + +สังเกตว่าข้อความสะอาดไม่มีสัญลักษณ์แปลกหรืออักขระหักหั่น. นั่นคือผลของ **image preprocessing for text** ที่ทำอย่างถูกต้อง + +--- + +## เคล็ดลับระดับมืออาชีพ & กรณีพิเศษ + +| สถานการณ์ | สิ่งที่ต้องปรับ | เหตุผล | +|-----------|----------------|-----| +| PNG ความละเอียดต่ำมาก (≤ 72 dpi) | เพิ่ม `ImagePreprocessMode.SUPER_RESOLUTION` หากมี | การอัปสแคลให้ recogniser มีพิกเซลมากขึ้นทำงานได้ดีขึ้น | +| ข้อความหมุน > 5° | เพิ่ม tolerance ของ deskew หรือหมุนภาพด้วย `Pillow` ก่อนส่งให้ engine | มุมเอียงมากอาจหลุดจากการ deskew อัตโนมัติ | +| พื้นหลังมีลวดลายหนาแน่น | เปิด `ImagePreprocessMode.BACKGROUND_REMOVAL` | ลบสิ่งรบกวนที่ไม่ใช่ข้อความซึ่งอาจทำให้ recogniser อ่านผิด | +| เอกสารหลายภาษา | ตั้ง `ocr_engine.language = "eng+spa"` (หรือคล้ายกัน) | Engine จะเลือกชุดอักขระที่เหมาะ, เพิ่มความแม่นยำโดยรวม | + +จำไว้ว่า **improve OCR accuracy** ไม่ได้มีวิธีเดียวที่ใช้ได้กับทุกกรณี; คุณอาจต้องทดลองปรับ flag การเตรียมภาพให้เหมาะกับชุดข้อมูลของคุณ + +--- + +## สคริปต์เต็ม – พร้อมคัดลอก & วาง + +ด้านล่างเป็นตัวอย่างที่สมบูรณ์และสามารถรันได้ ซึ่งรวมทุกขั้นตอนที่อธิบายไว้. บันทึกเป็น `improve_ocr_accuracy.py` แล้วรันด้วย `python improve_ocr_accuracy.py` + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +รันแล้วดูผลในคอนโซล, คุณจะเห็นผลของ **extract text from image** ทันที. หากผลลัพธ์ไม่ตรงใจ, ปรับ flag `preprocess_mode` ตามที่อธิบายในตาราง “Pro Tips” + +--- + +## สรุป + +เราได้เดินผ่านสูตรปฏิบัติจริงเพื่อ **improve OCR accuracy** ด้วย Python. ด้วยการสร้าง `OcrEngine`, โหลด PNG, **preprocess image for OCR**, และสุดท้าย **recognize text from PNG**, คุณสามารถ **extract text from image** ได้อย่างเชื่อถือได้แม้แหล่งภาพจะไม่สมบูรณ์ + +ขั้นตอนต่อไป? ลองทำลูปอ่านหลายภาพ, เก็บผลลัพธ์ลง CSV, หรือทดลองโหมดเตรียมภาพเพิ่มเติมเช่นการเพิ่มคอนทราสต์. แนวคิดเดียวกันใช้ได้กับ PDF, ใบเสร็จสแกน, หรือโน้ตมือเขียน — เพียงเปลี่ยนอินพุตและปรับตั้งค่า + +มีคำถามเกี่ยวกับประเภทภาพเฉพาะหรืออยากรู้วิธีผสานเข้ากับเว็บเซอร์วิส? แสดงความคิดเห็น, เราจะสำรวจร่วมกัน. Happy coding, และขอให้ผลลัพธ์ OCR ของคุณใสเหมือนคริสตัล! + +## สิ่งที่คุณควรเรียนต่อไป + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/thai/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..c1f4535f3 --- /dev/null +++ b/ocr/thai/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-31 +description: เรียนรู้วิธีใช้พื้นที่สนใจของ OCR เพื่อโหลดภาพสำหรับ OCR และดึงข้อความจากสี่เหลี่ยม + เหมาะอย่างยิ่งสำหรับการจดจำจำนวนเงินในใบแจ้งหนี้ +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: th +og_description: เชี่ยวชาญการกำหนดพื้นที่สนใจของ OCR เพื่อโหลดภาพสำหรับ OCR ดึงข้อความจากสี่เหลี่ยมและจดจำข้อความจากใบแจ้งหนี้ในบทเรียนเดียว +og_title: OCR พื้นที่สนใจ – คู่มือ Python ทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR พื้นที่สนใจ – ดึงข้อความจากสี่เหลี่ยมใน Python +url: /th/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – ดึงข้อความจากสี่เหลี่ยมใน Python + +เคยสงสัยไหมว่า **ocr region of interest** ส่วนใดส่วนหนึ่งของใบแจ้งหนี้ที่สแกนแล้วโดยไม่ต้องส่งทั้งหน้าเข้าไปในเอนจิน? คุณไม่ได้เป็นคนแรกที่มองใบเสร็จที่เบลอแล้วคิดว่า “จะดึงจำนวนเงินที่อยู่ตรงมุมขวาล่างได้อย่างไร?” ข่าวดีคือคุณสามารถบอกไลบรารี OCR ว่าจะมองที่ไหนได้อย่างชัดเจน ทำให้ความเร็วและความแม่นยำเพิ่มขึ้นอย่างมาก + +ในคู่มือนี้เราจะเดินผ่านตัวอย่างที่ทำงานได้เต็มรูปแบบซึ่งแสดงให้คุณเห็นวิธี **load image for OCR**, กำหนด **region of interest**, แล้ว **extract text from rectangle** เพื่อสุดท้าย **recognize text from invoice** และตอบคำถามคลาสสิก “วิธีดึงจำนวนเงิน” ไม่มีการอ้างอิงแบบคลุมเครือ—มีโค้ดที่เป็นรูปธรรม คำอธิบายที่ชัดเจน และเคล็ดลับระดับมืออาชีพที่คุณอยากรู้ตั้งแต่แรก + +--- + +## สิ่งที่คุณจะสร้าง + +เมื่อจบบทเรียนนี้คุณจะมีสคริปต์ Python เล็ก ๆ ที่ทำสิ่งต่อไปนี้: + +1. โหลดรูปใบแจ้งหนี้จากดิสก์ +2. ทำเครื่องหมายสี่เหลี่ยม ROI ที่จำนวนเงินทั้งหมดอยู่ +3. รัน OCR เฉพาะภายใน ROI นั้น +4. พิมพ์สตริงจำนวนเงินที่ทำความสะอาดแล้ว + +ทั้งหมดนี้ทำงานกับไลบรารี OCR ใด ๆ ที่รองรับ ROI—ในที่นี้เราจะใช้แพ็คเกจ `SimpleOCR` ที่เป็นตัวอย่างจำลองซึ่งทำหน้าที่คล้ายกับ Tesseract หรือ EasyOCR คุณสามารถเปลี่ยนเป็นแพ็คเกจอื่นได้; แนวคิดยังคงเหมือนเดิม + +--- + +## ข้อกำหนดเบื้องต้น + +- Python 3.8+ ติดตั้งแล้ว (`python --version` ควรแสดง ≥3.8) +- แพ็คเกจ OCR ที่ติดตั้งผ่าน pip (เช่น `pip install simpleocr`) +- รูปใบแจ้งหนี้ (PNG หรือ JPEG) อยู่ในโฟลเดอร์ที่คุณอ้างอิงได้ +- ความคุ้นเคยพื้นฐานกับฟังก์ชันและคลาสของ Python (ไม่มีอะไรซับซ้อน) + +ถ้าคุณมีทั้งหมดแล้ว เยี่ยม—มาเริ่มกันเลย หากยังไม่มี ให้ดึงรูปภาพมาไว้ก่อน; ขั้นตอนต่อไปไม่ขึ้นกับเนื้อหาไฟล์จริง + +--- + +## ขั้นตอนที่ 1: Load Image for OCR + +สิ่งแรกที่ทุก workflow ของ OCR ต้องการคือบิตแมพเพื่ออ่าน Here’s how you do it with our `SimpleOCR` engine: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** ใช้เส้นทางแบบ absolute หรือ `os.path.join` เพื่อหลีกเลี่ยงข้อผิดพลาด “file not found” เมื่อรันสคริปต์จากไดเรกทอรีทำงานที่ต่างกัน + +--- + +## ขั้นตอนที่ 2: Define OCR Region of Interest + +แทนที่จะให้เอนจินสแกนทั้งหน้า เราบอกให้มัน *ตรง* ว่าจำนวนเงินอยู่ที่ไหน นี่คือขั้นตอน **ocr region of interest** และเป็นกุญแจสำคัญในการดึงข้อมูลที่เชื่อถือได้ โดยเฉพาะเมื่อเอกสารมีหัวหรือท้ายที่มีเสียงรบกวน + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +ทำไมต้องใช้ตัวเลขเหล่านั้น? `x` และ `y` คือการออฟเซ็ตพิกเซลจากมุมบน‑ซ้าย ส่วน `width` และ `height` บรรยายขนาดของกล่อง หากคุณไม่แน่ใจ ให้เปิดรูปในโปรแกรมแก้ไขใด ๆ เปิด尺尺 (ruler) แล้วบันทึกพิกัด หลาย IDE ยังสามารถแสดงตำแหน่งเคอร์เซอร์ขณะชี้เม้าส์ได้อีกด้วย + +--- + +## ขั้นตอนที่ 3: Extract Text from Rectangle + +เมื่อ ROI ถูกตั้งค่าแล้ว เราขอให้เอนจิน **recognize text from invoice** แต่จำกัดไว้ที่สี่เหลี่ยมที่เรากำหนดไว้ การเรียกนี้จะคืนอ็อบเจ็กต์ผลลัพธ์ที่มักจะมีสตริงดิบ, คะแนนความเชื่อมั่น, และบางครั้งก็มี bounding boxes + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +เบื้องหลัง `recognize()` จะวนลูปแต่ละ ROI, ครอบตัดสไลซ์นั้น, รันโมเดล OCR, แล้วต่อผลลัพธ์เข้าด้วยกัน นี่คือเหตุผลที่การกำหนด **extract text from rectangle** ที่กระชับสามารถลดเวลาในการประมวลผลหลายวินาทีสำหรับงานแบตช์ + +--- + +## ขั้นตอนที่ 4: How to Extract Amount – Clean the Output + +OCR ไม่สมบูรณ์แบบ; คุณมักจะได้ช่องว่าง, line feed, หรืออักขระที่อ่านผิด (เช่น “S” กับ “5”) การใช้ `strip()` ร่วมกับ regex เล็ก ๆ มักจะเพียงพอสำหรับค่าการเงิน + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** หากคุณต้องการส่งจำนวนเงินไปยังฐานข้อมูลหรือเกตเวย์การชำระเงิน คุณต้องการรูปแบบที่คาดเดาได้ การลบ whitespace และกรองอักขระที่ไม่ใช่ตัวเลขจะช่วยป้องกันข้อผิดพลาดในขั้นตอนต่อไป + +--- + +## ขั้นตอนที่ 5: Recognize Text from Invoice – Full Script + +รวมทุกอย่างเข้าด้วยกัน นี่คือสคริปต์เต็มที่พร้อมรัน บันทึกเป็น `extract_amount.py` แล้วเรียก `python extract_amount.py` + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### ผลลัพธ์ที่คาดหวัง + +``` +Amount: 1,245.67 +``` + +หาก ROI ไม่ตรงตำแหน่ง คุณอาจเห็นอย่างเช่น `Amount: 1245.6S`—สังเกตว่า “S” แปลก ๆ ปรับพิกัดสี่เหลี่ยมแล้วรันใหม่จนผลลัพธ์ดูสะอาด + +--- + +## ปัญหาที่พบบ่อย & กรณีขอบ + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|---------| +| **ROI เล็กเกินไป** | ข้อความจำนวนเงินถูกตัดขาด ทำให้การรับรู้ไม่ครบ | ขยาย `width`/`height` ประมาณ 10‑20 % แล้วทดสอบใหม่ | +| **DPI ไม่ถูกต้อง** | การสแกนความละเอียดต่ำ (≤150 dpi) ลดความแม่นยำของ OCR | รีแซมพล์ภาพเป็น 300 dpi ก่อนโหลด หรือขอให้สแกนที่ DPI สูงกว่า | +| **หลายสกุลเงิน** | Regex จับกลุ่มตัวเลขแรกซึ่งอาจเป็นหมายเลขใบแจ้งหนี้ | ปรับ regex ให้มองหาสัญลักษณ์สกุลเงิน (`$`, `€`, `£`) ก่อนตัวเลข | +| **ใบแจ้งหนี้หมุน** | OCR สมมติว่าข้อความอยู่ในแนวตั้ง; หน้าเอียงทำให้การรับรู้ล้มเหลว | ใช้การแก้ไขการหมุน (`ocr_engine.rotate(90)`) ก่อนเพิ่ม ROI | +| **สัญญาณรบกวนในพื้นหลัง** | เงาหรือตราประทับทำให้โมเดลสับสน | ทำการพรี‑โปรเซสด้วย threshold (`cv2.threshold`) หรือใช้ฟิลเตอร์ลดนอยส์ | + +การจัดการกับกรณีขอบเหล่านี้ตั้งแต่เนิ่น ๆ จะช่วยคุณประหยัดเวลาการดีบักหลายชั่วโมงในภายหลัง + +--- + +## เคล็ดลับระดับมืออาชีพสำหรับโปรเจกต์จริง + +- **Batch Processing:** วนลูปโฟลเดอร์ใบแจ้งหนี้ทั้งหมด, คำนวณ ROI แบบไดนามิก (เช่น จากการตรวจจับเทมเพลต) แล้วบันทึกผลลัพธ์เป็น CSV +- **Template Matching:** หากต้องจัดการหลายรูปแบบใบแจ้งหนี้ ให้เก็บแผนที่ JSON ของ `template_id → ROI coordinates` แล้วสลับ ROI ตามคลาสิฟายเออร์เทมเพลตอย่างรวดเร็ว +- **Parallel Execution:** ใช้ `concurrent.futures.ThreadPoolExecutor` เพื่อรันหลายอินสแตนซ์ OCR พร้อมกัน—เหมาะกับไพพ์ไลน์แบค‑ออฟฟิศที่ต้องประมวลผลจำนวนมาก +- **Confidence Filtering:** ผลลัพธ์ OCR ส่วนใหญ่มีคะแนนความเชื่อมั่น กรองผลลัพธ์ที่ต่ำกว่าเกณฑ์ (เช่น 85 %) แล้วทำเครื่องหมายให้ตรวจสอบด้วยมือ + +--- + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, และสุดท้าย **recognize text from invoice** เพื่อให้ตอบคำถามคลาสสิก **how to extract amount** สคริปต์สั้น ๆ นี้ยังยืดหยุ่นพอที่จะปรับให้เข้ากับรูปแบบเอกสาร, ภาษา, และแบ็ค‑เอนด์ OCR ต่าง ๆ + +เมื่อคุณเชี่ยวชาญพื้นฐานแล้ว ลองขยาย workflow: เพิ่มการสแกนบาร์โค้ด, ผสานกับ PDF parser, หรือส่งจำนวนเงินที่ดึงได้ไปยัง API ระบบบัญชี ไม่จำกัดอะไรเลย และด้วย ROI ที่กำหนดอย่างชัดเจน คุณจะได้ผลลัพธ์ที่เร็วและสะอาดยิ่งขึ้นเสมอ + +หากเจออุปสรรคใด ๆ คอมเมนต์ด้านล่างได้เลย—ขอให้ OCR สนุก! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ocr region of interest example") + + +## คุณควรเรียนรู้อะไรต่อไป? + +- [วิธีดึงข้อความจากรูปภาพโดยการเตรียมสี่เหลี่ยมใน OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [ดึงข้อความจากรูปภาพด้วย Java และ Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [ดึงข้อความจากรูปภาพ – การปรับแต่ง 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/turkish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/turkish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..520c3dfb0 --- /dev/null +++ b/ocr/turkish/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-05-31 +description: Asenkron OCR öğreticisi, hızlı görüntü metni çıkarımı için Python'da + asyncio ile Aspose OCR kullanımını gösterir. Adım adım asenkron OCR uygulamasını + öğrenin. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: tr +og_description: Async OCR öğreticisi, Python'da asyncio ile Aspose OCR kullanarak + verimli görüntü metni çıkarımı yapmanızı adım adım gösterir. +og_title: Asenkron OCR Öğreticisi – Aspose OCR ile Python asyncio +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Asenkron OCR Öğreticisi – Aspose OCR ile Python asyncio +url: /tr/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Async OCR Eğitimi – Python asyncio ile Aspose OCR + +Uygulamanızı engellemeden optik karakter tanıma (OCR) nasıl çalıştırılır merak ettiniz mi? Bir **async OCR tutorial**'da tam olarak bunu göreceksiniz—Python'un `asyncio` ve Aspose OCR kütüphanesini kullanarak bloklamayan metin çıkarma. + +Ağır bir görüntünün işlenmesini beklemek zorunda kaldıysanız, bu kılavuz size olay döngünüzün sorunsuz çalışmasını sağlayan temiz, eşzamanlı bir çözüm sunar. + +İlerleyen bölümlerde ihtiyacınız olan her şeyi ele alacağız: kütüphanenin kurulumu, eşzamanlı bir yardımcı fonksiyonun hazırlanması, sonucun işlenmesi ve hatta birden fazla görüntüye ölçeklendirme için hızlı bir ipucu. Sonunda **async OCR tutorial**'ı `asyncio` kullanan herhangi bir Python projesine ekleyebileceksiniz. + +## Gerekenler + +* Python 3.9+ (`asyncio` API'miz 3.7 ve üzeri sürümlerde kararlıdır) +* Aktif bir Aspose OCR lisansı ya da ücretsiz deneme (kütüphane saf Python'dır, yerel ikili dosyalar içermez) +* Okumak istediğiniz küçük bir görüntü dosyası (`.jpg`, `.png`, vb.) – bilinen bir klasörde tutun + +Başka bir dış araç gerekmez; her şey saf Python'da çalışır. + +## Adım 1: Aspose OCR Paketi Kurulumu + +İlk olarak, Aspose OCR paketini PyPI'dan alın. Bir terminal açın ve şu komutu çalıştırın: + +```bash +pip install aspose-ocr +``` + +> **Pro ipucu:** Sanal bir ortam içinde çalışıyorsanız (şiddetle tavsiye edilir), önce onu etkinleştirin. Bu, bağımlılıkları izole eder ve sürüm çakışmalarını önler. + +## Adım 2: OCR Motorunu Asenkron Olarak Başlatma + +Bizim **async OCR tutorial**'ımızın kalbi, asenkron bir yardımcı fonksiyondur. Bu fonksiyon bir `OcrEngine` örneği oluşturur, bir görüntüyü yükler ve ardından `recognize_async()` metodunu çağırır. Motor kendisi senkron olsa da, sarmalayıcı metod bir awaitable döndürür, böylece olay döngüsü yanıt vermeye devam eder. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Neden bu şekilde yapıyoruz:** +*Yardımcı içinde motoru oluşturmak, daha sonra birçok OCR işini paralel çalıştırırsanız iş parçacığı güvenliğini sağlar. `await` anahtar kelimesi, ağır işlemler kütüphanenin dahili iş parçacığı havuzunda gerçekleşirken kontrolü olay döngüsüne geri verir.* + +## Adım 3: Yardımcı Fonksiyonu Asenkron Bir Ana Foniyondan Çalıştırma + +Şimdi `async_ocr()`'ı çağıran ve sonucu yazdıran küçük bir `main()` coroutine'ine ihtiyacımız var. Bu, bir `asyncio` betiğinin tipik giriş noktasını yansıtır. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Arka planda ne oluyor?** +`asyncio.run()` yeni bir olay döngüsü oluşturur, `main()`'ı zamanlar ve `main()` tamamlandığında döngüyü temiz bir şekilde kapatır. Bu desen, Python 3.7+ içinde asenkron programları başlatmanın önerilen yoludur. + +## Adım 4: Tam Betiği Test Etme + +Yukarıdaki iki kod bloğunu tek bir dosyada, örneğin `async_ocr_demo.py` olarak kaydedin. Komut satırından çalıştırın: + +```bash +python async_ocr_demo.py +``` + +Her şey doğru şekilde ayarlandıysa aşağıdakine benzer bir çıktı görmelisiniz: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Tam çıktı, `photo.jpg` dosyasının içeriğine bağlı olacaktır. Önemli nokta, görüntü büyük olsa bile betiğin hızlı bir şekilde bitmesidir; çünkü OCR işlemi arka planda gerçekleşir. + +## Adım 5: Ölçeklendirme – Birden Fazla Görüntüyü Aynı Anda İşleme + +Sık sorulan bir soru, *“Her dosya için yeni bir süreç başlatmadan bir dosya topluluğunu OCR yapabilir miyim?”* sorusudur. Kesinlikle. Yardımcı fonksiyonumuz tamamen asenkron olduğu için, `asyncio.gather()` ile birçok coroutine toplayabiliriz: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Neden bu çalışıyor:** `asyncio.gather()` tüm OCR görevlerini bir kerede zamanlar. Altındaki Aspose OCR kütüphanesi hâlâ kendi iş parçacığı havuzunu kullanır, ancak Python bakış açısından her şey bloklamaz kalır, böylece tek bir senkron çağrının alacağı sürede onlarca görüntüyü işleyebilirsiniz. + +## Adım 6: Hataları Zarifçe Ele Alma + +Harici dosyalarla çalışırken kaçınılmaz olarak eksik dosyalar, bozuk görüntüler veya lisans sorunlarıyla karşılaşırsınız. OCR çağrısını bir `try/except` bloğuna sararak olay döngüsünün çalışmasını sürdürün: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Artık `batch_ocr()` yerine `safe_async_ocr`'ı çağırabilir, tek bir hatalı dosyanın bütün topluluğu iptal etmesini önleyebilirsiniz. + +## Görsel Genel Bakış + +![Async OCR tutorial diagram](async-ocr-diagram.png){alt="Async OCR tutorial akış diyagramı, async_ocr yardımcı, olay döngüsü ve Aspose OCR motorunu gösteriyor"} + +Yukarıdaki diyagram akışı görselleştirir: olay döngüsü → `async_ocr` → `OcrEngine` → arka plan iş parçacığı → sonuç döngüye geri döner. + +## Yaygın Tuzaklar ve Nasıl Kaçınılır + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Yardımcı içinde Bloklayıcı I/O** | `await` olmadan `open()` kullanılması döngüyü bloklayabilir. | `aiofiles` ile dosya okuma yapın, ya da `engine.load_image`'in halletmesine izin verin (zaten bloklamaz). | +| **Coroutine'lar arasında tek bir `OcrEngine` yeniden kullanımı** | Motor iş parçacığı güvenli değildir; eşzamanlı çağrılar durumu bozabilir. | Her `async_ocr` çağrısında yeni bir motor örneği oluşturun (gösterildiği gibi). | +| **Lisans eksikliği** | Aspose OCR çalışma zamanında lisansla ilgili bir istisna fırlatır. | Lisansınızı erken kaydedin (`OcrEngine.set_license("license.json")`). | +| **Büyük görüntüler bellek dalgalanmalarına neden olur** | Kütüphane tüm görüntüyü RAM'e yükler. | Bellek bir sorun ise OCR'dan önce görüntüleri küçültün. | + +## Özet: Neler Başardık + +Bu **async OCR tutorial**'da şunları yaptık: + +1. Aspose OCR kütüphanesini kurduk. +2. `async_ocr` yardımcı fonksiyonunu, tanıma işlemini bloklamadan çalışacak şekilde oluşturduk. +3. Yardımcı fonksiyonu temiz bir `asyncio` giriş noktasından çalıştırdık. +4. `asyncio.gather` ile toplu işleme gösterdik. +5. Hata yönetimi ve en iyi uygulama ipuçlarını ekledik. + +Bunların hepsi saf Python'dur, böylece mevcut async kodu yeniden yazmadan bir web sunucusuna, bir CLI aracına veya bir veri hattına ekleyebilirsiniz. + +## Sonraki Adımlar ve İlgili Konular + +* **Asenkron görüntü ön işleme** – OCR'dan önce görüntüleri eşzamanlı olarak indirmek için `aiohttp` kullanın. +* **OCR sonuçlarını depolama** – bu öğreticiyi PostgreSQL için `asyncpg` gibi bir async veritabanı sürücüsüyle birleştirin. +* **Performans ayarı** – kütüphane böyle bir seçenek sunuyorsa `engine.recognize_async(max_threads=4)` ile deney yapın. +* **Alternatif OCR motorları** – maliyet‑yarar analizi için Aspose OCR'ı Tesseract'ın async sarmalayıcılarıyla karşılaştırın. + +Denemekten çekinmeyin: PDF'leri deneyin, dil ayarlarını değiştirin veya sonuçları bir sohbet botuna bağlayın. Sağlam bir **async OCR tutorial** temeli olduğunda sınır yoktur. + +Kodlamaktan keyif alın, ve metin çıkarımınız her daim hızlı olsun! + +## Sonra Ne Öğrenmelisiniz? + +- [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/) +- [Aspose OCR Eğitimi – Optik Karakter Tanıma](/ocr/english/) +- [Aspose.OCR Kullanarak Dil ile Görüntü Metni OCR Nasıl Yapılır](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/turkish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..d16b8cab7 --- /dev/null +++ b/ocr/turkish/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2026-05-31 +description: OCR'da otomatik dil algılaması artık çok kolay. Görüntü OCR'sini nasıl + yükleyeceğinizi, otomatik dil algılamasını nasıl etkinleştireceğinizi ve metin görüntüsünü + sadece birkaç adımda nasıl tanıyacağınızı öğrenin. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: tr +og_description: OCR'da otomatik dil algılaması artık çok kolay. Otomatik dil algılamasını + etkinleştirmek, görüntü OCR'sini yüklemek ve metin görüntüsünü tanımak için bu adım + adım öğreticiyi izleyin. +og_title: OCR ile Otomatik Dil Tespiti – Tam Python Rehberi +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: OCR ile Otomatik Dil Tespiti – Tam Python Rehberi +url: /tr/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Otomatik Dil Algılama ile OCR – Tam Python Rehberi + +Hiç bir OCR motorunun taranmış bir belgenin dilini size ne aradığını söylemeden *tahmin* etmesini düşündünüz mü? İşte **otomatik dil algılama** tam da bunu yapar ve çok dilli PDF'lerle, sokak işareti fotoğraflarıyla veya farklı yazı sistemlerini karıştıran herhangi bir görüntüyle çalışırken tamamen oyunu değiştirir. + +Bu öğreticide, **otomatik dil algılamayı etkinleştirme**, **görüntü OCR yükleme** ve **görüntüden metin tanıma** işlemlerini Python‑stilinde bir API kullanarak nasıl yapacağınızı adım adım göstereceğiz. Sonunda, algılanan dil kodunu ve çıkarılan metni ekrana yazdıran, manuel dil ayarı gerektirmeyen bağımsız bir betiğiniz olacak. + +## Öğrenecekleriniz + +- Bir OCR motoru örneği oluşturmayı ve **otomatik dil algılamayı** etkinleştirmeyi. +- Diskten **görüntü OCR** yüklemek için tam adımları. +- Motorun `recognize()` metodunu nasıl çağıracağınızı ve dil kodunu içeren bir sonuç alacağınızı. +- Düşük çözünürlüklü görüntüler veya desteklenmeyen yazı sistemleri gibi kenar durumlarını ele almak için ipuçları. + +Çok dilli OCR konusunda önceden bir deneyime sahip olmanıza gerek yok; sadece temel bir Python kurulumu ve bir görüntü dosyası yeterli. + +--- + +## Ön Koşullar + +1. Python 3.8+ yüklü (herhangi bir güncel sürüm çalışır). +2. `OcrEngine`, `LanguageAutoDetectMode` vb. sağlayan OCR kütüphanesi – bu rehberde hayali bir paket olan `myocr` varsayacağız. Şu komutla kurun: + + ```bash + pip install myocr + ``` + +3. En az iki farklı dilde metin içeren bir görüntü dosyası (`multilingual_sample.png`). +4. Biraz merak—eğer OCR ile hiç çalışmadıysanız endişelenmeyin; kod kasıtlı olarak basittir. + +--- + +## Adım 1: Otomatik Dil Algılamayı Etkinleştirme + +Motorun kendi kendine dili *bulması* gerektiğini ona söylemeniz gerekir. İşte **otomatik dil algılama** bayrağının devreye girdiği yer. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Why this matters:** +> When `AUTO_DETECT` is set, the engine runs a lightweight language classifier on the image before the heavy‑weight character recognition kicks in. That means you don’t have to guess whether the text is English, Russian, French, or any combination thereof. The engine will automatically pick the best language model for each region of the image. + +> **Neden Önemli:** +> `AUTO_DETECT` ayarlandığında, motor ağır karakter tanıma işlemine geçmeden önce görüntü üzerinde hafif bir dil sınıflandırıcısı çalıştırır. Bu sayede metnin İngilizce, Rusça, Fransızca veya bunların bir kombinasyonu olup olmadığını tahmin etmeniz gerekmez. Motor, görüntünün her bölgesi için en uygun dil modelini otomatik olarak seçecektir. + +--- + +## Adım 2: Görüntü OCR Yükleme + +Motor artık dilleri otomatik olarak algılaması gerektiğini bildiğine göre, ona çalışacak bir şey vermemiz gerekiyor. **Görüntü OCR yükleme** adımı bitmap'i okur ve iç tamponları hazırlar. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Pro tip:** +> If your image is larger than 300 dpi, consider downscaling it to around 150‑200 dpi. Too much detail can actually *slow* down the language detection stage without improving accuracy. + +> **Pro ipucu:** +> Görüntünüz 300 dpi'den büyükse, yaklaşık 150‑200 dpi'ye küçültmeyi düşünün. Çok fazla detay, doğruluğu artırmadan dil algılama aşamasını *yavaşlatabilir*. + +--- + +## Adım 3: Görüntüden Metin Tanıma + +Görüntü bellekte ve dil algılama etkinleştirildiğinde, son adım motoru **görüntüden metin tanıma** yapmaya istemektir. Bu tek çağrı tüm ağır işi yapar. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +| Özellik | Açıklama | +|-----------|-------------| +| `language` | Algılanan dilin ISO‑639‑1 kodu (ör. İngilizce için `"en"`). | +| `text` | Görüntünün düz metin transkripsiyonu. | + +--- + +## Adım 4: Algılanan Dili ve Çıkarılan Metni Almak + +Şimdi motorun keşfettiğini basitçe ekrana yazdırıyoruz. Bu, **detect language OCR** yeteneğinin pratikte nasıl çalıştığını gösterir. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Örnek çıktı** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **What if the engine returns `None`?** +> That usually means the image is too blurry or the text is too small (< 8 pt). Try increasing contrast or using a higher‑resolution source. + +> **Motor `None` döndürürse ne olur?** +> Bu genellikle görüntünün çok bulanık olduğu veya metnin çok küçük (< 8 pt) olduğu anlamına gelir. Kontrastı artırmayı veya daha yüksek çözünürlüklü bir kaynak kullanmayı deneyin. + +--- + +## Tam Çalışan Örnek (Otomatik Dil Algılamayı Uçtan Uca Etkinleştirme) + +Her şeyi bir araya getirerek, **otomatik dil algılamayı etkinleştirme**, **görüntü OCR yükleme**, **görüntüden metin tanıma** ve **dil algılama OCR** işlemlerini tek seferde yapan hazır bir betik sunuyoruz. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Bu betiği `automatic_language_detection_ocr.py` olarak kaydedin, `YOUR_DIRECTORY` kısmını PNG dosyanızın bulunduğu klasörle değiştirin ve çalıştırın: + +```bash +python automatic_language_detection_ocr.py +``` + +Çıktıda, örnek çıktıda gösterildiği gibi, önce dil kodu ardından çıkarılan metni görmelisiniz. + +--- + +## Yaygın Kenar Durumlarını Ele Alma + +| Durum | Önerilen Çözüm | +|-----------|----------------| +| **Çok düşük çözünürlüklü görüntü** (100 dpi altında) | Yüklemeden önce bikübik filtre ile ölçeklendirin veya daha yüksek çözünürlüklü bir kaynak isteyin. | +| **Tek bir görüntüde karışık yazı sistemleri** (ör. İngilizce + Kiril) | Motor genellikle sayfayı bölgelere ayırır; hatalı algılamalar fark ederseniz `engine.enable_region_split = True` ayarlayın. | +| **Desteklenmeyen dil** | OCR kütüphanesinin ihtiyacınız olan yazı sistemi için bir dil paketi içerdiğini doğrulayın; ek modeller indirmeniz gerekebilir. | +| **Büyük toplu işleme** | Motoru bir kez başlatın, ardından birden fazla `load_image` / `recognize` döngüsü boyunca yeniden kullanın, böylece modelin tekrar tekrar yüklenmesinin önüne geçilir. | + +--- + +## Görsel Genel Bakış + +![otomatik dil algılama örnek çıktısı](https://example.com/auto-lang-detect.png "otomatik dil algılama") + +*Alt text:* otomatik dil algılama örnek çıktısı, algılanan dil kodunu ve çıkarılan çok dilli metni gösterir. + +--- + +## Sonuç + +**Otomatik dil algılama** sürecini baştan sona ele aldık—motoru oluşturma, otomatik dil algılamayı etkinleştirme, bir görüntüyü OCR için yükleme, metni tanıma ve sonunda algılanan dili elde etme. Bu uçtan uca akış, her seferinde dil modellerini manuel olarak yapılandırmadan çok dilli belgeleri işleyebilmenizi sağlar. + +Daha ileri gitmek isterseniz şunları düşünebilirsiniz: + +- **Toplu işleme** yüzlerce görüntüyü aynı `OcrEngine` örneğini yeniden kullanan bir döngü ile işlemek. +- **Son‑işleme** çıkarılan metni bir imla denetleyicisi veya dile özgü bir ayrıştırıcı ile işlemek. +- **Entegrasyon** scripti, kullanıcı yüklemelerini kabul eden ve `language` ve `text` alanlarıyla JSON döndüren bir web servisine. + +Farklı görüntü formatları (`.jpg`, `.tif`) ile deney yapın ve algılama doğruluğunun nasıl değiştiğini görün. Sorularınız veya okunması zor bir görüntünüz varsa aşağıya yorum bırakın—mutlu kodlamalar! + +## Sonra Ne Öğrenmelisiniz? + +- [Aspose.OCR Kullanarak Dil ile Görüntü Metni OCR Nasıl Yapılır](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Aspose.OCR Kullanarak Dil Seçimiyle C# Görüntü Metni Çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR ile Çoklu Diller İçin Görüntü Metni Tanıma](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8fccf5f16 --- /dev/null +++ b/ocr/turkish/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Python ile toplu resim‑metin dönüştürme betiği sayesinde görüntüleri + metne nasıl dönüştüreceğinizi öğrenin. Aspose.OCR kullanarak taranmış görüntülerden + dakikalar içinde metin tanıyın. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: tr +og_description: Görüntüleri anında Python ile metne dönüştürün. Bu rehber, toplu görüntüden + metne dönüşümünü ve Aspose.OCR ile taranmış görüntülerden metin tanıma yöntemlerini + gösterir. +og_title: Görüntüleri Metne Dönüştürme Python – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Resimleri Metne Dönüştürme Python – Tam Adım Adım Rehber +url: /tr/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntüleri Metne Dönüştürme Python – Tam Adım‑Adım Kılavuz + +Kütüphaneler arasında saatler harcamadan **convert images to text python** nasıl yapılır diye hiç merak ettiniz mi? Tek başınıza değilsiniz. İster eski makbuzları dijitalleştiriyor, taranmış faturalardan veri çekiyor, ister PDF'lerin aranabilir bir arşivini oluşturuyor olun, resimleri düz metin dosyalarına dönüştürmek birçok geliştirici için günlük bir iş. + +Bu öğreticide, taranmış görüntülerden metni tanıyan, her sonucu ayrı bir `.txt` dosyası olarak kaydeden ve tümünü sadece birkaç Python satırıyla yapan bir **bulk image to text conversion** işlem hattını adım adım göstereceğiz. Gizemli API'ler aramak yok—Aspose.OCR işi üstlenir ve size tam olarak nasıl bağlayacağınızı göstereceğiz. + +## Öğrenecekleriniz + +- Aspose.OCR for Python paketini nasıl kurup yapılandıracağınızı. +- `BatchOcrEngine` kullanarak **convert images to text python** için gereken tam kod. +- Desteklenmeyen formatlar veya bozuk dosyalar gibi yaygın tuzakları ele almanın ipuçları. +- **recognize text from scanned images** adımının gerçekten başarılı olduğunu doğrulamanın yolları. + +Bu kılavuzun sonunda, binlerce görüntüyü tek seferde işleyebilen, çalıştırmaya hazır bir betiğiniz olacak—herhangi bir toplu‑işleme senaryosu için mükemmel. + +## Önkoşullar + +- Makinenizde yüklü Python 3.8+. +- Metne dönüştürmek istediğiniz görüntü dosyaları (PNG, JPEG, TIFF, vb.) içeren bir klasör. +- Aktif bir Aspose Cloud hesabı veya ücretsiz deneme lisansı (ücretsiz seviye test için yeterlidir). + +Eğer bunlara sahipseniz, başlayalım. + +--- + +## Adım 1 – Python Ortamınızı Kurun + +Herhangi bir OCR kodu yazmaya başlamadan önce, temiz bir sanal ortam içinde çalıştığınızdan emin olun. Bu, bağımlılıkları izole eder ve sürüm çakışmalarını önler. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Proje dizininizi düzenli tutun—`ocr_project` adlı bir alt klasör oluşturup betiği oraya yerleştirin. Bu, yol yönetimini sonradan çok kolaylaştırır. + +## Adım 2 – Aspose.OCR for Python'ı Kurun + +Aspose.OCR ticari bir kütüphane, ancak PyPI'dan çekebileceğiniz ücretsiz bir NuGet‑stili tekerlek (wheel) ile birlikte gelir. Etkinleştirilmiş sanal ortam içinde aşağıdaki komutu çalıştırın: + +```bash +pip install aspose-ocr +``` + +Eğer izin hatası alırsanız, `--user` bayrağını ekleyin veya komutu `sudo` ile çalıştırın (sadece Linux/macOS). Kurulumdan sonra aşağıdakine benzer bir şey görmelisiniz: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Neden Aspose?** Birçok açık kaynaklı OCR aracının aksine, Aspose.OCR kutudan çıkar çıkmaz **bulk image to text conversion**'ı destekler ve ekstra yapılandırma olmadan çok çeşitli görüntü formatlarını işler. Ayrıca “convert images to text python” görevini tek satırda yapmanızı sağlayan bir `BatchOcrEngine` sınıfı sunar. + +## Adım 3 – Batch OCR ile Görüntüleri Metne Dönüştürme Python + +Şimdi öğreticinin kalbine geliyoruz. Aşağıda tamamen çalıştırılabilir bir betik var ve şu adımları yapar: + +1. OCR motor sınıflarını içe aktarır. +2. Bir `BatchOcrEngine` örneği oluşturur. +3. Motoru bir görüntü giriş klasörüne yönlendirir. +4. Motoru, çıkarılan her metin dosyasını bir çıktı klasörüne yazmaya ayarlar. +5. `recognize()` metodunu çalıştırır; bu metod **recognize text from scanned images** işlemini tek tek gerçekleştirir. + +Aşağıdakini proje klasörünüz içinde `batch_ocr.py` olarak kaydedin: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Nasıl Çalışır + +- **`BatchOcrEngine`** normal `OcrEngine`'i sarar ancak klasör‑seviyesinde bir orkestrasyon ekler; bu, toplu olarak **convert images to text python** yapmak istediğinizde tam ihtiyacınız olan şeydir. +- `input_folder` özelliği, motorun kaynak görüntülere nereden bakacağını söyler. Dizini otomatik olarak tarar ve desteklenen her dosya tipini kuyruğa ekler. +- `output_folder` özelliği, her `.txt` dosyasının nereye yerleştirileceğini belirler. Motor, orijinal dosya adını yansıtır, böylece `receipt1.png` `receipt1.txt` olur. +- `recognize()` çağrısı, her görüntüyü yükleyen, OCR çalıştıran ve sonucu yazan dahili döngüyü tetikler. Metot, tüm dosyalar işlenene kadar bloklanır, bu da sonraki işlemleri zincirlemenizi (ör. çıktı klasörünü ziplemek) kolaylaştırır. + +#### Beklenen Çıktı + +Betik çalıştırıldığında: + +```bash +python batch_ocr.py +``` + +Şu çıktıyı görmelisiniz: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +`output_texts` klasörünün içinde her görüntü için bir düz metin dosyası bulacaksınız. Herhangi birini bir metin düzenleyiciyle açtığınızda ham OCR sonucunu göreceksiniz—genellikle orijinal basılı metne yakın bir tahmin. + +## Adım 4 – Sonuçları Doğrulama ve Hataları Ele Alma + +En iyi OCR motorları bile düşük çözünürlüklü taramalarda veya çok eğik sayfalarda sorun yaşayabilir. İşte çıktıyı hızlıca kontrol etmenin ve hataları kaydetmenin bir yolu. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Bunu neden ekleyelim?** +- Motorun sessizce boş bir dize üretmesi durumlarını yakalar (okunamayan görüntülerde yaygındır). +- Sorunlu dosyaların bir listesini verir, böylece manuel olarak inceleyebilir veya farklı ayarlarla yeniden çalıştırabilirsiniz (ör. `OcrEngine.preprocess` seçeneklerini artırmak). + +### Kenar Durumları ve Ayarlamalar + +| Durum | Önerilen Çözüm | +|-----------|----------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Adım 5 – Tüm İş Akışını Otomatikleştirme (Opsiyonel) + +Bu dönüşümü her gece çalıştırmanız gerekiyorsa, betiği basit bir shell veya Windows batch dosyasına sarın ve `cron` (Linux/macOS) ya da Task Scheduler (Windows) ile zamanlayın. İşte Unix‑benzeri sistemler için minimal bir `run_ocr.sh`: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Çalıştırılabilir yapın (`chmod +x run_ocr.sh`) ve bir cron girdisi ekleyin: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Bu, dönüşümü her gün saat 02:00'de çalıştırır ve çıktıyı daha sonra incelemek üzere kaydeder. + +--- + +## Sonuç + +Artık Aspose.OCR’un `BatchOcrEngine`’i kullanarak **convert images to text python** yapmak için kanıtlanmış, üretim‑hazır bir yönteme sahipsiniz. Betik **bulk image to text conversion**'ı yönetir, her sonucu özenle ayrı bir dosyaya yazar ve **recognize text from scanned images** işlemini doğru şekilde yaptığınızdan emin olmak için doğrulama adımları içerir. + +Buradan şunları yapabilirsiniz: + +- Farklı OCR ayarları (dil paketleri, eğikliği düzeltme, gürültü azaltma) ile denemeler yapın. +- Oluşturulan metni Elasticsearch gibi bir arama indeksine yönlendirerek anında tam‑metin arama sağlayın. +- Bu işlem hattını PDF dönüşüm araçlarıyla birleştirerek taranmış PDF'leri tek seferde işleyin. + +Sorularınız mı var, yoksa belirli bir dosya türüyle ilgili bir sorun mu fark ettiniz? Aşağıya yorum bırakın, birlikte sorun giderelim. Mutlu kodlamalar, OCR işlemleriniz hızlı ve hatasız olsun! + +## Sonra Ne Öğrenmelisiniz? + +- [Görüntüden 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/) +- [Aspose.OCR Kullanarak Dil Seçimiyle Görüntü Metni Çıkarma 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/turkish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..35ff84a3a --- /dev/null +++ b/ocr/turkish/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-31 +description: Python'da lisans örneği oluşturun ve lisans yolunu kolayca yapılandırın. + Açık kod örnekleriyle Aspose OCR lisanslamasını nasıl ayarlayacağınızı öğrenin. +draft: false +keywords: +- create license instance +- configure license path +language: tr +og_description: Python'da lisans örneği oluşturun ve lisans yolunu anında yapılandırın. + Aspose OCR'ı güvenle etkinleştirmek için bu öğreticiyi izleyin. +og_title: Python'da Lisans Örneği Oluşturma – Tam Kurulum Kılavuzu +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Python'da lisans örneği oluşturma – Adım adım kılavuz +url: /tr/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python’da Lisans Örneği Oluşturma – Tam Kurulum Kılavuzu + +Python’da Aspose OCR için **create license instance** oluşturmanız mı gerekiyor? Doğru yerdesiniz. Bu öğreticide ayrıca **configure license path** nasıl yapılır, SDK’nın `.lic` dosyanızı nerede bulacağını nasıl ayarlarsınız, onu da göstereceğiz. + +Boş bir betiğe bakıp OCR motorunun lisanssız ürün hakkında şikayet etmesinden bıktıysanız yalnız değilsiniz. Çözüm genellikle sadece birkaç satır koddan ibarettir—tam olarak nereye koymanız gerektiğini bildiğinizde. Bu kılavuzun sonunda, metin, resim ve PDF’leri sorunsuz bir şekilde tanıyabilen tam lisanslı bir Aspose OCR ortamına sahip olacaksınız. + +## Öğrenecekleriniz + +- `asposeocr` paketini kullanarak **create license instance** nasıl yapılır. +- Geliştirme ve üretim ortamları için **configure license path** nasıl ayarlanır. +- Yaygın tuzaklar (dosyanın eksik olması, yanlış izinler) ve bunlardan nasıl kaçınılır. +- Herhangi bir projeye ekleyebileceğiniz tam çalışan bir betik. + +Aspose OCR ile ilgili önceden bir deneyime ihtiyacınız yok, sadece çalışan bir Python 3 kurulumunuz ve geçerli bir lisans dosyanız olması yeterli. + +--- + +## Adım 1: Aspose OCR Python Paketini Yükleyin + +**create license instance** oluşturabilmek için kütüphanenin kendisi sisteminizde olmalı. Bir terminal açın ve şu komutu çalıştırın: + +```bash +pip install aspose-ocr +``` + +> **Pro ipucu:** Sanal ortam (virtual environment) kullanıyorsanız (şiddetle tavsiye edilir) önce onu etkinleştirin. Bu, bağımlılıkların düzenli kalmasını ve sürüm çakışmalarının önlenmesini sağlar. + +## Adım 2: License Sınıfını İçe Aktarın + +SDK artık kullanılabilir olduğuna göre, betiğinizin ilk satırı `License` sınıfını içe aktarmalı. Bu, **create license instance** oluşturmak için kullanacağımız nesnedir. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Neden hemen içe aktaralım? Çünkü `License` nesnesi **any OCR call** öncesinde **instantiate** edilmelidir; aksi takdirde bir görüntü işlemeye çalıştığınız anda SDK lisans hatası verir. + +## Adım 3: Lisans Örneği Oluşturun + +Beklediğiniz an geldi — gerçekten **create license instance**. Tek bir satırdır, ancak bağlamı önemlidir. + +```python +# Step 3: Create a License instance +license = License() +``` + +`license` değişkeni artık mevcut Python süreci için tüm lisans davranışını kontrol eden bir nesne tutar. Bunu, Aspose OCR’a “Haklarım var, çalıştırabilirim” diyen bir kapı bekçisi gibi düşünün. + +## Adım 4: Lisans Yolunu Yapılandırın + +Nesne hazır olduğuna göre, `.lic` dosyamıza işaret etmemiz gerekiyor. İşte **configure license path** burada devreye girer. Yer tutucuyu lisans dosyanızın mutlak yolu ile değiştirin. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Dikkat etmeniz gereken birkaç nokta: + +1. **Raw string (`r"…"`)** Windows’ta ters bölücülerin kaçış karakteri olarak yorumlanmasını önler. +2. **Mutlak yol** kullanmak, betik farklı bir çalışma dizininden başlatılsa bile karışıklığı önler. +3. Eğer lisansı proje içinde bir klasöre koymayı tercih ediyorsanız (göreceli yol), temel yolun betiğin konumu olması gerektiğini unutmayın, geçerli kabuk dizini değil. + +### Eksik Dosyalarla Baş Etme + +Yol hatalıysa ya da dosya okunamıyorsa, `set_license` bir istisna fırlatır. Kullanıcı dostu bir mesaj vermek için çağrıyı `try/except` bloğuna alın: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Bu snippet **configures license path** güvenli bir şekilde yapar ve neyin yanlış gittiğini tam olarak bildirir — gizemli yığın izleri yerine. + +## Adım 5: Lisansın Aktif Olduğunu Doğrulayın + +Kısa bir bütünlük kontrolü, ileride saatler süren hata ayıklamayı önler. `set_license` çağrısını yaptıktan sonra basit bir OCR işlemi deneyin. Lisans geçerliyse SDK görüntüyü lisans hatası vermeden işler. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Tanımlanan metin ekrana basıldıysa, tebrikler — **create license instance** ve **configure license path** işlemlerini başarıyla tamamladınız. Lisans istisnası alıyorsanız, yolu ve dosya izinlerini tekrar kontrol edin. + +## Kenar Durumları ve En İyi Uygulamalar + +| Durum | Ne Yapmalı | +|-----------|------------| +| **Lisans dosyası bir ağ paylaşımında** | Paylaşımı bir sürücü harfiyle eşleyin veya UNC yolu (`\\server\share\license.lic`) kullanın. Python sürecinin okuma izni olduğundan emin olun. | +| **Docker konteyneri içinde çalıştırma** | `.lic` dosyasını imaj içine kopyalayın ve `/app/license/Aspose.OCR.Java.lic` gibi mutlak bir yol ile referans verin. | +| **Birden fazla Python yorumlayıcısı** (ör. conda ortamları) | Lisans dosyasını her ortam için bir kez kurun ya da merkezi bir konumda tutup her yorumlayıcıyı ona yönlendirin. | +| **Çalışma zamanında lisans dosyası eksik** | (Destekleniyorsa) deneme moduna geçiş yapın ya da net bir log mesajı ile abort edin. | + +### Yaygın Tuzaklar + +- **Windows’ta ileri eğik çizgi (`/`) kullanmak** – Python kabul eder, ancak SDK’nın eski sürümleri bunu yanlış yorumlayabilir. Raw string ya da çift ters bölücü kullanın. +- **`License` sınıfını içe aktarmayı unutmak** – Betik `NameError` ile çökerek durur. Örneği oluşturmadan önce daima içe aktarın. +- **OCR metodlarından sonra `set_license` çağırmak** – SDK lisansı ilk kullanımda kontrol eder, bu yüzden yolu **ilk** olarak ayarlayın. + +## Tam Çalışan Örnek + +Aşağıda her şeyi bir araya getiren tam bir betik bulunuyor. `ocr_setup.py` adıyla kaydedin ve komut satırından çalıştırın. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Beklenen çıktı** (geçerli bir görüntü varsayarsak): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Lisans dosyası bulunamazsa, gizemli “License not found” istisnası yerine net bir hata mesajı alırsınız. + +--- + +## Sonuç + +Python’da **create license instance** ve Aspose OCR SDK için **configure license path** nasıl yapılacağını tam olarak öğrendiniz. Adımlar basit: paketi kurun, `License` sınıfını içe aktarın, örneği oluşturun, `.lic` dosyanıza işaret edin ve küçük bir OCR testiyle doğrulayın. + +Bu bilgiyle OCR yeteneklerini web servislerine, masaüstü uygulamalarına ya da otomatik iş akışlarına lisans hatalarıyla takılmadan entegre edebilirsiniz. Sonraki adım olarak gelişmiş OCR ayarlarını keşfetmeyi düşünün — dil paketleri, görüntü ön işleme ya da toplu işleme — hepsi şu anda kurduğunuz sağlam temelin üzerine inşa edilecek. + +Dağıtım, Docker ya da birden fazla lisans yönetimi hakkında sorularınız mı var? Yorum bırakın, iyi kodlamalar! + + +## Sonraki Öğrenmeniz Gerekenler + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..0f5f7b283 --- /dev/null +++ b/ocr/turkish/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Python OCR kullanarak taranmış görüntülerden aranabilir PDF oluşturun. + Taranmış görüntü PDF'sini nasıl dönüştüreceğinizi, TIFF'i PDF'ye nasıl dönüştüreceğinizi + ve dakikalar içinde OCR metin katmanı eklemeyi öğrenin. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: tr +og_description: Aranabilir PDF'yi anında oluşturun. Bu kılavuz, OCR çalıştırmayı, + taranmış görüntü PDF'sini dönüştürmeyi ve tek bir Python betiği kullanarak OCR metin + katmanı eklemeyi gösterir. +og_title: Python ile Aranabilir PDF Oluşturma – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Python ile Aranabilir PDF Oluşturma – Adım Adım Kılavuz +url: /tr/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python ile Aranabilir PDF Oluşturma – Adım Adım Kılavuz + +Hiç bir taranmış sayfadan **aranabilir PDF** oluşturmanın, onlarca aracı bir arada kullanmadan nasıl yapılacağını merak ettiniz mi? Tek başınıza değilsiniz. Birçok ofis iş akışında taranmış bir TIFF veya JPEG ortak bir sürücüye düşer ve bir sonraki kişi metni elle kopyala‑yapıştırmak zorunda kalır—acı verici, hataya açık ve zaman kaybettirici. + +Bu öğreticide, **taranmış görüntü PDF'yi dönüştürmenizi**, **TIFF'i PDF'ye çevirmenizi** ve **OCR metin katmanı eklemenizi** tek bir adımda sağlayan temiz, programatik bir çözümü adım adım inceleyeceğiz. Sonunda OCR çalıştıran, gizli metni gömen ve indeksleyebileceğiniz, arayabileceğiniz veya güvenle paylaşabileceğiniz bir aranabilir PDF üreten, kullanıma hazır bir betiğe sahip olacaksınız. + +## Gereksinimler + +- Python 3.9+ (herhangi bir yeni sürüm çalışır) +- `aspose-ocr` ve `aspose-pdf` paketleri (`pip install aspose-ocr aspose-pdf` ile kurulur) +- Taranmış bir görüntü dosyası (`.tif`, `.png`, `.jpg`, hatta sadece bir görüntü içeren bir PDF sayfası) +- Orta seviyede bir RAM miktarı (OCR motoru hafiftir; bir dizüstü bilgisayar bile bunu kaldırır) + +> **Pro ipucu:** Windows kullanıyorsanız, paketleri edinmenin en kolay yolu komutu yükseltilmiş bir PowerShell penceresinde çalıştırmaktır. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Gereksinimler halledildiğine göre, koda dalalım. + +## Adım 1: OCR Motoru Örneği Oluşturma – *create searchable pdf* + +İlk yaptığımız şey OCR motorunu başlatmaktır. Bunu, her pikseli okuyup karakterlere dönüştürecek bir beyin olarak düşünün. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Neden önemli:** Motoru yalnızca bir kez başlatmak bellek kullanımını düşük tutar. Her sayfa için bir döngü içinde `OcrEngine()` çağırırsanız, kaynaklarınız çabucak tükenir. + +## Adım 2: Taranmış Görüntüyü Yükleme – *convert tiff to pdf* & *convert scanned image pdf* + +Sonra, motoru işlemek istediğiniz dosyaya yönlendirin. API herhangi bir raster görüntüyü kabul eder, bu yüzden bir TIFF JPEG kadar iyi çalışır. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Eğer sadece taranmış bir görüntü içeren bir PDF'niz varsa, `load_image`'i yine de kullanabilirsiniz çünkü Aspose ilk sayfayı otomatik olarak çıkarır. + +## Adım 3: PDF Kaydetme Seçeneklerini Hazırlama – *add OCR text layer* + +Burada son PDF'nin nasıl görünmesi gerektiğini yapılandırıyoruz. Kritik bayrak `create_searchable_pdf`; bunu `True` olarak ayarlamak, kütüphaneye görsel içeriği yansıtan görünmez bir metin katmanı eklemesini söyler. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Metin katmanının yaptığı şey:** Oluşturulan dosyayı Adobe Reader'da açıp metni seçmeye çalıştığınızda gizli karakterleri göreceksiniz. Arama motorları da bunları indeksleyebilir—uyumluluk veya arşivleme için mükemmel. + +## Adım 4: OCR'ı Çalıştır ve Kaydet – *how to run OCR* tek bir çağrıda + +Şimdi sihir gerçekleşiyor. Tek bir metod çağrısı tanıma motorunu çalıştırır ve aranabilir PDF'yi diske yazar. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +`recognize` metodu, hataları inceleyebileceğiniz bir durum nesnesi döndürür, ancak çoğu basit senaryo için yukarıdaki basit çağrı yeterlidir. + +### Beklenen Çıktı + +Betik çalıştırıldığında şu çıktı verir: + +``` +PDF saved as searchable PDF. +``` + +`scanned_page_searchable.pdf` dosyasını açarsanız, metni seçebildiğinizi, kopyala‑yapıştırabildiğinizi ve hatta `Ctrl+F` araması yapabildiğinizi fark edeceksiniz. Bu, **create searchable pdf** iş akışının temel özelliğidir. + +## Tam Çalışan Betik + +Aşağıda eksiksiz, çalıştırmaya hazır betik yer alıyor. Yer tutucu yolları gerçek dosya konumlarınızla değiştirmeniz yeterli. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Bunu `create_searchable_pdf.py` olarak kaydedin ve çalıştırın: + +```bash +python create_searchable_pdf.py +``` + +## Yaygın Sorular & Kenar Durumları + +### 1️⃣ Çok sayfalı PDF'leri işleyebilir miyim? + +Evet. `ocr_engine.load_image("file.pdf")` kullanın ve ardından her sayfa için `ocr_engine.recognize(pdf_save_options, page_number)` ile döngü oluşturun. Kütüphane otomatik olarak çok sayfalı bir aranabilir PDF oluşturur. + +### 2️⃣ Kaynak dosyam yüksek çözünürlüklü bir TIFF (300 dpi+) ise ne olur? + +Daha yüksek DPI, daha iyi OCR doğruluğu sağlar ancak aynı zamanda daha fazla bellek kullanır. `MemoryError` alırsanız, önce görüntüyü küçültün: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ OCR dilini nasıl değiştiririm? + +Görüntüyü yüklemeden önce motorun `language` özelliğini ayarlayın: + +```python +ocr_engine.language = "fra" # French +``` + +Desteklenen dil kodlarının tam listesi Aspose belgelerinde bulunur. + +### 4️⃣ Orijinal görüntü kalitesini korumam gerekirse? + +`PdfSaveOptions` sınıfının bir `compression` özelliği vardır. Raster veriyi tam olarak olduğu gibi korumak için `PdfCompression.None` olarak ayarlayın. + +```python +pdf_save_options.compression = "None" +``` + +## Üretim‑Hazır Dağıtımlar İçin İpuçları + +- **Toplu işleme:** Temel mantığı, dosya yolu listesi kabul eden bir fonksiyon içinde paketleyin. Her başarı/başarısızlığı denetim izleri için bir CSV'ye kaydedin. +- **Paralellik:** OCR'ı birden çok çekirdekte çalıştırmak için `concurrent.futures.ThreadPoolExecutor` kullanın. Her thread'in kendi `OcrEngine` örneğine ihtiyacı olduğunu unutmayın. +- **Güvenlik:** Hassas belgelerle çalışıyorsanız, betiği izole bir ortamda çalıştırın ve işleme sonrasında geçici dosyaları hemen silin. + +## Sonuç + +Artık kısa bir Python betiği kullanarak taranmış görüntülerden **aranabilir PDF** dosyaları oluşturmayı biliyorsunuz. Bir OCR motorunu başlatarak, bir TIFF'i (veya herhangi bir raster'ı) yükleyerek, `PdfSaveOptions`'ı **add OCR text layer** olarak yapılandırarak ve sonunda `recognize`'ı çağırarak, tüm **convert scanned image pdf** ve **convert TIFF to PDF** süreci tek bir tekrarlanabilir komut haline geliyor. + +Sonraki adımlar? Bu betiği bir dosya izleyiciyle zincirleyerek, bir klasöre düşen her yeni taramanın otomatik olarak aranabilir olmasını sağlayın. Ya da çok dilli arşivleri desteklemek için farklı OCR dilleriyle deneyler yapın. OCR'ı PDF oluşturmayla birleştirdiğinizde sınır yoktur. + +**how to run OCR** hakkında başka dillerde veya çerçevelerde sorularınız mı var? Aşağıya bir yorum bırakın, iyi kodlamalar! + +![Taranmış görüntü → OCR motoru → aranabilir PDF (create searchable pdf) akışını gösteren diyagram](searchable-pdf-flow.png "Aranabilir pdf akış diyagramı") + + +## Sonraki Öğrenmeniz Gerekenler + +- [Aspose.OCR ile .NET'te PDF'yi OCR'lamak](/ocr/english/net/text-recognition/recognize-pdf/) +- [Görüntüleri PDF'ye Dönüştür C# – Çok Sayfalı OCR Sonucunu Kaydet](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) +- [Aspose.OCR Kullanarak Dil ile Görüntü Metnini OCR'lamak](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/turkish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0eb071e96 --- /dev/null +++ b/ocr/turkish/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: OCR doğruluğunu Python ile artırmak için görüntüleri OCR öncesinde işleyin. + Görüntü dosyalarından metin çıkarmayı, PNG’den metin tanımayı ve sonuçları iyileştirmeyi + öğrenin. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: tr +og_description: Python'da metin için görüntü ön işleme uygulayarak OCR doğruluğunu + artırın. Görüntü dosyalarından metin çıkarmak ve PNG'den metni zahmetsizce tanımak + için bu rehberi izleyin. +og_title: Python'da OCR Doğruluğunu Artırma – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Python'da OCR Doğruluğunu Geliştirin – Tam Adım Adım Rehber +url: /tr/python-java/general/improve-ocr-accuracy-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 OCR Doğruluğunu Artırma – Tam Adım‑Adım Kılavuz + +OCR doğruluğunu **artırmaya** çalıştığınızda çıktının karışık geldiğini hiç gördünüz mü? Tek başınıza değilsiniz. Çoğu geliştirici, ham görüntü gürültülü, eğik ya da düşük kontrast olduğunda takılı kalıyor. İyi haber? Birkaç ön‑işleme tekniği, bulanık bir ekran görüntüsünü temiz, makine‑okunur bir metne dönüştürebilir. + +Bu öğreticide, **görüntüyü OCR için ön‑işleyen**, tanıma motorunu çalıştıran ve sonunda **görüntüden metin çıkaran** gerçek bir örnek üzerinden ilerleyeceğiz – özellikle bir PNG dosyası için. Sonuna kadar **PNG'den metin tanıma** işlemini daha yüksek bir başarı oranıyla nasıl yapacağınızı öğrenecek ve herhangi bir projeye ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına sahip olacaksınız. + +## Neler Öğreneceksiniz + +- OCR motorları için görüntü ön‑işlemenin neden önemli olduğu +- En büyük performans artışını sağlayan ön‑işleme modları (gürültü giderme, eğik düzeltme) +- Python’da bir `OcrEngine` örneğinin nasıl yapılandırılacağı +- **Görüntüden metin çıkaran** tam, çalıştırılabilir betik +- Döndürülmüş taramalar ya da düşük çözünürlüklü fotoğraflar gibi uç durumların nasıl ele alınacağı + +OCR SDK dışındaki ek kütüphanelere gerek yok, ancak Python 3.8+ ve okumak istediğiniz bir PNG görüntüsü gerekir. + +--- + +![Diagram showing steps to improve OCR accuracy in Python](image.png "Improve OCR accuracy workflow") + +*Alt metin: OCR doğruluğunu artırma iş akışını gösteren, ön‑işleme ve tanıma adımlarını açıklayan diyagram.* + +## Önkoşullar + +- Python 3.8 veya daha yeni bir sürümünün yüklü olması +- `OcrEngine`, `OcrEngineSettings` ve `ImagePreprocessMode` sağlayan OCR SDK'sına erişim (aşağıdaki kod genel bir API kullanıyor; gerekirse satıcı sınıflarınızla değiştirin) +- Bir PNG görüntüsü (`input.png`) erişebileceğiniz bir klasörde bulunmalı + +Sanal ortam kullanıyorsanız, şimdi etkinleştirin—fantezi bir şey yok, sadece `python -m venv venv && source venv/bin/activate`. + +--- + +## Adım 1: OCR Motoru Örneğini Oluşturun – OCR Doğruluğunu Artırmaya Başlayın + +İlk olarak bir OCR motor nesnesine ihtiyacınız var. Bunu, pikselleri okuyup karakterleri üretecek beyin olarak düşünün. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Neden önemli: bir motor olmadan hiçbir ön‑işleme uygulayamazsınız ve ham görüntü doğrudan tanıyıcıya verilir—genellikle doğruluk açısından en kötü senaryo. + +--- + +## Adım 2: Hedef PNG'yi Yükleyin – PNG'den Metin Tanıma İçin Sahneyi Hazırlayın + +Şimdi motorun üzerinde çalışacağı dosyayı belirtiyoruz. PNG kayıpsızdır, bu da JPEG'e göre bize küçük bir avantaj sağlar. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Görüntü başka bir yerde ise yolu sadece ayarlayın. Motor, desteklenen herhangi bir formatı kabul eder, ancak PNG genellikle keskin karakter kenarları için gereken ince detayları korur. + +--- + +## Adım 3: Ön‑İşlemeyi Yapılandırın – OCR İçin Görüntüyü Ön‑İşleyin + +İşte sihrin gerçekleştiği yer. Bir ayar nesnesi oluşturuyor, lekeleri silmek için gürültü giderme etkinleştiriyor ve eğik metni otomatik olarak düzeltmek için eğik düzeltmeyi açıyoruz. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Neden Gürültü Giderme + Eğik Düzeltme? + +- **Gürültü Giderme**: Rastgele piksel gürültüsü, desen‑eşleştirme algoritmalarını şaşırtır. Onu kaldırmak harfleri keskinleştirir. +- **Eğik Düzeltme**: 2 derecelik bir eğim bile güven skorlarını büyük ölçüde düşürebilir. Eğik düzeltme, temel çizgiyi hizalayarak tanıyıcının fontları daha güvenilir eşleştirmesini sağlar. + +Görüntüleriniz özellikle karanlıksa ek bayraklarla (ör. `ImagePreprocessMode.CONTRAST_ENHANCE`) deney yapabilirsiniz. SDK dokümantasyonu genellikle tüm kullanılabilir modları listeler. + +--- + +## Adım 4: Ayarları Motora Uygulayın – Ön‑İşlemeyi OCR'a Bağlayın + +Ayar nesnesini motora atayın, böylece bir sonraki tanıma çalışması tanımladığımız dönüşümleri kullanır. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Bu adımı atlayarsanız, motor varsayılanına (çoğu zaman “ön‑işleme yok”) geri döner ve **daha düşük OCR doğruluğu** görürsünüz. + +--- + +## Adım 5: Tanıma Sürecini Çalıştırın – Görüntüden Metin Çıkarın + +Her şey bağlandıktan sonra, motoru işini yapması için son olarak çağırıyoruz. Çağrı senkroniktir ve tanınan dizeyi içeren bir sonuç nesnesi döner. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Arka planda motor şimdi: + +1. PNG'yi belleğe yükler +2. Ayarlarımıza göre gürültü giderme ve eğik düzeltme uygular +3. Sinir ağı ya da klasik desen eşleştiriciyi çalıştırır +4. Çıktıyı `recognition_result` içine paketler + +--- + +## Adım 6: Tanınan Metni Çıktılayın – İyileşmeyi Doğrulayın + +Çıkarılan dizeyi ekrana yazdıralım. Gerçek bir uygulamada bunu bir dosyaya, veritabanına ya da başka bir servise gönderebilirsiniz. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Beklenen Çıktı + +Görüntü “Hello, OCR World!” cümlesini içeriyorsa şu satırı görmelisiniz: + +``` +Hello, OCR World! +``` + +Metnin temiz olduğunu fark edin—gereksiz semboller ya da kırık karakterler yok. Bu, **metin için görüntü ön‑işlemenin** doğru uygulanmasının sonucudur. + +--- + +## Pro İpuçları & Uç Durumlar + +| Durum | Ne Ayarlanmalı | Neden | +|-----------|----------------|-----| +| Çok düşük çözünürlüklü PNG (≤ 72 dpi) | `ImagePreprocessMode.SUPER_RESOLUTION` mevcutsa ekleyin | Upsampling, tanıyıcıya daha fazla piksel sağlayarak doğruluğu artırabilir | +| Metin 5° den fazla döndürülmüş | Eğik düzeltme toleransını artırın veya motoru beslemeden önce `Pillow` ile manuel döndürün | Aşırı açıların otomatik eğik düzeltmeyi atlaması olasıdır | +| Yoğun arka plan desenleri | `ImagePreprocessMode.BACKGROUND_REMOVAL` etkinleştirin | Metin dışı gürültüyü kaldırarak yanlış okuma riskini azaltır | +| Çok dilli belge | `ocr_engine.language = "eng+spa"` (veya benzeri) ayarlayın | Motor doğru karakter setini seçer, genel doğruluğu artırır | + +Unutmayın, **OCR doğruluğunu artırma** tek bir çözüm değildir; veri setinize göre ön‑işleme bayraklarını yinelemeniz gerekebilir. + +--- + +## Tam Betik – Kopyala & Yapıştır İçin Hazır + +Aşağıda, tartıştığımız tüm adımları içeren, çalıştırılabilir tam örnek bulunuyor. `improve_ocr_accuracy.py` olarak kaydedin ve `python improve_ocr_accuracy.py` komutuyla çalıştırın. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Çalıştırın, konsolu izleyin ve **görüntüden metin çıkarma** sonucunu anında göreceksiniz. Çıktı beklentilerinizi karşılamazsa, “Pro İpuçları” tablosunda anlatıldığı gibi `preprocess_mode` bayraklarını ayarlayın. + +--- + +## Sonuç + +Python kullanarak **OCR doğruluğunu artırma** için pratik bir tarif üzerinden geçtik. Bir `OcrEngine` oluşturup bir PNG yükleyerek, **OCR için görüntüyü ön‑işleyip**, ardından **PNG'den metin tanıma** yaparak, kaynak mükemmel olmasa bile **görüntüden metin çıkarma** işlemini güvenilir bir şekilde gerçekleştirebilirsiniz. + +Sonraki adımlar? Bir döngüyle birden fazla görüntüyü işleyin, her sonucu bir CSV'ye kaydedin ya da kontrast artırma gibi ek ön‑işleme modlarıyla deney yapın. Aynı desen PDF'ler, taranmış makbuzlar ya da el yazısı notlar için de çalışır—sadece girdi dosyasını değiştirin ve ayarları uyarlayın. + +Belirli bir görüntü türü hakkında sorularınız mı var ya da bunu bir web servisine nasıl entegre edeceğinizi merak ediyor musunuz? Yorum bırakın, birlikte bu senaryoları keşfedelim. Mutlu kodlamalar, OCR sonuçlarınız her daim kristal‑gibi berrak olsun! + +## Sonraki Öğrenmeniz Gerekenler + +- [Extract Text from Image with Aspose OCR – Step‑by‑Step Guide](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/turkish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..1423efe41 --- /dev/null +++ b/ocr/turkish/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: OCR ilgi bölgesini kullanarak OCR için görüntü yüklemeyi ve dikdörtgenden + metin çıkarmayı öğrenin; faturadaki tutarı tanımak için mükemmeldir. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: tr +og_description: Tek bir öğreticide OCR için görüntü yükleme, dikdörtgenden metin çıkarma + ve faturadan metin tanıma konularında bölge ilgi alanını (ROI) ustalaşın. +og_title: OCR İlgi Alanı – Adım Adım Python Rehberi +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR İlgi Bölgesi – Python'da Dikdörtgenden Metin Çıkarma +url: /tr/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR İlgi Bölgesi – Python’da Dikdörtgenden Metin Çıkarma + +Hiç **ocr region of interest** bir taranmış faturanın belirli bir kısmını tüm sayfayı motorun içine vermeden çıkarmayı düşündünüz mü? İlk defa bulanık bir makbuzu elinize alıp “Sağ alt köşede bir yerde bulunan tutarı nasıl çıkarırım?” diye düşünüyorsanız yalnız değilsiniz. İyi haber, OCR kütüphanesine tam olarak nerede bakması gerektiğini söyleyebilir, böylece hız ve doğruluğu büyük ölçüde artırabilirsiniz. + +Bu rehberde, **load image for OCR**, bir **region of interest** tanımlama ve ardından **extract text from rectangle** işlemini gösteren tam, çalıştırılabilir bir örnek üzerinden ilerleyeceğiz; sonunda **recognize text from invoice** yaparak klasik “tutarı nasıl çıkarırım” sorusuna yanıt bulacaksınız. Belirsiz referanslar yok—sadece somut kod, net açıklamalar ve daha önce bilmek isteyeceğiniz birkaç profesyonel ipucu. + +--- + +## Ne Oluşturacaksınız + +Bu öğreticinin sonunda, aşağıdaki işlevi gören küçük bir Python betiğiniz olacak: + +1. Diskten bir fatura görüntüsü yükler. +2. Toplam tutarın bulunduğu dikdörtgen bir ROI işaretler. +3. OCR’u yalnızca bu ROI içinde çalıştırır. +4. Temizlenmiş tutar dizesini ekrana yazdırır. + +Tüm bunlar ROI destekleyen herhangi bir OCR kütüphanesiyle çalışır—burada popüler araçlar olan Tesseract veya EasyOCR’a benzer bir hayali `SimpleOCR` paketini kullanacağız. İsterseniz değiştirebilirsiniz; kavramlar aynı kalır. + +--- + +## Önkoşullar + +- Python 3.8+ yüklü (`python --version` komutu ≥3.8 göstermeli). +- Pip ile kurulabilir bir OCR paketi (ör. `pip install simpleocr`). +- Bir fatura görüntüsü (PNG veya JPEG) erişebileceğiniz bir klasörde. +- Python fonksiyonları ve sınıfları hakkında temel bilgi (karmaşık bir şey değil). + +Bu koşullara sahipseniz harika—derhal başlayalım. Değilseniz önce görüntüyü temin edin; geri kalan adımlar dosyanın içeriğinden bağımsızdır. + +--- + +## Adım 1: Load Image for OCR + +Her OCR iş akışının ilk ihtiyacı, okunacak bir bitmap’dir. Çoğu kütüphane, dosya yolunu kabul eden basit bir `load_image` metodu sunar. İşte `SimpleOCR` motorumuzla bunu nasıl yapacağınız: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Betiği farklı bir çalışma dizininden çalıştırdığınızda “dosya bulunamadı” hatalarını önlemek için mutlak yollar ya da `os.path.join` kullanın. + +--- + +## Adım 2: Define OCR Region of Interest + +Motorun tüm sayfayı taramasına izin vermek yerine, tutarın tam olarak nerede olduğunu *tam olarak* söylüyoruz. Bu, **ocr region of interest** adımıdır ve özellikle belge gürültülü başlıklar veya altbilgiler içerdiğinde güvenilir çıkarımın anahtarıdır. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Bu sayılar neden? `x` ve `y`, sol‑üst köşeden piksel offset’leridir; `width` ve `height` ise kutunun boyutlarını tanımlar. Emin değilseniz, görüntüyü herhangi bir editörde açın, cetveli etkinleştirin ve koordinatları not alın. Birçok IDE, imleç konumunu üzerine gelince gösterir. + +--- + +## Adım 3: Extract Text from Rectangle + +ROI ayarlandığına göre, motoru **recognize text from invoice** yapmaya ama sadece az önce eklediğimiz dikdörtgenle sınırlı kalmaya çağırıyoruz. Çağrı, genellikle ham dize, güven skorları ve bazen sınırlayıcı kutuları içeren bir sonuç nesnesi döndürür. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Arka planda, `recognize()` her ROI üzerinden döner, o dilimi kırpar, OCR modelini çalıştırır ve sonuçları birleştirir. Bu yüzden sıkı bir **extract text from rectangle** bölgesi tanımlamak, toplu işler için işlem süresini saniyelerce kısaltabilir. + +--- + +## Adım 4: How to Extract Amount – Clean the Output + +OCR mükemmel değildir; genellikle gereksiz boşluklar, satır sonları ya da yanlış okunmuş karakterler (ör. “S” yerine “5”) elde edersiniz. Basit bir `strip()` ve küçük bir regex çoğu para değeri için işinizi görür. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Neden önemli:** Tutarı bir veritabanına ya da ödeme geçidine göndermeyi planlıyorsanız, öngörülebilir bir formata ihtiyacınız var. Boşlukları temizlemek ve sayısal olmayan karakterleri filtrelemek, sonraki hataları önler. + +--- + +## Adım 5: Recognize Text from Invoice – Full Script + +Hepsini bir araya getirdiğimizde, tam ve çalıştırılabilir betik aşağıdadır. `extract_amount.py` olarak kaydedin ve `python extract_amount.py` komutuyla çalıştırın. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Beklenen Çıktı + +``` +Amount: 1,245.67 +``` + +ROI yanlış hizalanmışsa, `Amount: 1245.6S` gibi bir şey görebilirsiniz—gereksiz “S”ye dikkat edin. Dikdörtgen koordinatlarını ayarlayın ve çıktı temiz olana kadar tekrar çalıştırın. + +--- + +## Yaygın Tuzaklar & Kenar Durumları + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI too small** | Tutar metni kesilir, kısmi tanıma olur. | `width`/`height` değerlerini %10‑20 artırın ve yeniden test edin. | +| **Incorrect DPI** | Düşük çözünürlüklü taramalar (≤150 dpi) OCR doğruluğunu düşürür. | Görüntüyü 300 dpi’ye yeniden örnekleyin ya da tarayıcıdan daha yüksek DPI isteyin. | +| **Multiple currencies** | Regex ilk sayısal grubu alır, bu bir fatura numarası olabilir. | Regex’i para birimi simgeleri (`$`, `€`, `£`) öncesinde arayacak şekilde iyileştirin. | +| **Rotated invoices** | OCR motorları dik metin varsayar; döndürülmüş sayfalar tanıma hatası verir. | ROI eklemeden önce bir döndürme düzeltmesi (`ocr_engine.rotate(90)`) uygulayın. | +| **Noise in background** | Gölge ya da damga modeli karıştırır. | Basit bir eşikleme (`cv2.threshold`) ya da gürültü azaltma filtresi kullanın. | + +Bu kenar durumlarını erken ele almak, ileride saatlerce hata ayıklamaktan sizi kurtarır. + +--- + +## Gerçek Dünya Projeleri İçin Pro İpuçları + +- **Batch Processing:** Bir klasördeki faturalar üzerinde döngü kurun, ROI’yi dinamik olarak (ör. şablon algılamaya dayalı) hesaplayın ve sonuçları CSV’ye kaydedin. +- **Template Matching:** Birden fazla fatura düzeniyle çalışıyorsanız, `template_id → ROI coordinates` haritasını JSON’da tutun. Hızlı bir düzen sınıflandırıcısıyla ROI’yi değiştirin. +- **Parallel Execution:** `concurrent.futures.ThreadPoolExecutor` kullanarak birden çok OCR örneğini aynı anda çalıştırın—yüksek hacimli back‑office hatları için mükemmel. +- **Confidence Filtering:** Çoğu OCR sonucu bir güven skoru içerir. Belirli bir eşik (ör. %85) altındaki sonuçları atın ve manuel inceleme için işaretleyin. + +--- + +## Sonuç + +**ocr region of interest**, **load image for OCR**, **extract text from rectangle** ve sonunda **recognize text from invoice** adımlarını kapsayan her şeyi ele aldık; klasik **how to extract amount** sorusuna yanıt bulduk. Betik kompakt, ancak farklı belge formatları, diller ve OCR arka uçlarıyla uyum sağlayacak kadar esnek. + +Temelleri kavradığınıza göre, iş akışını genişletmeyi düşünün: barkod tarama ekleyin, bir PDF ayrıştırıcıyla bütünleştirin ya da çıkarılan tutarı bir muhasebe API’sine gönderin. ROI iyi tanımlandığı sürece her zaman daha hızlı ve temiz sonuçlar elde edeceksiniz. + +Bir sorunla karşılaşırsanız, aşağıya yorum bırakın—iyi OCR’lamalar! + +![ocr bölgesi örneği](https://example.com/ocr_roi_example.png "ocr bölgesi örneği") + + +## Sonraki Öğrenmeniz Gerekenler + +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image Java with Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [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/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md b/ocr/vietnamese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md new file mode 100644 index 000000000..3e2e8c20b --- /dev/null +++ b/ocr/vietnamese/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Hướng dẫn OCR bất đồng bộ, trình bày cách sử dụng Aspose OCR trong Python + với asyncio để trích xuất văn bản từ hình ảnh nhanh chóng. Học cách triển khai OCR + bất đồng bộ từng bước. +draft: false +keywords: +- async ocr tutorial +- asynchronous OCR with Python +- Aspose OCR library +- Python asyncio OCR +- image text extraction +language: vi +og_description: Bài hướng dẫn OCR bất đồng bộ hướng dẫn bạn cách sử dụng Aspose OCR + trong Python với asyncio để trích xuất văn bản từ hình ảnh một cách hiệu quả. +og_title: Hướng dẫn OCR bất đồng bộ – Python asyncio với Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + headline: Async OCR Tutorial – Python asyncio with Aspose OCR + type: TechArticle +- description: Async OCR tutorial showing how to use Aspose OCR in Python with asyncio + for fast image text extraction. Learn step‑by‑step async OCR implementation. + name: Async OCR Tutorial – Python asyncio with Aspose OCR + steps: + - name: Installed the Aspose OCR library. + text: Installed the Aspose OCR library. + - name: Built an `async_ocr` helper that runs recognition without blocking. + text: Built an `async_ocr` helper that runs recognition without blocking. + - name: Ran the helper from a clean `asyncio` entry point. + text: Ran the helper from a clean `asyncio` entry point. + - name: Demonstrated batch processing with `asyncio.gather`. + text: Demonstrated batch processing with `asyncio.gather`. + - name: Added error handling and best‑practice tips. + text: Added error handling and best‑practice tips. + type: HowTo +tags: +- OCR +- Python +- asyncio +title: Hướng dẫn OCR bất đồng bộ – Python asyncio với Aspose OCR +url: /vi/python-java/general/async-ocr-tutorial-python-asyncio-with-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hướng Dẫn OCR Bất Đồng Bộ – Python asyncio với Aspose OCR + +Bạn đã bao giờ tự hỏi làm sao chạy nhận dạng ký tự quang học (OCR) mà không làm chậm ứng dụng? Trong **hướng dẫn OCR bất đồng bộ** này, bạn sẽ thấy chính xác điều đó — trích xuất văn bản không chặn bằng cách sử dụng `asyncio` của Python và thư viện Aspose OCR. + +Nếu bạn đã chờ đợi một hình ảnh nặng được xử lý, hướng dẫn này cung cấp giải pháp bất đồng bộ sạch sẽ, giữ cho vòng lặp sự kiện của bạn luôn hoạt động. + +Trong các phần tiếp theo, chúng ta sẽ bao quát mọi thứ bạn cần: cài đặt thư viện, tạo helper bất đồng bộ, xử lý kết quả, và thậm chí một mẹo nhanh để mở rộng xử lý nhiều hình ảnh. Khi kết thúc, bạn sẽ có thể chèn **hướng dẫn OCR bất đồng bộ** vào bất kỳ dự án Python nào đã sử dụng `asyncio`. + +## Những Gì Bạn Cần Chuẩn Bị + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +* Python 3.9+ (API `asyncio` chúng ta dùng đã ổn định từ 3.7 trở lên) +* Giấy phép Aspose OCR hợp lệ hoặc bản dùng thử miễn phí (thư viện hoàn toàn bằng Python, không có binary gốc) +* Một tệp hình ảnh nhỏ (`.jpg`, `.png`, …) mà bạn muốn đọc – lưu nó trong một thư mục đã biết + +Không cần công cụ bên ngoài nào khác; mọi thứ chạy trong Python thuần. + +## Bước 1: Cài Đặt Gói Aspose OCR + +Đầu tiên, lấy gói Aspose OCR từ PyPI. Mở terminal và chạy: + +```bash +pip install aspose-ocr +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn đang làm việc trong môi trường ảo (được khuyến nghị mạnh), hãy kích hoạt nó trước. Điều này giữ các phụ thuộc cách ly và tránh xung đột phiên bản. + +## Bước 2: Khởi Tạo Engine OCR Bất Đồng Bộ + +Trái tim của **hướng dẫn OCR bất đồng bộ** là một hàm helper bất đồng bộ. Nó tạo một thể hiện `OcrEngine`, tải hình ảnh, và sau đó gọi `recognize_async()`. Engine bản thân là đồng bộ, nhưng phương thức wrapper trả về một awaitable, cho phép vòng lặp sự kiện vẫn phản hồi. + +```python +import asyncio +from asposeocr import OcrEngine + +async def async_ocr(image_path: str) -> str: + """ + Perform OCR on the given image without blocking the event loop. + + Args: + image_path: Path to the image file you want to process. + + Returns: + Recognized text as a string. + """ + # Initialise the OCR engine – this is cheap, so we do it per call. + engine = OcrEngine() + + # Load the target image into the engine. + engine.load_image(image_path) + + # Start asynchronous recognition and await the result. + result = await engine.recognize_async() + + # Return only the plain text part of the result. + return result.text +``` + +**Lý do chúng ta làm như vậy:** +*Việc tạo engine bên trong helper đảm bảo an toàn luồng nếu bạn sau này chạy nhiều job OCR song song. Từ khóa `await` trả lại quyền kiểm soát cho vòng lặp sự kiện trong khi công việc nặng được thực hiện trong pool thread nội bộ của thư viện.* + +## Bước 3: Gọi Helper Từ Hàm `async` Chính + +Bây giờ chúng ta cần một coroutine `main()` nhỏ gọi `async_ocr()` và in kết quả. Điều này mô phỏng điểm vào tiêu chuẩn cho một script `asyncio`. + +```python +async def main(): + # Replace with the path to your own image. + image_file = "YOUR_DIRECTORY/photo.jpg" + + # Await the OCR result – the call is non‑blocking. + text = await async_ocr(image_file) + + # Show the recognized text. + print("Async OCR result:", text) + +# Run the coroutine using asyncio's high‑level API. +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Điều gì đang diễn ra phía sau?** +`asyncio.run()` tạo một vòng lặp sự kiện mới, lên lịch `main()`, và tắt vòng lặp một cách sạch sẽ khi `main()` hoàn thành. Mẫu này là cách được khuyến nghị để khởi động chương trình bất đồng bộ trong Python 3.7+. + +## Bước 4: Kiểm Tra Toàn Bộ Script + +Lưu hai khối mã trên vào một tệp duy nhất, ví dụ `async_ocr_demo.py`. Chạy nó từ dòng lệnh: + +```bash +python async_ocr_demo.py +``` + +Nếu mọi thứ được thiết lập đúng, bạn sẽ thấy một đầu ra giống như: + +``` +Async OCR result: The quick brown fox jumps over the lazy dog. +``` + +Kết quả chính xác sẽ phụ thuộc vào nội dung của `photo.jpg`. Điểm quan trọng là script kết thúc nhanh chóng, ngay cả khi hình ảnh lớn, vì công việc OCR diễn ra ở nền. + +## Bước 5: Mở Rộng – Xử Lý Nhiều Hình Ảnh Đồng Thời + +Một câu hỏi thường gặp là, *“Tôi có thể OCR một loạt tệp mà không khởi chạy tiến trình mới cho mỗi tệp không?”* Chắc chắn rồi. Vì helper của chúng ta hoàn toàn bất đồng bộ, chúng ta có thể gom nhiều coroutine lại với `asyncio.gather()`: + +```python +async def batch_ocr(image_paths): + # Build a list of coroutine objects. + tasks = [async_ocr(path) for path in image_paths] + + # Run them concurrently and collect results. + return await asyncio.gather(*tasks) + +# Example usage: +if __name__ == "__main__": + files = [ + "imgs/img1.jpg", + "imgs/img2.png", + "imgs/img3.tif", + ] + results = asyncio.run(batch_ocr(files)) + for path, text in zip(files, results): + print(f"{path}: {text[:50]}...") # Show first 50 chars of each result +``` + +**Tại sao cách này hoạt động:** `asyncio.gather()` lên lịch tất cả các task OCR cùng một lúc. Thư viện Aspose OCR vẫn sử dụng pool thread riêng, nhưng từ góc nhìn của Python mọi thứ vẫn không chặn, cho phép bạn xử lý hàng chục hình ảnh trong thời gian một lời gọi đồng bộ sẽ mất. + +## Bước 6: Xử Lý Lỗi Một Cách Nhẹ Nhàng + +Khi làm việc với tệp bên ngoài, bạn sẽ gặp các trường hợp thiếu tệp, hình ảnh hỏng, hoặc vấn đề giấy phép. Bao bọc lời gọi OCR trong khối `try/except` để giữ vòng lặp sự kiện luôn hoạt động: + +```python +async def safe_async_ocr(image_path): + try: + return await async_ocr(image_path) + except Exception as e: + # Log the error and return an empty string or a placeholder. + print(f"Error processing {image_path}: {e}") + return "" +``` + +Bây giờ `batch_ocr()` có thể gọi `safe_async_ocr` thay thế, đảm bảo một tệp lỗi không làm dừng toàn bộ batch. + +## Tổng Quan Hình Ảnh + +![Hướng dẫn OCR bất đồng bộ diagram](async-ocr-diagram.png){alt="Lưu đồ hướng dẫn OCR bất đồng bộ hiển thị helper async_ocr, vòng lặp sự kiện và engine Aspose OCR"} + +Sơ đồ trên minh họa luồng: vòng lặp sự kiện → `async_ocr` → `OcrEngine` → thread nền → kết quả trả lại vòng lặp. + +## Những Sai Lầm Thường Gặp & Cách Tránh + +| Sai lầm | Nguyên nhân | Cách khắc phục | +|---------|-------------|----------------| +| **I/O chặn bên trong helper** | Sử dụng `open()` mà không có `await` có thể chặn vòng lặp. | Dùng `aiofiles` để đọc file, hoặc để `engine.load_image` xử lý (đã không chặn). | +| **Tái sử dụng cùng một `OcrEngine` trong nhiều coroutine** | Engine không an toàn với thread; các lời gọi đồng thời có thể làm hỏng trạng thái. | Tạo một engine mới trong mỗi lời gọi `async_ocr` (như đã minh họa). | +| **Thiếu giấy phép** | Aspose OCR ném ngoại lệ liên quan đến giấy phép khi chạy. | Đăng ký giấy phép sớm (`OcrEngine.set_license("license.json")`). | +| **Hình ảnh lớn gây tăng đột biến bộ nhớ** | Thư viện tải toàn bộ hình ảnh vào RAM. | Thu nhỏ kích thước hình ảnh trước khi OCR nếu lo ngại về bộ nhớ. | + +## Tóm Tắt: Những Gì Chúng Ta Đã Đạt Được + +Trong **hướng dẫn OCR bất đồng bộ** này, chúng ta đã: + +1. Cài đặt thư viện Aspose OCR. +2. Xây dựng helper `async_ocr` chạy nhận dạng mà không chặn. +3. Chạy helper từ điểm vào `asyncio` sạch sẽ. +4. Trình diễn xử lý batch với `asyncio.gather`. +5. Thêm xử lý lỗi và các mẹo thực hành tốt. + +Tất cả đều bằng Python thuần, vì vậy bạn có thể đưa nó vào server web, công cụ CLI, hoặc pipeline dữ liệu mà không cần viết lại code async hiện có. + +## Các Bước Tiếp Theo & Chủ Đề Liên Quan + +* **Tiền xử lý ảnh bất đồng bộ** – dùng `aiohttp` để tải ảnh đồng thời trước khi OCR. +* **Lưu trữ kết quả OCR** – kết hợp hướng dẫn này với driver cơ sở dữ liệu async như `asyncpg` cho PostgreSQL. +* **Tối ưu hiệu năng** – thử `engine.recognize_async(max_threads=4)` nếu thư viện hỗ trợ tùy chọn này. +* **Các engine OCR thay thế** – so sánh Aspose OCR với wrapper async của Tesseract để phân tích chi phí‑lợi ích. + +Hãy tự do thử nghiệm: đưa PDF vào, điều chỉnh cài đặt ngôn ngữ, hoặc kết nối kết quả với chatbot. Khi đã có nền tảng **hướng dẫn OCR bất đồng bộ** vững chắc, khả năng của bạn sẽ không giới hạn. + +Chúc lập trình vui vẻ, và chúc việc trích xuất văn bản của bạn luôn nhanh chóng! + +## Bạn Nên Học Gì Tiếp Theo? + +- [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/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/automatic-language-detection-with-ocr-complete-python-guide/_index.md b/ocr/vietnamese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md new file mode 100644 index 000000000..5ac2d4245 --- /dev/null +++ b/ocr/vietnamese/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-05-31 +description: Phát hiện ngôn ngữ tự động trong OCR trở nên dễ dàng. Tìm hiểu cách tải + OCR hình ảnh, bật phát hiện ngôn ngữ tự động và nhận dạng văn bản trong hình ảnh + chỉ trong vài bước. +draft: false +keywords: +- automatic language detection +- recognize text image +- load image ocr +- enable auto language detection +- detect language ocr +language: vi +og_description: Phát hiện ngôn ngữ tự động trong OCR trở nên dễ dàng. Hãy làm theo + hướng dẫn từng bước này để bật tính năng phát hiện ngôn ngữ tự động, tải OCR hình + ảnh và nhận dạng văn bản trong hình ảnh. +og_title: Phát hiện ngôn ngữ tự động với OCR – Hướng dẫn Python toàn diện +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + headline: Automatic Language Detection with OCR – Complete Python Guide + type: TechArticle +- description: Automatic language detection in OCR made easy. Learn how to load image + OCR, enable auto language detection, and recognize text image in just a few steps. + name: Automatic Language Detection with OCR – Complete Python Guide + steps: + - name: Python 3.8+ installed (any recent version works). + text: Python 3.8+ installed (any recent version works). + - name: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + text: 'The OCR library that provides `OcrEngine`, `LanguageAutoDetectMode`, etc. + – for this guide we’ll assume a hypothetical package called `myocr`. Install + it with:' + - name: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + text: An image file (`multilingual_sample.png`) that contains text in at least + two different languages. + - name: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + text: A little curiosity—if you’ve never touched OCR before, don’t worry; the + code is deliberately straightforward. + type: HowTo +tags: +- OCR +- Python +- Multilingual +- Computer Vision +title: Phát hiện ngôn ngữ tự động với OCR – Hướng dẫn Python toàn diện +url: /vi/python-java/general/automatic-language-detection-with-ocr-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Phát hiện Ngôn ngữ Tự động với OCR – Hướng dẫn Python Toàn diện + +Bạn đã bao giờ tự hỏi làm sao để một engine OCR *đoán* ngôn ngữ của tài liệu đã quét mà không cần bạn chỉ định trước? Đó chính là những gì **phát hiện ngôn ngữ tự động** thực hiện, và nó thực sự là một bước đột phá khi bạn làm việc với các PDF đa ngôn ngữ, ảnh biển hiệu đường phố, hoặc bất kỳ hình ảnh nào kết hợp nhiều chữ viết. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ thực hành cho thấy cách **bật phát hiện ngôn ngữ tự động**, **tải OCR ảnh**, và **nhận dạng văn bản từ ảnh** bằng một API kiểu Python. Khi kết thúc, bạn sẽ có một script độc lập in ra cả mã ngôn ngữ được phát hiện và văn bản đã trích xuất—không cần thiết lập ngôn ngữ thủ công. + +## Những gì bạn sẽ học + +- Cách tạo một instance của OCR engine và bật **phát hiện ngôn ngữ tự động**. +- Các bước chính để **tải OCR ảnh** từ đĩa. +- Cách gọi phương thức `recognize()` của engine và nhận lại kết quả bao gồm mã ngôn ngữ. +- Mẹo xử lý các trường hợp đặc biệt như ảnh độ phân giải thấp hoặc script không được hỗ trợ. + +Bạn không cần kinh nghiệm trước về OCR đa ngôn ngữ; chỉ cần một môi trường Python cơ bản và một file ảnh. + +--- + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn đã có: + +1. Python 3.8+ được cài đặt (bất kỳ phiên bản gần đây nào đều được). +2. Thư viện OCR cung cấp `OcrEngine`, `LanguageAutoDetectMode`, v.v. – trong hướng dẫn này chúng ta sẽ giả định một package tên `myocr`. Cài đặt bằng lệnh: + + ```bash + pip install myocr + ``` + +3. Một file ảnh (`multilingual_sample.png`) chứa văn bản ít nhất hai ngôn ngữ khác nhau. +4. Một chút tò mò—nếu bạn chưa từng chạm tới OCR, đừng lo; code được viết rất đơn giản. + +--- + +## Bước 1: Bật Phát hiện Ngôn ngữ Tự động + +Điều đầu tiên bạn cần làm là thông báo cho engine rằng nó nên *tự mình* xác định ngôn ngữ. Đây là nơi cờ **phát hiện ngôn ngữ tự động** được sử dụng. + +```python +from myocr import OcrEngine, LanguageAutoDetectMode + +# Step 1: Create an OCR engine instance +engine = OcrEngine() + +# Step 2: Enable automatic language detection +engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT +``` + +> **Tại sao điều này quan trọng:** +> Khi `AUTO_DETECT` được bật, engine sẽ chạy một bộ phân loại ngôn ngữ nhẹ trên ảnh trước khi bước nhận dạng ký tự nặng nề bắt đầu. Điều này có nghĩa là bạn không cần phải đoán văn bản là tiếng Anh, Nga, Pháp, hay bất kỳ sự kết hợp nào. Engine sẽ tự động chọn mô hình ngôn ngữ phù hợp nhất cho mỗi vùng của ảnh. + +--- + +## Bước 2: Tải OCR Ảnh + +Bây giờ engine đã biết rằng nó phải tự động phát hiện ngôn ngữ, chúng ta cần cung cấp cho nó một ảnh để làm việc. Bước **tải OCR ảnh** sẽ đọc bitmap và chuẩn bị các buffer nội bộ. + +```python +# Step 3: Load the image containing multilingual text +image_path = "YOUR_DIRECTORY/multilingual_sample.png" +engine.load_image(image_path) +``` + +> **Mẹo chuyên nghiệp:** +> Nếu ảnh của bạn có độ phân giải lớn hơn 300 dpi, hãy cân nhắc giảm kích thước xuống khoảng 150‑200 dpi. Quá nhiều chi tiết có thể *làm chậm* giai đoạn phát hiện ngôn ngữ mà không cải thiện độ chính xác. + +--- + +## Bước 3: Nhận dạng Văn bản từ Ảnh + +Với ảnh đã được nạp vào bộ nhớ và phát hiện ngôn ngữ đã bật, phần cuối cùng là yêu cầu engine **nhận dạng văn bản ảnh**. Lệnh duy nhất này thực hiện toàn bộ công việc nặng. + +```python +# Step 4: Perform OCR recognition +result = engine.recognize() +``` + +`result` là một đối tượng thường chứa ít nhất hai thuộc tính: + +| Thuộc tính | Mô tả | +|-----------|------| +| `language` | Mã ISO‑639‑1 của ngôn ngữ được phát hiện (ví dụ, `"en"` cho tiếng Anh). | +| `text` | Bản sao văn bản thuần từ ảnh. | + +--- + +## Bước 4: Lấy Ngôn ngữ Được Phát hiện và Văn bản Đã Trích xuất + +Bây giờ chúng ta chỉ cần in ra những gì engine đã phát hiện. Điều này minh họa khả năng **detect language OCR** trong thực tế. + +```python +# Step 5: Display the detected language and extracted text +print("Detected language:", result.language) # e.g. "en", "ru", "fr" +print("Text:", result.text) +``` + +**Kết quả mẫu** + +``` +Detected language: fr +Text: Bonjour le monde! This is a multilingual sample. +``` + +> **Nếu engine trả về `None` thì sao?** +> Thông thường điều này có nghĩa ảnh quá mờ hoặc văn bản quá nhỏ (< 8 pt). Hãy thử tăng độ tương phản hoặc dùng nguồn ảnh có độ phân giải cao hơn. + +--- + +## Ví dụ Hoàn chỉnh (Bật Phát hiện Ngôn ngữ Tự động Từ Đầu tới Cuối) + +Kết hợp mọi thứ lại, dưới đây là một script sẵn sàng chạy, bao gồm **bật phát hiện ngôn ngữ tự động**, **tải OCR ảnh**, **nhận dạng văn bản ảnh**, và **detect language OCR** trong một lần thực thi. + +```python +# automatic_language_detection_ocr.py +from myocr import OcrEngine, LanguageAutoDetectMode + +def main(): + # Create engine and turn on auto language detection + engine = OcrEngine() + engine.language_auto_detect_mode = LanguageAutoDetectMode.AUTO_DETECT + + # Load the image (adjust the path to your own file) + image_path = "YOUR_DIRECTORY/multilingual_sample.png" + engine.load_image(image_path) + + # Run OCR + result = engine.recognize() + + # Output results + print("Detected language:", result.language) + print("Text:", result.text) + +if __name__ == "__main__": + main() +``` + +Lưu file này dưới tên `automatic_language_detection_ocr.py`, thay `YOUR_DIRECTORY` bằng thư mục chứa PNG của bạn, và chạy: + +```bash +python automatic_language_detection_ocr.py +``` + +Bạn sẽ thấy mã ngôn ngữ theo sau là văn bản đã trích xuất, giống như kết quả mẫu ở trên. + +--- + +## Xử lý Các Trường hợp Thường gặp + +| Tình huống | Giải pháp đề xuất | +|-----------|-------------------| +| **Ảnh độ phân giải rất thấp** (dưới 100 dpi) | Phóng to bằng bộ lọc bicubic trước khi tải, hoặc yêu cầu nguồn ảnh có độ phân giải cao hơn. | +| **Kết hợp nhiều script trong một ảnh** (ví dụ: tiếng Anh + Cyrillic) | Engine thường sẽ chia trang thành các vùng; nếu bạn thấy lỗi phát hiện, hãy đặt `engine.enable_region_split = True`. | +| **Ngôn ngữ không được hỗ trợ** | Kiểm tra xem thư viện OCR có gói ngôn ngữ cho script bạn cần không; có thể bạn phải tải thêm mô hình. | +| **Xử lý batch lớn** | Khởi tạo engine một lần, sau đó tái sử dụng cho nhiều vòng `load_image` / `recognize` để tránh việc tải mô hình lặp lại. | + +--- + +## Tổng quan Trực quan + +![kết quả ví dụ phát hiện ngôn ngữ tự động](https://example.com/auto-lang-detect.png "phát hiện ngôn ngữ tự động") + +*Alt text:* ví dụ kết quả phát hiện ngôn ngữ tự động hiển thị mã ngôn ngữ và văn bản đa ngôn ngữ đã trích xuất. + +--- + +## Kết luận + +Chúng ta vừa hoàn thành **phát hiện ngôn ngữ tự động** từ đầu đến cuối—tạo engine, bật phát hiện ngôn ngữ tự động, tải ảnh cho OCR, nhận dạng văn bản, và cuối cùng lấy ngôn ngữ đã phát hiện. Quy trình end‑to‑end này cho phép bạn xử lý tài liệu đa ngôn ngữ mà không cần cấu hình mô hình ngôn ngữ thủ công mỗi lần. + +Nếu bạn muốn tiến xa hơn, hãy cân nhắc: + +- **Batching** hàng trăm ảnh bằng một vòng lặp tái sử dụng cùng một instance của `OcrEngine`. +- **Post‑processing** văn bản đã trích xuất bằng bộ kiểm tra chính tả hoặc tokenizer riêng cho từng ngôn ngữ. +- **Tích hợp** script vào một dịch vụ web nhận tải lên từ người dùng và trả về JSON với các trường `language` và `text`. + +Hãy thử nghiệm với các định dạng ảnh khác nhau (`.jpg`, `.tif`) và xem độ chính xác phát hiện thay đổi như thế nào. Có câu hỏi hay ảnh khó đọc? Để lại bình luận bên dưới—chúc bạn lập trình vui! + + +## Bạn Nên Học Gì Tiếp Theo? + +- [Cách OCR Văn bản Ảnh với Ngôn ngữ Sử dụng Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-language-selection/) +- [Trích xuất văn bản ảnh C# với lựa chọn ngôn ngữ bằng Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Nhận dạng văn bản ảnh với Aspose OCR cho nhiều ngôn ngữ](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2a999b4c2 --- /dev/null +++ b/ocr/vietnamese/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-31 +description: Tìm hiểu cách chuyển đổi hình ảnh thành văn bản bằng Python với script + chuyển đổi hàng loạt hình ảnh sang văn bản. Nhận dạng văn bản từ hình ảnh đã quét + bằng Aspose.OCR trong vài phút. +draft: false +keywords: +- convert images to text python +- bulk image to text conversion +- recognize text from scanned images +language: vi +og_description: Chuyển đổi hình ảnh thành văn bản bằng Python ngay lập tức. Hướng + dẫn này cho thấy cách chuyển đổi hàng loạt hình ảnh sang văn bản và cách nhận dạng + văn bản từ hình ảnh đã quét bằng Aspose.OCR. +og_title: Chuyển Đổi Hình Ảnh Sang Văn Bản Python – Hướng Dẫn Đầy Đủ +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + headline: Convert Images to Text Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Learn how to convert images to text python with a bulk image to text + conversion script. Recognize text from scanned images using Aspose.OCR in minutes. + name: Convert Images to Text Python – Complete Step‑by‑Step Guide + steps: + - name: Imports the OCR engine classes. + text: Imports the OCR engine classes. + - name: Instantiates a `BatchOcrEngine`. + text: Instantiates a `BatchOcrEngine`. + - name: Points the engine at an input folder of images. + text: Points the engine at an input folder of images. + - name: Directs the engine to write each extracted text file into an output folder. + text: Directs the engine to write each extracted text file into an output folder. + - name: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + text: Fires the `recognize()` method, which **recognize text from scanned images** + one by one. + type: HowTo +tags: +- OCR +- Python +- Aspose +title: Chuyển Đổi Hình Ảnh Thành Văn Bản Python – Hướng Dẫn Chi Tiết Từng Bước +url: /vi/python-java/general/convert-images-to-text-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển Đổi Hình Ảnh Thành Văn Bản Python – Hướng Dẫn Toàn Diện Từng Bước + +Bạn đã bao giờ tự hỏi làm thế nào để **convert images to text python** mà không phải săn lùng hàng tá thư viện? Bạn không phải là người duy nhất. Dù bạn đang số hoá các biên lai cũ, trích xuất dữ liệu từ hoá đơn đã quét, hay xây dựng một kho lưu trữ PDF có thể tìm kiếm, việc biến ảnh thành các tệp văn bản thuần là công việc hằng ngày của nhiều nhà phát triển. + +Trong tutorial này, chúng ta sẽ đi qua một pipeline **bulk image to text conversion** nhận dạng văn bản từ các ảnh đã quét, lưu mỗi kết quả dưới dạng tệp `.txt` riêng biệt, và thực hiện tất cả chỉ với vài dòng Python. Không cần tìm kiếm các API lạ – Aspose.OCR sẽ làm phần việc nặng, và chúng tôi sẽ chỉ cho bạn cách tích hợp nó. + +## Những Điều Bạn Sẽ Học + +- Cách cài đặt và cấu hình gói Aspose.OCR cho Python. +- Mã chính xác cần thiết để **convert images to text python** bằng `BatchOcrEngine`. +- Mẹo xử lý các vấn đề thường gặp như định dạng không được hỗ trợ hoặc tệp hỏng. +- Cách xác minh rằng bước **recognize text from scanned images** thực sự đã thành công. + +Kết thúc hướng dẫn này, bạn sẽ có một script sẵn sàng chạy, có thể xử lý hàng ngàn hình ảnh trong một lần – hoàn hảo cho bất kỳ kịch bản xử lý hàng loạt nào. + +## Yêu Cầu Trước + +- Python 3.8+ đã được cài đặt trên máy của bạn. +- Một thư mục chứa các tệp ảnh (PNG, JPEG, TIFF, v.v.) mà bạn muốn chuyển thành văn bản. +- Một tài khoản Aspose Cloud đang hoạt động hoặc giấy phép dùng thử miễn phí (gói miễn phí đủ cho việc thử nghiệm). + +Nếu bạn đã có những thứ trên, hãy bắt đầu. + +--- + +## Bước 1 – Thiết Lập Môi Trường Python + +Trước khi viết bất kỳ mã OCR nào, hãy chắc chắn bạn đang làm việc trong một môi trường ảo sạch sẽ. Điều này giúp cô lập các phụ thuộc và tránh xung đột phiên bản. + +```bash +# Create a new virtual environment named venv +python -m venv venv + +# Activate the environment (Windows) +venv\Scripts\activate + +# Activate the environment (macOS / Linux) +source venv/bin/activate +``` + +> **Pro tip:** Giữ thư mục dự án của bạn gọn gàng—tạo một thư mục con có tên `ocr_project` và đặt script vào đó. Điều này sẽ giúp việc xử lý đường dẫn trở nên dễ dàng hơn sau này. + +## Bước 2 – Cài Đặt Aspose.OCR cho Python + +Aspose.OCR là một thư viện thương mại, nhưng nó đi kèm với một wheel kiểu NuGet miễn phí mà bạn có thể tải từ PyPI. Chạy lệnh sau trong môi trường ảo đã kích hoạt: + +```bash +pip install aspose-ocr +``` + +Nếu gặp lỗi quyền, thêm cờ `--user` hoặc chạy lệnh với `sudo` (chỉ dành cho Linux/macOS). Sau khi cài đặt, bạn sẽ thấy một thông báo giống như: + +``` +Successfully installed aspose-ocr-23.9.0 +``` + +> **Why Aspose?** Không giống như nhiều công cụ OCR mã nguồn mở, Aspose.OCR hỗ trợ **bulk image to text conversion** ngay từ đầu và xử lý đa dạng định dạng ảnh mà không cần cấu hình thêm. Nó còn cung cấp lớp `BatchOcrEngine` giúp nhiệm vụ “convert images to text python” trở thành một thao tác một dòng. + +## Bước 3 – Chuyển Đổi Hình Ảnh Thành Văn Bản Python với Batch OCR + +Bây giờ là phần cốt lõi của tutorial. Dưới đây là một script có thể chạy ngay: + +1. Nhập các lớp engine OCR. +2. Tạo một đối tượng `BatchOcrEngine`. +3. Chỉ định thư mục đầu vào chứa các ảnh. +4. Chỉ định thư mục đầu ra để ghi mỗi tệp văn bản đã trích xuất. +5. Gọi phương thức `recognize()`, thực hiện **recognize text from scanned images** từng ảnh một. + +Lưu đoạn mã sau dưới tên `batch_ocr.py` trong thư mục dự án của bạn: + +```python +# batch_ocr.py +# ------------------------------------------------- +# Bulk Image to Text Conversion using Aspose.OCR +# ------------------------------------------------- + +# Step 1: Import the OCR engine classes +from asposeocr import BatchOcrEngine, OcrEngine + +# Step 2: Create a batch OCR engine instance +batch_engine = BatchOcrEngine() + +# Step 3: Set the folder that contains the images to be processed +# Replace 'YOUR_DIRECTORY' with the absolute path to your images folder +batch_engine.input_folder = "YOUR_DIRECTORY/input_images" + +# Step 4: Set the folder where the extracted text files will be saved +# Make sure this folder exists or Aspose will raise an error +batch_engine.output_folder = "YOUR_DIRECTORY/output_texts" + +# Optional: Adjust OCR settings if you need higher accuracy +# For example, enable language detection for multilingual documents +# batch_engine.ocr_engine.language = "eng+spa" # English + Spanish + +# Step 5: Run the batch recognition – each supported image in the input folder is processed +batch_engine.recognize() + +# Step 6: Notify that the batch operation has finished +print("Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts.") +``` + +### Cách Hoạt Động + +- **`BatchOcrEngine`** bao bọc `OcrEngine` thông thường nhưng thêm khả năng điều phối ở mức thư mục, chính xác những gì bạn cần khi muốn **convert images to text python** hàng loạt. +- Thuộc tính `input_folder` cho engine biết nơi tìm các ảnh nguồn. Nó sẽ tự động quét thư mục và đưa vào hàng đợi mọi tệp được hỗ trợ. +- Thuộc tính `output_folder` xác định nơi mỗi tệp `.txt` sẽ được lưu. Engine sẽ giữ nguyên tên tệp gốc, vì vậy `receipt1.png` sẽ trở thành `receipt1.txt`. +- Gọi `recognize()` kích hoạt vòng lặp nội bộ tải mỗi ảnh, chạy OCR và ghi kết quả. Phương thức này sẽ chờ cho tới khi mọi tệp được xử lý, giúp bạn dễ dàng nối tiếp các hành động khác (ví dụ: nén thư mục đầu ra). + +#### Kết Quả Dự Kiến + +Khi bạn chạy script: + +```bash +python batch_ocr.py +``` + +Bạn sẽ thấy: + +``` +Batch processing complete. Text files saved to YOUR_DIRECTORY/output_texts. +``` + +Trong thư mục `output_texts` sẽ có một tệp văn bản thuần cho mỗi ảnh. Mở bất kỳ tệp nào bằng trình soạn thảo văn bản và bạn sẽ thấy kết quả OCR thô — thường là một bản sao gần đúng với văn bản in gốc. + +## Bước 4 – Kiểm Tra Kết Quả và Xử Lý Lỗi + +Ngay cả những engine OCR tốt nhất cũng có thể gặp khó khăn với các bản quét độ phân giải thấp hoặc trang bị lệch nghiêm trọng. Dưới đây là cách nhanh chóng kiểm tra tính hợp lý của đầu ra và ghi lại bất kỳ lỗi nào. + +```python +import os + +def verify_output(output_dir): + txt_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.txt')] + empty_files = [f for f in txt_files if os.path.getsize(os.path.join(output_dir, f)) == 0] + + if empty_files: + print("Warning: The following files are empty – OCR may have failed:") + for f in empty_files: + print(f" • {f}") + else: + print("All text files contain data. OCR succeeded for every image.") + +# Run verification after batch processing +verify_output(batch_engine.output_folder) +``` + +**Tại sao thêm phần này?** +- Nó bắt các trường hợp engine trả về chuỗi rỗng một cách im lặng (thường gặp với ảnh không đọc được). +- Nó cung cấp danh sách các tệp gặp vấn đề để bạn có thể kiểm tra thủ công hoặc chạy lại với cài đặt khác (ví dụ: tăng tùy chọn `OcrEngine.preprocess`). + +### Các Trường Hợp Đặc Biệt & Điều Chỉnh + +| Situation | Suggested Fix | +|-----------|----------------| +| Images are rotated 90° | Set `batch_engine.ocr_engine.rotation_correction = True`. | +| Mixed languages (English + French) | Use `batch_engine.ocr_engine.language = "eng+fra"` before `recognize()`. | +| Huge PDFs converted to images first | Split PDFs into single‑page images, then feed the folder to the batch engine. | +| Memory errors on very large batches | Process smaller sub‑folders sequentially, or increase `batch_engine.max_memory_usage`. | + +## Bước 5 – Tự Động Hóa Toàn Bộ Quy Trình (Tùy Chọn) + +Nếu bạn cần chạy chuyển đổi này hàng đêm, hãy gói script trong một file shell hoặc batch đơn giản, và lên lịch với `cron` (Linux/macOS) hoặc Task Scheduler (Windows). Dưới đây là một `run_ocr.sh` tối thiểu cho hệ thống kiểu Unix: + +```bash +#!/usr/bin/env bash +# run_ocr.sh – Automate bulk image to text conversion + +# Activate virtual environment +source /path/to/venv/bin/activate + +# Execute the OCR script +python /path/to/ocr_project/batch_ocr.py + +# Deactivate after completion +deactivate +``` + +Đánh dấu nó là thực thi được (`chmod +x run_ocr.sh`) và thêm một entry vào cron: + +```cron +0 2 * * * /path/to/run_ocr.sh >> /var/log/ocr_batch.log 2>&1 +``` + +Lệnh này sẽ chạy chuyển đổi mỗi ngày lúc 2 AM và ghi lại bất kỳ đầu ra nào để xem lại sau. + +--- + +## Kết Luận + +Bạn đã có một phương pháp đã được chứng minh, sẵn sàng cho môi trường production để **convert images to text python** bằng `BatchOcrEngine` của Aspose.OCR. Script này xử lý **bulk image to text conversion**, ghi mỗi kết quả vào tệp riêng, và bao gồm các bước xác minh để đảm bảo bạn thực sự **recognize text from scanned images** một cách chính xác. + +Từ đây bạn có thể: + +- Thử nghiệm các cài đặt OCR khác nhau (gói ngôn ngữ, deskew, giảm nhiễu). +- Đưa văn bản đã tạo vào một chỉ mục tìm kiếm như Elasticsearch để tìm kiếm toàn văn ngay lập tức. +- Kết hợp pipeline này với công cụ chuyển PDF để xử lý các PDF đã quét trong một lần. + +Có câu hỏi, hoặc gặp vấn đề với một loại tệp cụ thể? Hãy để lại bình luận bên dưới, chúng ta sẽ cùng giải quyết. Chúc bạn lập trình vui vẻ, và hy vọng các lần chạy OCR của bạn luôn nhanh và không lỗi! + +## Bạn Nên Học Gì Tiếp Theo? + +- [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 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/vietnamese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..6b11a5d99 --- /dev/null +++ b/ocr/vietnamese/python-java/general/create-license-instance-in-python-step-by-step-guide/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-05-31 +description: Tạo đối tượng giấy phép trong Python và cấu hình đường dẫn giấy phép + một cách dễ dàng. Tìm hiểu cách thiết lập giấy phép Aspose OCR với các ví dụ mã + rõ ràng. +draft: false +keywords: +- create license instance +- configure license path +language: vi +og_description: Tạo một thể hiện giấy phép trong Python và cấu hình đường dẫn giấy + phép ngay lập tức. Hãy làm theo hướng dẫn này để kích hoạt Aspose OCR một cách tự + tin. +og_title: Tạo thể hiện giấy phép trong Python – Hướng dẫn cài đặt đầy đủ +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + headline: Create license instance in Python – Step‑by‑Step Guide + type: TechArticle +- description: Create license instance in Python and configure license path easily. + Learn how to set up Aspose OCR licensing with clear code examples. + name: Create license instance in Python – Step‑by‑Step Guide + steps: + - name: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + text: '**Raw strings (`r"…"`)** prevent backslashes from being interpreted as + escape characters on Windows.' + - name: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + text: Use an **absolute path** to avoid confusion when the script is launched + from a different working directory. + - name: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + text: If you prefer a relative path (e.g., when bundling the license with your + project), make sure the relative base is the script’s location, not the current + shell directory. + type: HowTo +tags: +- Aspose OCR +- Python licensing +- SDK setup +title: Tạo đối tượng giấy phép trong Python – Hướng dẫn từng bước +url: /vi/python-java/general/create-license-instance-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo đối tượng license trong Python – Hướng dẫn thiết lập đầy đủ + +Cần **tạo đối tượng license** cho Aspose OCR trong Python? Bạn đang ở đúng chỗ. Trong hướng dẫn này chúng tôi cũng sẽ chỉ cho bạn cách **cấu hình đường dẫn license** để SDK biết nơi tìm file `.lic` của bạn. + +Nếu bạn đã bao giờ nhìn chằm chằm vào một script trống và tự hỏi tại sao engine OCR cứ phàn nàn về sản phẩm chưa được cấp phép, bạn không phải là người duy nhất. Giải pháp thường chỉ là một vài dòng code—một khi bạn biết chính xác nơi đặt chúng. Khi hoàn thành hướng dẫn này, bạn sẽ có môi trường Aspose OCR đã được cấp phép đầy đủ, sẵn sàng nhận dạng văn bản, hình ảnh và PDF mà không gặp rắc rối. + +## Những gì bạn sẽ học + +- Cách **tạo đối tượng license** bằng gói `asposeocr`. +- Cách **cấu hình đường dẫn license** đúng cho môi trường phát triển và sản xuất. +- Các lỗi thường gặp (file thiếu, quyền truy cập sai) và cách tránh chúng. +- Một script hoàn chỉnh, có thể chạy ngay mà bạn có thể đưa vào bất kỳ dự án nào. + +Không yêu cầu kinh nghiệm trước với Aspose OCR, chỉ cần một cài đặt Python 3 hoạt động và một file license hợp lệ. + +--- + +## Bước 1: Cài đặt gói Aspose OCR cho Python + +Trước khi chúng ta có thể **tạo đối tượng license**, thư viện cần phải được cài đặt. Mở terminal và chạy: + +```bash +pip install aspose-ocr +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn đang sử dụng môi trường ảo (được khuyến nghị mạnh), hãy kích hoạt nó trước. Điều này giúp giữ các phụ thuộc gọn gàng và tránh xung đột phiên bản. + +## Bước 2: Nhập lớp License + +Bây giờ SDK đã sẵn sàng, dòng đầu tiên trong script của bạn nên nhập lớp `License`. Đây là đối tượng chúng ta sẽ dùng để **tạo đối tượng license**. + +```python +# Import the License class from Aspose OCR +from asposeocr import License +``` + +Tại sao phải nhập ngay lập tức? Vì đối tượng `License` phải được khởi tạo **trước** khi gọi bất kỳ phương thức OCR nào; nếu không SDK sẽ ném lỗi cấp phép ngay khi bạn cố xử lý một hình ảnh. + +## Bước 3: Tạo đối tượng License + +Đây là khoảnh khắc bạn đang chờ đợi—thực sự **tạo đối tượng license**. Nó chỉ một dòng, nhưng ngữ cảnh xung quanh rất quan trọng. + +```python +# Step 3: Create a License instance +license = License() +``` + +Biến `license` bây giờ chứa một đối tượng kiểm soát toàn bộ hành vi cấp phép cho quá trình Python hiện tại. Hãy nghĩ nó như người gác cổng nói với Aspose OCR: “Này, tôi có quyền chạy.” + +## Bước 4: Cấu hình đường dẫn License + +Với đối tượng đã sẵn sàng, chúng ta cần chỉ định file `.lic` của mình. Đó là lúc **cấu hình đường dẫn license** trở nên cần thiết. Thay thế placeholder bằng đường dẫn tuyệt đối tới file license của bạn. + +```python +# Step 4: Apply your license file (replace with your actual path) +license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") +``` + +Một vài lưu ý: + +1. **Chuỗi raw (`r"…"`)** ngăn các dấu gạch chéo ngược bị hiểu là ký tự escape trên Windows. +2. Sử dụng **đường dẫn tuyệt đối** để tránh nhầm lẫn khi script được chạy từ thư mục làm việc khác. +3. Nếu bạn thích đường dẫn tương đối (ví dụ, khi gói license cùng dự án), hãy chắc chắn rằng cơ sở tương đối là vị trí của script, không phải thư mục shell hiện tại. + +### Xử lý trường hợp file bị thiếu + +Nếu đường dẫn sai hoặc file không đọc được, `set_license` sẽ ném một ngoại lệ. Bao bọc lời gọi trong khối `try/except` để đưa ra thông báo lỗi thân thiện: + +```python +try: + license.set_license(r"C:\Path\To\Your\Aspose.OCR.Java.lic") + print("License applied successfully!") +except Exception as e: + print(f"Failed to apply license: {e}") + # Optional: exit the program if licensing is critical + import sys + sys.exit(1) +``` + +Đoạn mã này **cấu hình đường dẫn license** một cách an toàn và cho bạn biết chính xác lỗi gì đã xảy ra—không còn những stack trace bí ẩn. + +## Bước 5: Xác minh License đã hoạt động + +Một kiểm tra nhanh sẽ tiết kiệm hàng giờ debug sau này. Sau khi gọi `set_license`, thử một thao tác OCR đơn giản. Nếu license hợp lệ, SDK sẽ xử lý hình ảnh mà không ném lỗi cấp phép. + +```python +from asposeocr import OcrEngine + +# Initialize OCR engine (license already applied) +engine = OcrEngine() + +# Load a test image (replace with an actual image path) +engine.load_image_from_file(r"C:\Path\To\TestImage.png") + +# Perform OCR +result = engine.recognize() +print("Recognized text:", result.text) +``` + +Nếu bạn thấy văn bản đã nhận dạng được in ra, chúc mừng—bạn đã thành công **tạo đối tượng license** và **cấu hình đường dẫn license**. Nếu gặp ngoại lệ về cấp phép, hãy kiểm tra lại đường dẫn và quyền truy cập file. + +## Các trường hợp đặc biệt & Thực hành tốt nhất + +| Tình huống | Cách xử lý | +|-----------|------------| +| **File license nằm trên một chia sẻ mạng** | Gắn chia sẻ vào một ký tự ổ đĩa hoặc dùng đường dẫn UNC (`\\server\share\license.lic`). Đảm bảo quá trình Python có quyền đọc. | +| **Chạy trong Docker container** | Sao chép file `.lic` vào image và tham chiếu bằng đường dẫn tuyệt đối như `/app/license/Aspose.OCR.Java.lic`. | +| **Nhiều interpreter Python** (ví dụ, môi trường conda) | Cài đặt file license một lần cho mỗi môi trường hoặc giữ ở vị trí trung tâm và trỏ mỗi interpreter tới đó. | +| **File license không tồn tại khi chạy** | Giảm nhẹ bằng chế độ dùng thử (nếu hỗ trợ) hoặc dừng lại với thông báo log rõ ràng. | + +### Những lỗi thường gặp + +- **Dùng dấu gạch chéo xuôi trên Windows** – Python chấp nhận, nhưng một số phiên bản SDK cũ có thể hiểu sai. Hãy dùng chuỗi raw hoặc dấu gạch chéo ngược kép. +- **Quên nhập `License`** – Script sẽ bị crash với `NameError`. Luôn nhập trước khi khởi tạo. +- **Gọi `set_license` sau các phương thức OCR** – SDK kiểm tra cấp phép khi lần dùng đầu tiên, vì vậy hãy đặt đường dẫn **trước**. + +## Ví dụ hoàn chỉnh + +Dưới đây là một script đầy đủ kết hợp mọi bước. Lưu lại dưới tên `ocr_setup.py` và chạy từ dòng lệnh. + +```python +#!/usr/bin/env python3 +""" +Full example: create license instance and configure license path for Aspose OCR. +""" + +# ---- Imports -------------------------------------------------------------- +from asposeocr import License, OcrEngine + +# ---- Step 1: Create License Instance --------------------------------------- +license = License() + +# ---- Step 2: Configure License Path ---------------------------------------- +# Update the path to point at your actual .lic file. +LICENSE_PATH = r"C:\Path\To\Your\Aspose.OCR.Java.lic" + +try: + license.set_license(LICENSE_PATH) + print("✅ License applied successfully.") +except Exception as err: + print(f"❌ Failed to apply license: {err}") + # Exit if licensing is essential for the rest of the app + import sys + sys.exit(1) + +# ---- Step 3: Verify Licensing with a Simple OCR Call ----------------------- +engine = OcrEngine() + +# Replace with a real image file you want to test. +TEST_IMAGE = r"C:\Path\To\TestImage.png" + +try: + engine.load_image_from_file(TEST_IMAGE) + result = engine.recognize() + print("\n--- OCR Result -------------------------------------------------") + print(result.text) +except Exception as e: + print(f"Error during OCR processing: {e}") +``` + +**Kết quả mong đợi** (giả sử hình ảnh hợp lệ): + +``` +✅ License applied successfully. + +--- OCR Result ------------------------------------------------- +Hello, Aspose OCR! +``` + +Nếu file license không tìm thấy, bạn sẽ nhận được thông báo lỗi rõ ràng thay vì ngoại lệ “License not found” khó hiểu. + +--- + +## Kết luận + +Bây giờ bạn đã biết chính xác cách **tạo đối tượng license** trong Python và **cấu hình đường dẫn license** cho SDK Aspose OCR. Các bước rất đơn giản: cài gói, nhập `License`, khởi tạo, chỉ tới file `.lic` của bạn, và xác minh bằng một bài kiểm tra OCR nhỏ. + +Với kiến thức này, bạn có thể nhúng khả năng OCR vào các dịch vụ web, ứng dụng desktop, hoặc pipeline tự động mà không gặp rắc rối về cấp phép. Tiếp theo, hãy khám phá các cài đặt OCR nâng cao—gói ngôn ngữ, tiền xử lý hình ảnh, hoặc xử lý batch—mỗi thứ đều dựa trên nền tảng vững chắc mà bạn vừa thiết lập. + +Có câu hỏi về triển khai, Docker, hoặc quản lý nhiều license? Hãy để lại bình luận, chúc bạn lập trình vui vẻ! + +## Bạn nên học gì tiếp theo? + +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) +- [How to Set License and Verify Aspose.OCR License in Java](/ocr/english/java/ocr-basics/set-license/) +- [How to OCR Image Text with Language Using Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/create-searchable-pdf-with-python-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..6724d45a0 --- /dev/null +++ b/ocr/vietnamese/python-java/general/create-searchable-pdf-with-python-step-by-step-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-31 +description: Tạo PDF có thể tìm kiếm từ hình ảnh đã quét bằng Python OCR. Học cách + chuyển đổi PDF hình ảnh đã quét, chuyển đổi TIFF sang PDF và thêm lớp văn bản OCR + trong vài phút. +draft: false +keywords: +- create searchable pdf +- convert scanned image pdf +- convert tiff to pdf +- how to run OCR +- add OCR text layer +language: vi +og_description: Tạo PDF có thể tìm kiếm ngay lập tức. Hướng dẫn này chỉ cách chạy + OCR, chuyển đổi PDF ảnh quét và thêm lớp văn bản OCR bằng một script Python duy + nhất. +og_title: Tạo PDF có thể tìm kiếm bằng Python – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + headline: Create Searchable PDF with Python – Step‑by‑Step Guide + type: TechArticle +- description: Create searchable PDF from scanned images using Python OCR. Learn how + to convert scanned image PDF, convert TIFF to PDF, and add OCR text layer in minutes. + name: Create Searchable PDF with Python – Step‑by‑Step Guide + steps: + - name: Expected Output + text: 'Running the script prints:' + - name: 1️⃣ Can I process multi‑page PDFs? + text: Yes. Use `ocr_engine.load_image("file.pdf")` and then loop over each page + with `ocr_engine.recognize(pdf_save_options, page_number)`. The library will + automatically generate a multi‑page searchable PDF. + - name: 2️⃣ What if my source file is a high‑resolution TIFF (300 dpi+)? + text: 'Higher DPI yields better OCR accuracy but also larger memory usage. If + you hit a `MemoryError`, downscale the image first:' + - name: 3️⃣ How do I change the language of the OCR? + text: 'Set the `language` property on the engine before loading the image:' + - name: 4️⃣ What if I need to keep the original image quality? + text: The `PdfSaveOptions` class has a `compression` property. Set it to `PdfCompression.None` + to preserve the raster data exactly as it was. + type: HowTo +tags: +- OCR +- Python +- PDF +- Document Automation +title: Tạo PDF có thể tìm kiếm bằng Python – Hướng dẫn từng bước +url: /vi/python-java/general/create-searchable-pdf-with-python-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 bằng Python – Hướng dẫn từng bước + +Bạn đã bao giờ tự hỏi làm thế nào để **tạo PDF có thể tìm kiếm** từ một trang đã quét mà không phải dùng hàng chục công cụ? Bạn không phải là người duy nhất. Trong nhiều quy trình văn phòng, một tệp TIFF hoặc JPEG đã quét được lưu vào ổ chia sẻ, và người tiếp theo phải sao chép‑dán văn bản thủ công—đau đầu, dễ gây lỗi và tốn thời gian. + +Trong hướng dẫn này, chúng ta sẽ đi qua một giải pháp lập trình sạch sẽ cho phép bạn **chuyển đổi PDF ảnh đã quét**, **chuyển đổi TIFF sang PDF**, và **thêm lớp văn bản OCR** trong một lần. Khi kết thúc, bạn sẽ có một script sẵn sàng sử dụng, chạy OCR, nhúng văn bản ẩn, và tạo ra một PDF có thể tìm kiếm mà bạn có thể lập chỉ mục, tìm kiếm hoặc chia sẻ một cách tự tin. + +## Những gì bạn cần + +- Python 3.9+ (bất kỳ phiên bản mới nào cũng hoạt động) +- `aspose-ocr` và `aspose-pdf` packages (cài đặt bằng `pip install aspose-ocr aspose-pdf`) +- Một tệp ảnh đã quét (`.tif`, `.png`, `.jpg`, hoặc thậm chí một trang PDF chỉ chứa hình ảnh) +- Một lượng RAM vừa đủ (engine OCR nhẹ; ngay cả laptop cũng xử lý được) + +> **Mẹo chuyên nghiệp:** Nếu bạn đang dùng Windows, cách dễ nhất để lấy các gói là chạy lệnh trong cửa sổ PowerShell được nâng quyền. + +```bash +pip install aspose-ocr aspose-pdf +``` + +Bây giờ các điều kiện tiên quyết đã được giải quyết, chúng ta hãy đi sâu vào mã. + +## Bước 1: Tạo một thể hiện OCR Engine – *create searchable pdf* + +Điều đầu tiên chúng ta làm là khởi động OCR engine. Hãy nghĩ nó như bộ não sẽ đọc từng pixel và chuyển chúng thành ký tự. + +```python +from aspose.ocr import OcrEngine + +# Initialize the OCR engine – this is the core of the create searchable pdf process +ocr_engine = OcrEngine() +``` + +> **Tại sao điều này quan trọng:** Khởi tạo engine chỉ một lần giúp giảm mức sử dụng bộ nhớ. Nếu bạn gọi `OcrEngine()` trong một vòng lặp cho mỗi trang, bạn sẽ nhanh chóng hết tài nguyên. + +## Bước 2: Tải ảnh đã quét – *convert tiff to pdf* & *convert scanned image pdf* + +Tiếp theo, chỉ định engine tới tệp bạn muốn xử lý. API chấp nhận bất kỳ hình ảnh raster nào, vì vậy TIFF hoạt động tốt như JPEG. + +```python +# Load the image you want to OCR. Replace the path with your own file location. +ocr_engine.load_image("YOUR_DIRECTORY/scanned_page.tif") +``` + +Nếu bạn có một PDF chỉ chứa ảnh đã quét, bạn vẫn có thể sử dụng `load_image` vì Aspose sẽ tự động trích xuất trang đầu tiên. + +## Bước 3: Chuẩn bị tùy chọn lưu PDF – *add OCR text layer* + +Ở đây chúng ta cấu hình cách PDF cuối cùng sẽ hiển thị. Cờ quan trọng là `create_searchable_pdf`; đặt nó thành `True` sẽ yêu cầu thư viện nhúng một lớp văn bản vô hình phản ánh nội dung hình ảnh. + +```python +from aspose.pdf import PdfSaveOptions + +pdf_save_options = PdfSaveOptions() +pdf_save_options.create_searchable_pdf = True # embed OCR text layer +pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" +``` + +> **Chức năng của lớp văn bản:** Khi bạn mở tệp kết quả trong Adobe Reader và cố gắng chọn văn bản, bạn sẽ thấy các ký tự ẩn. Các công cụ tìm kiếm cũng có thể lập chỉ mục chúng—hoàn hảo cho việc tuân thủ hoặc lưu trữ. + +## Bước 4: Chạy OCR và Lưu – *how to run OCR* trong một lần gọi + +Bây giờ phép màu xảy ra. Một lần gọi phương thức sẽ chạy engine nhận dạng và ghi PDF có thể tìm kiếm vào đĩa. + +```python +# Run OCR and generate the searchable PDF in one go +ocr_engine.recognize(pdf_save_options) + +print("PDF saved as searchable PDF.") +``` + +Phương thức `recognize` trả về một đối tượng trạng thái mà bạn có thể kiểm tra lỗi, nhưng đối với hầu hết các kịch bản đơn giản, lời gọi đơn giản ở trên là đủ. + +### Kết quả mong đợi + +Chạy script sẽ in ra: + +``` +PDF saved as searchable PDF. +``` + +Nếu bạn mở `scanned_page_searchable.pdf` bạn sẽ thấy có thể chọn văn bản, sao chép‑dán, và thậm chí thực hiện tìm kiếm `Ctrl+F`. Đó là dấu hiệu của quy trình **create searchable pdf**. + +## Script Hoàn chỉnh + +Dưới đây là script hoàn chỉnh, sẵn sàng chạy. Chỉ cần thay thế các đường dẫn placeholder bằng vị trí tệp thực tế của bạn. + +```python +# ------------------------------------------------------------ +# create_searchable_pdf.py – Convert scanned image to searchable PDF +# ------------------------------------------------------------ + +from aspose.ocr import OcrEngine +from aspose.pdf import PdfSaveOptions + +def main(): + # 1️⃣ Initialize OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load image (TIFF, JPEG, PNG, or scanned PDF page) + image_path = "YOUR_DIRECTORY/scanned_page.tif" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure PDF output – embed OCR text layer + pdf_save_options = PdfSaveOptions() + pdf_save_options.create_searchable_pdf = True + pdf_save_options.output_path = "YOUR_DIRECTORY/scanned_page_searchable.pdf" + + # 4️⃣ Run OCR and write searchable PDF + ocr_engine.recognize(pdf_save_options) + + print("PDF saved as searchable PDF.") + +if __name__ == "__main__": + main() +``` + +Lưu lại dưới tên `create_searchable_pdf.py` và thực thi: + +```bash +python create_searchable_pdf.py +``` + +## Câu hỏi Thường gặp & Trường hợp Đặc biệt + +### 1️⃣ Tôi có thể xử lý PDF đa trang không? + +Có. Sử dụng `ocr_engine.load_image("file.pdf")` và sau đó lặp qua mỗi trang bằng `ocr_engine.recognize(pdf_save_options, page_number)`. Thư viện sẽ tự động tạo một PDF có thể tìm kiếm đa trang. + +### 2️⃣ Nếu tệp nguồn của tôi là TIFF độ phân giải cao (300 dpi+)? + +DPI cao hơn cho độ chính xác OCR tốt hơn nhưng cũng tiêu tốn bộ nhớ lớn hơn. Nếu bạn gặp `MemoryError`, hãy giảm kích thước ảnh trước: + +```python +from PIL import Image +img = Image.open(image_path) +img = img.resize((int(img.width * 0.5), int(img.height * 0.5)), Image.ANTIALIAS) +img.save("temp.tif") +ocr_engine.load_image("temp.tif") +``` + +### 3️⃣ Làm thế nào để thay đổi ngôn ngữ của OCR? + +Đặt thuộc tính `language` trên engine trước khi tải ảnh: + +```python +ocr_engine.language = "fra" # French +``` + +Danh sách đầy đủ các mã ngôn ngữ được hỗ trợ có trong tài liệu Aspose. + +### 4️⃣ Nếu tôi cần giữ nguyên chất lượng ảnh gốc thì sao? + +Lớp `PdfSaveOptions` có thuộc tính `compression`. Đặt nó thành `PdfCompression.None` để giữ nguyên dữ liệu raster như ban đầu. + +```python +pdf_save_options.compression = "None" +``` + +## Mẹo cho Triển khai Sẵn sàng Sản xuất + +- **Xử lý hàng loạt:** Đóng gói logic cốt lõi trong một hàm nhận danh sách đường dẫn tệp. Ghi lại mỗi lần thành công/ thất bại vào file CSV để theo dõi kiểm toán. +- **Song song:** Sử dụng `concurrent.futures.ThreadPoolExecutor` để chạy OCR trên nhiều lõi. Chỉ cần nhớ mỗi luồng cần một thể hiện `OcrEngine` riêng. +- **Bảo mật:** Nếu bạn xử lý tài liệu nhạy cảm, chạy script trong môi trường sandbox và xóa ngay các tệp tạm sau khi xử lý. + +## Kết luận + +Bây giờ bạn đã biết cách **tạo PDF có thể tìm kiếm** từ các ảnh đã quét bằng một script Python ngắn gọn. Bằng cách khởi tạo OCR engine, tải một TIFF (hoặc bất kỳ raster nào), cấu hình `PdfSaveOptions` để **thêm lớp văn bản OCR**, và cuối cùng gọi `recognize`, toàn bộ quy trình **convert scanned image pdf** và **convert TIFF to PDF** trở thành một lệnh duy nhất, có thể lặp lại. + +Bước tiếp theo? Hãy thử nối script này với một file‑watcher để bất kỳ bản quét mới nào được thả vào thư mục sẽ tự động trở thành có thể tìm kiếm. Hoặc thử nghiệm các ngôn ngữ OCR khác nhau để hỗ trợ lưu trữ đa ngôn ngữ. Không giới hạn khi bạn kết hợp OCR với việc tạo PDF. + +Có thêm câu hỏi về **cách chạy OCR** trong các ngôn ngữ hoặc framework khác? Để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +![Sơ đồ hiển thị luồng từ ảnh đã quét → OCR engine → PDF có thể tìm kiếm (create searchable pdf)](searchable-pdf-flow.png "Create searchable pdf flow diagram") + + +## Bạn nên học gì tiếp theo? + +- [Cách OCR PDF trong .NET với Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [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 văn bản hình ảnh với ngôn ngữ bằng Aspose.OCR](/ocr/english/java/ocr-operations/perform-ocr-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/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md b/ocr/vietnamese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..5705697e7 --- /dev/null +++ b/ocr/vietnamese/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-31 +description: Cải thiện độ chính xác OCR với Python bằng cách tiền xử lý hình ảnh cho + OCR. Tìm hiểu cách trích xuất văn bản từ các tệp hình ảnh, nhận dạng văn bản từ + PNG và nâng cao kết quả. +draft: false +keywords: +- improve OCR accuracy +- preprocess image for OCR +- extract text from image +- recognize text from PNG +- image preprocessing for text +language: vi +og_description: Cải thiện độ chính xác OCR trong Python bằng cách áp dụng tiền xử + lý hình ảnh cho văn bản. Hãy làm theo hướng dẫn này để trích xuất văn bản từ các + tệp hình ảnh và nhận dạng văn bản từ PNG một cách dễ dàng. +og_title: Cải thiện độ chính xác OCR trong Python – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + headline: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + type: TechArticle +- description: Improve OCR accuracy with Python by preprocessing images for OCR. Learn + how to extract text from image files, recognize text from PNG, and boost results. + name: Improve OCR Accuracy in Python – Complete Step‑by‑Step Guide + steps: + - name: Loads the PNG into memory + text: Loads the PNG into memory + - name: Applies denoise and deskew based on our settings + text: Applies denoise and deskew based on our settings + - name: Runs the neural‑network or classic pattern matcher + text: Runs the neural‑network or classic pattern matcher + - name: Packages the output into `recognition_result` + text: Packages the output into `recognition_result` + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: Cải thiện độ chính xác OCR trong Python – Hướng dẫn chi tiết từng bước +url: /vi/python-java/general/improve-ocr-accuracy-in-python-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cải thiện độ chính xác OCR trong Python – Hướng dẫn đầy đủ từng bước + +Bạn đã bao giờ cố gắng **cải thiện độ chính xác OCR** nhưng chỉ nhận được kết quả rối loạn chưa? Bạn không phải là người duy nhất. Hầu hết các nhà phát triển gặp khó khăn khi hình ảnh thô bị nhiễu, lệch, hoặc chỉ đơn giản là độ tương phản thấp. Tin tốt là gì? Một vài thủ thuật tiền xử lý có thể biến một ảnh chụp màn hình mờ thành văn bản sạch, có thể đọc được bởi máy. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ thực tế mà **tiền xử lý một hình ảnh cho OCR**, chạy công cụ nhận dạng, và cuối cùng **trích xuất văn bản từ hình ảnh** — cụ thể là một tệp PNG. Khi kết thúc, bạn sẽ biết chính xác cách **nhận dạng văn bản từ PNG** với tỷ lệ thành công cao hơn, và bạn sẽ có một đoạn mã có thể tái sử dụng để chèn vào bất kỳ dự án nào. + +## Những gì bạn sẽ học + +- Tại sao tiền xử lý hình ảnh lại quan trọng đối với các engine OCR +- Các chế độ tiền xử lý nào (loại bỏ nhiễu, chỉnh nghiêng) mang lại cải thiện lớn nhất +- Cách cấu hình một thể hiện `OcrEngine` trong Python +- Script hoàn chỉnh, có thể chạy được mà **trích xuất văn bản từ hình ảnh** +- Mẹo xử lý các trường hợp đặc biệt như bản quét bị xoay hoặc hình ảnh độ phân giải thấp + +Không cần thư viện bên ngoài nào ngoài OCR SDK, nhưng bạn sẽ cần Python 3.8+ và một hình ảnh PNG mà bạn muốn đọc. + +--- + +![Sơ đồ minh họa các bước cải thiện độ chính xác OCR trong Python](image.png "Quy trình cải thiện độ chính xác OCR") + +*Văn bản thay thế: sơ đồ quy trình cải thiện độ chính xác OCR minh họa các bước tiền xử lý và nhận dạng.* + +## Yêu cầu trước + +- Cài đặt Python 3.8 hoặc mới hơn +- Truy cập vào OCR SDK cung cấp `OcrEngine`, `OcrEngineSettings`, và `ImagePreprocessMode` (mã dưới đây sử dụng API chung; thay thế bằng các lớp của nhà cung cấp nếu cần) +- Một hình ảnh PNG (`input.png`) được đặt trong thư mục bạn có thể tham chiếu + +Nếu bạn đang sử dụng môi trường ảo, hãy kích hoạt ngay—không cần gì phức tạp, chỉ cần `python -m venv venv && source venv/bin/activate`. + +--- + +## Bước 1: Tạo thể hiện OCR Engine – Bắt đầu cải thiện độ chính xác OCR + +Điều đầu tiên bạn cần là một đối tượng OCR engine. Hãy nghĩ nó như bộ não sẽ sau này đọc các pixel và tạo ra các ký tự. + +```python +# Step 1: Initialise the OCR engine +ocr_engine = OcrEngine() +``` + +Tại sao điều này quan trọng: nếu không có engine, bạn không thể áp dụng bất kỳ tiền xử lý nào, và hình ảnh thô sẽ được đưa trực tiếp cho bộ nhận dạng—thường là trường hợp tệ nhất cho độ chính xác. + +--- + +## Bước 2: Tải PNG mục tiêu – Chuẩn bị môi trường cho việc Nhận dạng Văn bản từ PNG + +Bây giờ chúng ta cho engine biết tệp nào sẽ được xử lý. PNG là định dạng không mất dữ liệu, điều này đã mang lại cho chúng ta một lợi thế nhỏ so với JPEG. + +```python +# Step 2: Load the image you want to process +ocr_engine.load_image("YOUR_DIRECTORY/input.png") +``` + +Nếu hình ảnh nằm ở nơi khác, chỉ cần điều chỉnh đường dẫn. Engine chấp nhận bất kỳ định dạng nào được hỗ trợ, nhưng PNG thường giữ lại các chi tiết tinh tế cần thiết cho các cạnh ký tự sắc nét. + +--- + +## Bước 3: Cấu hình Tiền xử lý – Tiền xử lý Hình ảnh cho OCR + +Đây là nơi phép thuật diễn ra. Chúng ta tạo một đối tượng cài đặt, bật tính năng loại bỏ nhiễu để xóa các đốm, và bật chế độ chỉnh nghiêng để văn bản bị nghiêng được tự động làm thẳng. + +```python +# Step 3: Prepare preprocessing settings to improve accuracy +preprocess_settings = OcrEngineSettings() +preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW +) +``` + +### Tại sao Loại bỏ Nhiễu + Chỉnh nghiêng? + +- **Denoise**: Nhiễu pixel ngẫu nhiên làm rối loạn các thuật toán khớp mẫu. Loại bỏ nó làm nét các ký tự. +- **Deskew**: Ngay cả một góc nghiêng 2 độ cũng có thể làm giảm đáng kể điểm tin cậy. Chỉnh nghiêng căn chỉnh đường cơ sở, cho phép bộ nhận dạng khớp phông chữ một cách đáng tin cậy hơn. + +Bạn có thể thử nghiệm các cờ bổ sung (ví dụ, `ImagePreprocessMode.CONTRAST_ENHANCE`) nếu hình ảnh của bạn đặc biệt tối. Tài liệu SDK thường liệt kê tất cả các chế độ khả dụng. + +--- + +## Bước 4: Áp dụng Cài đặt cho Engine – Liên kết Tiền xử lý với OCR + +Gán đối tượng cài đặt cho engine để lần nhận dạng tiếp theo sử dụng các biến đổi chúng ta vừa định nghĩa. + +```python +# Step 4: Apply the settings to the engine +ocr_engine.settings = preprocess_settings +``` + +Nếu bạn bỏ qua bước này, engine sẽ quay lại mặc định (thường là “không tiền xử lý”), và bạn sẽ thấy **độ chính xác OCR thấp hơn**. + +--- + +## Bước 5: Chạy quy trình Nhận dạng – Trích xuất Văn bản từ Hình ảnh + +Khi mọi thứ đã được kết nối, cuối cùng chúng ta yêu cầu engine thực hiện công việc của nó. Lệnh gọi là đồng bộ, trả về một đối tượng kết quả chứa chuỗi đã nhận dạng. + +```python +# Step 5: Run the recognition process +recognition_result = ocr_engine.recognize() +``` + +Trong quá trình thực thi, engine hiện sẽ: + +1. Tải PNG vào bộ nhớ +2. Áp dụng loại bỏ nhiễu và chỉnh nghiêng dựa trên cài đặt của chúng ta +3. Chạy mạng nơ-ron hoặc bộ khớp mẫu cổ điển +4. Đóng gói kết quả vào `recognition_result` + +--- + +## Bước 6: Xuất Văn bản Đã Nhận dạng – Xác minh Cải thiện + +Hãy in ra chuỗi đã trích xuất. Trong một ứng dụng thực tế, bạn có thể ghi nó vào tệp, cơ sở dữ liệu, hoặc truyền cho dịch vụ khác. + +```python +# Step 6: Output the recognized text +print(recognition_result.text) +``` + +### Kết quả Dự kiến + +Nếu hình ảnh chứa câu “Hello, OCR World!” bạn sẽ thấy: + +``` +Hello, OCR World! +``` + +Chú ý cách văn bản sạch sẽ—không có ký tự lạ hay bị gãy. Đó là kết quả của **tiền xử lý hình ảnh cho văn bản** đúng cách. + +--- + +## Mẹo chuyên nghiệp & Các trường hợp đặc biệt + +| Tình huống | Cần Điều chỉnh | Lý do | +|-----------|----------------|------| +| PNG độ phân giải rất thấp (≤ 72 dpi) | Thêm `ImagePreprocessMode.SUPER_RESOLUTION` nếu có | Tăng mẫu có thể cung cấp cho bộ nhận dạng nhiều pixel hơn để làm việc | +| Văn bản bị xoay > 5° | Tăng độ chịu lỗi chỉnh nghiêng hoặc tự quay bằng `Pillow` trước khi đưa vào engine | Góc nghiêng lớn đôi khi vượt qua chức năng tự động chỉnh nghiêng | +| Nền có họa tiết dày đặc | Bật `ImagePreprocessMode.BACKGROUND_REMOVAL` | Loại bỏ nhiễu không phải văn bản mà nếu không sẽ bị đọc sai | +| Tài liệu đa ngôn ngữ | Đặt `ocr_engine.language = "eng+spa"` (hoặc tương tự) | Engine chọn bộ ký tự phù hợp, cải thiện độ chính xác tổng thể | + +Hãy nhớ, **cải thiện độ chính xác OCR** không phải là giải pháp một kích cỡ cho mọi trường hợp; bạn có thể cần lặp lại việc điều chỉnh các cờ tiền xử lý cho bộ dữ liệu cụ thể của mình. + +--- + +## Script Đầy đủ – Sẵn sàng sao chép & dán + +Dưới đây là ví dụ hoàn chỉnh, có thể chạy được, bao gồm mọi bước chúng ta đã thảo luận. Lưu lại dưới tên `improve_ocr_accuracy.py` và thực thi bằng `python improve_ocr_accuracy.py`. + +```python +""" +Improve OCR Accuracy in Python – Full Example +Author: Your Name (2026) +Requires: OCR SDK providing OcrEngine, OcrEngineSettings, ImagePreprocessMode +""" + +# Import the necessary classes from the OCR SDK +from ocr_sdk import OcrEngine, OcrEngineSettings, ImagePreprocessMode + +def main(): + # 1️⃣ Initialise the OCR engine + ocr_engine = OcrEngine() + + # 2️⃣ Load the PNG you want to read + image_path = "YOUR_DIRECTORY/input.png" + ocr_engine.load_image(image_path) + + # 3️⃣ Configure preprocessing: denoise + deskew + preprocess_settings = OcrEngineSettings() + preprocess_settings.preprocess_mode = ( + ImagePreprocessMode.DENOISE | ImagePreprocessMode.DESKEW + ) + + # 4️⃣ Apply the settings + ocr_engine.settings = preprocess_settings + + # 5️⃣ Run recognition + recognition_result = ocr_engine.recognize() + + # 6️⃣ Print the extracted text + print("=== Recognized Text ===") + print(recognition_result.text) + +if __name__ == "__main__": + main() +``` + +Chạy nó, quan sát console, và bạn sẽ ngay lập tức thấy kết quả **trích xuất văn bản từ hình ảnh**. Nếu đầu ra không đúng, hãy điều chỉnh các cờ `preprocess_mode` như mô tả trong bảng “Mẹo chuyên nghiệp”. + +--- + +## Kết luận + +Chúng ta vừa đi qua một công thức thực tế để **cải thiện độ chính xác OCR** bằng Python. Bằng cách tạo một `OcrEngine`, tải một PNG, **tiền xử lý hình ảnh cho OCR**, và cuối cùng **nhận dạng văn bản từ PNG**, bạn có thể một cách đáng tin cậy **trích xuất văn bản từ hình ảnh** ngay cả khi nguồn không hoàn hảo. + +Bước tiếp theo? Hãy thử đưa một loạt hình ảnh vào vòng lặp, lưu mỗi kết quả vào CSV, hoặc thử nghiệm các chế độ tiền xử lý bổ sung như tăng độ tương phản. Cấu trúc này cũng áp dụng cho PDF, biên lai quét, hoặc ghi chú viết tay—chỉ cần thay đổi đầu vào và điều chỉnh cài đặt. + +Có câu hỏi về một loại hình ảnh cụ thể hoặc muốn biết cách tích hợp vào dịch vụ web? Hãy để lại bình luận, và chúng tôi sẽ cùng khám phá các kịch bản đó. Chúc lập trình vui vẻ, và hy vọng kết quả OCR của bạn luôn trong suốt! + +## Bạn nên học gì tiếp theo? + +- [Trích xuất Văn bản từ Hình ảnh với Aspose OCR – Hướng dẫn từng bước](/ocr/english/python/general/extract-text-from-image-with-aspose-ocr-step-by-step-guide/) +- [Trích xuất Văn bản từ Hình ảnh – Tối ưu hóa OCR với Aspose.OCR cho .NET](/ocr/english/net/ocr-optimization/) +- [Cách Trích xuất Văn bản từ Hình ảnh bằng cách Chuẩn bị Các Hình chữ nhật trong OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md b/ocr/vietnamese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md new file mode 100644 index 000000000..dc3a4dd4e --- /dev/null +++ b/ocr/vietnamese/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-31 +description: Tìm hiểu cách sử dụng vùng quan tâm OCR để tải hình ảnh cho OCR và trích + xuất văn bản từ hình chữ nhật, hoàn hảo cho việc nhận dạng số tiền trên hóa đơn. +draft: false +keywords: +- ocr region of interest +- extract text from rectangle +- load image for ocr +- how to extract amount +- recognize text from invoice +language: vi +og_description: Thành thạo vùng quan tâm OCR để tải hình ảnh cho OCR, trích xuất văn + bản từ hình chữ nhật và nhận dạng văn bản từ hoá đơn trong một hướng dẫn duy nhất. +og_title: OCR Vùng Quan Tâm – Hướng Dẫn Python Từng Bước +schemas: +- author: Aspose + dateModified: '2026-05-31' + description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + headline: OCR Region of Interest – Extract Text from Rectangle in Python + type: TechArticle +- description: Learn how to use OCR region of interest to load image for OCR and extract + text from rectangle, perfect for recognizing amount on an invoice. + name: OCR Region of Interest – Extract Text from Rectangle in Python + steps: + - name: Loads an invoice image from disk. + text: Loads an invoice image from disk. + - name: Marks a rectangular ROI where the total amount lives. + text: Marks a rectangular ROI where the total amount lives. + - name: Runs OCR only inside that ROI. + text: Runs OCR only inside that ROI. + - name: Prints the cleaned‑up amount string. + text: Prints the cleaned‑up amount string. + type: HowTo +tags: +- OCR +- Python +- Image Processing +title: OCR Vùng quan tâm – Trích xuất văn bản từ hình chữ nhật trong Python +url: /vi/python-java/general/ocr-region-of-interest-extract-text-from-rectangle-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Region of Interest – Trích xuất Văn bản từ Hình chữ nhật trong Python + +Bạn đã bao giờ tự hỏi làm sao **ocr region of interest** một phần cụ thể của hoá đơn đã quét mà không phải đưa toàn bộ trang vào engine? Bạn không phải là người đầu tiên nhìn vào một biên lai mờ và nghĩ, “Làm sao tôi lấy được số tiền nằm ở góc dưới bên phải?” Tin tốt là bạn có thể chỉ cho thư viện OCR biết chính xác nơi cần tìm, giúp tăng tốc độ và độ chính xác đáng kể. + +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 được, cho bạn thấy cách **load image for OCR**, định nghĩa một **region of interest**, và sau đó **extract text from rectangle** để cuối cùng **recognize text from invoice** và trả lời câu hỏi cổ điển “làm sao lấy được số tiền”. Không có những tham chiếu mơ hồ—chỉ có code cụ thể, giải thích rõ ràng, và một vài mẹo chuyên nghiệp mà bạn ước mình biết từ trước. + +--- + +## Những gì bạn sẽ xây dựng + +Khi kết thúc tutorial này, bạn sẽ có một script Python nhỏ mà: + +1. Tải ảnh hoá đơn từ đĩa. +2. Đánh dấu một ROI hình chữ nhật nơi tổng số tiền nằm. +3. Chỉ chạy OCR trong ROI đó. +4. In ra chuỗi số tiền đã được làm sạch. + +Tất cả đều hoạt động với bất kỳ thư viện OCR nào hỗ trợ ROI—ở đây chúng ta sẽ dùng một package giả tưởng nhưng đại diện `SimpleOCR` mô phỏng các công cụ phổ biến như Tesseract hoặc EasyOCR. Bạn có thể thay thế nó; các khái niệm vẫn giữ nguyên. + +--- + +## Yêu cầu trước + +- Python 3.8+ đã được cài đặt (`python --version` nên hiển thị ≥3.8). +- Một package OCR có thể cài qua pip (ví dụ: `pip install simpleocr`). +- Một ảnh hoá đơn (PNG hoặc JPEG) được đặt trong thư mục bạn có thể tham chiếu. +- Kiến thức cơ bản về hàm và lớp trong Python (không cần gì phức tạp). + +Nếu bạn đã có những thứ trên, tuyệt vời—cùng bắt đầu. Nếu chưa, hãy lấy ảnh trước; các bước còn lại không phụ thuộc vào nội dung thực tế của file. + +--- + +## Bước 1: Load Image for OCR + +Điều đầu tiên bất kỳ quy trình OCR nào cần là một bitmap để đọc. Hầu hết các thư viện cung cấp một phương thức `load_image` đơn giản nhận đường dẫn file. Đây là cách thực hiện với engine `SimpleOCR` của chúng ta: + +```python +# Step 1: Create an OCR engine instance and load the invoice image +from simpleocr import OcrEngine + +# Initialize the engine (you can pass language settings here if needed) +ocr_engine = OcrEngine() + +# Load the image – replace the path with yours +ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") +``` + +> **Pro tip:** Sử dụng đường dẫn tuyệt đối hoặc `os.path.join` để tránh những lỗi “file not found” khi chạy script từ thư mục làm việc khác. + +--- + +## Bước 2: Define OCR Region of Interest + +Thay vì để engine quét toàn bộ trang, chúng ta chỉ cho nó *chính xác* nơi số tiền nằm. Đây là bước **ocr region of interest**, và nó là chìa khóa để trích xuất đáng tin cậy, đặc biệt khi tài liệu có tiêu đề hoặc chân trang gây nhiễu. + +```python +# Step 2: Define the region of interest (ROI) where the amount appears +# Rectangle(x, y, width, height) – adjust these values for your layout +from simpleocr import Rectangle + +amount_region = Rectangle(120, 340, 200, 40) # x=120, y=340, w=200, h=40 +ocr_engine.add_roi(amount_region) +``` + +Tại sao lại dùng những con số đó? `x` và `y` là khoảng cách pixel từ góc trên‑trái, trong khi `width` và `height` mô tả kích thước hộp. Nếu không chắc, mở ảnh trong bất kỳ trình chỉnh sửa nào, bật thước đo, và ghi lại tọa độ. Nhiều IDE còn cho phép bạn xem vị trí con trỏ khi di chuột. + +--- + +## Bước 3: Extract Text from Rectangle + +Khi ROI đã được đặt, chúng ta yêu cầu engine **recognize text from invoice** nhưng chỉ trong hình chữ nhật vừa thêm. Lệnh này trả về một đối tượng kết quả thường chứa chuỗi thô, điểm tin cậy, và đôi khi cả bounding box. + +```python +# Step 3: Perform OCR on the specified ROI +ocr_result = ocr_engine.recognize() +``` + +Ở phía sau, `recognize()` lặp qua từng ROI, cắt phần ảnh tương ứng, chạy mô hình OCR, và ghép các kết quả lại. Vì vậy việc định nghĩa một **extract text from rectangle** chặt chẽ có thể giảm vài giây thời gian xử lý cho các job batch. + +--- + +## Bước 4: How to Extract Amount – Clean the Output + +OCR không hoàn hảo; bạn thường nhận được các khoảng trắng thừa, ký tự xuống dòng, hoặc thậm chí ký tự bị nhận sai (ví dụ “S” thay vì “5”). Một `strip()` nhanh và một regex nhỏ thường đủ để xử lý các giá trị tiền tệ. + +```python +# Step 4: Clean and display the recognized amount +import re + +raw_amount = ocr_result.text.strip() +# Simple regex to keep digits, commas, periods, and optional currency symbols +clean_amount = re.search(r'[\d,.]+', raw_amount) +if clean_amount: + print("Amount:", clean_amount.group()) +else: + print("Could not locate a numeric amount in the ROI.") +``` + +> **Why this matters:** Nếu bạn định đưa số tiền vào cơ sở dữ liệu hoặc cổng thanh toán, bạn cần một định dạng dự đoán được. Loại bỏ khoảng trắng và lọc các ký tự không phải số ngăn ngừa lỗi ở các bước tiếp theo. + +--- + +## Bước 5: Recognize Text from Invoice – Full Script + +Kết hợp tất cả lại, đây là script hoàn chỉnh, sẵn sàng chạy. Lưu lại dưới tên `extract_amount.py` và thực thi `python extract_amount.py`. + +```python +# extract_amount.py +import re +from simpleocr import OcrEngine, Rectangle + +def main(): + # Initialize OCR engine + ocr_engine = OcrEngine() + + # Load the invoice image (adjust the path) + ocr_engine.load_image("YOUR_DIRECTORY/invoice.png") + + # Define ROI where the amount is located + amount_region = Rectangle(120, 340, 200, 40) + ocr_engine.add_roi(amount_region) + + # Run OCR on the ROI + ocr_result = ocr_engine.recognize() + + # Clean and print the amount + raw_amount = ocr_result.text.strip() + match = re.search(r'[\d,.]+', raw_amount) + if match: + print("Amount:", match.group()) + else: + print("Could not locate a numeric amount in the ROI.") + +if __name__ == "__main__": + main() +``` + +### Expected Output + +``` +Amount: 1,245.67 +``` + +Nếu ROI không căn chỉnh đúng, bạn có thể thấy kết quả như `Amount: 1245.6S`—có ký tự “S” lạ. Điều chỉnh lại tọa độ hình chữ nhật và chạy lại cho tới khi output sạch sẽ. + +--- + +## Common Pitfalls & Edge Cases + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **ROI quá nhỏ** | Văn bản số tiền bị cắt, dẫn đến nhận dạng không đầy đủ. | Mở rộng `width`/`height` khoảng 10‑20 % và kiểm tra lại. | +| **DPI không đúng** | Ảnh scan độ phân giải thấp (≤150 dpi) làm giảm độ chính xác OCR. | Tăng mẫu ảnh lên 300 dpi trước khi load, hoặc yêu cầu máy scan ở DPI cao hơn. | +| **Nhiều loại tiền tệ** | Regex lấy nhóm số đầu tiên, có thể là số hoá đơn. | Tinh chỉnh regex để tìm ký hiệu tiền tệ (`$`, `€`, `£`) trước các chữ số. | +| **Hoá đơn bị xoay** | Các engine OCR giả định văn bản thẳng đứng; trang xoay làm mất nhận dạng. | Áp dụng chỉnh sửa góc (`ocr_engine.rotate(90)`) trước khi thêm ROI. | +| **Nhiễu nền** | Bóng hoặc dấu tem gây rối mô hình. | Tiền xử lý bằng ngưỡng đơn giản (`cv2.threshold`) hoặc bộ lọc giảm nhiễu. | + +Giải quyết những trường hợp này sớm sẽ tiết kiệm hàng giờ debug sau này. + +--- + +## Pro Tips for Real‑World Projects + +- **Batch Processing:** Lặp qua một thư mục hoá đơn, tính ROI động (ví dụ dựa trên phát hiện mẫu), và lưu kết quả vào CSV. +- **Template Matching:** Nếu bạn xử lý nhiều bố cục hoá đơn, duy trì một bản đồ JSON `template_id → ROI coordinates`. Chuyển ROI dựa trên bộ phân loại mẫu nhanh. +- **Parallel Execution:** Dùng `concurrent.futures.ThreadPoolExecutor` để chạy nhiều instance OCR đồng thời—rất hữu ích cho pipeline back‑office khối lượng lớn. +- **Confidence Filtering:** Hầu hết kết quả OCR có điểm tin cậy. Loại bỏ các kết quả dưới ngưỡng (ví dụ 85 %) và đánh dấu để kiểm tra thủ công. + +--- + +## Kết luận + +Chúng ta đã bao quát mọi thứ cần thiết để **ocr region of interest**, **load image for OCR**, **extract text from rectangle**, và cuối cùng **recognize text from invoice** nhằm trả lời câu hỏi cổ điển **how to extract amount**. Script ngắn gọn, nhưng đủ linh hoạt để thích nghi với các định dạng tài liệu, ngôn ngữ, và backend OCR khác nhau. + +Bây giờ bạn đã nắm vững nền tảng, hãy mở rộng quy trình: thêm quét mã vạch, tích hợp với parser PDF, hoặc đẩy số tiền đã trích xuất lên API kế toán. Không có giới hạn, và với ROI được định nghĩa rõ ràng, bạn luôn nhận được kết quả nhanh hơn, sạch hơn. + +Nếu gặp khó khăn, để lại bình luận bên dưới—chúc bạn OCR vui vẻ! + +![ocr region of interest example](https://example.com/ocr_roi_example.png "ví dụ về OCR region of interest") + + +## Bạn nên học gì tiếp theo? + +- [Cách Trích xuất Văn bản từ Hình ảnh bằng cách Chuẩn bị Hình chữ nhật trong OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Trích xuất Văn bản từ Hình ảnh Java với Aspose.OCR Detect Areas Mode](/ocr/english/java/ocr-operations/perform-ocr-detect-areas-mode/) +- [Trích xuất Văn bản từ Hình ảnh – Tối ưu hoá OCR với Aspose.OCR cho .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file